]> git.sesse.net Git - ffmpeg/blob - libavfilter/avfiltergraph.c
09bbe106cf1c186dfee87c50c8447000539afcd7
[ffmpeg] / libavfilter / avfiltergraph.c
1 /*
2  * filter graphs
3  * Copyright (c) 2008 Vitor Sessak
4  * Copyright (c) 2007 Bobby Bingham
5  *
6  * This file is part of FFmpeg.
7  *
8  * FFmpeg is free software; you can redistribute it and/or
9  * modify it under the terms of the GNU Lesser General Public
10  * License as published by the Free Software Foundation; either
11  * version 2.1 of the License, or (at your option) any later version.
12  *
13  * FFmpeg is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
16  * Lesser General Public License for more details.
17  *
18  * You should have received a copy of the GNU Lesser General Public
19  * License along with FFmpeg; if not, write to the Free Software
20  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
21  */
22
23 #include <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->input_count; 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->output_count; 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->output_count) {
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]->input_count == 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->input_count; 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                     snprintf(inst_name, sizeof(inst_name), "auto-inserted scaler %d",
352                              scaler_count++);
353                     snprintf(scale_args, sizeof(scale_args), "0:0:%s", graph->scale_sws_opts);
354                     if ((ret = avfilter_graph_create_filter(&convert,
355                                                             avfilter_get_by_name("scale"),
356                                                             inst_name, scale_args, NULL,
357                                                             graph)) < 0)
358                         return ret;
359                     break;
360                 case AVMEDIA_TYPE_AUDIO:
361                     if (!(filter = avfilter_get_by_name("aresample"))) {
362                         av_log(log_ctx, AV_LOG_ERROR, "'resample' filter "
363                                "not present, cannot convert audio formats.\n");
364                         return AVERROR(EINVAL);
365                     }
366
367                     snprintf(inst_name, sizeof(inst_name), "auto-inserted resampler %d",
368                              resampler_count++);
369                     if ((ret = avfilter_graph_create_filter(&convert,
370                                                             avfilter_get_by_name("aresample"),
371                                                             inst_name, NULL, NULL, graph)) < 0)
372                         return ret;
373                     break;
374                 default:
375                     return AVERROR(EINVAL);
376                 }
377
378                 if ((ret = avfilter_insert_filter(link, convert, 0, 0)) < 0)
379                     return ret;
380
381                 filter_query_formats(convert);
382                 inlink  = convert->inputs[0];
383                 outlink = convert->outputs[0];
384                 if (!ff_merge_formats( inlink->in_formats,  inlink->out_formats) ||
385                     !ff_merge_formats(outlink->in_formats, outlink->out_formats))
386                     ret |= AVERROR(ENOSYS);
387                 if (inlink->type == AVMEDIA_TYPE_AUDIO &&
388                     (!ff_merge_samplerates(inlink->in_samplerates,
389                                            inlink->out_samplerates) ||
390                      !ff_merge_channel_layouts(inlink->in_channel_layouts,
391                                                inlink->out_channel_layouts)))
392                     ret |= AVERROR(ENOSYS);
393                 if (outlink->type == AVMEDIA_TYPE_AUDIO &&
394                     (!ff_merge_samplerates(outlink->in_samplerates,
395                                            outlink->out_samplerates) ||
396                      !ff_merge_channel_layouts(outlink->in_channel_layouts,
397                                                outlink->out_channel_layouts)))
398                     ret |= AVERROR(ENOSYS);
399
400                 if (ret < 0) {
401                     av_log(log_ctx, AV_LOG_ERROR,
402                            "Impossible to convert between the formats supported by the filter "
403                            "'%s' and the filter '%s'\n", link->src->name, link->dst->name);
404                     return ret;
405                 }
406 #endif
407             }
408         }
409     }
410
411     return 0;
412 }
413
414 static int pick_format(AVFilterLink *link, AVFilterLink *ref)
415 {
416     if (!link || !link->in_formats)
417         return 0;
418
419     if (link->type == AVMEDIA_TYPE_VIDEO) {
420         if(ref && ref->type == AVMEDIA_TYPE_VIDEO){
421             int has_alpha= av_pix_fmt_descriptors[ref->format].nb_components % 2 == 0;
422             enum PixelFormat best= PIX_FMT_NONE;
423             int i;
424             for (i=0; i<link->in_formats->format_count; i++) {
425                 enum PixelFormat p = link->in_formats->formats[i];
426                 best= avcodec_find_best_pix_fmt2(best, p, ref->format, has_alpha, NULL);
427             }
428             link->in_formats->formats[0] = best;
429         }
430     }
431
432     link->in_formats->format_count = 1;
433     link->format = link->in_formats->formats[0];
434
435     if (link->type == AVMEDIA_TYPE_AUDIO) {
436         if (!link->in_samplerates->format_count) {
437             av_log(link->src, AV_LOG_ERROR, "Cannot select sample rate for"
438                    " the link between filters %s and %s.\n", link->src->name,
439                    link->dst->name);
440             return AVERROR(EINVAL);
441         }
442         link->in_samplerates->format_count = 1;
443         link->sample_rate = link->in_samplerates->formats[0];
444
445         if (!link->in_channel_layouts->nb_channel_layouts) {
446             av_log(link->src, AV_LOG_ERROR, "Cannot select channel layout for"
447                    "the link between filters %s and %s.\n", link->src->name,
448                    link->dst->name);
449             return AVERROR(EINVAL);
450         }
451         link->in_channel_layouts->nb_channel_layouts = 1;
452         link->channel_layout = link->in_channel_layouts->channel_layouts[0];
453     }
454
455     ff_formats_unref(&link->in_formats);
456     ff_formats_unref(&link->out_formats);
457     ff_formats_unref(&link->in_samplerates);
458     ff_formats_unref(&link->out_samplerates);
459     ff_channel_layouts_unref(&link->in_channel_layouts);
460     ff_channel_layouts_unref(&link->out_channel_layouts);
461
462     return 0;
463 }
464
465 #define REDUCE_FORMATS(fmt_type, list_type, list, var, nb, add_format) \
466 do {                                                                   \
467     for (i = 0; i < filter->input_count; i++) {                        \
468         AVFilterLink *link = filter->inputs[i];                        \
469         fmt_type fmt;                                                  \
470                                                                        \
471         if (!link->out_ ## list || link->out_ ## list->nb != 1)        \
472             continue;                                                  \
473         fmt = link->out_ ## list->var[0];                              \
474                                                                        \
475         for (j = 0; j < filter->output_count; j++) {                   \
476             AVFilterLink *out_link = filter->outputs[j];               \
477             list_type *fmts;                                           \
478                                                                        \
479             if (link->type != out_link->type ||                        \
480                 out_link->in_ ## list->nb == 1)                        \
481                 continue;                                              \
482             fmts = out_link->in_ ## list;                              \
483                                                                        \
484             if (!out_link->in_ ## list->nb) {                          \
485                 add_format(&out_link->in_ ##list, fmt);                \
486                 break;                                                 \
487             }                                                          \
488                                                                        \
489             for (k = 0; k < out_link->in_ ## list->nb; k++)            \
490                 if (fmts->var[k] == fmt) {                             \
491                     fmts->var[0]  = fmt;                               \
492                     fmts->nb = 1;                                      \
493                     ret = 1;                                           \
494                     break;                                             \
495                 }                                                      \
496         }                                                              \
497     }                                                                  \
498 } while (0)
499
500 static int reduce_formats_on_filter(AVFilterContext *filter)
501 {
502     int i, j, k, ret = 0;
503
504     REDUCE_FORMATS(int,      AVFilterFormats,        formats,         formats,
505                    format_count, ff_add_format);
506     REDUCE_FORMATS(int,      AVFilterFormats,        samplerates,     formats,
507                    format_count, ff_add_format);
508     REDUCE_FORMATS(uint64_t, AVFilterChannelLayouts, channel_layouts,
509                    channel_layouts, nb_channel_layouts, ff_add_channel_layout);
510
511     return ret;
512 }
513
514 static void reduce_formats(AVFilterGraph *graph)
515 {
516     int i, reduced;
517
518     do {
519         reduced = 0;
520
521         for (i = 0; i < graph->filter_count; i++)
522             reduced |= reduce_formats_on_filter(graph->filters[i]);
523     } while (reduced);
524 }
525
526 static void swap_samplerates_on_filter(AVFilterContext *filter)
527 {
528     AVFilterLink *link = NULL;
529     int sample_rate;
530     int i, j;
531
532     for (i = 0; i < filter->input_count; i++) {
533         link = filter->inputs[i];
534
535         if (link->type == AVMEDIA_TYPE_AUDIO &&
536             link->out_samplerates->format_count == 1)
537             break;
538     }
539     if (i == filter->input_count)
540         return;
541
542     sample_rate = link->out_samplerates->formats[0];
543
544     for (i = 0; i < filter->output_count; i++) {
545         AVFilterLink *outlink = filter->outputs[i];
546         int best_idx, best_diff = INT_MAX;
547
548         if (outlink->type != AVMEDIA_TYPE_AUDIO ||
549             outlink->in_samplerates->format_count < 2)
550             continue;
551
552         for (j = 0; j < outlink->in_samplerates->format_count; j++) {
553             int diff = abs(sample_rate - outlink->in_samplerates->formats[j]);
554
555             if (diff < best_diff) {
556                 best_diff = diff;
557                 best_idx  = j;
558             }
559         }
560         FFSWAP(int, outlink->in_samplerates->formats[0],
561                outlink->in_samplerates->formats[best_idx]);
562     }
563 }
564
565 static void swap_samplerates(AVFilterGraph *graph)
566 {
567     int i;
568
569     for (i = 0; i < graph->filter_count; i++)
570         swap_samplerates_on_filter(graph->filters[i]);
571 }
572
573 static void swap_channel_layouts_on_filter(AVFilterContext *filter)
574 {
575     AVFilterLink *link = NULL;
576     uint64_t chlayout;
577     int i, j;
578
579     for (i = 0; i < filter->input_count; i++) {
580         link = filter->inputs[i];
581
582         if (link->type == AVMEDIA_TYPE_AUDIO &&
583             link->out_channel_layouts->nb_channel_layouts == 1)
584             break;
585     }
586     if (i == filter->input_count)
587         return;
588
589     chlayout = link->out_channel_layouts->channel_layouts[0];
590
591     for (i = 0; i < filter->output_count; i++) {
592         AVFilterLink *outlink = filter->outputs[i];
593         int best_idx, best_score = INT_MIN;
594
595         if (outlink->type != AVMEDIA_TYPE_AUDIO ||
596             outlink->in_channel_layouts->nb_channel_layouts < 2)
597             continue;
598
599         for (j = 0; j < outlink->in_channel_layouts->nb_channel_layouts; j++) {
600             uint64_t out_chlayout = outlink->in_channel_layouts->channel_layouts[j];
601             int matched_channels  = av_get_channel_layout_nb_channels(chlayout &
602                                                                       out_chlayout);
603             int extra_channels     = av_get_channel_layout_nb_channels(out_chlayout &
604                                                                        (~chlayout));
605             int score = matched_channels - extra_channels;
606
607             if (score > best_score) {
608                 best_score = score;
609                 best_idx   = j;
610             }
611         }
612         FFSWAP(uint64_t, outlink->in_channel_layouts->channel_layouts[0],
613                outlink->in_channel_layouts->channel_layouts[best_idx]);
614     }
615
616 }
617
618 static void swap_channel_layouts(AVFilterGraph *graph)
619 {
620     int i;
621
622     for (i = 0; i < graph->filter_count; i++)
623         swap_channel_layouts_on_filter(graph->filters[i]);
624 }
625
626 static void swap_sample_fmts_on_filter(AVFilterContext *filter)
627 {
628     AVFilterLink *link = NULL;
629     int format, bps;
630     int i, j;
631
632     for (i = 0; i < filter->input_count; i++) {
633         link = filter->inputs[i];
634
635         if (link->type == AVMEDIA_TYPE_AUDIO &&
636             link->out_formats->format_count == 1)
637             break;
638     }
639     if (i == filter->input_count)
640         return;
641
642     format = link->out_formats->formats[0];
643     bps    = av_get_bytes_per_sample(format);
644
645     for (i = 0; i < filter->output_count; i++) {
646         AVFilterLink *outlink = filter->outputs[i];
647         int best_idx, best_score = INT_MIN;
648
649         if (outlink->type != AVMEDIA_TYPE_AUDIO ||
650             outlink->in_formats->format_count < 2)
651             continue;
652
653         for (j = 0; j < outlink->in_formats->format_count; j++) {
654             int out_format = outlink->in_formats->formats[j];
655             int out_bps    = av_get_bytes_per_sample(out_format);
656             int score;
657
658             if (av_get_packed_sample_fmt(out_format) == format ||
659                 av_get_planar_sample_fmt(out_format) == format) {
660                 best_idx   = j;
661                 break;
662             }
663
664             /* for s32 and float prefer double to prevent loss of information */
665             if (bps == 4 && out_bps == 8) {
666                 best_idx = j;
667                 break;
668             }
669
670             /* prefer closest higher or equal bps */
671             score = -abs(out_bps - bps);
672             if (out_bps >= bps)
673                 score += INT_MAX/2;
674
675             if (score > best_score) {
676                 best_score = score;
677                 best_idx   = j;
678             }
679         }
680         FFSWAP(int, outlink->in_formats->formats[0],
681                outlink->in_formats->formats[best_idx]);
682     }
683 }
684
685 static void swap_sample_fmts(AVFilterGraph *graph)
686 {
687     int i;
688
689     for (i = 0; i < graph->filter_count; i++)
690         swap_sample_fmts_on_filter(graph->filters[i]);
691
692 }
693
694 static int pick_formats(AVFilterGraph *graph)
695 {
696     int i, j, ret;
697     int change;
698
699     do{
700         change = 0;
701         for (i = 0; i < graph->filter_count; i++) {
702             AVFilterContext *filter = graph->filters[i];
703             if (filter->input_count){
704                 for (j = 0; j < filter->input_count; j++){
705                     if(filter->inputs[j]->in_formats && filter->inputs[j]->in_formats->format_count == 1) {
706                         pick_format(filter->inputs[j], NULL);
707                         change = 1;
708                     }
709                 }
710             }
711             if (filter->output_count){
712                 for (j = 0; j < filter->output_count; j++){
713                     if(filter->outputs[j]->in_formats && filter->outputs[j]->in_formats->format_count == 1) {
714                         pick_format(filter->outputs[j], NULL);
715                         change = 1;
716                     }
717                 }
718             }
719             if (filter->input_count && filter->output_count && filter->inputs[0]->format>=0) {
720                 for (j = 0; j < filter->output_count; j++) {
721                     if(filter->outputs[j]->format<0) {
722                         pick_format(filter->outputs[j], filter->inputs[0]);
723                         change = 1;
724                     }
725                 }
726             }
727         }
728     }while(change);
729
730     for (i = 0; i < graph->filter_count; i++) {
731         AVFilterContext *filter = graph->filters[i];
732
733         for (j = 0; j < filter->input_count; j++)
734             if ((ret = pick_format(filter->inputs[j], NULL)) < 0)
735                 return ret;
736         for (j = 0; j < filter->output_count; j++)
737             if ((ret = pick_format(filter->outputs[j], NULL)) < 0)
738                 return ret;
739     }
740     return 0;
741 }
742
743 /**
744  * Configure the formats of all the links in the graph.
745  */
746 static int graph_config_formats(AVFilterGraph *graph, AVClass *log_ctx)
747 {
748     int ret;
749
750     /* find supported formats from sub-filters, and merge along links */
751     if ((ret = query_formats(graph, log_ctx)) < 0)
752         return ret;
753
754     /* Once everything is merged, it's possible that we'll still have
755      * multiple valid media format choices. We try to minimize the amount
756      * of format conversion inside filters */
757     reduce_formats(graph);
758
759     /* for audio filters, ensure the best format, sample rate and channel layout
760      * is selected */
761     swap_sample_fmts(graph);
762     swap_samplerates(graph);
763     swap_channel_layouts(graph);
764
765     if ((ret = pick_formats(graph)) < 0)
766         return ret;
767
768     return 0;
769 }
770
771 static int ff_avfilter_graph_config_pointers(AVFilterGraph *graph,
772                                              AVClass *log_ctx)
773 {
774     unsigned i, j;
775     int sink_links_count = 0, n = 0;
776     AVFilterContext *f;
777     AVFilterLink **sinks;
778
779     for (i = 0; i < graph->filter_count; i++) {
780         f = graph->filters[i];
781         for (j = 0; j < f->input_count; j++) {
782             f->inputs[j]->graph     = graph;
783             f->inputs[j]->age_index = -1;
784         }
785         for (j = 0; j < f->output_count; j++) {
786             f->outputs[j]->graph    = graph;
787             f->outputs[j]->age_index= -1;
788         }
789         if (!f->output_count) {
790             if (f->input_count > INT_MAX - sink_links_count)
791                 return AVERROR(EINVAL);
792             sink_links_count += f->input_count;
793         }
794     }
795     sinks = av_calloc(sink_links_count, sizeof(*sinks));
796     if (!sinks)
797         return AVERROR(ENOMEM);
798     for (i = 0; i < graph->filter_count; i++) {
799         f = graph->filters[i];
800         if (!f->output_count) {
801             for (j = 0; j < f->input_count; j++) {
802                 sinks[n] = f->inputs[j];
803                 f->inputs[j]->age_index = n++;
804             }
805         }
806     }
807     av_assert0(n == sink_links_count);
808     graph->sink_links       = sinks;
809     graph->sink_links_count = sink_links_count;
810     return 0;
811 }
812
813 int avfilter_graph_config(AVFilterGraph *graphctx, void *log_ctx)
814 {
815     int ret;
816
817     if ((ret = graph_check_validity(graphctx, log_ctx)))
818         return ret;
819     if ((ret = graph_config_formats(graphctx, log_ctx)))
820         return ret;
821     if ((ret = graph_config_links(graphctx, log_ctx)))
822         return ret;
823     if ((ret = ff_avfilter_graph_config_pointers(graphctx, log_ctx)))
824         return ret;
825
826     return 0;
827 }
828
829 int avfilter_graph_send_command(AVFilterGraph *graph, const char *target, const char *cmd, const char *arg, char *res, int res_len, int flags)
830 {
831     int i, r = AVERROR(ENOSYS);
832
833     if(!graph)
834         return r;
835
836     if((flags & AVFILTER_CMD_FLAG_ONE) && !(flags & AVFILTER_CMD_FLAG_FAST)) {
837         r=avfilter_graph_send_command(graph, target, cmd, arg, res, res_len, flags | AVFILTER_CMD_FLAG_FAST);
838         if(r != AVERROR(ENOSYS))
839             return r;
840     }
841
842     if(res_len && res)
843         res[0]= 0;
844
845     for (i = 0; i < graph->filter_count; i++) {
846         AVFilterContext *filter = graph->filters[i];
847         if(!strcmp(target, "all") || (filter->name && !strcmp(target, filter->name)) || !strcmp(target, filter->filter->name)){
848             r = avfilter_process_command(filter, cmd, arg, res, res_len, flags);
849             if(r != AVERROR(ENOSYS)) {
850                 if((flags & AVFILTER_CMD_FLAG_ONE) || r<0)
851                     return r;
852             }
853         }
854     }
855
856     return r;
857 }
858
859 int avfilter_graph_queue_command(AVFilterGraph *graph, const char *target, const char *command, const char *arg, int flags, double ts)
860 {
861     int i;
862
863     if(!graph)
864         return 0;
865
866     for (i = 0; i < graph->filter_count; i++) {
867         AVFilterContext *filter = graph->filters[i];
868         if(filter && (!strcmp(target, "all") || !strcmp(target, filter->name) || !strcmp(target, filter->filter->name))){
869             AVFilterCommand **que = &filter->command_queue, *next;
870             while(*que && (*que)->time <= ts)
871                 que = &(*que)->next;
872             next= *que;
873             *que= av_mallocz(sizeof(AVFilterCommand));
874             (*que)->command = av_strdup(command);
875             (*que)->arg     = av_strdup(arg);
876             (*que)->time    = ts;
877             (*que)->flags   = flags;
878             (*que)->next    = next;
879             if(flags & AVFILTER_CMD_FLAG_ONE)
880                 return 0;
881         }
882     }
883
884     return 0;
885 }
886
887 static void heap_bubble_up(AVFilterGraph *graph,
888                            AVFilterLink *link, int index)
889 {
890     AVFilterLink **links = graph->sink_links;
891
892     while (index) {
893         int parent = (index - 1) >> 1;
894         if (links[parent]->current_pts >= link->current_pts)
895             break;
896         links[index] = links[parent];
897         links[index]->age_index = index;
898         index = parent;
899     }
900     links[index] = link;
901     link->age_index = index;
902 }
903
904 static void heap_bubble_down(AVFilterGraph *graph,
905                              AVFilterLink *link, int index)
906 {
907     AVFilterLink **links = graph->sink_links;
908
909     while (1) {
910         int child = 2 * index + 1;
911         if (child >= graph->sink_links_count)
912             break;
913         if (child + 1 < graph->sink_links_count &&
914             links[child + 1]->current_pts < links[child]->current_pts)
915             child++;
916         if (link->current_pts < links[child]->current_pts)
917             break;
918         links[index] = links[child];
919         links[index]->age_index = index;
920         index = child;
921     }
922     links[index] = link;
923     link->age_index = index;
924 }
925
926 void ff_avfilter_graph_update_heap(AVFilterGraph *graph, AVFilterLink *link)
927 {
928     heap_bubble_up  (graph, link, link->age_index);
929     heap_bubble_down(graph, link, link->age_index);
930 }
931
932
933 int avfilter_graph_request_oldest(AVFilterGraph *graph)
934 {
935     while (graph->sink_links_count) {
936         AVFilterLink *oldest = graph->sink_links[0];
937         int r = avfilter_request_frame(oldest);
938         if (r != AVERROR_EOF)
939             return r;
940         /* EOF: remove the link from the heap */
941         if (oldest->age_index < --graph->sink_links_count)
942             heap_bubble_down(graph, graph->sink_links[graph->sink_links_count],
943                              oldest->age_index);
944         oldest->age_index = -1;
945     }
946     return AVERROR_EOF;
947 }