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 /**
106  * Check for the validity of graph.
107  *
108  * A graph is considered valid if all its input and output pads are
109  * connected.
110  *
111  * @return 0 in case of success, a negative value otherwise
112  */
113 static int graph_check_validity(AVFilterGraph *graph, AVClass *log_ctx)
114 {
115     AVFilterContext *filt;
116     int i, j;
117
118     for (i = 0; i < graph->filter_count; i++) {
119         filt = graph->filters[i];
120
121         for (j = 0; j < filt->nb_inputs; j++) {
122             if (!filt->inputs[j] || !filt->inputs[j]->src) {
123                 av_log(log_ctx, AV_LOG_ERROR,
124                        "Input pad \"%s\" for the filter \"%s\" of type \"%s\" not connected to any source\n",
125                        filt->input_pads[j].name, filt->name, filt->filter->name);
126                 return AVERROR(EINVAL);
127             }
128         }
129
130         for (j = 0; j < filt->nb_outputs; j++) {
131             if (!filt->outputs[j] || !filt->outputs[j]->dst) {
132                 av_log(log_ctx, AV_LOG_ERROR,
133                        "Output pad \"%s\" for the filter \"%s\" of type \"%s\" not connected to any destination\n",
134                        filt->output_pads[j].name, filt->name, filt->filter->name);
135                 return AVERROR(EINVAL);
136             }
137         }
138     }
139
140     return 0;
141 }
142
143 /**
144  * Configure all the links of graphctx.
145  *
146  * @return 0 in case of success, a negative value otherwise
147  */
148 static int graph_config_links(AVFilterGraph *graph, AVClass *log_ctx)
149 {
150     AVFilterContext *filt;
151     int i, ret;
152
153     for (i=0; i < graph->filter_count; i++) {
154         filt = graph->filters[i];
155
156         if (!filt->nb_outputs) {
157             if ((ret = avfilter_config_links(filt)))
158                 return ret;
159         }
160     }
161
162     return 0;
163 }
164
165 AVFilterContext *avfilter_graph_get_filter(AVFilterGraph *graph, char *name)
166 {
167     int i;
168
169     for (i = 0; i < graph->filter_count; i++)
170         if (graph->filters[i]->name && !strcmp(name, graph->filters[i]->name))
171             return graph->filters[i];
172
173     return NULL;
174 }
175
176 static int filter_query_formats(AVFilterContext *ctx)
177 {
178     int ret;
179     AVFilterFormats *formats;
180     AVFilterChannelLayouts *chlayouts;
181     AVFilterFormats *samplerates;
182     enum AVMediaType type = ctx->inputs  && ctx->inputs [0] ? ctx->inputs [0]->type :
183                             ctx->outputs && ctx->outputs[0] ? ctx->outputs[0]->type :
184                             AVMEDIA_TYPE_VIDEO;
185
186     if ((ret = ctx->filter->query_formats(ctx)) < 0)
187         return ret;
188
189     formats = avfilter_make_all_formats(type);
190     if (!formats)
191         return AVERROR(ENOMEM);
192     avfilter_set_common_formats(ctx, formats);
193     if (type == AVMEDIA_TYPE_AUDIO) {
194         samplerates = ff_all_samplerates();
195         if (!samplerates)
196             return AVERROR(ENOMEM);
197         ff_set_common_samplerates(ctx, samplerates);
198         chlayouts = ff_all_channel_layouts();
199         if (!chlayouts)
200             return AVERROR(ENOMEM);
201         ff_set_common_channel_layouts(ctx, chlayouts);
202     }
203     return 0;
204 }
205
206 static int insert_conv_filter(AVFilterGraph *graph, AVFilterLink *link,
207                               const char *filt_name, const char *filt_args)
208 {
209     static int auto_count = 0, ret;
210     char inst_name[32];
211     AVFilterContext *filt_ctx;
212
213     if (graph->disable_auto_convert) {
214         av_log(NULL, AV_LOG_ERROR,
215                "The filters '%s' and '%s' do not have a common format "
216                "and automatic conversion is disabled.\n",
217                link->src->name, link->dst->name);
218         return AVERROR(EINVAL);
219     }
220
221     snprintf(inst_name, sizeof(inst_name), "auto-inserted %s %d",
222             filt_name, auto_count++);
223
224     if ((ret = avfilter_graph_create_filter(&filt_ctx,
225                                             avfilter_get_by_name(filt_name),
226                                             inst_name, filt_args, NULL, graph)) < 0)
227         return ret;
228     if ((ret = avfilter_insert_filter(link, filt_ctx, 0, 0)) < 0)
229         return ret;
230
231     filter_query_formats(filt_ctx);
232
233     if ( ((link = filt_ctx-> inputs[0]) &&
234            !avfilter_merge_formats(link->in_formats, link->out_formats)) ||
235          ((link = filt_ctx->outputs[0]) &&
236            !avfilter_merge_formats(link->in_formats, link->out_formats))
237        ) {
238         av_log(NULL, AV_LOG_ERROR,
239                "Impossible to convert between the formats supported by the filter "
240                "'%s' and the filter '%s'\n", link->src->name, link->dst->name);
241         return AVERROR(EINVAL);
242     }
243
244     if (link->type == AVMEDIA_TYPE_AUDIO &&
245          (((link = filt_ctx-> inputs[0]) &&
246            !ff_merge_channel_layouts(link->in_channel_layouts, link->out_channel_layouts)) ||
247          ((link = filt_ctx->outputs[0]) &&
248            !ff_merge_channel_layouts(link->in_channel_layouts, link->out_channel_layouts)))
249        ) {
250         av_log(NULL, AV_LOG_ERROR,
251                "Impossible to convert between the channel layouts formats supported by the filter "
252                "'%s' and the filter '%s'\n", link->src->name, link->dst->name);
253         return AVERROR(EINVAL);
254     }
255
256     return 0;
257 }
258
259 static int query_formats(AVFilterGraph *graph, AVClass *log_ctx)
260 {
261     int i, j, ret;
262     char filt_args[128];
263     AVFilterFormats *formats;
264     AVFilterChannelLayouts *chlayouts;
265     AVFilterFormats *samplerates;
266     int scaler_count = 0, resampler_count = 0;
267
268     for (j = 0; j < 2; j++) {
269     /* ask all the sub-filters for their supported media formats */
270     for (i = 0; i < graph->filter_count; i++) {
271         /* Call query_formats on sources first.
272            This is a temporary workaround for amerge,
273            until format renegociation is implemented. */
274         if (!graph->filters[i]->nb_inputs == j)
275             continue;
276         if (graph->filters[i]->filter->query_formats)
277             ret = filter_query_formats(graph->filters[i]);
278         else
279             ret = ff_default_query_formats(graph->filters[i]);
280         if (ret < 0)
281             return ret;
282     }
283     }
284
285     /* go through and merge as many format lists as possible */
286     for (i = 0; i < graph->filter_count; i++) {
287         AVFilterContext *filter = graph->filters[i];
288
289         for (j = 0; j < filter->nb_inputs; j++) {
290             AVFilterLink *link = filter->inputs[j];
291 #if 0
292             if (!link) continue;
293
294             if (!link->in_formats || !link->out_formats)
295                 return AVERROR(EINVAL);
296
297             if (link->type == AVMEDIA_TYPE_VIDEO &&
298                 !avfilter_merge_formats(link->in_formats, link->out_formats)) {
299
300                 /* couldn't merge format lists, auto-insert scale filter */
301                 snprintf(filt_args, sizeof(filt_args), "0:0:%s",
302                          graph->scale_sws_opts);
303                 if (ret = insert_conv_filter(graph, link, "scale", filt_args))
304                     return ret;
305             }
306             else if (link->type == AVMEDIA_TYPE_AUDIO) {
307                 if (!link->in_channel_layouts || !link->out_channel_layouts)
308                     return AVERROR(EINVAL);
309
310                 /* Merge all three list before checking: that way, in all
311                  * three categories, aconvert will use a common format
312                  * whenever possible. */
313                 formats   = avfilter_merge_formats(link->in_formats,   link->out_formats);
314                 chlayouts   = ff_merge_channel_layouts(link->in_channel_layouts  , link->out_channel_layouts);
315                 samplerates = ff_merge_samplerates    (link->in_samplerates, link->out_samplerates);
316
317                 if (!formats || !chlayouts || !samplerates)
318                     if (ret = insert_conv_filter(graph, link, "aresample", NULL))
319                        return ret;
320 #else
321             int convert_needed = 0;
322
323             if (!link)
324                 continue;
325
326             if (link->in_formats != link->out_formats &&
327                 !ff_merge_formats(link->in_formats,
328                                         link->out_formats))
329                 convert_needed = 1;
330             if (link->type == AVMEDIA_TYPE_AUDIO) {
331                 if (link->in_channel_layouts != link->out_channel_layouts &&
332                     !ff_merge_channel_layouts(link->in_channel_layouts,
333                                               link->out_channel_layouts))
334                     convert_needed = 1;
335                 if (link->in_samplerates != link->out_samplerates &&
336                     !ff_merge_samplerates(link->in_samplerates,
337                                           link->out_samplerates))
338                     convert_needed = 1;
339             }
340
341             if (convert_needed) {
342                 AVFilterContext *convert;
343                 AVFilter *filter;
344                 AVFilterLink *inlink, *outlink;
345                 char scale_args[256];
346                 char inst_name[30];
347
348                 /* couldn't merge format lists. auto-insert conversion filter */
349                 switch (link->type) {
350                 case AVMEDIA_TYPE_VIDEO:
351                     if (!(filter = avfilter_get_by_name("scale"))) {
352                         av_log(log_ctx, AV_LOG_ERROR, "'scale' filter "
353                                "not present, cannot convert pixel formats.\n");
354                         return AVERROR(EINVAL);
355                     }
356
357                     snprintf(inst_name, sizeof(inst_name), "auto-inserted scaler %d",
358                              scaler_count++);
359                     snprintf(scale_args, sizeof(scale_args), "0:0:%s", graph->scale_sws_opts);
360                     if ((ret = avfilter_graph_create_filter(&convert, filter,
361                                                             inst_name, scale_args, NULL,
362                                                             graph)) < 0)
363                         return ret;
364                     break;
365                 case AVMEDIA_TYPE_AUDIO:
366                     if (!(filter = avfilter_get_by_name("aresample"))) {
367                         av_log(log_ctx, AV_LOG_ERROR, "'resample' filter "
368                                "not present, cannot convert audio formats.\n");
369                         return AVERROR(EINVAL);
370                     }
371
372                     snprintf(inst_name, sizeof(inst_name), "auto-inserted resampler %d",
373                              resampler_count++);
374                     if ((ret = avfilter_graph_create_filter(&convert, filter,
375                                                             inst_name, NULL, NULL, graph)) < 0)
376                         return ret;
377                     break;
378                 default:
379                     return AVERROR(EINVAL);
380                 }
381
382                 if ((ret = avfilter_insert_filter(link, convert, 0, 0)) < 0)
383                     return ret;
384
385                 filter_query_formats(convert);
386                 inlink  = convert->inputs[0];
387                 outlink = convert->outputs[0];
388                 if (!ff_merge_formats( inlink->in_formats,  inlink->out_formats) ||
389                     !ff_merge_formats(outlink->in_formats, outlink->out_formats))
390                     ret |= AVERROR(ENOSYS);
391                 if (inlink->type == AVMEDIA_TYPE_AUDIO &&
392                     (!ff_merge_samplerates(inlink->in_samplerates,
393                                            inlink->out_samplerates) ||
394                      !ff_merge_channel_layouts(inlink->in_channel_layouts,
395                                                inlink->out_channel_layouts)))
396                     ret |= AVERROR(ENOSYS);
397                 if (outlink->type == AVMEDIA_TYPE_AUDIO &&
398                     (!ff_merge_samplerates(outlink->in_samplerates,
399                                            outlink->out_samplerates) ||
400                      !ff_merge_channel_layouts(outlink->in_channel_layouts,
401                                                outlink->out_channel_layouts)))
402                     ret |= AVERROR(ENOSYS);
403
404                 if (ret < 0) {
405                     av_log(log_ctx, AV_LOG_ERROR,
406                            "Impossible to convert between the formats supported by the filter "
407                            "'%s' and the filter '%s'\n", link->src->name, link->dst->name);
408                     return ret;
409                 }
410 #endif
411             }
412         }
413     }
414
415     return 0;
416 }
417
418 static int pick_format(AVFilterLink *link, AVFilterLink *ref)
419 {
420     if (!link || !link->in_formats)
421         return 0;
422
423     if (link->type == AVMEDIA_TYPE_VIDEO) {
424         if(ref && ref->type == AVMEDIA_TYPE_VIDEO){
425             int has_alpha= av_pix_fmt_descriptors[ref->format].nb_components % 2 == 0;
426             enum PixelFormat best= PIX_FMT_NONE;
427             int i;
428             for (i=0; i<link->in_formats->format_count; i++) {
429                 enum PixelFormat p = link->in_formats->formats[i];
430                 best= avcodec_find_best_pix_fmt2(best, p, ref->format, has_alpha, NULL);
431             }
432             link->in_formats->formats[0] = best;
433         }
434     }
435
436     link->in_formats->format_count = 1;
437     link->format = link->in_formats->formats[0];
438
439     if (link->type == AVMEDIA_TYPE_AUDIO) {
440         if (!link->in_samplerates->format_count) {
441             av_log(link->src, AV_LOG_ERROR, "Cannot select sample rate for"
442                    " the link between filters %s and %s.\n", link->src->name,
443                    link->dst->name);
444             return AVERROR(EINVAL);
445         }
446         link->in_samplerates->format_count = 1;
447         link->sample_rate = link->in_samplerates->formats[0];
448
449         if (!link->in_channel_layouts->nb_channel_layouts) {
450             av_log(link->src, AV_LOG_ERROR, "Cannot select channel layout for"
451                    "the link between filters %s and %s.\n", link->src->name,
452                    link->dst->name);
453             return AVERROR(EINVAL);
454         }
455         link->in_channel_layouts->nb_channel_layouts = 1;
456         link->channel_layout = link->in_channel_layouts->channel_layouts[0];
457     }
458
459     ff_formats_unref(&link->in_formats);
460     ff_formats_unref(&link->out_formats);
461     ff_formats_unref(&link->in_samplerates);
462     ff_formats_unref(&link->out_samplerates);
463     ff_channel_layouts_unref(&link->in_channel_layouts);
464     ff_channel_layouts_unref(&link->out_channel_layouts);
465
466     return 0;
467 }
468
469 #define REDUCE_FORMATS(fmt_type, list_type, list, var, nb, add_format) \
470 do {                                                                   \
471     for (i = 0; i < filter->nb_inputs; i++) {                          \
472         AVFilterLink *link = filter->inputs[i];                        \
473         fmt_type fmt;                                                  \
474                                                                        \
475         if (!link->out_ ## list || link->out_ ## list->nb != 1)        \
476             continue;                                                  \
477         fmt = link->out_ ## list->var[0];                              \
478                                                                        \
479         for (j = 0; j < filter->nb_outputs; j++) {                     \
480             AVFilterLink *out_link = filter->outputs[j];               \
481             list_type *fmts;                                           \
482                                                                        \
483             if (link->type != out_link->type ||                        \
484                 out_link->in_ ## list->nb == 1)                        \
485                 continue;                                              \
486             fmts = out_link->in_ ## list;                              \
487                                                                        \
488             if (!out_link->in_ ## list->nb) {                          \
489                 add_format(&out_link->in_ ##list, fmt);                \
490                 break;                                                 \
491             }                                                          \
492                                                                        \
493             for (k = 0; k < out_link->in_ ## list->nb; k++)            \
494                 if (fmts->var[k] == fmt) {                             \
495                     fmts->var[0]  = fmt;                               \
496                     fmts->nb = 1;                                      \
497                     ret = 1;                                           \
498                     break;                                             \
499                 }                                                      \
500         }                                                              \
501     }                                                                  \
502 } while (0)
503
504 static int reduce_formats_on_filter(AVFilterContext *filter)
505 {
506     int i, j, k, ret = 0;
507
508     REDUCE_FORMATS(int,      AVFilterFormats,        formats,         formats,
509                    format_count, ff_add_format);
510     REDUCE_FORMATS(int,      AVFilterFormats,        samplerates,     formats,
511                    format_count, ff_add_format);
512     REDUCE_FORMATS(uint64_t, AVFilterChannelLayouts, channel_layouts,
513                    channel_layouts, nb_channel_layouts, ff_add_channel_layout);
514
515     return ret;
516 }
517
518 static void reduce_formats(AVFilterGraph *graph)
519 {
520     int i, reduced;
521
522     do {
523         reduced = 0;
524
525         for (i = 0; i < graph->filter_count; i++)
526             reduced |= reduce_formats_on_filter(graph->filters[i]);
527     } while (reduced);
528 }
529
530 static void swap_samplerates_on_filter(AVFilterContext *filter)
531 {
532     AVFilterLink *link = NULL;
533     int sample_rate;
534     int i, j;
535
536     for (i = 0; i < filter->nb_inputs; i++) {
537         link = filter->inputs[i];
538
539         if (link->type == AVMEDIA_TYPE_AUDIO &&
540             link->out_samplerates->format_count == 1)
541             break;
542     }
543     if (i == filter->nb_inputs)
544         return;
545
546     sample_rate = link->out_samplerates->formats[0];
547
548     for (i = 0; i < filter->nb_outputs; i++) {
549         AVFilterLink *outlink = filter->outputs[i];
550         int best_idx, best_diff = INT_MAX;
551
552         if (outlink->type != AVMEDIA_TYPE_AUDIO ||
553             outlink->in_samplerates->format_count < 2)
554             continue;
555
556         for (j = 0; j < outlink->in_samplerates->format_count; j++) {
557             int diff = abs(sample_rate - outlink->in_samplerates->formats[j]);
558
559             if (diff < best_diff) {
560                 best_diff = diff;
561                 best_idx  = j;
562             }
563         }
564         FFSWAP(int, outlink->in_samplerates->formats[0],
565                outlink->in_samplerates->formats[best_idx]);
566     }
567 }
568
569 static void swap_samplerates(AVFilterGraph *graph)
570 {
571     int i;
572
573     for (i = 0; i < graph->filter_count; i++)
574         swap_samplerates_on_filter(graph->filters[i]);
575 }
576
577 static void swap_channel_layouts_on_filter(AVFilterContext *filter)
578 {
579     AVFilterLink *link = NULL;
580     uint64_t chlayout;
581     int i, j;
582
583     for (i = 0; i < filter->nb_inputs; i++) {
584         link = filter->inputs[i];
585
586         if (link->type == AVMEDIA_TYPE_AUDIO &&
587             link->out_channel_layouts->nb_channel_layouts == 1)
588             break;
589     }
590     if (i == filter->nb_inputs)
591         return;
592
593     chlayout = link->out_channel_layouts->channel_layouts[0];
594
595     for (i = 0; i < filter->nb_outputs; i++) {
596         AVFilterLink *outlink = filter->outputs[i];
597         int best_idx, best_score = INT_MIN;
598
599         if (outlink->type != AVMEDIA_TYPE_AUDIO ||
600             outlink->in_channel_layouts->nb_channel_layouts < 2)
601             continue;
602
603         for (j = 0; j < outlink->in_channel_layouts->nb_channel_layouts; j++) {
604             uint64_t out_chlayout = outlink->in_channel_layouts->channel_layouts[j];
605             int matched_channels  = av_get_channel_layout_nb_channels(chlayout &
606                                                                       out_chlayout);
607             int extra_channels     = av_get_channel_layout_nb_channels(out_chlayout &
608                                                                        (~chlayout));
609             int score = matched_channels - extra_channels;
610
611             if (score > best_score) {
612                 best_score = score;
613                 best_idx   = j;
614             }
615         }
616         FFSWAP(uint64_t, outlink->in_channel_layouts->channel_layouts[0],
617                outlink->in_channel_layouts->channel_layouts[best_idx]);
618     }
619
620 }
621
622 static void swap_channel_layouts(AVFilterGraph *graph)
623 {
624     int i;
625
626     for (i = 0; i < graph->filter_count; i++)
627         swap_channel_layouts_on_filter(graph->filters[i]);
628 }
629
630 static void swap_sample_fmts_on_filter(AVFilterContext *filter)
631 {
632     AVFilterLink *link = NULL;
633     int format, bps;
634     int i, j;
635
636     for (i = 0; i < filter->nb_inputs; i++) {
637         link = filter->inputs[i];
638
639         if (link->type == AVMEDIA_TYPE_AUDIO &&
640             link->out_formats->format_count == 1)
641             break;
642     }
643     if (i == filter->nb_inputs)
644         return;
645
646     format = link->out_formats->formats[0];
647     bps    = av_get_bytes_per_sample(format);
648
649     for (i = 0; i < filter->nb_outputs; i++) {
650         AVFilterLink *outlink = filter->outputs[i];
651         int best_idx, best_score = INT_MIN;
652
653         if (outlink->type != AVMEDIA_TYPE_AUDIO ||
654             outlink->in_formats->format_count < 2)
655             continue;
656
657         for (j = 0; j < outlink->in_formats->format_count; j++) {
658             int out_format = outlink->in_formats->formats[j];
659             int out_bps    = av_get_bytes_per_sample(out_format);
660             int score;
661
662             if (av_get_packed_sample_fmt(out_format) == format ||
663                 av_get_planar_sample_fmt(out_format) == format) {
664                 best_idx   = j;
665                 break;
666             }
667
668             /* for s32 and float prefer double to prevent loss of information */
669             if (bps == 4 && out_bps == 8) {
670                 best_idx = j;
671                 break;
672             }
673
674             /* prefer closest higher or equal bps */
675             score = -abs(out_bps - bps);
676             if (out_bps >= bps)
677                 score += INT_MAX/2;
678
679             if (score > best_score) {
680                 best_score = score;
681                 best_idx   = j;
682             }
683         }
684         FFSWAP(int, outlink->in_formats->formats[0],
685                outlink->in_formats->formats[best_idx]);
686     }
687 }
688
689 static void swap_sample_fmts(AVFilterGraph *graph)
690 {
691     int i;
692
693     for (i = 0; i < graph->filter_count; i++)
694         swap_sample_fmts_on_filter(graph->filters[i]);
695
696 }
697
698 static int pick_formats(AVFilterGraph *graph)
699 {
700     int i, j, ret;
701     int change;
702
703     do{
704         change = 0;
705         for (i = 0; i < graph->filter_count; i++) {
706             AVFilterContext *filter = graph->filters[i];
707             if (filter->nb_inputs){
708                 for (j = 0; j < filter->nb_inputs; j++){
709                     if(filter->inputs[j]->in_formats && filter->inputs[j]->in_formats->format_count == 1) {
710                         pick_format(filter->inputs[j], NULL);
711                         change = 1;
712                     }
713                 }
714             }
715             if (filter->nb_outputs){
716                 for (j = 0; j < filter->nb_outputs; j++){
717                     if(filter->outputs[j]->in_formats && filter->outputs[j]->in_formats->format_count == 1) {
718                         pick_format(filter->outputs[j], NULL);
719                         change = 1;
720                     }
721                 }
722             }
723             if (filter->nb_inputs && filter->nb_outputs && filter->inputs[0]->format>=0) {
724                 for (j = 0; j < filter->nb_outputs; j++) {
725                     if(filter->outputs[j]->format<0) {
726                         pick_format(filter->outputs[j], filter->inputs[0]);
727                         change = 1;
728                     }
729                 }
730             }
731         }
732     }while(change);
733
734     for (i = 0; i < graph->filter_count; i++) {
735         AVFilterContext *filter = graph->filters[i];
736
737         for (j = 0; j < filter->nb_inputs; j++)
738             if ((ret = pick_format(filter->inputs[j], NULL)) < 0)
739                 return ret;
740         for (j = 0; j < filter->nb_outputs; j++)
741             if ((ret = pick_format(filter->outputs[j], NULL)) < 0)
742                 return ret;
743     }
744     return 0;
745 }
746
747 /**
748  * Configure the formats of all the links in the graph.
749  */
750 static int graph_config_formats(AVFilterGraph *graph, AVClass *log_ctx)
751 {
752     int ret;
753
754     /* find supported formats from sub-filters, and merge along links */
755     if ((ret = query_formats(graph, log_ctx)) < 0)
756         return ret;
757
758     /* Once everything is merged, it's possible that we'll still have
759      * multiple valid media format choices. We try to minimize the amount
760      * of format conversion inside filters */
761     reduce_formats(graph);
762
763     /* for audio filters, ensure the best format, sample rate and channel layout
764      * is selected */
765     swap_sample_fmts(graph);
766     swap_samplerates(graph);
767     swap_channel_layouts(graph);
768
769     if ((ret = pick_formats(graph)) < 0)
770         return ret;
771
772     return 0;
773 }
774
775 static int ff_avfilter_graph_config_pointers(AVFilterGraph *graph,
776                                              AVClass *log_ctx)
777 {
778     unsigned i, j;
779     int sink_links_count = 0, n = 0;
780     AVFilterContext *f;
781     AVFilterLink **sinks;
782
783     for (i = 0; i < graph->filter_count; i++) {
784         f = graph->filters[i];
785         for (j = 0; j < f->nb_inputs; j++) {
786             f->inputs[j]->graph     = graph;
787             f->inputs[j]->age_index = -1;
788         }
789         for (j = 0; j < f->nb_outputs; j++) {
790             f->outputs[j]->graph    = graph;
791             f->outputs[j]->age_index= -1;
792         }
793         if (!f->nb_outputs) {
794             if (f->nb_inputs > INT_MAX - sink_links_count)
795                 return AVERROR(EINVAL);
796             sink_links_count += f->nb_inputs;
797         }
798     }
799     sinks = av_calloc(sink_links_count, sizeof(*sinks));
800     if (!sinks)
801         return AVERROR(ENOMEM);
802     for (i = 0; i < graph->filter_count; i++) {
803         f = graph->filters[i];
804         if (!f->nb_outputs) {
805             for (j = 0; j < f->nb_inputs; j++) {
806                 sinks[n] = f->inputs[j];
807                 f->inputs[j]->age_index = n++;
808             }
809         }
810     }
811     av_assert0(n == sink_links_count);
812     graph->sink_links       = sinks;
813     graph->sink_links_count = sink_links_count;
814     return 0;
815 }
816
817 int avfilter_graph_config(AVFilterGraph *graphctx, void *log_ctx)
818 {
819     int ret;
820
821     if ((ret = graph_check_validity(graphctx, log_ctx)))
822         return ret;
823     if ((ret = graph_config_formats(graphctx, log_ctx)))
824         return ret;
825     if ((ret = graph_config_links(graphctx, log_ctx)))
826         return ret;
827     if ((ret = ff_avfilter_graph_config_pointers(graphctx, log_ctx)))
828         return ret;
829
830     return 0;
831 }
832
833 int avfilter_graph_send_command(AVFilterGraph *graph, const char *target, const char *cmd, const char *arg, char *res, int res_len, int flags)
834 {
835     int i, r = AVERROR(ENOSYS);
836
837     if(!graph)
838         return r;
839
840     if((flags & AVFILTER_CMD_FLAG_ONE) && !(flags & AVFILTER_CMD_FLAG_FAST)) {
841         r=avfilter_graph_send_command(graph, target, cmd, arg, res, res_len, flags | AVFILTER_CMD_FLAG_FAST);
842         if(r != AVERROR(ENOSYS))
843             return r;
844     }
845
846     if(res_len && res)
847         res[0]= 0;
848
849     for (i = 0; i < graph->filter_count; i++) {
850         AVFilterContext *filter = graph->filters[i];
851         if(!strcmp(target, "all") || (filter->name && !strcmp(target, filter->name)) || !strcmp(target, filter->filter->name)){
852             r = avfilter_process_command(filter, cmd, arg, res, res_len, flags);
853             if(r != AVERROR(ENOSYS)) {
854                 if((flags & AVFILTER_CMD_FLAG_ONE) || r<0)
855                     return r;
856             }
857         }
858     }
859
860     return r;
861 }
862
863 int avfilter_graph_queue_command(AVFilterGraph *graph, const char *target, const char *command, const char *arg, int flags, double ts)
864 {
865     int i;
866
867     if(!graph)
868         return 0;
869
870     for (i = 0; i < graph->filter_count; i++) {
871         AVFilterContext *filter = graph->filters[i];
872         if(filter && (!strcmp(target, "all") || !strcmp(target, filter->name) || !strcmp(target, filter->filter->name))){
873             AVFilterCommand **que = &filter->command_queue, *next;
874             while(*que && (*que)->time <= ts)
875                 que = &(*que)->next;
876             next= *que;
877             *que= av_mallocz(sizeof(AVFilterCommand));
878             (*que)->command = av_strdup(command);
879             (*que)->arg     = av_strdup(arg);
880             (*que)->time    = ts;
881             (*que)->flags   = flags;
882             (*que)->next    = next;
883             if(flags & AVFILTER_CMD_FLAG_ONE)
884                 return 0;
885         }
886     }
887
888     return 0;
889 }
890
891 static void heap_bubble_up(AVFilterGraph *graph,
892                            AVFilterLink *link, int index)
893 {
894     AVFilterLink **links = graph->sink_links;
895
896     while (index) {
897         int parent = (index - 1) >> 1;
898         if (links[parent]->current_pts >= link->current_pts)
899             break;
900         links[index] = links[parent];
901         links[index]->age_index = index;
902         index = parent;
903     }
904     links[index] = link;
905     link->age_index = index;
906 }
907
908 static void heap_bubble_down(AVFilterGraph *graph,
909                              AVFilterLink *link, int index)
910 {
911     AVFilterLink **links = graph->sink_links;
912
913     while (1) {
914         int child = 2 * index + 1;
915         if (child >= graph->sink_links_count)
916             break;
917         if (child + 1 < graph->sink_links_count &&
918             links[child + 1]->current_pts < links[child]->current_pts)
919             child++;
920         if (link->current_pts < links[child]->current_pts)
921             break;
922         links[index] = links[child];
923         links[index]->age_index = index;
924         index = child;
925     }
926     links[index] = link;
927     link->age_index = index;
928 }
929
930 void ff_avfilter_graph_update_heap(AVFilterGraph *graph, AVFilterLink *link)
931 {
932     heap_bubble_up  (graph, link, link->age_index);
933     heap_bubble_down(graph, link, link->age_index);
934 }
935
936
937 int avfilter_graph_request_oldest(AVFilterGraph *graph)
938 {
939     while (graph->sink_links_count) {
940         AVFilterLink *oldest = graph->sink_links[0];
941         int r = avfilter_request_frame(oldest);
942         if (r != AVERROR_EOF)
943             return r;
944         /* EOF: remove the link from the heap */
945         if (oldest->age_index < --graph->sink_links_count)
946             heap_bubble_down(graph, graph->sink_links[graph->sink_links_count],
947                              oldest->age_index);
948         oldest->age_index = -1;
949     }
950     return AVERROR_EOF;
951 }