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