使用libavfilter过滤video时出现大量内存泄漏

我有一个相对简单的FFMPEG C程序,video帧被馈送,通过滤波器图处理并发送到帧渲染器。

以下是一些代码段:

/* Filter graph here */ char args[512]; enum AVPixelFormat pix_fmts[] = {AV_PIX_FMT_RGB32 }; AVFilterGraph *filter_graph; avfilter_register_all(); AVFilter *buffersrc = avfilter_get_by_name("buffer"); AVFilter *buffersink = avfilter_get_by_name("ffbuffersink"); AVBufferSinkParams *buffersink_params; AVFilterInOut *outputs = avfilter_inout_alloc(); AVFilterInOut *inputs = avfilter_inout_alloc(); filter_graph = avfilter_graph_alloc(); snprintf(args, sizeof(args), "video_size=%dx%d:pix_fmt=%d:time_base=%d/%d:pixel_aspect=%d/%d", av->codec_ctx->width, av->codec_ctx->height, av->codec_ctx->pix_fmt, av->codec_ctx->time_base.num, av->codec_ctx->time_base.den, av->codec_ctx->sample_aspect_ratio.num, av->codec_ctx->sample_aspect_ratio.den); if(avfilter_graph_create_filter(&av->buffersrc_ctx, buffersrc, "in",args, NULL, filter_graph) pixel_fmts = pix_fmts; if(avfilter_graph_create_filter(&av->buffersink_ctx, buffersink, "out",NULL, buffersink_params, filter_graph) name = av_strdup("in"); outputs->filter_ctx = av->buffersrc_ctx; outputs->pad_idx = 0; outputs->next = NULL; inputs->name = av_strdup("out"); inputs->filter_ctx = av->buffersink_ctx; inputs->pad_idx = 0; inputs->next = NULL; const char *filter_descr = "vflip"; if (avfilter_graph_parse_ptr(filter_graph, filter_descr, &inputs, &outputs, NULL) < 0) { printf("Cannot parse filter graph\n"); return(0); } if (avfilter_graph_config(filter_graph, NULL) < 0) { printf("Cannot configure filter graph\n"); return(0); } av_free(buffersink_params); avfilter_inout_free(&inputs); avfilter_inout_free(&outputs); 

以上代码在其他地方调用:

 av->frame_in->pts = av_frame_get_best_effort_timestamp(av->frame_in); /* push the decoded frame into the filtergraph*/ if (av_buffersrc_add_frame(av->buffersrc_ctx, av->frame_in) buffersink_ctx, av->frame_out) < 0) { printf( "Error while sourcing the filtergraph\n"); break; } /* do stuff with frame */ 

现在,代码工作得很好,video以我期望的方式出现(垂直翻转用于测试目的)。

我遇到的最大问题是存在大量内存泄漏。 高分辨率video将在几秒钟内消耗2Gb并使程序崩溃。 我跟踪泄漏到这段代码:

 /* push the decoded frame into the filtergraph*/ if (av_buffersrc_add_frame(av->buffersrc_ctx, av->frame_in) < 0) 

如果我通过执行av->frame_out=av->frame_in;绕过filterav->frame_out=av->frame_in; 没有将框架推入其中(并且显然没有从框架中拉出),没有泄漏并且内存使用是稳定的。

现在,我对C很新,所以要温柔,但似乎我应该以某种方式清除buffersrc_ctx,但不知道如何。 我查看了官方文件但找不到任何东西。

有人可以提供建议吗?

发布后5分钟,看起来我所要做的就是每次处理后的非参考帧。

  av_frame_unref(av->frame_in); av_frame_unref(av->frame_out);