Merge remote-tracking branch 'qatar/master'
[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 <ctype.h>
24 #include <string.h>
25
26 #include "libavutil/audioconvert.h"
27 #include "libavutil/avassert.h"
28 #include "libavutil/pixdesc.h"
29 #include "avfilter.h"
30 #include "avfiltergraph.h"
31 #include "formats.h"
32 #include "internal.h"
33
34 #include "libavutil/audioconvert.h"
35 #include "libavutil/log.h"
36
37 static const AVClass filtergraph_class = {
38     .class_name = "AVFilterGraph",
39     .item_name  = av_default_item_name,
40     .version    = LIBAVUTIL_VERSION_INT,
41 };
42
43 AVFilterGraph *avfilter_graph_alloc(void)
44 {
45     AVFilterGraph *ret = av_mallocz(sizeof(AVFilterGraph));
46     if (!ret)
47         return NULL;
48 #if FF_API_GRAPH_AVCLASS
49     ret->av_class = &filtergraph_class;
50 #endif
51     return ret;
52 }
53
54 void avfilter_graph_free(AVFilterGraph **graph)
55 {
56     if (!*graph)
57         return;
58     for (; (*graph)->filter_count > 0; (*graph)->filter_count--)
59         avfilter_free((*graph)->filters[(*graph)->filter_count - 1]);
60     av_freep(&(*graph)->sink_links);
61     av_freep(&(*graph)->scale_sws_opts);
62     av_freep(&(*graph)->filters);
63     av_freep(graph);
64 }
65
66 int avfilter_graph_add_filter(AVFilterGraph *graph, AVFilterContext *filter)
67 {
68     AVFilterContext **filters = av_realloc(graph->filters,
69                                            sizeof(AVFilterContext*) * (graph->filter_count+1));
70     if (!filters)
71         return AVERROR(ENOMEM);
72
73     graph->filters = filters;
74     graph->filters[graph->filter_count++] = filter;
75
76     return 0;
77 }
78
79 int avfilter_graph_create_filter(AVFilterContext **filt_ctx, AVFilter *filt,
80                                  const char *name, const char *args, void *opaque,
81                                  AVFilterGraph *graph_ctx)
82 {
83     int ret;
84
85     if ((ret = avfilter_open(filt_ctx, filt, name)) < 0)
86         goto fail;
87     if ((ret = avfilter_init_filter(*filt_ctx, args, opaque)) < 0)
88         goto fail;
89     if ((ret = avfilter_graph_add_filter(graph_ctx, *filt_ctx)) < 0)
90         goto fail;
91     return 0;
92
93 fail:
94     if (*filt_ctx)
95         avfilter_free(*filt_ctx);
96     *filt_ctx = NULL;
97     return ret;
98 }
99
100 void avfilter_graph_set_auto_convert(AVFilterGraph *graph, unsigned flags)
101 {
102     graph->disable_auto_convert = flags;
103 }
104
105 int ff_avfilter_graph_check_validity(AVFilterGraph *graph, AVClass *log_ctx)
106 {
107     AVFilterContext *filt;
108     int i, j;
109
110     for (i = 0; i < graph->filter_count; i++) {
111         filt = graph->filters[i];
112
113         for (j = 0; j < filt->input_count; j++) {
114             if (!filt->inputs[j] || !filt->inputs[j]->src) {
115                 av_log(log_ctx, AV_LOG_ERROR,
116                        "Input pad \"%s\" for the filter \"%s\" of type \"%s\" not connected to any source\n",
117                        filt->input_pads[j].name, filt->name, filt->filter->name);
118                 return AVERROR(EINVAL);
119             }
120         }
121
122         for (j = 0; j < filt->output_count; j++) {
123             if (!filt->outputs[j] || !filt->outputs[j]->dst) {
124                 av_log(log_ctx, AV_LOG_ERROR,
125                        "Output pad \"%s\" for the filter \"%s\" of type \"%s\" not connected to any destination\n",
126                        filt->output_pads[j].name, filt->name, filt->filter->name);
127                 return AVERROR(EINVAL);
128             }
129         }
130     }
131
132     return 0;
133 }
134
135 int ff_avfilter_graph_config_links(AVFilterGraph *graph, AVClass *log_ctx)
136 {
137     AVFilterContext *filt;
138     int i, ret;
139
140     for (i=0; i < graph->filter_count; i++) {
141         filt = graph->filters[i];
142
143         if (!filt->output_count) {
144             if ((ret = avfilter_config_links(filt)))
145                 return ret;
146         }
147     }
148
149     return 0;
150 }
151
152 AVFilterContext *avfilter_graph_get_filter(AVFilterGraph *graph, char *name)
153 {
154     int i;
155
156     for (i = 0; i < graph->filter_count; i++)
157         if (graph->filters[i]->name && !strcmp(name, graph->filters[i]->name))
158             return graph->filters[i];
159
160     return NULL;
161 }
162
163 static int insert_conv_filter(AVFilterGraph *graph, AVFilterLink *link,
164                               const char *filt_name, const char *filt_args)
165 {
166     static int auto_count = 0, ret;
167     char inst_name[32];
168     AVFilterContext *filt_ctx;
169
170     if (graph->disable_auto_convert) {
171         av_log(NULL, AV_LOG_ERROR,
172                "The filters '%s' and '%s' do not have a common format "
173                "and automatic conversion is disabled.\n",
174                link->src->name, link->dst->name);
175         return AVERROR(EINVAL);
176     }
177
178     snprintf(inst_name, sizeof(inst_name), "auto-inserted %s %d",
179             filt_name, auto_count++);
180
181     if ((ret = avfilter_graph_create_filter(&filt_ctx,
182                                             avfilter_get_by_name(filt_name),
183                                             inst_name, filt_args, NULL, graph)) < 0)
184         return ret;
185     if ((ret = avfilter_insert_filter(link, filt_ctx, 0, 0)) < 0)
186         return ret;
187
188     filt_ctx->filter->query_formats(filt_ctx);
189
190     if ( ((link = filt_ctx-> inputs[0]) &&
191            !avfilter_merge_formats(link->in_formats, link->out_formats)) ||
192          ((link = filt_ctx->outputs[0]) &&
193            !avfilter_merge_formats(link->in_formats, link->out_formats))
194        ) {
195         av_log(NULL, AV_LOG_ERROR,
196                "Impossible to convert between the formats supported by the filter "
197                "'%s' and the filter '%s'\n", link->src->name, link->dst->name);
198         return AVERROR(EINVAL);
199     }
200
201     if (link->type == AVMEDIA_TYPE_AUDIO &&
202          (((link = filt_ctx-> inputs[0]) &&
203            (!ff_merge_channel_layouts(link->in_channel_layouts, link->out_channel_layouts) ||
204             !avfilter_merge_formats(link->in_packing,   link->out_packing))) ||
205          ((link = filt_ctx->outputs[0]) &&
206            (!ff_merge_channel_layouts(link->in_channel_layouts, link->out_channel_layouts) ||
207             !avfilter_merge_formats(link->in_packing,   link->out_packing))))
208        ) {
209         av_log(NULL, AV_LOG_ERROR,
210                "Impossible to convert between the channel layouts/packing formats supported by the filter "
211                "'%s' and the filter '%s'\n", link->src->name, link->dst->name);
212         return AVERROR(EINVAL);
213     }
214
215     return 0;
216 }
217
218 static int query_formats(AVFilterGraph *graph, AVClass *log_ctx)
219 {
220     int i, j, ret;
221     char filt_args[128];
222     AVFilterFormats *formats, *packing;
223     AVFilterChannelLayouts *chlayouts;
224     AVFilterFormats *samplerates;
225     int scaler_count = 0, resampler_count = 0;
226
227     /* ask all the sub-filters for their supported media formats */
228     for (i = 0; i < graph->filter_count; i++) {
229         if (graph->filters[i]->filter->query_formats)
230             graph->filters[i]->filter->query_formats(graph->filters[i]);
231         else
232             avfilter_default_query_formats(graph->filters[i]);
233     }
234
235     /* go through and merge as many format lists as possible */
236     for (i = 0; i < graph->filter_count; i++) {
237         AVFilterContext *filter = graph->filters[i];
238
239         for (j = 0; j < filter->input_count; j++) {
240             AVFilterLink *link = filter->inputs[j];
241 #if 0
242             if (!link) continue;
243
244             if (!link->in_formats || !link->out_formats)
245                 return AVERROR(EINVAL);
246
247             if (link->type == AVMEDIA_TYPE_VIDEO &&
248                 !avfilter_merge_formats(link->in_formats, link->out_formats)) {
249
250                 /* couldn't merge format lists, auto-insert scale filter */
251                 snprintf(filt_args, sizeof(filt_args), "0:0:%s",
252                          graph->scale_sws_opts);
253                 if (ret = insert_conv_filter(graph, link, "scale", filt_args))
254                     return ret;
255             }
256             else if (link->type == AVMEDIA_TYPE_AUDIO) {
257                 if (!link->in_channel_layouts || !link->out_channel_layouts ||
258                     !link->in_packing   || !link->out_packing)
259                     return AVERROR(EINVAL);
260
261                 /* Merge all three list before checking: that way, in all
262                  * three categories, aconvert will use a common format
263                  * whenever possible. */
264                 formats   = avfilter_merge_formats(link->in_formats,   link->out_formats);
265                 chlayouts   = ff_merge_channel_layouts(link->in_channel_layouts  , link->out_channel_layouts);
266                 samplerates = ff_merge_samplerates    (link->in_samplerates, link->out_samplerates);
267                 packing   = avfilter_merge_formats(link->in_packing,   link->out_packing);
268
269                 if (!formats || !chlayouts || !packing || !samplerates)
270                     if (ret = insert_conv_filter(graph, link, "aconvert", NULL))
271                        return ret;
272 #else
273             int convert_needed = 0;
274
275             if (!link)
276                 continue;
277
278             if (link->in_formats != link->out_formats &&
279                 !avfilter_merge_formats(link->in_formats,
280                                         link->out_formats))
281                 convert_needed = 1;
282             if (link->type == AVMEDIA_TYPE_AUDIO) {
283                 if (link->in_channel_layouts != link->out_channel_layouts &&
284                     !ff_merge_channel_layouts(link->in_channel_layouts,
285                                               link->out_channel_layouts))
286                     convert_needed = 1;
287                 if (link->in_samplerates != link->out_samplerates &&
288                     !ff_merge_samplerates(link->in_samplerates,
289                                           link->out_samplerates))
290                     convert_needed = 1;
291             }
292
293             if (convert_needed) {
294                 AVFilterContext *convert;
295                 AVFilter *filter;
296                 AVFilterLink *inlink, *outlink;
297                 char scale_args[256];
298                 char inst_name[30];
299
300                 /* couldn't merge format lists. auto-insert conversion filter */
301                 switch (link->type) {
302                 case AVMEDIA_TYPE_VIDEO:
303                     snprintf(inst_name, sizeof(inst_name), "auto-inserted scaler %d",
304                              scaler_count++);
305                     snprintf(scale_args, sizeof(scale_args), "0:0:%s", graph->scale_sws_opts);
306                     if ((ret = avfilter_graph_create_filter(&convert,
307                                                             avfilter_get_by_name("scale"),
308                                                             inst_name, scale_args, NULL,
309                                                             graph)) < 0)
310                         return ret;
311                     break;
312                 case AVMEDIA_TYPE_AUDIO:
313                     if (!(filter = avfilter_get_by_name("resample"))) {
314                         av_log(log_ctx, AV_LOG_ERROR, "'resample' filter "
315                                "not present, cannot convert audio formats.\n");
316                         return AVERROR(EINVAL);
317                     }
318
319                     snprintf(inst_name, sizeof(inst_name), "auto-inserted resampler %d",
320                              resampler_count++);
321                     if ((ret = avfilter_graph_create_filter(&convert,
322                                                             avfilter_get_by_name("resample"),
323                                                             inst_name, NULL, NULL, graph)) < 0)
324                         return ret;
325                     break;
326                 default:
327                     return AVERROR(EINVAL);
328                 }
329
330                 if ((ret = avfilter_insert_filter(link, convert, 0, 0)) < 0)
331                     return ret;
332
333                 convert->filter->query_formats(convert);
334                 inlink  = convert->inputs[0];
335                 outlink = convert->outputs[0];
336                 if (!avfilter_merge_formats( inlink->in_formats,  inlink->out_formats) ||
337                     !avfilter_merge_formats(outlink->in_formats, outlink->out_formats))
338                     ret |= AVERROR(ENOSYS);
339                 if (inlink->type == AVMEDIA_TYPE_AUDIO &&
340                     (!ff_merge_samplerates(inlink->in_samplerates,
341                                            inlink->out_samplerates) ||
342                      !ff_merge_channel_layouts(inlink->in_channel_layouts,
343                                                inlink->out_channel_layouts)))
344                     ret |= AVERROR(ENOSYS);
345                 if (outlink->type == AVMEDIA_TYPE_AUDIO &&
346                     (!ff_merge_samplerates(outlink->in_samplerates,
347                                            outlink->out_samplerates) ||
348                      !ff_merge_channel_layouts(outlink->in_channel_layouts,
349                                                outlink->out_channel_layouts)))
350                     ret |= AVERROR(ENOSYS);
351
352                 if (ret < 0) {
353                     av_log(log_ctx, AV_LOG_ERROR,
354                            "Impossible to convert between the formats supported by the filter "
355                            "'%s' and the filter '%s'\n", link->src->name, link->dst->name);
356                     return ret;
357                 }
358 #endif
359             }
360         }
361     }
362
363     return 0;
364 }
365
366 static int pick_format(AVFilterLink *link, AVFilterLink *ref)
367 {
368     if (!link || !link->in_formats)
369         return 0;
370
371     if (link->type == AVMEDIA_TYPE_VIDEO) {
372         if(ref && ref->type == AVMEDIA_TYPE_VIDEO){
373             int has_alpha= av_pix_fmt_descriptors[ref->format].nb_components % 2 == 0;
374             enum PixelFormat best= PIX_FMT_NONE;
375             int i;
376             for (i=0; i<link->in_formats->format_count; i++) {
377                 enum PixelFormat p = link->in_formats->formats[i];
378                 best= avcodec_find_best_pix_fmt2(best, p, ref->format, has_alpha, NULL);
379             }
380             link->in_formats->formats[0] = best;
381         }
382     }
383
384     link->in_formats->format_count = 1;
385     link->format = link->in_formats->formats[0];
386
387     if (link->type == AVMEDIA_TYPE_AUDIO) {
388         if (!link->in_samplerates->format_count) {
389             av_log(link->src, AV_LOG_ERROR, "Cannot select sample rate for"
390                    " the link between filters %s and %s.\n", link->src->name,
391                    link->dst->name);
392             return AVERROR(EINVAL);
393         }
394         link->in_samplerates->format_count = 1;
395         link->sample_rate = link->in_samplerates->formats[0];
396
397         if (!link->in_channel_layouts->nb_channel_layouts) {
398             av_log(link->src, AV_LOG_ERROR, "Cannot select channel layout for"
399                    "the link between filters %s and %s.\n", link->src->name,
400                    link->dst->name);
401             return AVERROR(EINVAL);
402         }
403         link->in_channel_layouts->nb_channel_layouts = 1;
404         link->channel_layout = link->in_channel_layouts->channel_layouts[0];
405     }
406
407     avfilter_formats_unref(&link->in_formats);
408     avfilter_formats_unref(&link->out_formats);
409     avfilter_formats_unref(&link->in_samplerates);
410     avfilter_formats_unref(&link->out_samplerates);
411     ff_channel_layouts_unref(&link->in_channel_layouts);
412     ff_channel_layouts_unref(&link->out_channel_layouts);
413
414     return 0;
415 }
416
417 #define REDUCE_FORMATS(fmt_type, list_type, list, var, nb, add_format) \
418 do {                                                                   \
419     for (i = 0; i < filter->input_count; i++) {                        \
420         AVFilterLink *link = filter->inputs[i];                        \
421         fmt_type fmt;                                                  \
422                                                                        \
423         if (!link->out_ ## list || link->out_ ## list->nb != 1)        \
424             continue;                                                  \
425         fmt = link->out_ ## list->var[0];                              \
426                                                                        \
427         for (j = 0; j < filter->output_count; j++) {                   \
428             AVFilterLink *out_link = filter->outputs[j];               \
429             list_type *fmts;                                           \
430                                                                        \
431             if (link->type != out_link->type ||                        \
432                 out_link->in_ ## list->nb == 1)                        \
433                 continue;                                              \
434             fmts = out_link->in_ ## list;                              \
435                                                                        \
436             if (!out_link->in_ ## list->nb) {                          \
437                 add_format(&out_link->in_ ##list, fmt);                \
438                 break;                                                 \
439             }                                                          \
440                                                                        \
441             for (k = 0; k < out_link->in_ ## list->nb; k++)            \
442                 if (fmts->var[k] == fmt) {                             \
443                     fmts->var[0]  = fmt;                               \
444                     fmts->nb = 1;                                      \
445                     ret = 1;                                           \
446                     break;                                             \
447                 }                                                      \
448         }                                                              \
449     }                                                                  \
450 } while (0)
451
452 static int reduce_formats_on_filter(AVFilterContext *filter)
453 {
454     int i, j, k, ret = 0;
455
456     REDUCE_FORMATS(int,      AVFilterFormats,        formats,         formats,
457                    format_count, avfilter_add_format);
458     REDUCE_FORMATS(int,      AVFilterFormats,        samplerates,     formats,
459                    format_count, avfilter_add_format);
460     REDUCE_FORMATS(uint64_t, AVFilterChannelLayouts, channel_layouts,
461                    channel_layouts, nb_channel_layouts, ff_add_channel_layout);
462
463     return ret;
464 }
465
466 static void reduce_formats(AVFilterGraph *graph)
467 {
468     int i, reduced;
469
470     do {
471         reduced = 0;
472
473         for (i = 0; i < graph->filter_count; i++)
474             reduced |= reduce_formats_on_filter(graph->filters[i]);
475     } while (reduced);
476 }
477
478 static void swap_samplerates_on_filter(AVFilterContext *filter)
479 {
480     AVFilterLink *link = NULL;
481     int sample_rate;
482     int i, j;
483
484     for (i = 0; i < filter->input_count; i++) {
485         link = filter->inputs[i];
486
487         if (link->type == AVMEDIA_TYPE_AUDIO &&
488             link->out_samplerates->format_count == 1)
489             break;
490     }
491     if (i == filter->input_count)
492         return;
493
494     sample_rate = link->out_samplerates->formats[0];
495
496     for (i = 0; i < filter->output_count; i++) {
497         AVFilterLink *outlink = filter->outputs[i];
498         int best_idx, best_diff = INT_MAX;
499
500         if (outlink->type != AVMEDIA_TYPE_AUDIO ||
501             outlink->in_samplerates->format_count < 2)
502             continue;
503
504         for (j = 0; j < outlink->in_samplerates->format_count; j++) {
505             int diff = abs(sample_rate - outlink->in_samplerates->formats[j]);
506
507             if (diff < best_diff) {
508                 best_diff = diff;
509                 best_idx  = j;
510             }
511         }
512         FFSWAP(int, outlink->in_samplerates->formats[0],
513                outlink->in_samplerates->formats[best_idx]);
514     }
515 }
516
517 static void swap_samplerates(AVFilterGraph *graph)
518 {
519     int i;
520
521     for (i = 0; i < graph->filter_count; i++)
522         swap_samplerates_on_filter(graph->filters[i]);
523 }
524
525 static void swap_channel_layouts_on_filter(AVFilterContext *filter)
526 {
527     AVFilterLink *link = NULL;
528     uint64_t chlayout;
529     int i, j;
530
531     for (i = 0; i < filter->input_count; i++) {
532         link = filter->inputs[i];
533
534         if (link->type == AVMEDIA_TYPE_AUDIO &&
535             link->out_channel_layouts->nb_channel_layouts == 1)
536             break;
537     }
538     if (i == filter->input_count)
539         return;
540
541     chlayout = link->out_channel_layouts->channel_layouts[0];
542
543     for (i = 0; i < filter->output_count; i++) {
544         AVFilterLink *outlink = filter->outputs[i];
545         int best_idx, best_score = INT_MIN;
546
547         if (outlink->type != AVMEDIA_TYPE_AUDIO ||
548             outlink->in_channel_layouts->nb_channel_layouts < 2)
549             continue;
550
551         for (j = 0; j < outlink->in_channel_layouts->nb_channel_layouts; j++) {
552             uint64_t out_chlayout = outlink->in_channel_layouts->channel_layouts[j];
553             int matched_channels  = av_get_channel_layout_nb_channels(chlayout &
554                                                                       out_chlayout);
555             int extra_channels     = av_get_channel_layout_nb_channels(out_chlayout &
556                                                                        (~chlayout));
557             int score = matched_channels - extra_channels;
558
559             if (score > best_score) {
560                 best_score = score;
561                 best_idx   = j;
562             }
563         }
564         FFSWAP(uint64_t, outlink->in_channel_layouts->channel_layouts[0],
565                outlink->in_channel_layouts->channel_layouts[best_idx]);
566     }
567
568 }
569
570 static void swap_channel_layouts(AVFilterGraph *graph)
571 {
572     int i;
573
574     for (i = 0; i < graph->filter_count; i++)
575         swap_channel_layouts_on_filter(graph->filters[i]);
576 }
577
578 static int pick_formats(AVFilterGraph *graph)
579 {
580     int i, j, ret;
581     int change;
582
583     do{
584         change = 0;
585         for (i = 0; i < graph->filter_count; i++) {
586             AVFilterContext *filter = graph->filters[i];
587             if (filter->input_count){
588                 for (j = 0; j < filter->input_count; j++){
589                     if(filter->inputs[j]->in_formats && filter->inputs[j]->in_formats->format_count == 1) {
590                         pick_format(filter->inputs[j], NULL);
591                         change = 1;
592                     }
593                 }
594             }
595             if (filter->output_count){
596                 for (j = 0; j < filter->output_count; j++){
597                     if(filter->outputs[j]->in_formats && filter->outputs[j]->in_formats->format_count == 1) {
598                         pick_format(filter->outputs[j], NULL);
599                         change = 1;
600                     }
601                 }
602             }
603             if (filter->input_count && filter->output_count && filter->inputs[0]->format>=0) {
604                 for (j = 0; j < filter->output_count; j++) {
605                     if(filter->outputs[j]->format<0) {
606                         pick_format(filter->outputs[j], filter->inputs[0]);
607                         change = 1;
608                     }
609                 }
610             }
611         }
612     }while(change);
613
614     for (i = 0; i < graph->filter_count; i++) {
615         AVFilterContext *filter = graph->filters[i];
616
617         for (j = 0; j < filter->input_count; j++)
618             if ((ret = pick_format(filter->inputs[j], NULL)) < 0)
619                 return ret;
620         for (j = 0; j < filter->output_count; j++)
621             if ((ret = pick_format(filter->outputs[j], NULL)) < 0)
622                 return ret;
623     }
624     return 0;
625 }
626
627 int ff_avfilter_graph_config_formats(AVFilterGraph *graph, AVClass *log_ctx)
628 {
629     int ret;
630
631     /* find supported formats from sub-filters, and merge along links */
632     if ((ret = query_formats(graph, log_ctx)) < 0)
633         return ret;
634
635     /* Once everything is merged, it's possible that we'll still have
636      * multiple valid media format choices. We try to minimize the amount
637      * of format conversion inside filters */
638     reduce_formats(graph);
639
640     /* for audio filters, ensure the best sample rate and channel layout
641      * is selected */
642     swap_samplerates(graph);
643     swap_channel_layouts(graph);
644
645     if ((ret = pick_formats(graph)) < 0)
646         return ret;
647
648     return 0;
649 }
650
651 static int ff_avfilter_graph_config_pointers(AVFilterGraph *graph,
652                                              AVClass *log_ctx)
653 {
654     unsigned i, j;
655     int sink_links_count = 0, n = 0;
656     AVFilterContext *f;
657     AVFilterLink **sinks;
658
659     for (i = 0; i < graph->filter_count; i++) {
660         f = graph->filters[i];
661         for (j = 0; j < f->input_count; j++) {
662             f->inputs[j]->graph     = graph;
663             f->inputs[j]->age_index = -1;
664         }
665         for (j = 0; j < f->output_count; j++) {
666             f->outputs[j]->graph    = graph;
667             f->outputs[j]->age_index= -1;
668         }
669         if (!f->output_count) {
670             if (f->input_count > INT_MAX - sink_links_count)
671                 return AVERROR(EINVAL);
672             sink_links_count += f->input_count;
673         }
674     }
675     sinks = av_calloc(sink_links_count, sizeof(*sinks));
676     if (!sinks)
677         return AVERROR(ENOMEM);
678     for (i = 0; i < graph->filter_count; i++) {
679         f = graph->filters[i];
680         if (!f->output_count) {
681             for (j = 0; j < f->input_count; j++) {
682                 sinks[n] = f->inputs[j];
683                 f->inputs[j]->age_index = n++;
684             }
685         }
686     }
687     av_assert0(n == sink_links_count);
688     graph->sink_links       = sinks;
689     graph->sink_links_count = sink_links_count;
690     return 0;
691 }
692
693 int avfilter_graph_config(AVFilterGraph *graphctx, void *log_ctx)
694 {
695     int ret;
696
697     if ((ret = ff_avfilter_graph_check_validity(graphctx, log_ctx)))
698         return ret;
699     if ((ret = ff_avfilter_graph_config_formats(graphctx, log_ctx)))
700         return ret;
701     if ((ret = ff_avfilter_graph_config_links(graphctx, log_ctx)))
702         return ret;
703     if ((ret = ff_avfilter_graph_config_pointers(graphctx, log_ctx)))
704         return ret;
705
706     return 0;
707 }
708
709 int avfilter_graph_send_command(AVFilterGraph *graph, const char *target, const char *cmd, const char *arg, char *res, int res_len, int flags)
710 {
711     int i, r = AVERROR(ENOSYS);
712
713     if(!graph)
714         return r;
715
716     if((flags & AVFILTER_CMD_FLAG_ONE) && !(flags & AVFILTER_CMD_FLAG_FAST)) {
717         r=avfilter_graph_send_command(graph, target, cmd, arg, res, res_len, flags | AVFILTER_CMD_FLAG_FAST);
718         if(r != AVERROR(ENOSYS))
719             return r;
720     }
721
722     if(res_len && res)
723         res[0]= 0;
724
725     for (i = 0; i < graph->filter_count; i++) {
726         AVFilterContext *filter = graph->filters[i];
727         if(!strcmp(target, "all") || (filter->name && !strcmp(target, filter->name)) || !strcmp(target, filter->filter->name)){
728             r = avfilter_process_command(filter, cmd, arg, res, res_len, flags);
729             if(r != AVERROR(ENOSYS)) {
730                 if((flags & AVFILTER_CMD_FLAG_ONE) || r<0)
731                     return r;
732             }
733         }
734     }
735
736     return r;
737 }
738
739 int avfilter_graph_queue_command(AVFilterGraph *graph, const char *target, const char *command, const char *arg, int flags, double ts)
740 {
741     int i;
742
743     if(!graph)
744         return 0;
745
746     for (i = 0; i < graph->filter_count; i++) {
747         AVFilterContext *filter = graph->filters[i];
748         if(filter && (!strcmp(target, "all") || !strcmp(target, filter->name) || !strcmp(target, filter->filter->name))){
749             AVFilterCommand **que = &filter->command_queue, *next;
750             while(*que && (*que)->time <= ts)
751                 que = &(*que)->next;
752             next= *que;
753             *que= av_mallocz(sizeof(AVFilterCommand));
754             (*que)->command = av_strdup(command);
755             (*que)->arg     = av_strdup(arg);
756             (*que)->time    = ts;
757             (*que)->flags   = flags;
758             (*que)->next    = next;
759             if(flags & AVFILTER_CMD_FLAG_ONE)
760                 return 0;
761         }
762     }
763
764     return 0;
765 }
766
767 static void heap_bubble_up(AVFilterGraph *graph,
768                            AVFilterLink *link, int index)
769 {
770     AVFilterLink **links = graph->sink_links;
771
772     while (index) {
773         int parent = (index - 1) >> 1;
774         if (links[parent]->current_pts >= link->current_pts)
775             break;
776         links[index] = links[parent];
777         links[index]->age_index = index;
778         index = parent;
779     }
780     links[index] = link;
781     link->age_index = index;
782 }
783
784 static void heap_bubble_down(AVFilterGraph *graph,
785                              AVFilterLink *link, int index)
786 {
787     AVFilterLink **links = graph->sink_links;
788
789     while (1) {
790         int child = 2 * index + 1;
791         if (child >= graph->sink_links_count)
792             break;
793         if (child + 1 < graph->sink_links_count &&
794             links[child + 1]->current_pts < links[child]->current_pts)
795             child++;
796         if (link->current_pts < links[child]->current_pts)
797             break;
798         links[index] = links[child];
799         links[index]->age_index = index;
800         index = child;
801     }
802     links[index] = link;
803     link->age_index = index;
804 }
805
806 void ff_avfilter_graph_update_heap(AVFilterGraph *graph, AVFilterLink *link)
807 {
808     heap_bubble_up  (graph, link, link->age_index);
809     heap_bubble_down(graph, link, link->age_index);
810 }
811
812
813 int avfilter_graph_request_oldest(AVFilterGraph *graph)
814 {
815     while (graph->sink_links_count) {
816         AVFilterLink *oldest = graph->sink_links[0];
817         int r = avfilter_request_frame(oldest);
818         if (r != AVERROR_EOF)
819             return r;
820         /* EOF: remove the link from the heap */
821         if (oldest->age_index < --graph->sink_links_count)
822             heap_bubble_down(graph, graph->sink_links[graph->sink_links_count],
823                              oldest->age_index);
824         oldest->age_index = -1;
825     }
826     return AVERROR_EOF;
827 }