# Qt ffmpeg錄像存儲實現詳解
## 前言
在多媒體應用開發中,音視頻錄制與存儲是核心功能之一。Qt作為跨平臺應用框架,結合FFmpeg強大的多媒體處理能力,可以構建高效的錄像存儲系統。本文將詳細介紹在Qt中如何利用FFmpeg實現錄像存儲功能,涵蓋環境配置、核心流程、代碼實現及優化策略。
---
## 一、環境準備
### 1.1 開發環境要求
- **Qt版本**:5.15或更高(推薦使用Qt6)
- **FFmpeg版本**:4.x或更高
- **編譯器**:MSVC(Windows)、GCC(Linux)、Clang(macOS)
### 1.2 FFmpeg集成
#### Windows平臺
1. 下載預編譯的FFmpeg開發包(包含`include`、`lib`、`dll`)
2. 在Qt項目文件(.pro)中添加:
```qmake
win32 {
INCLUDEPATH += $$PWD/ffmpeg/include
LIBS += -L$$PWD/ffmpeg/lib -lavcodec -lavformat -lavutil -lswscale
}
# 安裝FFmpeg開發包
sudo apt install libavcodec-dev libavformat-dev libavutil-dev # Ubuntu
brew install ffmpeg # macOS
graph TD
A[視頻源] --> B[FFmpeg編碼]
C[音頻源] --> B
B --> D[MP4容器封裝]
D --> E[本地存儲]
extern "C" {
#include <libavcodec/avcodec.h>
#include <libavformat/avformat.h>
#include <libswscale/swscale.h>
}
#include <QDebug>
#include <QDateTime>
class FFmpegRecorder : public QObject {
Q_OBJECT
public:
explicit FFmpegRecorder(QObject *parent = nullptr);
bool startRecording(const QString &filename, int width, int height);
void stopRecording();
void encodeFrame(AVFrame *frame);
private:
AVFormatContext *m_formatCtx = nullptr;
AVCodecContext *m_videoCodecCtx = nullptr;
AVStream *m_videoStream = nullptr;
bool m_isRecording = false;
};
bool FFmpegRecorder::startRecording(const QString &filename, int width, int height) {
// 1. 分配輸出上下文
avformat_alloc_output_context2(&m_formatCtx, nullptr, nullptr,
filename.toLocal8Bit().data());
if (!m_formatCtx) {
qWarning() << "Could not create output context";
return false;
}
// 2. 查找H.264編碼器
const AVCodec *codec = avcodec_find_encoder(AV_CODEC_ID_H264);
if (!codec) {
qWarning() << "H.264 encoder not found";
return false;
}
// 3. 創建視頻流
m_videoStream = avformat_new_stream(m_formatCtx, codec);
m_videoCodecCtx = avcodec_alloc_context3(codec);
// 4. 配置編碼參數
m_videoCodecCtx->width = width;
m_videoCodecCtx->height = height;
m_videoCodecCtx->pix_fmt = AV_PIX_FMT_YUV420P;
m_videoCodecCtx->time_base = (AVRational){1, 30}; // 30fps
// 5. 打開編碼器
if (avcodec_open2(m_videoCodecCtx, codec, nullptr) < 0) {
qWarning() << "Could not open codec";
return false;
}
// 6. 打開輸出文件
if (!(m_formatCtx->oformat->flags & AVFMT_NOFILE)) {
if (avio_open(&m_formatCtx->pb, filename.toLocal8Bit().data(),
AVIO_FLAG_WRITE) < 0) {
qWarning() << "Could not open output file";
return false;
}
}
// 7. 寫入文件頭
avformat_write_header(m_formatCtx, nullptr);
m_isRecording = true;
return true;
}
void FFmpegRecorder::encodeFrame(AVFrame *frame) {
if (!m_isRecording) return;
AVPacket *pkt = av_packet_alloc();
// 發送幀到編碼器
if (avcodec_send_frame(m_videoCodecCtx, frame) < 0) {
qWarning() << "Error sending frame to encoder";
return;
}
// 接收編碼后的包
while (avcodec_receive_packet(m_videoCodecCtx, pkt) >= 0) {
av_packet_rescale_ts(pkt, m_videoCodecCtx->time_base,
m_videoStream->time_base);
pkt->stream_index = m_videoStream->index;
// 寫入文件
av_interleaved_write_frame(m_formatCtx, pkt);
av_packet_unref(pkt);
}
}
void FFmpegRecorder::stopRecording() {
if (!m_isRecording) return;
// 寫入文件尾
av_write_trailer(m_formatCtx);
// 關閉編碼器
if (m_videoCodecCtx) {
avcodec_close(m_videoCodecCtx);
avcodec_free_context(&m_videoCodecCtx);
}
// 關閉輸出文件
if (m_formatCtx && !(m_formatCtx->oformat->flags & AVFMT_NOFILE)) {
avio_close(m_formatCtx->pb);
}
avformat_free_context(m_formatCtx);
m_isRecording = false;
}
// 使用QCamera采集
QCamera *camera = new QCamera(this);
QCameraViewfinder *viewfinder = new QCameraViewfinder(this);
camera->setViewfinder(viewfinder);
camera->start();
// 視頻幀捕獲
QVideoProbe *probe = new QVideoProbe(this);
if (probe->setSource(camera)) {
connect(probe, &QVideoProbe::videoFrameProbed, [this](const QVideoFrame &frame){
// 轉換為AVFrame并編碼
AVFrame *avFrame = convertQtFrameToAVFrame(frame);
m_recorder->encodeFrame(avFrame);
});
}
// 使用QAudioInput
QAudioFormat format;
format.setSampleRate(44100);
format.setChannelCount(2);
format.setSampleSize(16);
format.setCodec("audio/pcm");
QAudioInput *audioInput = new QAudioInput(format, this);
audioInput->start(m_recorder->audioDevice());
硬件加速:使用h264_nvenc
(NVIDIA)或h264_qsv
(Intel)編碼器
const AVCodec *codec = avcodec_find_encoder_by_name("h264_nvenc");
多線程編碼:
m_videoCodecCtx->thread_count = 4; // 使用4個編碼線程
// 設置CRF(Constant Rate Factor)
av_opt_set(m_videoCodecCtx->priv_data, "crf", "23", 0);
// 設置預設(preset)
av_opt_set(m_videoCodecCtx->priv_data, "preset", "fast", 0);
// 每5分鐘創建新文件
QTimer *splitTimer = new QTimer(this);
connect(splitTimer, &QTimer::timeout, [this](){
stopRecording();
startRecording(generateNewFilename(), width, height);
});
splitTimer->start(5 * 60 * 1000);
tune zerolatency
參數
av_opt_set(m_videoCodecCtx->priv_data, "tune", "zerolatency", 0);
ffprobe
分析文件結構本文詳細介紹了Qt+FFmpeg實現錄像存儲的全流程。實際開發中還需考慮更多細節如錯誤恢復、跨平臺兼容等。建議參考FFmpeg官方文檔和Qt Multimedia模塊的示例代碼進行深入開發。
擴展閱讀: - FFmpeg官方文檔 - Qt Multimedia示例 “`
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。