avcodec_parameterslaipuhuo.com
bool ImageToVideo::InitVideo()
{
InitFfmpeg();
AVFormatContext* pFormatCtx = NULL;
_errnum = avformat_alloc_output_context2(&pFormatCtx, NULL, NULL, _destVideoFileName.c_str());
if (_errnum < 0)
{
av_strerror(_errnum, _errbuf, sizeof(_errbuf));
return false;
}
_initFree.pFormatCtx = pFormatCtx;
// h264视频编码器
const AVCodec* vcodec = avcodec_find_encoder(AVCodecID::AV_CODEC_ID_H264);
if (!vcodec)
{
return false;
}
// 创建编码器上下文
AVCodecContext* pVideoCodecCtx = avcodec_alloc_context3(vcodec);
if (!pVideoCodecCtx)
{
return false;
}
_initFree.pVideoCodecCtx = pVideoCodecCtx;
// 比特率、宽度、高度
pVideoCodecCtx->bit_rate = 4000000;
pVideoCodecCtx->width = _videoWidth; // 视频宽度
pVideoCodecCtx->height = _videoHeight; // 视频高度
// 时间基数、帧率
pVideoCodecCtx->time_base = { 1, 25 };
pVideoCodecCtx->framerate = { 25, 1 };
// 关键帧间隔
pVideoCodecCtx https://www.laipuhuo.com->gop_size = 10;
// 不使用b帧
pVideoCodecCtx->max_b_frames = 0;
// 帧、编码格式
pVideoCodecCtx->pix_fmt = AVPixelFormat::AV_PIX_FMT_YUV420P;
pVideoCodecCtx->codec_id = AVCodecID::AV_CODEC_ID_H264;
// 预设:快速
av_opt_set(pVideoCodecCtx->priv_data, "preset", "superfast", 0);
// 全局头
pVideoCodecCtx->flags |= AV_CODEC_FLAG_GLOBAL_HEADER;
_errnum = avcodec_open2(pVideoCodecCtx, vcodec, NULL);
if (_errnum < 0)
{
return false;
}
// 为封装器创建视频流
AVStream* pVideoStream = avformat_new_stream(pFormatCtx, NULL);
if (!pVideoStream)
{
return false;
}
_initFree.pVideo https://www.laipuhuo.comStream = pVideoStream;
pVideoStream->codec->codec_tag = 0;
pVideoStream->codecpar->codec_tag = 0;
// 配置视频流的编码参数
avcodec_parameters_from_context(pVideoStream->codecpar, pVideoCodecCtx);
// 打开输出流IO
_errnum = https://www.laipuhuo.comavio_open(&pFormatCtx->pb, _destVideoFileName.c_str(), AVIO_FLAG_WRITE); // 打开AVIO流
if (_errnum < 0)
{
avio_close(pFormatCtx->pb);
return false;
}
_errnum =www.laipuhuo.com avformat_write_header(pFormatCtx, NULL);
if (_errnum < 0)
{
return false;
}
return true;
}


