avcodec_open2返回无效参数(errnum -22)



我正在尝试使用h264编解码器将AVFrames矢量编码为MP4文件。

一切似乎都很好,直到avcodec_open2函数,它返回一个"无效参数";(-22)错误。

* stream形参是AVStream的指针。

下面是设置流参数的代码:

stream->codecpar->codec_id = AV_CODEC_ID_H264;
stream->codecpar->codec_type = AVMEDIA_TYPE_VIDEO;
stream->codecpar->width = settings.resolution[0]; // 270
stream->codecpar->height = settings.resolution[1]; // 480
stream->codecpar->format = AV_PIX_FMT_YUV420P;
stream->codecpar->bit_rate = 400000;
AVRational framerate = { 1, 30};
stream->time_base = av_inv_q(framerate);
下面是打开编解码器上下文的代码:

// Open the codec context
AVCodecContext* codec_ctx = avcodec_alloc_context3(codec);
if (!codec_ctx) {
std::cout << "Error allocating codec context" << std::endl;
avformat_free_context(format_ctx);
return;
}
ret = avcodec_parameters_to_context(codec_ctx, stream->codecpar);
if (ret < 0) {
std::cout << "Error setting codec context parameters: " << av_err2str(ret) << std::endl;
avcodec_free_context(&codec_ctx);
avformat_free_context(format_ctx);
return;
}
ret = avcodec_open2(codec_ctx, codec, nullptr);
if (ret < 0) {
wxMessageBox("Error opening codec: ");
wxMessageBox(av_err2str(ret));
avcodec_free_context(&codec_ctx);
avformat_free_context(format_ctx);
return;
}

我尝试了@philipp在ffmpeg-avcodec-open2-returns-invalid-argument中建议的解决方案,但它没有解决我的错误。

我不知道是什么导致这个错误在我的代码,有人可以帮助我吗?

看起来codec_ctx->time_base未初始化。

在执行ret = avcodec_open2(codec_ctx, codec, nullptr);之前,添加以下代码行:

codec_ctx->time_base = stream->time_base;

codec_ctx->time_base的默认值为{0, 0},导致avcodec_open2返回错误状态

注意执行avcodec_parameters_to_context(codec_ctx, stream->codecpar)不会复制time_base,因为time_base不是stream->codecpar的一部分。

最新更新