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