avfilter/can_merge_formats: fix memleak
[ffmpeg.git] / libavfilter / avfiltergraph.c
1 /*
2  * filter graphs
3  * Copyright (c) 2008 Vitor Sessak
4  * Copyright (c) 2007 Bobby Bingham
5  *
6  * This file is part of FFmpeg.
7  *
8  * FFmpeg is free software; you can redistribute it and/or
9  * modify it under the terms of the GNU Lesser General Public
10  * License as published by the Free Software Foundation; either
11  * version 2.1 of the License, or (at your option) any later version.
12  *
13  * FFmpeg is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
16  * Lesser General Public License for more details.
17  *
18  * You should have received a copy of the GNU Lesser General Public
19  * License along with FFmpeg; if not, write to the Free Software
20  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
21  */
22
23 #include "config.h"
24
25 #include <string.h>
26
27 #include "libavutil/avassert.h"
28 #include "libavutil/avstring.h"
29 #include "libavutil/bprint.h"
30 #include "libavutil/channel_layout.h"
31 #include "libavutil/opt.h"
32 #include "libavutil/pixdesc.h"
33 #include "libavcodec/avcodec.h" // avcodec_find_best_pix_fmt_of_2()
34
35 #include "avfilter.h"
36 #include "formats.h"
37 #include "internal.h"
38 #include "thread.h"
39
40 #define OFFSET(x) offsetof(AVFilterGraph, x)
41 #define FLAGS AV_OPT_FLAG_VIDEO_PARAM|AV_OPT_FLAG_FILTERING_PARAM
42 static const AVOption filtergraph_options[] = {
43     { "thread_type", "Allowed thread types", OFFSET(thread_type), AV_OPT_TYPE_FLAGS,
44         { .i64 = AVFILTER_THREAD_SLICE }, 0, INT_MAX, FLAGS, "thread_type" },
45         { "slice", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = AVFILTER_THREAD_SLICE }, .flags = FLAGS, .unit = "thread_type" },
46     { "threads",     "Maximum number of threads", OFFSET(nb_threads),
47         AV_OPT_TYPE_INT,   { .i64 = 0 }, 0, INT_MAX, FLAGS },
48     {"scale_sws_opts"       , "default scale filter options"        , OFFSET(scale_sws_opts)        ,
49         AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, FLAGS },
50     {"aresample_swr_opts"   , "default aresample filter options"    , OFFSET(aresample_swr_opts)    ,
51         AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, FLAGS },
52     { NULL },
53 };
54
55 static const AVClass filtergraph_class = {
56     .class_name = "AVFilterGraph",
57     .item_name  = av_default_item_name,
58     .version    = LIBAVUTIL_VERSION_INT,
59     .option     = filtergraph_options,
60     .category   = AV_CLASS_CATEGORY_FILTER,
61 };
62
63 #if !HAVE_THREADS
64 void ff_graph_thread_free(AVFilterGraph *graph)
65 {
66 }
67
68 int ff_graph_thread_init(AVFilterGraph *graph)
69 {
70     graph->thread_type = 0;
71     graph->nb_threads  = 1;
72     return 0;
73 }
74 #endif
75
76 AVFilterGraph *avfilter_graph_alloc(void)
77 {
78     AVFilterGraph *ret = av_mallocz(sizeof(*ret));
79     if (!ret)
80         return NULL;
81
82     ret->internal = av_mallocz(sizeof(*ret->internal));
83     if (!ret->internal) {
84         av_freep(&ret);
85         return NULL;
86     }
87
88     ret->av_class = &filtergraph_class;
89     av_opt_set_defaults(ret);
90
91     return ret;
92 }
93
94 void ff_filter_graph_remove_filter(AVFilterGraph *graph, AVFilterContext *filter)
95 {
96     int i;
97     for (i = 0; i < graph->nb_filters; i++) {
98         if (graph->filters[i] == filter) {
99             FFSWAP(AVFilterContext*, graph->filters[i],
100                    graph->filters[graph->nb_filters - 1]);
101             graph->nb_filters--;
102             return;
103         }
104     }
105 }
106
107 void avfilter_graph_free(AVFilterGraph **graph)
108 {
109     if (!*graph)
110         return;
111
112     while ((*graph)->nb_filters)
113         avfilter_free((*graph)->filters[0]);
114
115     ff_graph_thread_free(*graph);
116
117     av_freep(&(*graph)->sink_links);
118
119     av_freep(&(*graph)->scale_sws_opts);
120     av_freep(&(*graph)->aresample_swr_opts);
121     av_freep(&(*graph)->resample_lavr_opts);
122     av_freep(&(*graph)->filters);
123     av_freep(&(*graph)->internal);
124     av_freep(graph);
125 }
126
127 #if FF_API_AVFILTER_OPEN
128 int avfilter_graph_add_filter(AVFilterGraph *graph, AVFilterContext *filter)
129 {
130     AVFilterContext **filters = av_realloc(graph->filters,
131                                            sizeof(*filters) * (graph->nb_filters + 1));
132     if (!filters)
133         return AVERROR(ENOMEM);
134
135     graph->filters = filters;
136     graph->filters[graph->nb_filters++] = filter;
137
138 #if FF_API_FOO_COUNT
139     graph->filter_count_unused = graph->nb_filters;
140 #endif
141
142     filter->graph = graph;
143
144     return 0;
145 }
146 #endif
147
148 int avfilter_graph_create_filter(AVFilterContext **filt_ctx, AVFilter *filt,
149                                  const char *name, const char *args, void *opaque,
150                                  AVFilterGraph *graph_ctx)
151 {
152     int ret;
153
154     *filt_ctx = avfilter_graph_alloc_filter(graph_ctx, filt, name);
155     if (!*filt_ctx)
156         return AVERROR(ENOMEM);
157
158     ret = avfilter_init_str(*filt_ctx, args);
159     if (ret < 0)
160         goto fail;
161
162     return 0;
163
164 fail:
165     if (*filt_ctx)
166         avfilter_free(*filt_ctx);
167     *filt_ctx = NULL;
168     return ret;
169 }
170
171 void avfilter_graph_set_auto_convert(AVFilterGraph *graph, unsigned flags)
172 {
173     graph->disable_auto_convert = flags;
174 }
175
176 AVFilterContext *avfilter_graph_alloc_filter(AVFilterGraph *graph,
177                                              const AVFilter *filter,
178                                              const char *name)
179 {
180     AVFilterContext **filters, *s;
181
182     if (graph->thread_type && !graph->internal->thread) {
183         int ret = ff_graph_thread_init(graph);
184         if (ret < 0) {
185             av_log(graph, AV_LOG_ERROR, "Error initializing threading.\n");
186             return NULL;
187         }
188     }
189
190     s = ff_filter_alloc(filter, name);
191     if (!s)
192         return NULL;
193
194     filters = av_realloc(graph->filters, sizeof(*filters) * (graph->nb_filters + 1));
195     if (!filters) {
196         avfilter_free(s);
197         return NULL;
198     }
199
200     graph->filters = filters;
201     graph->filters[graph->nb_filters++] = s;
202
203 #if FF_API_FOO_COUNT
204     graph->filter_count_unused = graph->nb_filters;
205 #endif
206
207     s->graph = graph;
208
209     return s;
210 }
211
212 /**
213  * Check for the validity of graph.
214  *
215  * A graph is considered valid if all its input and output pads are
216  * connected.
217  *
218  * @return 0 in case of success, a negative value otherwise
219  */
220 static int graph_check_validity(AVFilterGraph *graph, AVClass *log_ctx)
221 {
222     AVFilterContext *filt;
223     int i, j;
224
225     for (i = 0; i < graph->nb_filters; i++) {
226         const AVFilterPad *pad;
227         filt = graph->filters[i];
228
229         for (j = 0; j < filt->nb_inputs; j++) {
230             if (!filt->inputs[j] || !filt->inputs[j]->src) {
231                 pad = &filt->input_pads[j];
232                 av_log(log_ctx, AV_LOG_ERROR,
233                        "Input pad \"%s\" with type %s of the filter instance \"%s\" of %s not connected to any source\n",
234                        pad->name, av_get_media_type_string(pad->type), filt->name, filt->filter->name);
235                 return AVERROR(EINVAL);
236             }
237         }
238
239         for (j = 0; j < filt->nb_outputs; j++) {
240             if (!filt->outputs[j] || !filt->outputs[j]->dst) {
241                 pad = &filt->output_pads[j];
242                 av_log(log_ctx, AV_LOG_ERROR,
243                        "Output pad \"%s\" with type %s of the filter instance \"%s\" of %s not connected to any destination\n",
244                        pad->name, av_get_media_type_string(pad->type), filt->name, filt->filter->name);
245                 return AVERROR(EINVAL);
246             }
247         }
248     }
249
250     return 0;
251 }
252
253 /**
254  * Configure all the links of graphctx.
255  *
256  * @return 0 in case of success, a negative value otherwise
257  */
258 static int graph_config_links(AVFilterGraph *graph, AVClass *log_ctx)
259 {
260     AVFilterContext *filt;
261     int i, ret;
262
263     for (i = 0; i < graph->nb_filters; i++) {
264         filt = graph->filters[i];
265
266         if (!filt->nb_outputs) {
267             if ((ret = avfilter_config_links(filt)))
268                 return ret;
269         }
270     }
271
272     return 0;
273 }
274
275 AVFilterContext *avfilter_graph_get_filter(AVFilterGraph *graph, char *name)
276 {
277     int i;
278
279     for (i = 0; i < graph->nb_filters; i++)
280         if (graph->filters[i]->name && !strcmp(name, graph->filters[i]->name))
281             return graph->filters[i];
282
283     return NULL;
284 }
285
286 static void sanitize_channel_layouts(void *log, AVFilterChannelLayouts *l)
287 {
288     if (!l)
289         return;
290     if (l->nb_channel_layouts) {
291         if (l->all_layouts || l->all_counts)
292             av_log(log, AV_LOG_WARNING, "All layouts set on non-empty list\n");
293         l->all_layouts = l->all_counts = 0;
294     } else {
295         if (l->all_counts && !l->all_layouts)
296             av_log(log, AV_LOG_WARNING, "All counts without all layouts\n");
297         l->all_layouts = 1;
298     }
299 }
300
301 static int filter_query_formats(AVFilterContext *ctx)
302 {
303     int ret, i;
304     AVFilterFormats *formats;
305     AVFilterChannelLayouts *chlayouts;
306     AVFilterFormats *samplerates;
307     enum AVMediaType type = ctx->inputs  && ctx->inputs [0] ? ctx->inputs [0]->type :
308                             ctx->outputs && ctx->outputs[0] ? ctx->outputs[0]->type :
309                             AVMEDIA_TYPE_VIDEO;
310
311     if ((ret = ctx->filter->query_formats(ctx)) < 0) {
312         if (ret != AVERROR(EAGAIN))
313             av_log(ctx, AV_LOG_ERROR, "Query format failed for '%s': %s\n",
314                    ctx->name, av_err2str(ret));
315         return ret;
316     }
317
318     for (i = 0; i < ctx->nb_inputs; i++)
319         sanitize_channel_layouts(ctx, ctx->inputs[i]->out_channel_layouts);
320     for (i = 0; i < ctx->nb_outputs; i++)
321         sanitize_channel_layouts(ctx, ctx->outputs[i]->in_channel_layouts);
322
323     formats = ff_all_formats(type);
324     if (!formats)
325         return AVERROR(ENOMEM);
326     ff_set_common_formats(ctx, formats);
327     if (type == AVMEDIA_TYPE_AUDIO) {
328         samplerates = ff_all_samplerates();
329         if (!samplerates)
330             return AVERROR(ENOMEM);
331         ff_set_common_samplerates(ctx, samplerates);
332         chlayouts = ff_all_channel_layouts();
333         if (!chlayouts)
334             return AVERROR(ENOMEM);
335         ff_set_common_channel_layouts(ctx, chlayouts);
336     }
337     return 0;
338 }
339
340 static int formats_declared(AVFilterContext *f)
341 {
342     int i;
343
344     for (i = 0; i < f->nb_inputs; i++) {
345         if (!f->inputs[i]->out_formats)
346             return 0;
347         if (f->inputs[i]->type == AVMEDIA_TYPE_AUDIO &&
348             !(f->inputs[i]->out_samplerates &&
349               f->inputs[i]->out_channel_layouts))
350             return 0;
351     }
352     for (i = 0; i < f->nb_outputs; i++) {
353         if (!f->outputs[i]->in_formats)
354             return 0;
355         if (f->outputs[i]->type == AVMEDIA_TYPE_AUDIO &&
356             !(f->outputs[i]->in_samplerates &&
357               f->outputs[i]->in_channel_layouts))
358             return 0;
359     }
360     return 1;
361 }
362
363 static AVFilterFormats *clone_filter_formats(AVFilterFormats *arg)
364 {
365     AVFilterFormats *a = av_memdup(arg, sizeof(*arg));
366     if (a) {
367         a->refcount = 0;
368         a->refs     = NULL;
369         a->formats  = av_memdup(a->formats, sizeof(*a->formats) * a->nb_formats);
370         if (!a->formats && arg->formats)
371             av_freep(&a);
372     }
373     return a;
374 }
375
376 static int can_merge_formats(AVFilterFormats *a_arg,
377                              AVFilterFormats *b_arg,
378                              enum AVMediaType type,
379                              int is_sample_rate)
380 {
381     AVFilterFormats *a, *b, *ret;
382     if (a_arg == b_arg)
383         return 1;
384     a = clone_filter_formats(a_arg);
385     b = clone_filter_formats(b_arg);
386     if (is_sample_rate) {
387         ret = ff_merge_samplerates(a, b);
388     } else {
389         ret = ff_merge_formats(a, b, type);
390     }
391     if (ret) {
392         av_freep(&ret->formats);
393         av_freep(&ret->refs);
394         av_freep(&ret);
395         return 1;
396     } else {
397         av_freep(&a->formats);
398         av_freep(&b->formats);
399         av_freep(&a);
400         av_freep(&b);
401         return 0;
402     }
403 }
404
405 /**
406  * Perform one round of query_formats() and merging formats lists on the
407  * filter graph.
408  * @return  >=0 if all links formats lists could be queried and merged;
409  *          AVERROR(EAGAIN) some progress was made in the queries or merging
410  *          and a later call may succeed;
411  *          AVERROR(EIO) (may be changed) plus a log message if no progress
412  *          was made and the negotiation is stuck;
413  *          a negative error code if some other error happened
414  */
415 static int query_formats(AVFilterGraph *graph, AVClass *log_ctx)
416 {
417     int i, j, ret;
418     int scaler_count = 0, resampler_count = 0;
419     int count_queried = 0;        /* successful calls to query_formats() */
420     int count_merged = 0;         /* successful merge of formats lists */
421     int count_already_merged = 0; /* lists already merged */
422     int count_delayed = 0;        /* lists that need to be merged later */
423
424     for (i = 0; i < graph->nb_filters; i++) {
425         AVFilterContext *f = graph->filters[i];
426         if (formats_declared(f))
427             continue;
428         if (f->filter->query_formats)
429             ret = filter_query_formats(f);
430         else
431             ret = ff_default_query_formats(f);
432         if (ret < 0 && ret != AVERROR(EAGAIN))
433             return ret;
434         /* note: EAGAIN could indicate a partial success, not counted yet */
435         count_queried += ret >= 0;
436     }
437
438     /* go through and merge as many format lists as possible */
439     for (i = 0; i < graph->nb_filters; i++) {
440         AVFilterContext *filter = graph->filters[i];
441
442         for (j = 0; j < filter->nb_inputs; j++) {
443             AVFilterLink *link = filter->inputs[j];
444             int convert_needed = 0;
445
446             if (!link)
447                 continue;
448
449             if (link->in_formats != link->out_formats
450                 && link->in_formats && link->out_formats)
451                 if (!can_merge_formats(link->in_formats, link->out_formats,
452                                       link->type, 0))
453                     convert_needed = 1;
454             if (link->type == AVMEDIA_TYPE_AUDIO) {
455                 if (link->in_samplerates != link->out_samplerates
456                     && link->in_samplerates && link->out_samplerates)
457                     if (!can_merge_formats(link->in_samplerates,
458                                            link->out_samplerates,
459                                            0, 1))
460                         convert_needed = 1;
461             }
462
463 #define MERGE_DISPATCH(field, statement)                                     \
464             if (!(link->in_ ## field && link->out_ ## field)) {              \
465                 count_delayed++;                                             \
466             } else if (link->in_ ## field == link->out_ ## field) {          \
467                 count_already_merged++;                                      \
468             } else if (!convert_needed) {                                    \
469                 count_merged++;                                              \
470                 statement                                                    \
471             }
472
473             if (link->type == AVMEDIA_TYPE_AUDIO) {
474                 MERGE_DISPATCH(channel_layouts,
475                     if (!ff_merge_channel_layouts(link->in_channel_layouts,
476                                                   link->out_channel_layouts))
477                         convert_needed = 1;
478                 )
479                 MERGE_DISPATCH(samplerates,
480                     if (!ff_merge_samplerates(link->in_samplerates,
481                                               link->out_samplerates))
482                         convert_needed = 1;
483                 )
484             }
485             MERGE_DISPATCH(formats,
486                 if (!ff_merge_formats(link->in_formats, link->out_formats,
487                                       link->type))
488                     convert_needed = 1;
489             )
490 #undef MERGE_DISPATCH
491
492             if (convert_needed) {
493                 AVFilterContext *convert;
494                 AVFilter *filter;
495                 AVFilterLink *inlink, *outlink;
496                 char scale_args[256];
497                 char inst_name[30];
498
499                 /* couldn't merge format lists. auto-insert conversion filter */
500                 switch (link->type) {
501                 case AVMEDIA_TYPE_VIDEO:
502                     if (!(filter = avfilter_get_by_name("scale"))) {
503                         av_log(log_ctx, AV_LOG_ERROR, "'scale' filter "
504                                "not present, cannot convert pixel formats.\n");
505                         return AVERROR(EINVAL);
506                     }
507
508                     snprintf(inst_name, sizeof(inst_name), "auto-inserted scaler %d",
509                              scaler_count++);
510
511                     if ((ret = avfilter_graph_create_filter(&convert, filter,
512                                                             inst_name, graph->scale_sws_opts, NULL,
513                                                             graph)) < 0)
514                         return ret;
515                     break;
516                 case AVMEDIA_TYPE_AUDIO:
517                     if (!(filter = avfilter_get_by_name("aresample"))) {
518                         av_log(log_ctx, AV_LOG_ERROR, "'aresample' filter "
519                                "not present, cannot convert audio formats.\n");
520                         return AVERROR(EINVAL);
521                     }
522
523                     snprintf(inst_name, sizeof(inst_name), "auto-inserted resampler %d",
524                              resampler_count++);
525                     scale_args[0] = '\0';
526                     if (graph->aresample_swr_opts)
527                         snprintf(scale_args, sizeof(scale_args), "%s",
528                                  graph->aresample_swr_opts);
529                     if ((ret = avfilter_graph_create_filter(&convert, filter,
530                                                             inst_name, graph->aresample_swr_opts,
531                                                             NULL, graph)) < 0)
532                         return ret;
533                     break;
534                 default:
535                     return AVERROR(EINVAL);
536                 }
537
538                 if ((ret = avfilter_insert_filter(link, convert, 0, 0)) < 0)
539                     return ret;
540
541                 filter_query_formats(convert);
542                 inlink  = convert->inputs[0];
543                 outlink = convert->outputs[0];
544                 if (!ff_merge_formats( inlink->in_formats,  inlink->out_formats,  inlink->type) ||
545                     !ff_merge_formats(outlink->in_formats, outlink->out_formats, outlink->type))
546                     ret |= AVERROR(ENOSYS);
547                 if (inlink->type == AVMEDIA_TYPE_AUDIO &&
548                     (!ff_merge_samplerates(inlink->in_samplerates,
549                                            inlink->out_samplerates) ||
550                      !ff_merge_channel_layouts(inlink->in_channel_layouts,
551                                                inlink->out_channel_layouts)))
552                     ret |= AVERROR(ENOSYS);
553                 if (outlink->type == AVMEDIA_TYPE_AUDIO &&
554                     (!ff_merge_samplerates(outlink->in_samplerates,
555                                            outlink->out_samplerates) ||
556                      !ff_merge_channel_layouts(outlink->in_channel_layouts,
557                                                outlink->out_channel_layouts)))
558                     ret |= AVERROR(ENOSYS);
559
560                 if (ret < 0) {
561                     av_log(log_ctx, AV_LOG_ERROR,
562                            "Impossible to convert between the formats supported by the filter "
563                            "'%s' and the filter '%s'\n", link->src->name, link->dst->name);
564                     return ret;
565                 }
566             }
567         }
568     }
569
570     av_log(graph, AV_LOG_DEBUG, "query_formats: "
571            "%d queried, %d merged, %d already done, %d delayed\n",
572            count_queried, count_merged, count_already_merged, count_delayed);
573     if (count_delayed) {
574         AVBPrint bp;
575
576         /* if count_queried > 0, one filter at least did set its formats,
577            that will give additional information to its neighbour;
578            if count_merged > 0, one pair of formats lists at least was merged,
579            that will give additional information to all connected filters;
580            in both cases, progress was made and a new round must be done */
581         if (count_queried || count_merged)
582             return AVERROR(EAGAIN);
583         av_bprint_init(&bp, 0, AV_BPRINT_SIZE_AUTOMATIC);
584         for (i = 0; i < graph->nb_filters; i++)
585             if (!formats_declared(graph->filters[i]))
586                 av_bprintf(&bp, "%s%s", bp.len ? ", " : "",
587                           graph->filters[i]->name);
588         av_log(graph, AV_LOG_ERROR,
589                "The following filters could not choose their formats: %s\n"
590                "Consider inserting the (a)format filter near their input or "
591                "output.\n", bp.str);
592         return AVERROR(EIO);
593     }
594     return 0;
595 }
596
597 static int pick_format(AVFilterLink *link, AVFilterLink *ref)
598 {
599     if (!link || !link->in_formats)
600         return 0;
601
602     if (link->type == AVMEDIA_TYPE_VIDEO) {
603         if(ref && ref->type == AVMEDIA_TYPE_VIDEO){
604             int has_alpha= av_pix_fmt_desc_get(ref->format)->nb_components % 2 == 0;
605             enum AVPixelFormat best= AV_PIX_FMT_NONE;
606             int i;
607             for (i=0; i<link->in_formats->nb_formats; i++) {
608                 enum AVPixelFormat p = link->in_formats->formats[i];
609                 best= avcodec_find_best_pix_fmt_of_2(best, p, ref->format, has_alpha, NULL);
610             }
611             av_log(link->src,AV_LOG_DEBUG, "picking %s out of %d ref:%s alpha:%d\n",
612                    av_get_pix_fmt_name(best), link->in_formats->nb_formats,
613                    av_get_pix_fmt_name(ref->format), has_alpha);
614             link->in_formats->formats[0] = best;
615         }
616     }
617
618     link->in_formats->nb_formats = 1;
619     link->format = link->in_formats->formats[0];
620
621     if (link->type == AVMEDIA_TYPE_AUDIO) {
622         if (!link->in_samplerates->nb_formats) {
623             av_log(link->src, AV_LOG_ERROR, "Cannot select sample rate for"
624                    " the link between filters %s and %s.\n", link->src->name,
625                    link->dst->name);
626             return AVERROR(EINVAL);
627         }
628         link->in_samplerates->nb_formats = 1;
629         link->sample_rate = link->in_samplerates->formats[0];
630
631         if (link->in_channel_layouts->all_layouts) {
632             av_log(link->src, AV_LOG_ERROR, "Cannot select channel layout for"
633                    " the link between filters %s and %s.\n", link->src->name,
634                    link->dst->name);
635             return AVERROR(EINVAL);
636         }
637         link->in_channel_layouts->nb_channel_layouts = 1;
638         link->channel_layout = link->in_channel_layouts->channel_layouts[0];
639         if ((link->channels = FF_LAYOUT2COUNT(link->channel_layout)))
640             link->channel_layout = 0;
641         else
642             link->channels = av_get_channel_layout_nb_channels(link->channel_layout);
643     }
644
645     ff_formats_unref(&link->in_formats);
646     ff_formats_unref(&link->out_formats);
647     ff_formats_unref(&link->in_samplerates);
648     ff_formats_unref(&link->out_samplerates);
649     ff_channel_layouts_unref(&link->in_channel_layouts);
650     ff_channel_layouts_unref(&link->out_channel_layouts);
651
652     return 0;
653 }
654
655 #define REDUCE_FORMATS(fmt_type, list_type, list, var, nb, add_format) \
656 do {                                                                   \
657     for (i = 0; i < filter->nb_inputs; i++) {                          \
658         AVFilterLink *link = filter->inputs[i];                        \
659         fmt_type fmt;                                                  \
660                                                                        \
661         if (!link->out_ ## list || link->out_ ## list->nb != 1)        \
662             continue;                                                  \
663         fmt = link->out_ ## list->var[0];                              \
664                                                                        \
665         for (j = 0; j < filter->nb_outputs; j++) {                     \
666             AVFilterLink *out_link = filter->outputs[j];               \
667             list_type *fmts;                                           \
668                                                                        \
669             if (link->type != out_link->type ||                        \
670                 out_link->in_ ## list->nb == 1)                        \
671                 continue;                                              \
672             fmts = out_link->in_ ## list;                              \
673                                                                        \
674             if (!out_link->in_ ## list->nb) {                          \
675                 add_format(&out_link->in_ ##list, fmt);                \
676                 ret = 1;                                               \
677                 break;                                                 \
678             }                                                          \
679                                                                        \
680             for (k = 0; k < out_link->in_ ## list->nb; k++)            \
681                 if (fmts->var[k] == fmt) {                             \
682                     fmts->var[0]  = fmt;                               \
683                     fmts->nb = 1;                                      \
684                     ret = 1;                                           \
685                     break;                                             \
686                 }                                                      \
687         }                                                              \
688     }                                                                  \
689 } while (0)
690
691 static int reduce_formats_on_filter(AVFilterContext *filter)
692 {
693     int i, j, k, ret = 0;
694
695     REDUCE_FORMATS(int,      AVFilterFormats,        formats,         formats,
696                    nb_formats, ff_add_format);
697     REDUCE_FORMATS(int,      AVFilterFormats,        samplerates,     formats,
698                    nb_formats, ff_add_format);
699
700     /* reduce channel layouts */
701     for (i = 0; i < filter->nb_inputs; i++) {
702         AVFilterLink *inlink = filter->inputs[i];
703         uint64_t fmt;
704
705         if (!inlink->out_channel_layouts ||
706             inlink->out_channel_layouts->nb_channel_layouts != 1)
707             continue;
708         fmt = inlink->out_channel_layouts->channel_layouts[0];
709
710         for (j = 0; j < filter->nb_outputs; j++) {
711             AVFilterLink *outlink = filter->outputs[j];
712             AVFilterChannelLayouts *fmts;
713
714             fmts = outlink->in_channel_layouts;
715             if (inlink->type != outlink->type || fmts->nb_channel_layouts == 1)
716                 continue;
717
718             if (fmts->all_layouts) {
719                 /* Turn the infinite list into a singleton */
720                 fmts->all_layouts = fmts->all_counts  = 0;
721                 ff_add_channel_layout(&outlink->in_channel_layouts, fmt);
722                 break;
723             }
724
725             for (k = 0; k < outlink->in_channel_layouts->nb_channel_layouts; k++) {
726                 if (fmts->channel_layouts[k] == fmt) {
727                     fmts->channel_layouts[0]  = fmt;
728                     fmts->nb_channel_layouts = 1;
729                     ret = 1;
730                     break;
731                 }
732             }
733         }
734     }
735
736     return ret;
737 }
738
739 static void reduce_formats(AVFilterGraph *graph)
740 {
741     int i, reduced;
742
743     do {
744         reduced = 0;
745
746         for (i = 0; i < graph->nb_filters; i++)
747             reduced |= reduce_formats_on_filter(graph->filters[i]);
748     } while (reduced);
749 }
750
751 static void swap_samplerates_on_filter(AVFilterContext *filter)
752 {
753     AVFilterLink *link = NULL;
754     int sample_rate;
755     int i, j;
756
757     for (i = 0; i < filter->nb_inputs; i++) {
758         link = filter->inputs[i];
759
760         if (link->type == AVMEDIA_TYPE_AUDIO &&
761             link->out_samplerates->nb_formats== 1)
762             break;
763     }
764     if (i == filter->nb_inputs)
765         return;
766
767     sample_rate = link->out_samplerates->formats[0];
768
769     for (i = 0; i < filter->nb_outputs; i++) {
770         AVFilterLink *outlink = filter->outputs[i];
771         int best_idx, best_diff = INT_MAX;
772
773         if (outlink->type != AVMEDIA_TYPE_AUDIO ||
774             outlink->in_samplerates->nb_formats < 2)
775             continue;
776
777         for (j = 0; j < outlink->in_samplerates->nb_formats; j++) {
778             int diff = abs(sample_rate - outlink->in_samplerates->formats[j]);
779
780             if (diff < best_diff) {
781                 best_diff = diff;
782                 best_idx  = j;
783             }
784         }
785         FFSWAP(int, outlink->in_samplerates->formats[0],
786                outlink->in_samplerates->formats[best_idx]);
787     }
788 }
789
790 static void swap_samplerates(AVFilterGraph *graph)
791 {
792     int i;
793
794     for (i = 0; i < graph->nb_filters; i++)
795         swap_samplerates_on_filter(graph->filters[i]);
796 }
797
798 #define CH_CENTER_PAIR (AV_CH_FRONT_LEFT_OF_CENTER | AV_CH_FRONT_RIGHT_OF_CENTER)
799 #define CH_FRONT_PAIR  (AV_CH_FRONT_LEFT           | AV_CH_FRONT_RIGHT)
800 #define CH_STEREO_PAIR (AV_CH_STEREO_LEFT          | AV_CH_STEREO_RIGHT)
801 #define CH_WIDE_PAIR   (AV_CH_WIDE_LEFT            | AV_CH_WIDE_RIGHT)
802 #define CH_SIDE_PAIR   (AV_CH_SIDE_LEFT            | AV_CH_SIDE_RIGHT)
803 #define CH_DIRECT_PAIR (AV_CH_SURROUND_DIRECT_LEFT | AV_CH_SURROUND_DIRECT_RIGHT)
804 #define CH_BACK_PAIR   (AV_CH_BACK_LEFT            | AV_CH_BACK_RIGHT)
805
806 /* allowable substitutions for channel pairs when comparing layouts,
807  * ordered by priority for both values */
808 static const uint64_t ch_subst[][2] = {
809     { CH_FRONT_PAIR,      CH_CENTER_PAIR     },
810     { CH_FRONT_PAIR,      CH_WIDE_PAIR       },
811     { CH_FRONT_PAIR,      AV_CH_FRONT_CENTER },
812     { CH_CENTER_PAIR,     CH_FRONT_PAIR      },
813     { CH_CENTER_PAIR,     CH_WIDE_PAIR       },
814     { CH_CENTER_PAIR,     AV_CH_FRONT_CENTER },
815     { CH_WIDE_PAIR,       CH_FRONT_PAIR      },
816     { CH_WIDE_PAIR,       CH_CENTER_PAIR     },
817     { CH_WIDE_PAIR,       AV_CH_FRONT_CENTER },
818     { AV_CH_FRONT_CENTER, CH_FRONT_PAIR      },
819     { AV_CH_FRONT_CENTER, CH_CENTER_PAIR     },
820     { AV_CH_FRONT_CENTER, CH_WIDE_PAIR       },
821     { CH_SIDE_PAIR,       CH_DIRECT_PAIR     },
822     { CH_SIDE_PAIR,       CH_BACK_PAIR       },
823     { CH_SIDE_PAIR,       AV_CH_BACK_CENTER  },
824     { CH_BACK_PAIR,       CH_DIRECT_PAIR     },
825     { CH_BACK_PAIR,       CH_SIDE_PAIR       },
826     { CH_BACK_PAIR,       AV_CH_BACK_CENTER  },
827     { AV_CH_BACK_CENTER,  CH_BACK_PAIR       },
828     { AV_CH_BACK_CENTER,  CH_DIRECT_PAIR     },
829     { AV_CH_BACK_CENTER,  CH_SIDE_PAIR       },
830 };
831
832 static void swap_channel_layouts_on_filter(AVFilterContext *filter)
833 {
834     AVFilterLink *link = NULL;
835     int i, j, k;
836
837     for (i = 0; i < filter->nb_inputs; i++) {
838         link = filter->inputs[i];
839
840         if (link->type == AVMEDIA_TYPE_AUDIO &&
841             link->out_channel_layouts->nb_channel_layouts == 1)
842             break;
843     }
844     if (i == filter->nb_inputs)
845         return;
846
847     for (i = 0; i < filter->nb_outputs; i++) {
848         AVFilterLink *outlink = filter->outputs[i];
849         int best_idx = -1, best_score = INT_MIN, best_count_diff = INT_MAX;
850
851         if (outlink->type != AVMEDIA_TYPE_AUDIO ||
852             outlink->in_channel_layouts->nb_channel_layouts < 2)
853             continue;
854
855         for (j = 0; j < outlink->in_channel_layouts->nb_channel_layouts; j++) {
856             uint64_t  in_chlayout = link->out_channel_layouts->channel_layouts[0];
857             uint64_t out_chlayout = outlink->in_channel_layouts->channel_layouts[j];
858             int  in_channels      = av_get_channel_layout_nb_channels(in_chlayout);
859             int out_channels      = av_get_channel_layout_nb_channels(out_chlayout);
860             int count_diff        = out_channels - in_channels;
861             int matched_channels, extra_channels;
862             int score = 100000;
863
864             if (FF_LAYOUT2COUNT(in_chlayout) || FF_LAYOUT2COUNT(out_chlayout)) {
865                 /* Compute score in case the input or output layout encodes
866                    a channel count; in this case the score is not altered by
867                    the computation afterwards, as in_chlayout and
868                    out_chlayout have both been set to 0 */
869                 if (FF_LAYOUT2COUNT(in_chlayout))
870                     in_channels = FF_LAYOUT2COUNT(in_chlayout);
871                 if (FF_LAYOUT2COUNT(out_chlayout))
872                     out_channels = FF_LAYOUT2COUNT(out_chlayout);
873                 score -= 10000 + FFABS(out_channels - in_channels) +
874                          (in_channels > out_channels ? 10000 : 0);
875                 in_chlayout = out_chlayout = 0;
876                 /* Let the remaining computation run, even if the score
877                    value is not altered */
878             }
879
880             /* channel substitution */
881             for (k = 0; k < FF_ARRAY_ELEMS(ch_subst); k++) {
882                 uint64_t cmp0 = ch_subst[k][0];
883                 uint64_t cmp1 = ch_subst[k][1];
884                 if (( in_chlayout & cmp0) && (!(out_chlayout & cmp0)) &&
885                     (out_chlayout & cmp1) && (!( in_chlayout & cmp1))) {
886                     in_chlayout  &= ~cmp0;
887                     out_chlayout &= ~cmp1;
888                     /* add score for channel match, minus a deduction for
889                        having to do the substitution */
890                     score += 10 * av_get_channel_layout_nb_channels(cmp1) - 2;
891                 }
892             }
893
894             /* no penalty for LFE channel mismatch */
895             if ( (in_chlayout & AV_CH_LOW_FREQUENCY) &&
896                 (out_chlayout & AV_CH_LOW_FREQUENCY))
897                 score += 10;
898             in_chlayout  &= ~AV_CH_LOW_FREQUENCY;
899             out_chlayout &= ~AV_CH_LOW_FREQUENCY;
900
901             matched_channels = av_get_channel_layout_nb_channels(in_chlayout &
902                                                                  out_chlayout);
903             extra_channels   = av_get_channel_layout_nb_channels(out_chlayout &
904                                                                  (~in_chlayout));
905             score += 10 * matched_channels - 5 * extra_channels;
906
907             if (score > best_score ||
908                 (count_diff < best_count_diff && score == best_score)) {
909                 best_score = score;
910                 best_idx   = j;
911                 best_count_diff = count_diff;
912             }
913         }
914         av_assert0(best_idx >= 0);
915         FFSWAP(uint64_t, outlink->in_channel_layouts->channel_layouts[0],
916                outlink->in_channel_layouts->channel_layouts[best_idx]);
917     }
918
919 }
920
921 static void swap_channel_layouts(AVFilterGraph *graph)
922 {
923     int i;
924
925     for (i = 0; i < graph->nb_filters; i++)
926         swap_channel_layouts_on_filter(graph->filters[i]);
927 }
928
929 static void swap_sample_fmts_on_filter(AVFilterContext *filter)
930 {
931     AVFilterLink *link = NULL;
932     int format, bps;
933     int i, j;
934
935     for (i = 0; i < filter->nb_inputs; i++) {
936         link = filter->inputs[i];
937
938         if (link->type == AVMEDIA_TYPE_AUDIO &&
939             link->out_formats->nb_formats == 1)
940             break;
941     }
942     if (i == filter->nb_inputs)
943         return;
944
945     format = link->out_formats->formats[0];
946     bps    = av_get_bytes_per_sample(format);
947
948     for (i = 0; i < filter->nb_outputs; i++) {
949         AVFilterLink *outlink = filter->outputs[i];
950         int best_idx = -1, best_score = INT_MIN;
951
952         if (outlink->type != AVMEDIA_TYPE_AUDIO ||
953             outlink->in_formats->nb_formats < 2)
954             continue;
955
956         for (j = 0; j < outlink->in_formats->nb_formats; j++) {
957             int out_format = outlink->in_formats->formats[j];
958             int out_bps    = av_get_bytes_per_sample(out_format);
959             int score;
960
961             if (av_get_packed_sample_fmt(out_format) == format ||
962                 av_get_planar_sample_fmt(out_format) == format) {
963                 best_idx   = j;
964                 break;
965             }
966
967             /* for s32 and float prefer double to prevent loss of information */
968             if (bps == 4 && out_bps == 8) {
969                 best_idx = j;
970                 break;
971             }
972
973             /* prefer closest higher or equal bps */
974             score = -abs(out_bps - bps);
975             if (out_bps >= bps)
976                 score += INT_MAX/2;
977
978             if (score > best_score) {
979                 best_score = score;
980                 best_idx   = j;
981             }
982         }
983         av_assert0(best_idx >= 0);
984         FFSWAP(int, outlink->in_formats->formats[0],
985                outlink->in_formats->formats[best_idx]);
986     }
987 }
988
989 static void swap_sample_fmts(AVFilterGraph *graph)
990 {
991     int i;
992
993     for (i = 0; i < graph->nb_filters; i++)
994         swap_sample_fmts_on_filter(graph->filters[i]);
995
996 }
997
998 static int pick_formats(AVFilterGraph *graph)
999 {
1000     int i, j, ret;
1001     int change;
1002
1003     do{
1004         change = 0;
1005         for (i = 0; i < graph->nb_filters; i++) {
1006             AVFilterContext *filter = graph->filters[i];
1007             if (filter->nb_inputs){
1008                 for (j = 0; j < filter->nb_inputs; j++){
1009                     if(filter->inputs[j]->in_formats && filter->inputs[j]->in_formats->nb_formats == 1) {
1010                         if ((ret = pick_format(filter->inputs[j], NULL)) < 0)
1011                             return ret;
1012                         change = 1;
1013                     }
1014                 }
1015             }
1016             if (filter->nb_outputs){
1017                 for (j = 0; j < filter->nb_outputs; j++){
1018                     if(filter->outputs[j]->in_formats && filter->outputs[j]->in_formats->nb_formats == 1) {
1019                         if ((ret = pick_format(filter->outputs[j], NULL)) < 0)
1020                             return ret;
1021                         change = 1;
1022                     }
1023                 }
1024             }
1025             if (filter->nb_inputs && filter->nb_outputs && filter->inputs[0]->format>=0) {
1026                 for (j = 0; j < filter->nb_outputs; j++) {
1027                     if(filter->outputs[j]->format<0) {
1028                         if ((ret = pick_format(filter->outputs[j], filter->inputs[0])) < 0)
1029                             return ret;
1030                         change = 1;
1031                     }
1032                 }
1033             }
1034         }
1035     }while(change);
1036
1037     for (i = 0; i < graph->nb_filters; i++) {
1038         AVFilterContext *filter = graph->filters[i];
1039
1040         for (j = 0; j < filter->nb_inputs; j++)
1041             if ((ret = pick_format(filter->inputs[j], NULL)) < 0)
1042                 return ret;
1043         for (j = 0; j < filter->nb_outputs; j++)
1044             if ((ret = pick_format(filter->outputs[j], NULL)) < 0)
1045                 return ret;
1046     }
1047     return 0;
1048 }
1049
1050 /**
1051  * Configure the formats of all the links in the graph.
1052  */
1053 static int graph_config_formats(AVFilterGraph *graph, AVClass *log_ctx)
1054 {
1055     int ret;
1056
1057     /* find supported formats from sub-filters, and merge along links */
1058     while ((ret = query_formats(graph, log_ctx)) == AVERROR(EAGAIN))
1059         av_log(graph, AV_LOG_DEBUG, "query_formats not finished\n");
1060     if (ret < 0)
1061         return ret;
1062
1063     /* Once everything is merged, it's possible that we'll still have
1064      * multiple valid media format choices. We try to minimize the amount
1065      * of format conversion inside filters */
1066     reduce_formats(graph);
1067
1068     /* for audio filters, ensure the best format, sample rate and channel layout
1069      * is selected */
1070     swap_sample_fmts(graph);
1071     swap_samplerates(graph);
1072     swap_channel_layouts(graph);
1073
1074     if ((ret = pick_formats(graph)) < 0)
1075         return ret;
1076
1077     return 0;
1078 }
1079
1080 static int ff_avfilter_graph_config_pointers(AVFilterGraph *graph,
1081                                              AVClass *log_ctx)
1082 {
1083     unsigned i, j;
1084     int sink_links_count = 0, n = 0;
1085     AVFilterContext *f;
1086     AVFilterLink **sinks;
1087
1088     for (i = 0; i < graph->nb_filters; i++) {
1089         f = graph->filters[i];
1090         for (j = 0; j < f->nb_inputs; j++) {
1091             f->inputs[j]->graph     = graph;
1092             f->inputs[j]->age_index = -1;
1093         }
1094         for (j = 0; j < f->nb_outputs; j++) {
1095             f->outputs[j]->graph    = graph;
1096             f->outputs[j]->age_index= -1;
1097         }
1098         if (!f->nb_outputs) {
1099             if (f->nb_inputs > INT_MAX - sink_links_count)
1100                 return AVERROR(EINVAL);
1101             sink_links_count += f->nb_inputs;
1102         }
1103     }
1104     sinks = av_calloc(sink_links_count, sizeof(*sinks));
1105     if (!sinks)
1106         return AVERROR(ENOMEM);
1107     for (i = 0; i < graph->nb_filters; i++) {
1108         f = graph->filters[i];
1109         if (!f->nb_outputs) {
1110             for (j = 0; j < f->nb_inputs; j++) {
1111                 sinks[n] = f->inputs[j];
1112                 f->inputs[j]->age_index = n++;
1113             }
1114         }
1115     }
1116     av_assert0(n == sink_links_count);
1117     graph->sink_links       = sinks;
1118     graph->sink_links_count = sink_links_count;
1119     return 0;
1120 }
1121
1122 static int graph_insert_fifos(AVFilterGraph *graph, AVClass *log_ctx)
1123 {
1124     AVFilterContext *f;
1125     int i, j, ret;
1126     int fifo_count = 0;
1127
1128     for (i = 0; i < graph->nb_filters; i++) {
1129         f = graph->filters[i];
1130
1131         for (j = 0; j < f->nb_inputs; j++) {
1132             AVFilterLink *link = f->inputs[j];
1133             AVFilterContext *fifo_ctx;
1134             AVFilter *fifo;
1135             char name[32];
1136
1137             if (!link->dstpad->needs_fifo)
1138                 continue;
1139
1140             fifo = f->inputs[j]->type == AVMEDIA_TYPE_VIDEO ?
1141                    avfilter_get_by_name("fifo") :
1142                    avfilter_get_by_name("afifo");
1143
1144             snprintf(name, sizeof(name), "auto-inserted fifo %d", fifo_count++);
1145
1146             ret = avfilter_graph_create_filter(&fifo_ctx, fifo, name, NULL,
1147                                                NULL, graph);
1148             if (ret < 0)
1149                 return ret;
1150
1151             ret = avfilter_insert_filter(link, fifo_ctx, 0, 0);
1152             if (ret < 0)
1153                 return ret;
1154         }
1155     }
1156
1157     return 0;
1158 }
1159
1160 int avfilter_graph_config(AVFilterGraph *graphctx, void *log_ctx)
1161 {
1162     int ret;
1163
1164     if ((ret = graph_check_validity(graphctx, log_ctx)))
1165         return ret;
1166     if ((ret = graph_insert_fifos(graphctx, log_ctx)) < 0)
1167         return ret;
1168     if ((ret = graph_config_formats(graphctx, log_ctx)))
1169         return ret;
1170     if ((ret = graph_config_links(graphctx, log_ctx)))
1171         return ret;
1172     if ((ret = ff_avfilter_graph_config_pointers(graphctx, log_ctx)))
1173         return ret;
1174
1175     return 0;
1176 }
1177
1178 int avfilter_graph_send_command(AVFilterGraph *graph, const char *target, const char *cmd, const char *arg, char *res, int res_len, int flags)
1179 {
1180     int i, r = AVERROR(ENOSYS);
1181
1182     if (!graph)
1183         return r;
1184
1185     if ((flags & AVFILTER_CMD_FLAG_ONE) && !(flags & AVFILTER_CMD_FLAG_FAST)) {
1186         r = avfilter_graph_send_command(graph, target, cmd, arg, res, res_len, flags | AVFILTER_CMD_FLAG_FAST);
1187         if (r != AVERROR(ENOSYS))
1188             return r;
1189     }
1190
1191     if (res_len && res)
1192         res[0] = 0;
1193
1194     for (i = 0; i < graph->nb_filters; i++) {
1195         AVFilterContext *filter = graph->filters[i];
1196         if (!strcmp(target, "all") || (filter->name && !strcmp(target, filter->name)) || !strcmp(target, filter->filter->name)) {
1197             r = avfilter_process_command(filter, cmd, arg, res, res_len, flags);
1198             if (r != AVERROR(ENOSYS)) {
1199                 if ((flags & AVFILTER_CMD_FLAG_ONE) || r < 0)
1200                     return r;
1201             }
1202         }
1203     }
1204
1205     return r;
1206 }
1207
1208 int avfilter_graph_queue_command(AVFilterGraph *graph, const char *target, const char *command, const char *arg, int flags, double ts)
1209 {
1210     int i;
1211
1212     if(!graph)
1213         return 0;
1214
1215     for (i = 0; i < graph->nb_filters; i++) {
1216         AVFilterContext *filter = graph->filters[i];
1217         if(filter && (!strcmp(target, "all") || !strcmp(target, filter->name) || !strcmp(target, filter->filter->name))){
1218             AVFilterCommand **queue = &filter->command_queue, *next;
1219             while (*queue && (*queue)->time <= ts)
1220                 queue = &(*queue)->next;
1221             next = *queue;
1222             *queue = av_mallocz(sizeof(AVFilterCommand));
1223             (*queue)->command = av_strdup(command);
1224             (*queue)->arg     = av_strdup(arg);
1225             (*queue)->time    = ts;
1226             (*queue)->flags   = flags;
1227             (*queue)->next    = next;
1228             if(flags & AVFILTER_CMD_FLAG_ONE)
1229                 return 0;
1230         }
1231     }
1232
1233     return 0;
1234 }
1235
1236 static void heap_bubble_up(AVFilterGraph *graph,
1237                            AVFilterLink *link, int index)
1238 {
1239     AVFilterLink **links = graph->sink_links;
1240
1241     while (index) {
1242         int parent = (index - 1) >> 1;
1243         if (links[parent]->current_pts >= link->current_pts)
1244             break;
1245         links[index] = links[parent];
1246         links[index]->age_index = index;
1247         index = parent;
1248     }
1249     links[index] = link;
1250     link->age_index = index;
1251 }
1252
1253 static void heap_bubble_down(AVFilterGraph *graph,
1254                              AVFilterLink *link, int index)
1255 {
1256     AVFilterLink **links = graph->sink_links;
1257
1258     while (1) {
1259         int child = 2 * index + 1;
1260         if (child >= graph->sink_links_count)
1261             break;
1262         if (child + 1 < graph->sink_links_count &&
1263             links[child + 1]->current_pts < links[child]->current_pts)
1264             child++;
1265         if (link->current_pts < links[child]->current_pts)
1266             break;
1267         links[index] = links[child];
1268         links[index]->age_index = index;
1269         index = child;
1270     }
1271     links[index] = link;
1272     link->age_index = index;
1273 }
1274
1275 void ff_avfilter_graph_update_heap(AVFilterGraph *graph, AVFilterLink *link)
1276 {
1277     heap_bubble_up  (graph, link, link->age_index);
1278     heap_bubble_down(graph, link, link->age_index);
1279 }
1280
1281
1282 int avfilter_graph_request_oldest(AVFilterGraph *graph)
1283 {
1284     while (graph->sink_links_count) {
1285         AVFilterLink *oldest = graph->sink_links[0];
1286         int r = ff_request_frame(oldest);
1287         if (r != AVERROR_EOF)
1288             return r;
1289         av_log(oldest->dst, AV_LOG_DEBUG, "EOF on sink link %s:%s.\n",
1290                oldest->dst ? oldest->dst->name : "unknown",
1291                oldest->dstpad ? oldest->dstpad->name : "unknown");
1292         /* EOF: remove the link from the heap */
1293         if (oldest->age_index < --graph->sink_links_count)
1294             heap_bubble_down(graph, graph->sink_links[graph->sink_links_count],
1295                              oldest->age_index);
1296         oldest->age_index = -1;
1297     }
1298     return AVERROR_EOF;
1299 }