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