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