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