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