You need to enable JavaScript to run this app. FFmpeg中如何正确释放BitStreamFilter(bsf)避免double free错误
优惠活动
大模型
产品
解决方案
定价
更多

FFmpeg中如何正确释放BitStreamFilter(bsf)避免double free错误

FFmpeg BitStreamFilter 双重释放问题排查与修复

问题背景

基于FFmpeg C接口开发MP4处理类,为实现异常安全用std::unique_ptr封装自定义释放逻辑,在处理H.264 MP4转Annex-B的BitStreamFilter时触发Double Free错误,AddressSanitizer定位错误发生在FFmpeg C库内部,与C++语法无关。
官方文档要求av_bsf_alloc()分配的上下文必须用av_bsf_free()释放:

@param ctx 用于写入新分配上下文的指针,过滤流程完成后必须通过av_bsf_free()释放。
即使BSF上下文未做任何实际过滤操作,只要后续调用avformat_close_input()就会触发崩溃。

复现方式

可执行程序调用

./ffmpeg_demuxer_test mymovie.mp4

编译命令

$ /usr/bin/c++ -std=c++17 -DDEBUG -D_DEBUG -D_GLIBCXX_ASSERTIONS -g -O0 \
    -fsanitize=address -fsanitize=enum -fsanitize=unreachable \
    -o ffmpeg_demuxer_test ffmpeg_demuxer_test.cpp \
    -lavformat -lavcodec

复现代码

extern "C" {
#include    <libavformat/avformat.h>
#include    <libavformat/avio.h>
#include    <libavcodec/avcodec.h>
}
#include    <iostream>
#include    <memory>


void ffmpeg_demuxer_avformat_context_free(AVFormatContext * context)
{
    if(context != nullptr) avformat_close_input(&context);
}

void ffmpeg_demuxer_av_bsf_free(AVBSFContext * context)
{
    if(context != nullptr) av_bsf_free(&context);
}


int main(int argc, char * argv [])
{
    if(argc != 2)
    {
        std::cout << "Usage: " << argv[0] << " movie.mp4" << std::endl;
        exit(1);
    }

    // init the AV libraries
    //
    av_register_all();
    avformat_network_init();

    // allocate the AVFormatContext
    //
    AVFormatContext * format_context(nullptr);
    int const r1(avformat_open_input(
                  &format_context
                , argv[1]
                , nullptr           // input format
                , nullptr));        // options
    if(r1 != 0
    || format_context == nullptr)
    {
        throw std::bad_alloc();
    }

    auto f_format_context = std::unique_ptr<
              AVFormatContext
            , decltype(&ffmpeg_demuxer_avformat_context_free)>(
                      format_context
                    , &ffmpeg_demuxer_avformat_context_free);


    // now allocate a stream
    //
    if(avformat_find_stream_info(f_format_context.get(), nullptr) < 0)
    {
        throw std::runtime_error("ffmpeg: Could not find stream info");
    }

    auto f_video_stream_index = av_find_best_stream(
              f_format_context.get()
            , AVMEDIA_TYPE_VIDEO
            , -1            // wanted stream (any)
            , -1            // related stream (none)
            , nullptr       // AVCodec *
            , 0);           // flags
    if(f_video_stream_index < 0)
    {
        throw std::runtime_error("ffmpeg: Could not find stream in input file");
    }
    if(static_cast<unsigned int>(f_video_stream_index) >= f_format_context->nb_streams)
    {
        throw std::range_error("ffmpeg: Stream index out of range");
    }

    auto f_stream = f_format_context->streams[f_video_stream_index];

    auto f_video_codec = f_stream->codecpar->codec_id;

    int f_bit_depth(0);
    switch(f_stream->codecpar->format)
    {
    case AV_PIX_FMT_YUV420P10LE:
        f_bit_depth = 10;
        break;

    case AV_PIX_FMT_YUV420P12LE:
        f_bit_depth = 12;
        break;

    default:
        f_bit_depth = 8;
        break;

    }

    bool f_mp4_h264 = f_video_codec == AV_CODEC_ID_H264 && (
               strcmp(f_format_context->iformat->long_name, "QuickTime / MOV") == 0
            || strcmp(f_format_context->iformat->long_name, "FLV (Flash Video)") == 0
            || strcmp(f_format_context->iformat->long_name, "Matroska / WebM") == 0
        );

    if(f_mp4_h264)
    {
        AVBitStreamFilter const * bsf_stream_filter(av_bsf_get_by_name("h264_mp4toannexb"));
        if(bsf_stream_filter == nullptr)
        {
            throw std::runtime_error("av_bsf_get_by_name(\"h264_mp4toannexb\") failed");
        }
        AVBSFContext * bsf_context(nullptr);
        int const r2(av_bsf_alloc(bsf_stream_filter, &bsf_context));
        if(r2 < 0
        || bsf_context == nullptr)
        {
            throw std::bad_alloc();
        }
        auto f_bsf_context = std::unique_ptr<
                  AVBSFContext
                , decltype(&ffmpeg_demuxer_av_bsf_free)>(
                          bsf_context
                        , &ffmpeg_demuxer_av_bsf_free);
        f_bsf_context->par_in = f_stream->codecpar;
        if(av_bsf_init(f_bsf_context.get()) < 0)
        {
            throw std::runtime_error("av_bsf_init() failed");
        }
    }

    return 0;
}

问题根因

错误出在f_bsf_context->par_in = f_stream->codecpar;这行代码的所有权规则违反:

  • f_stream->codecpar是AVFormatContext的内部资源,所有权归AVFormatContext所有,会在avformat_close_input()调用时被统一释放。
  • FFmpeg内部av_bsf_free()实现会主动调用avcodec_parameters_free()释放par_in指向的内存,即par_in的所有权归AVBSFContext所有。
    结合std::unique_ptr的销毁顺序:
  • f_bsf_context在if(f_mp4_h264)代码块结束时就会被销毁,先调用av_bsf_free()释放了f_stream->codecpar指向的内存。
  • f_format_context在main函数返回时才销毁,调用avformat_close_input()时又重复释放同一块codecpar内存,触发Double Free。

修复方案

不能直接赋值par_in的指针,必须先为BSF上下文分配独立的AVCodecParameters内存,再复制流参数的内容:
将原代码中赋值par_in的部分修改为:

// 为BSF分配独立的输入参数内存,所有权归BSF所有
f_bsf_context->par_in = avcodec_parameters_alloc();
if (!f_bsf_context->par_in) {
    throw std::bad_alloc();
}
// 复制流参数到BSF的独立内存中,不引用AVFormatContext的内部资源
avcodec_parameters_copy(f_bsf_context->par_in, f_stream->codecpar);

额外注意:

  • 如果需要提前终止BSF的生命周期,要确保av_bsf_free()在avformat_close_input()之前调用,避免反向释放顺序引发其他未定义行为。
  • 所有FFmpeg中标记为需要释放的结构体字段,都需要明确所有权归属,不能跨上下文直接共享指针。

内容的提问来源于stack exchange,提问作者Alexis Wilke

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.11.08 02:45:02