【问题标题】:How to change the settings of AVCodecContext after initialization (FFMPEG)初始化后如何更改 AVCodecContext 的设置(FFMPEG)
【发布时间】:2022-01-12 18:27:32
【问题描述】:

我有一个关于 Libavcodec 的问题,但在网上找不到答案。我正在尝试使用 H.264 对帧进行编码。我遇到的问题是我希望编码的帧具有可变的宽度和高度。我知道要在 Libavcodec 中编码帧,您需要将“宽度”和“高度”参数传递给 AvCodecContext 结构,然后将其初始化为:

AVCodec *codec = codec = avcodec_find_encoder(AV_CODEC_ID_H264);
AVCodecContext *context = avcodec_alloc_context3(encoder->codec);
context->width = 1920;
//OTHER SETTINGS HERE
//FINALLY...
avcodec_open2(context, codec, NULL);

假设在我初始化了这个上下文之后,我需要编码一个不同的帧,现在它的宽度为900。我不能简单地做context->width = 900,因为上下文已经设置为宽度1920 并初始化。我可以创建一个全新的 AvCodecContext 并使用avcodec_close() 删除前一个,如下所示:

AVCodec *codec = codec = avcodec_find_encoder(AV_CODEC_ID_H264);
AVCodecContext *context = avcodec_alloc_context3(encoder->codec);
context->width = 900;
//OTHER SETTINGS HERE
//FINALLY...
avcodec_open2(context, codec, NULL);

// DO THE ENCODING HERE

avcodec_close(context);

但是当我这样做时,我的程序意外崩溃了,我觉得每次我需要更改简单的宽度/高度设置时重新创建 AVCodecContext 开始效率低下。有人对我如何去做这件事有任何建议吗?非常感谢!

【问题讨论】:

    标签: ffmpeg libav


    【解决方案1】:

    这不是一回事。您必须重新初始化编码器,或将帧缩放/填充到相同大小

    【讨论】:

    • 谢谢!我是否在上面正确地重新初始化了编码器?或者,我将如何填充框架?
    • 创建过滤图。
    【解决方案2】:

    我遇到了同样的问题,我是这样解决的:

    首先我更改了codecContext的宽度和高度(它们应该是偶数):

    while (w%2 != 0) {
        w--;
    }
    while (h%2 != 0) {
        h--;
    }
    cctx->bit_rate = w*h*10;
    cctx->width = w;
    cctx->height = h;
    

    我用更改的 codecContext 初始化编解码器的秒数:

    codec->init(cctx);
    

    最后销毁并重新创建了 AVFrame(我找不到一种方法来重新初始化框架而无需重新创建并且简单地更改宽度和高度不起作用):

    if (videoFrame) {
    av_frame_free(&videoFrame);
    }
    
    if (!videoFrame) {
    videoFrame = av_frame_alloc();
    videoFrame->format = AV_PIX_FMT_YUV420P;
    videoFrame->width = cctx->width;
    videoFrame->height = cctx->height;
    
    if ((av_frame_get_buffer(videoFrame, 32)) < 0) {
        std::cout << "Failed to allocate picture" << std::endl;
        return;
    }
    

    }

    【讨论】:

      猜你喜欢
      • 2012-02-28
      • 1970-01-01
      • 1970-01-01
      • 2011-05-04
      • 2016-05-23
      • 2015-03-04
      • 2013-05-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多