1.写视频头
cpp
void writeVideoHeader(const char* videoFileName){
int r = avformat_alloc_output_context2(&pFormatCtx, nullptr, nullptr,videoFileName);
if(r < 0){
qDebug()<<"Error: avformat_alloc_output_context2: "<<av_err2str(r);
return;
}
pStream = avformat_new_stream(pFormatCtx,nullptr);
qDebug()<<"创建视频流成功";
pFormatCtx->streams[0]->codecpar->width = 1280;
pFormatCtx->streams[0]->codecpar->height = 720;
AVCodecContext *c= pStream->codec;
c->codec_type = AVMEDIA_TYPE_VIDEO;
c->codec_id = AV_CODEC_ID_H264;
c->bit_rate = 2000000;
c->width = 1080;
c->height = 720;
c->time_base.num = 1;
c->time_base.den = 30;
qDebug()<<"配置解码器选项成功";
r = avio_open(&pFormatCtx->pb, videoFileName, AVIO_FLAG_WRITE);
if(r < 0){
qDebug()<<"Error: avio_open: "<<av_err2str(r);
return;
}
qDebug()<<"打开视频流成功";
r = avformat_write_header(pFormatCtx, nullptr);
if(r < 0){
qDebug()<<"Error: avformat_write_header error"<<av_err2str(r)<<r;
return;
}
qDebug()<<"写入视频头部信息成功";
}
2.写视频帧
cpp
void writeAVFrame(AVPacket *packet){
qDebug()<<"原始视频帧信息:"<<packet->pts<<packet->dts<<packet->size;
int64_t video_max_pts = 0;
av_packet_rescale_ts(packet, pStream->time_base, pStream->time_base);
packet->stream_index = 0;
video_max_pts = qMax(packet->pts, video_max_pts);
qDebug("视频:PTS-> %d %d %d",packet->pts,packet->dts, &pStream->time_base);
qDebug()<<"计算时间基成功";
int r=av_write_frame(pFormatCtx, packet);
if (r<0) {
qDebug()<<"Error: av_write_frame: "<<av_err2str(r);
return;
}
qDebug()<<"写入视频帧成功";
}
3.关闭视频流
cpp
if(pFormatCtx){
av_write_trailer(pFormatCtx);
avio_close(pFormatCtx->pb);
avformat_free_context(pFormatCtx);
}