avcodec_open2 错误 -542398533:“外部库中的一般错误”

bot*_*357 5 c++ ffmpeg libavcodec

我在尝试使用 . 打开编解码器时遇到错误avcodec_open2()avi如果我指定而不是在函数h264中指定,我已经尝试了相同的代码,没有任何问题av_guess_format()

我不知道该怎么办。还有其他人遇到过类似的问题吗?

我正在使用的库是ffmpeg-20160219-git-98a0053-win32-dev。如果您能帮助我摆脱这种困惑,我将非常感激。

这是我的控制台输出:

视频编码
[libx264 @ 01383460] 检测到损坏的 ffmpeg 默认设置
[libx264 @ 01383460] 使用编码预设(例如 -vpre 中)
[libx264 @ 01383460] 预设用法:-vpre -vpre
[libx264 @ 01383460] 速度预设在 x264 中列出--help
[libx264 @ 01383460] 配置文件是可选的;x264 默认为高
无法打开视频编解码器,-542398533

这是我正在使用的代码:

// Video encoding sample
AVCodec *codec = NULL;
AVCodecContext *codecCtx= NULL;
AVFormatContext *pFormatCtx = NULL;
AVOutputFormat *pOutFormat = NULL;
AVStream * pVideoStream = NULL;;
AVFrame *picture = NULL;;

int i, x, y, ret;

printf("Video encoding\n");

// Register all formats and codecs
av_register_all();

// guess format from file extension
pOutFormat = av_guess_format("h264", NULL, NULL);
if (NULL==pOutFormat){
    cerr << "Could not guess output format" << endl;
    return -1;
}   

// allocate context
pFormatCtx = avformat_alloc_context();
pFormatCtx->oformat = pOutFormat;
memcpy(pFormatCtx->filename,filename,
    min(strlen(filename), sizeof(pFormatCtx->filename)));

// Add stream to pFormatCtx
pVideoStream = avformat_new_stream(pFormatCtx, 0);
if (!pVideoStream) 
{
    printf("Cannot add new video stream\n");
    return -1;
}

// Set stream's codec context
codecCtx = pVideoStream->codec;
codecCtx->codec_id = (AVCodecID)pOutFormat->video_codec;
codecCtx->codec_type = AVMEDIA_TYPE_VIDEO;
codecCtx->frame_number = 0;
// Put sample parameters.
codecCtx->bit_rate = 2000000;
// Resolution must be a multiple of two.
codecCtx->width  = 320;
codecCtx->height = 240;
codecCtx->time_base.den = 10;
codecCtx->time_base.num = 1;
pVideoStream->time_base.den = 10;
pVideoStream->time_base.num = 1;
codecCtx->gop_size = 12; // emit one intra frame every twelve frames at most
codecCtx->pix_fmt = AV_PIX_FMT_YUV420P;

if (codecCtx->codec_id == AV_CODEC_ID_H264)
{
    // Just for testing, we also add B frames 
    codecCtx->mb_decision = 2;
}
// Some formats want stream headers to be separate.
if(pFormatCtx->oformat->flags & AVFMT_GLOBALHEADER)
{
    codecCtx->flags |= CODEC_FLAG_GLOBAL_HEADER;
}

if(codecCtx->codec_id == AV_CODEC_ID_H264)
    av_opt_set(codecCtx->priv_data, "preset", "slow", 0);


// Open the codec.
codec = avcodec_find_encoder(codecCtx->codec_id);
if (codec == NULL) {
    fprintf(stderr, "Codec not found\n");
    return -1;
}
ret = avcodec_open2(codecCtx, codec, NULL); // returns -542398533 here
if (ret < 0) 
{
    printf("Cannot open video codec, %d\n",ret);
    return -1;
}
Run Code Online (Sandbox Code Playgroud)

Ron*_*tje 3

你的问题是这一行:

codecCtx = pVideoStream->codec;

AVCodecContext是使用全局默认值进行分配的,x264 拒绝这样做,因为它们不是最佳的。相反,使用avcodec_alloc_context3来分配它,这将设置 x264 特定的默认值。在编码结束时,不要忘记avcodec_free_context返回的指针。