lavfi: make filter_frame non-recursive.
[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 "config.h"
24
25 #include <string.h>
26
27 #include "libavutil/avassert.h"
28 #include "libavutil/avstring.h"
29 #include "libavutil/bprint.h"
30 #include "libavutil/channel_layout.h"
31 #include "libavutil/internal.h"
32 #include "libavutil/opt.h"
33 #include "libavutil/pixdesc.h"
34
35 #define FF_INTERNAL_FIELDS 1
36 #include "framequeue.h"
37
38 #include "avfilter.h"
39 #include "formats.h"
40 #include "internal.h"
41 #include "thread.h"
42
43 #define OFFSET(x) offsetof(AVFilterGraph, x)
44 #define FLAGS AV_OPT_FLAG_VIDEO_PARAM|AV_OPT_FLAG_FILTERING_PARAM
45 static const AVOption filtergraph_options[] = {
46     { "thread_type", "Allowed thread types", OFFSET(thread_type), AV_OPT_TYPE_FLAGS,
47         { .i64 = AVFILTER_THREAD_SLICE }, 0, INT_MAX, FLAGS, "thread_type" },
48         { "slice", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = AVFILTER_THREAD_SLICE }, .flags = FLAGS, .unit = "thread_type" },
49     { "threads",     "Maximum number of threads", OFFSET(nb_threads),
50         AV_OPT_TYPE_INT,   { .i64 = 0 }, 0, INT_MAX, FLAGS },
51     {"scale_sws_opts"       , "default scale filter options"        , OFFSET(scale_sws_opts)        ,
52         AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, FLAGS },
53     {"aresample_swr_opts"   , "default aresample filter options"    , OFFSET(aresample_swr_opts)    ,
54         AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, FLAGS },
55     { NULL },
56 };
57
58 static const AVClass filtergraph_class = {
59     .class_name = "AVFilterGraph",
60     .item_name  = av_default_item_name,
61     .version    = LIBAVUTIL_VERSION_INT,
62     .option     = filtergraph_options,
63     .category   = AV_CLASS_CATEGORY_FILTER,
64 };
65
66 #if !HAVE_THREADS
67 void ff_graph_thread_free(AVFilterGraph *graph)
68 {
69 }
70
71 int ff_graph_thread_init(AVFilterGraph *graph)
72 {
73     graph->thread_type = 0;
74     graph->nb_threads  = 1;
75     return 0;
76 }
77 #endif
78
79 AVFilterGraph *avfilter_graph_alloc(void)
80 {
81     AVFilterGraph *ret = av_mallocz(sizeof(*ret));
82     if (!ret)
83         return NULL;
84
85     ret->internal = av_mallocz(sizeof(*ret->internal));
86     if (!ret->internal) {
87         av_freep(&ret);
88         return NULL;
89     }
90
91     ret->av_class = &filtergraph_class;
92     av_opt_set_defaults(ret);
93     ff_framequeue_global_init(&ret->internal->frame_queues);
94
95     return ret;
96 }
97
98 void ff_filter_graph_remove_filter(AVFilterGraph *graph, AVFilterContext *filter)
99 {
100     int i, j;
101     for (i = 0; i < graph->nb_filters; i++) {
102         if (graph->filters[i] == filter) {
103             FFSWAP(AVFilterContext*, graph->filters[i],
104                    graph->filters[graph->nb_filters - 1]);
105             graph->nb_filters--;
106             filter->graph = NULL;
107             for (j = 0; j<filter->nb_outputs; j++)
108                 if (filter->outputs[j])
109                     filter->outputs[j]->graph = NULL;
110
111             return;
112         }
113     }
114 }
115
116 void avfilter_graph_free(AVFilterGraph **graph)
117 {
118     if (!*graph)
119         return;
120
121     while ((*graph)->nb_filters)
122         avfilter_free((*graph)->filters[0]);
123
124     ff_graph_thread_free(*graph);
125
126     av_freep(&(*graph)->sink_links);
127
128     av_freep(&(*graph)->scale_sws_opts);
129     av_freep(&(*graph)->aresample_swr_opts);
130     av_freep(&(*graph)->resample_lavr_opts);
131     av_freep(&(*graph)->filters);
132     av_freep(&(*graph)->internal);
133     av_freep(graph);
134 }
135
136 #if FF_API_AVFILTER_OPEN
137 int avfilter_graph_add_filter(AVFilterGraph *graph, AVFilterContext *filter)
138 {
139     AVFilterContext **filters = av_realloc(graph->filters,
140                                            sizeof(*filters) * (graph->nb_filters + 1));
141     if (!filters)
142         return AVERROR(ENOMEM);
143
144     graph->filters = filters;
145     graph->filters[graph->nb_filters++] = filter;
146
147     filter->graph = graph;
148
149     return 0;
150 }
151 #endif
152
153 int avfilter_graph_create_filter(AVFilterContext **filt_ctx, const AVFilter *filt,
154                                  const char *name, const char *args, void *opaque,
155                                  AVFilterGraph *graph_ctx)
156 {
157     int ret;
158
159     *filt_ctx = avfilter_graph_alloc_filter(graph_ctx, filt, name);
160     if (!*filt_ctx)
161         return AVERROR(ENOMEM);
162
163     ret = avfilter_init_str(*filt_ctx, args);
164     if (ret < 0)
165         goto fail;
166
167     return 0;
168
169 fail:
170     if (*filt_ctx)
171         avfilter_free(*filt_ctx);
172     *filt_ctx = NULL;
173     return ret;
174 }
175
176 void avfilter_graph_set_auto_convert(AVFilterGraph *graph, unsigned flags)
177 {
178     graph->disable_auto_convert = flags;
179 }
180
181 AVFilterContext *avfilter_graph_alloc_filter(AVFilterGraph *graph,
182                                              const AVFilter *filter,
183                                              const char *name)
184 {
185     AVFilterContext **filters, *s;
186
187     if (graph->thread_type && !graph->internal->thread_execute) {
188         if (graph->execute) {
189             graph->internal->thread_execute = graph->execute;
190         } else {
191             int ret = ff_graph_thread_init(graph);
192             if (ret < 0) {
193                 av_log(graph, AV_LOG_ERROR, "Error initializing threading.\n");
194                 return NULL;
195             }
196         }
197     }
198
199     s = ff_filter_alloc(filter, name);
200     if (!s)
201         return NULL;
202
203     filters = av_realloc(graph->filters, sizeof(*filters) * (graph->nb_filters + 1));
204     if (!filters) {
205         avfilter_free(s);
206         return NULL;
207     }
208
209     graph->filters = filters;
210     graph->filters[graph->nb_filters++] = s;
211
212     s->graph = graph;
213
214     return s;
215 }
216
217 /**
218  * Check for the validity of graph.
219  *
220  * A graph is considered valid if all its input and output pads are
221  * connected.
222  *
223  * @return >= 0 in case of success, a negative value otherwise
224  */
225 static int graph_check_validity(AVFilterGraph *graph, AVClass *log_ctx)
226 {
227     AVFilterContext *filt;
228     int i, j;
229
230     for (i = 0; i < graph->nb_filters; i++) {
231         const AVFilterPad *pad;
232         filt = graph->filters[i];
233
234         for (j = 0; j < filt->nb_inputs; j++) {
235             if (!filt->inputs[j] || !filt->inputs[j]->src) {
236                 pad = &filt->input_pads[j];
237                 av_log(log_ctx, AV_LOG_ERROR,
238                        "Input pad \"%s\" with type %s of the filter instance \"%s\" of %s not connected to any source\n",
239                        pad->name, av_get_media_type_string(pad->type), filt->name, filt->filter->name);
240                 return AVERROR(EINVAL);
241             }
242         }
243
244         for (j = 0; j < filt->nb_outputs; j++) {
245             if (!filt->outputs[j] || !filt->outputs[j]->dst) {
246                 pad = &filt->output_pads[j];
247                 av_log(log_ctx, AV_LOG_ERROR,
248                        "Output pad \"%s\" with type %s of the filter instance \"%s\" of %s not connected to any destination\n",
249                        pad->name, av_get_media_type_string(pad->type), filt->name, filt->filter->name);
250                 return AVERROR(EINVAL);
251             }
252         }
253     }
254
255     return 0;
256 }
257
258 /**
259  * Configure all the links of graphctx.
260  *
261  * @return >= 0 in case of success, a negative value otherwise
262  */
263 static int graph_config_links(AVFilterGraph *graph, AVClass *log_ctx)
264 {
265     AVFilterContext *filt;
266     int i, ret;
267
268     for (i = 0; i < graph->nb_filters; i++) {
269         filt = graph->filters[i];
270
271         if (!filt->nb_outputs) {
272             if ((ret = avfilter_config_links(filt)))
273                 return ret;
274         }
275     }
276
277     return 0;
278 }
279
280 AVFilterContext *avfilter_graph_get_filter(AVFilterGraph *graph, const char *name)
281 {
282     int i;
283
284     for (i = 0; i < graph->nb_filters; i++)
285         if (graph->filters[i]->name && !strcmp(name, graph->filters[i]->name))
286             return graph->filters[i];
287
288     return NULL;
289 }
290
291 static void sanitize_channel_layouts(void *log, AVFilterChannelLayouts *l)
292 {
293     if (!l)
294         return;
295     if (l->nb_channel_layouts) {
296         if (l->all_layouts || l->all_counts)
297             av_log(log, AV_LOG_WARNING, "All layouts set on non-empty list\n");
298         l->all_layouts = l->all_counts = 0;
299     } else {
300         if (l->all_counts && !l->all_layouts)
301             av_log(log, AV_LOG_WARNING, "All counts without all layouts\n");
302         l->all_layouts = 1;
303     }
304 }
305
306 static int filter_query_formats(AVFilterContext *ctx)
307 {
308     int ret, i;
309     AVFilterFormats *formats;
310     AVFilterChannelLayouts *chlayouts;
311     AVFilterFormats *samplerates;
312     enum AVMediaType type = ctx->inputs  && ctx->inputs [0] ? ctx->inputs [0]->type :
313                             ctx->outputs && ctx->outputs[0] ? ctx->outputs[0]->type :
314                             AVMEDIA_TYPE_VIDEO;
315
316     if ((ret = ctx->filter->query_formats(ctx)) < 0) {
317         if (ret != AVERROR(EAGAIN))
318             av_log(ctx, AV_LOG_ERROR, "Query format failed for '%s': %s\n",
319                    ctx->name, av_err2str(ret));
320         return ret;
321     }
322
323     for (i = 0; i < ctx->nb_inputs; i++)
324         sanitize_channel_layouts(ctx, ctx->inputs[i]->out_channel_layouts);
325     for (i = 0; i < ctx->nb_outputs; i++)
326         sanitize_channel_layouts(ctx, ctx->outputs[i]->in_channel_layouts);
327
328     formats = ff_all_formats(type);
329     if ((ret = ff_set_common_formats(ctx, formats)) < 0)
330         return ret;
331     if (type == AVMEDIA_TYPE_AUDIO) {
332         samplerates = ff_all_samplerates();
333         if ((ret = ff_set_common_samplerates(ctx, samplerates)) < 0)
334             return ret;
335         chlayouts = ff_all_channel_layouts();
336         if ((ret = ff_set_common_channel_layouts(ctx, chlayouts)) < 0)
337             return ret;
338     }
339     return 0;
340 }
341
342 static int formats_declared(AVFilterContext *f)
343 {
344     int i;
345
346     for (i = 0; i < f->nb_inputs; i++) {
347         if (!f->inputs[i]->out_formats)
348             return 0;
349         if (f->inputs[i]->type == AVMEDIA_TYPE_AUDIO &&
350             !(f->inputs[i]->out_samplerates &&
351               f->inputs[i]->out_channel_layouts))
352             return 0;
353     }
354     for (i = 0; i < f->nb_outputs; i++) {
355         if (!f->outputs[i]->in_formats)
356             return 0;
357         if (f->outputs[i]->type == AVMEDIA_TYPE_AUDIO &&
358             !(f->outputs[i]->in_samplerates &&
359               f->outputs[i]->in_channel_layouts))
360             return 0;
361     }
362     return 1;
363 }
364
365 static AVFilterFormats *clone_filter_formats(AVFilterFormats *arg)
366 {
367     AVFilterFormats *a = av_memdup(arg, sizeof(*arg));
368     if (a) {
369         a->refcount = 0;
370         a->refs     = NULL;
371         a->formats  = av_memdup(a->formats, sizeof(*a->formats) * a->nb_formats);
372         if (!a->formats && arg->formats)
373             av_freep(&a);
374     }
375     return a;
376 }
377
378 static int can_merge_formats(AVFilterFormats *a_arg,
379                              AVFilterFormats *b_arg,
380                              enum AVMediaType type,
381                              int is_sample_rate)
382 {
383     AVFilterFormats *a, *b, *ret;
384     if (a_arg == b_arg)
385         return 1;
386     a = clone_filter_formats(a_arg);
387     b = clone_filter_formats(b_arg);
388
389     if (!a || !b) {
390         if (a)
391             av_freep(&a->formats);
392         if (b)
393             av_freep(&b->formats);
394
395         av_freep(&a);
396         av_freep(&b);
397
398         return 0;
399     }
400
401     if (is_sample_rate) {
402         ret = ff_merge_samplerates(a, b);
403     } else {
404         ret = ff_merge_formats(a, b, type);
405     }
406     if (ret) {
407         av_freep(&ret->formats);
408         av_freep(&ret->refs);
409         av_freep(&ret);
410         return 1;
411     } else {
412         av_freep(&a->formats);
413         av_freep(&b->formats);
414         av_freep(&a);
415         av_freep(&b);
416         return 0;
417     }
418 }
419
420 /**
421  * Perform one round of query_formats() and merging formats lists on the
422  * filter graph.
423  * @return  >=0 if all links formats lists could be queried and merged;
424  *          AVERROR(EAGAIN) some progress was made in the queries or merging
425  *          and a later call may succeed;
426  *          AVERROR(EIO) (may be changed) plus a log message if no progress
427  *          was made and the negotiation is stuck;
428  *          a negative error code if some other error happened
429  */
430 static int query_formats(AVFilterGraph *graph, AVClass *log_ctx)
431 {
432     int i, j, ret;
433     int scaler_count = 0, resampler_count = 0;
434     int count_queried = 0;        /* successful calls to query_formats() */
435     int count_merged = 0;         /* successful merge of formats lists */
436     int count_already_merged = 0; /* lists already merged */
437     int count_delayed = 0;        /* lists that need to be merged later */
438
439     for (i = 0; i < graph->nb_filters; i++) {
440         AVFilterContext *f = graph->filters[i];
441         if (formats_declared(f))
442             continue;
443         if (f->filter->query_formats)
444             ret = filter_query_formats(f);
445         else
446             ret = ff_default_query_formats(f);
447         if (ret < 0 && ret != AVERROR(EAGAIN))
448             return ret;
449         /* note: EAGAIN could indicate a partial success, not counted yet */
450         count_queried += ret >= 0;
451     }
452
453     /* go through and merge as many format lists as possible */
454     for (i = 0; i < graph->nb_filters; i++) {
455         AVFilterContext *filter = graph->filters[i];
456
457         for (j = 0; j < filter->nb_inputs; j++) {
458             AVFilterLink *link = filter->inputs[j];
459             int convert_needed = 0;
460
461             if (!link)
462                 continue;
463
464             if (link->in_formats != link->out_formats
465                 && link->in_formats && link->out_formats)
466                 if (!can_merge_formats(link->in_formats, link->out_formats,
467                                       link->type, 0))
468                     convert_needed = 1;
469             if (link->type == AVMEDIA_TYPE_AUDIO) {
470                 if (link->in_samplerates != link->out_samplerates
471                     && link->in_samplerates && link->out_samplerates)
472                     if (!can_merge_formats(link->in_samplerates,
473                                            link->out_samplerates,
474                                            0, 1))
475                         convert_needed = 1;
476             }
477
478 #define MERGE_DISPATCH(field, statement)                                     \
479             if (!(link->in_ ## field && link->out_ ## field)) {              \
480                 count_delayed++;                                             \
481             } else if (link->in_ ## field == link->out_ ## field) {          \
482                 count_already_merged++;                                      \
483             } else if (!convert_needed) {                                    \
484                 count_merged++;                                              \
485                 statement                                                    \
486             }
487
488             if (link->type == AVMEDIA_TYPE_AUDIO) {
489                 MERGE_DISPATCH(channel_layouts,
490                     if (!ff_merge_channel_layouts(link->in_channel_layouts,
491                                                   link->out_channel_layouts))
492                         convert_needed = 1;
493                 )
494                 MERGE_DISPATCH(samplerates,
495                     if (!ff_merge_samplerates(link->in_samplerates,
496                                               link->out_samplerates))
497                         convert_needed = 1;
498                 )
499             }
500             MERGE_DISPATCH(formats,
501                 if (!ff_merge_formats(link->in_formats, link->out_formats,
502                                       link->type))
503                     convert_needed = 1;
504             )
505 #undef MERGE_DISPATCH
506
507             if (convert_needed) {
508                 AVFilterContext *convert;
509                 AVFilter *filter;
510                 AVFilterLink *inlink, *outlink;
511                 char scale_args[256];
512                 char inst_name[30];
513
514                 if (graph->disable_auto_convert) {
515                     av_log(log_ctx, AV_LOG_ERROR,
516                            "The filters '%s' and '%s' do not have a common format "
517                            "and automatic conversion is disabled.\n",
518                            link->src->name, link->dst->name);
519                     return AVERROR(EINVAL);
520                 }
521
522                 /* couldn't merge format lists. auto-insert conversion filter */
523                 switch (link->type) {
524                 case AVMEDIA_TYPE_VIDEO:
525                     if (!(filter = avfilter_get_by_name("scale"))) {
526                         av_log(log_ctx, AV_LOG_ERROR, "'scale' filter "
527                                "not present, cannot convert pixel formats.\n");
528                         return AVERROR(EINVAL);
529                     }
530
531                     snprintf(inst_name, sizeof(inst_name), "auto-inserted scaler %d",
532                              scaler_count++);
533
534                     if ((ret = avfilter_graph_create_filter(&convert, filter,
535                                                             inst_name, graph->scale_sws_opts, NULL,
536                                                             graph)) < 0)
537                         return ret;
538                     break;
539                 case AVMEDIA_TYPE_AUDIO:
540                     if (!(filter = avfilter_get_by_name("aresample"))) {
541                         av_log(log_ctx, AV_LOG_ERROR, "'aresample' filter "
542                                "not present, cannot convert audio formats.\n");
543                         return AVERROR(EINVAL);
544                     }
545
546                     snprintf(inst_name, sizeof(inst_name), "auto-inserted resampler %d",
547                              resampler_count++);
548                     scale_args[0] = '\0';
549                     if (graph->aresample_swr_opts)
550                         snprintf(scale_args, sizeof(scale_args), "%s",
551                                  graph->aresample_swr_opts);
552                     if ((ret = avfilter_graph_create_filter(&convert, filter,
553                                                             inst_name, graph->aresample_swr_opts,
554                                                             NULL, graph)) < 0)
555                         return ret;
556                     break;
557                 default:
558                     return AVERROR(EINVAL);
559                 }
560
561                 if ((ret = avfilter_insert_filter(link, convert, 0, 0)) < 0)
562                     return ret;
563
564                 if ((ret = filter_query_formats(convert)) < 0)
565                     return ret;
566
567                 inlink  = convert->inputs[0];
568                 outlink = convert->outputs[0];
569                 av_assert0( inlink-> in_formats->refcount > 0);
570                 av_assert0( inlink->out_formats->refcount > 0);
571                 av_assert0(outlink-> in_formats->refcount > 0);
572                 av_assert0(outlink->out_formats->refcount > 0);
573                 if (outlink->type == AVMEDIA_TYPE_AUDIO) {
574                     av_assert0( inlink-> in_samplerates->refcount > 0);
575                     av_assert0( inlink->out_samplerates->refcount > 0);
576                     av_assert0(outlink-> in_samplerates->refcount > 0);
577                     av_assert0(outlink->out_samplerates->refcount > 0);
578                     av_assert0( inlink-> in_channel_layouts->refcount > 0);
579                     av_assert0( inlink->out_channel_layouts->refcount > 0);
580                     av_assert0(outlink-> in_channel_layouts->refcount > 0);
581                     av_assert0(outlink->out_channel_layouts->refcount > 0);
582                 }
583                 if (!ff_merge_formats( inlink->in_formats,  inlink->out_formats,  inlink->type) ||
584                     !ff_merge_formats(outlink->in_formats, outlink->out_formats, outlink->type))
585                     ret = AVERROR(ENOSYS);
586                 if (inlink->type == AVMEDIA_TYPE_AUDIO &&
587                     (!ff_merge_samplerates(inlink->in_samplerates,
588                                            inlink->out_samplerates) ||
589                      !ff_merge_channel_layouts(inlink->in_channel_layouts,
590                                                inlink->out_channel_layouts)))
591                     ret = AVERROR(ENOSYS);
592                 if (outlink->type == AVMEDIA_TYPE_AUDIO &&
593                     (!ff_merge_samplerates(outlink->in_samplerates,
594                                            outlink->out_samplerates) ||
595                      !ff_merge_channel_layouts(outlink->in_channel_layouts,
596                                                outlink->out_channel_layouts)))
597                     ret = AVERROR(ENOSYS);
598
599                 if (ret < 0) {
600                     av_log(log_ctx, AV_LOG_ERROR,
601                            "Impossible to convert between the formats supported by the filter "
602                            "'%s' and the filter '%s'\n", link->src->name, link->dst->name);
603                     return ret;
604                 }
605             }
606         }
607     }
608
609     av_log(graph, AV_LOG_DEBUG, "query_formats: "
610            "%d queried, %d merged, %d already done, %d delayed\n",
611            count_queried, count_merged, count_already_merged, count_delayed);
612     if (count_delayed) {
613         AVBPrint bp;
614
615         /* if count_queried > 0, one filter at least did set its formats,
616            that will give additional information to its neighbour;
617            if count_merged > 0, one pair of formats lists at least was merged,
618            that will give additional information to all connected filters;
619            in both cases, progress was made and a new round must be done */
620         if (count_queried || count_merged)
621             return AVERROR(EAGAIN);
622         av_bprint_init(&bp, 0, AV_BPRINT_SIZE_AUTOMATIC);
623         for (i = 0; i < graph->nb_filters; i++)
624             if (!formats_declared(graph->filters[i]))
625                 av_bprintf(&bp, "%s%s", bp.len ? ", " : "",
626                           graph->filters[i]->name);
627         av_log(graph, AV_LOG_ERROR,
628                "The following filters could not choose their formats: %s\n"
629                "Consider inserting the (a)format filter near their input or "
630                "output.\n", bp.str);
631         return AVERROR(EIO);
632     }
633     return 0;
634 }
635
636 static int get_fmt_score(enum AVSampleFormat dst_fmt, enum AVSampleFormat src_fmt)
637 {
638     int score = 0;
639
640     if (av_sample_fmt_is_planar(dst_fmt) != av_sample_fmt_is_planar(src_fmt))
641         score ++;
642
643     if (av_get_bytes_per_sample(dst_fmt) < av_get_bytes_per_sample(src_fmt)) {
644         score += 100 * (av_get_bytes_per_sample(src_fmt) - av_get_bytes_per_sample(dst_fmt));
645     }else
646         score += 10  * (av_get_bytes_per_sample(dst_fmt) - av_get_bytes_per_sample(src_fmt));
647
648     if (av_get_packed_sample_fmt(dst_fmt) == AV_SAMPLE_FMT_S32 &&
649         av_get_packed_sample_fmt(src_fmt) == AV_SAMPLE_FMT_FLT)
650         score += 20;
651
652     if (av_get_packed_sample_fmt(dst_fmt) == AV_SAMPLE_FMT_FLT &&
653         av_get_packed_sample_fmt(src_fmt) == AV_SAMPLE_FMT_S32)
654         score += 2;
655
656     return score;
657 }
658
659 static enum AVSampleFormat find_best_sample_fmt_of_2(enum AVSampleFormat dst_fmt1, enum AVSampleFormat dst_fmt2,
660                                                      enum AVSampleFormat src_fmt)
661 {
662     int score1, score2;
663
664     score1 = get_fmt_score(dst_fmt1, src_fmt);
665     score2 = get_fmt_score(dst_fmt2, src_fmt);
666
667     return score1 < score2 ? dst_fmt1 : dst_fmt2;
668 }
669
670 static int pick_format(AVFilterLink *link, AVFilterLink *ref)
671 {
672     if (!link || !link->in_formats)
673         return 0;
674
675     if (link->type == AVMEDIA_TYPE_VIDEO) {
676         if(ref && ref->type == AVMEDIA_TYPE_VIDEO){
677             int has_alpha= av_pix_fmt_desc_get(ref->format)->nb_components % 2 == 0;
678             enum AVPixelFormat best= AV_PIX_FMT_NONE;
679             int i;
680             for (i=0; i<link->in_formats->nb_formats; i++) {
681                 enum AVPixelFormat p = link->in_formats->formats[i];
682                 best= av_find_best_pix_fmt_of_2(best, p, ref->format, has_alpha, NULL);
683             }
684             av_log(link->src,AV_LOG_DEBUG, "picking %s out of %d ref:%s alpha:%d\n",
685                    av_get_pix_fmt_name(best), link->in_formats->nb_formats,
686                    av_get_pix_fmt_name(ref->format), has_alpha);
687             link->in_formats->formats[0] = best;
688         }
689     } else if (link->type == AVMEDIA_TYPE_AUDIO) {
690         if(ref && ref->type == AVMEDIA_TYPE_AUDIO){
691             enum AVSampleFormat best= AV_SAMPLE_FMT_NONE;
692             int i;
693             for (i=0; i<link->in_formats->nb_formats; i++) {
694                 enum AVSampleFormat p = link->in_formats->formats[i];
695                 best = find_best_sample_fmt_of_2(best, p, ref->format);
696             }
697             av_log(link->src,AV_LOG_DEBUG, "picking %s out of %d ref:%s\n",
698                    av_get_sample_fmt_name(best), link->in_formats->nb_formats,
699                    av_get_sample_fmt_name(ref->format));
700             link->in_formats->formats[0] = best;
701         }
702     }
703
704     link->in_formats->nb_formats = 1;
705     link->format = link->in_formats->formats[0];
706
707     if (link->type == AVMEDIA_TYPE_AUDIO) {
708         if (!link->in_samplerates->nb_formats) {
709             av_log(link->src, AV_LOG_ERROR, "Cannot select sample rate for"
710                    " the link between filters %s and %s.\n", link->src->name,
711                    link->dst->name);
712             return AVERROR(EINVAL);
713         }
714         link->in_samplerates->nb_formats = 1;
715         link->sample_rate = link->in_samplerates->formats[0];
716
717         if (link->in_channel_layouts->all_layouts) {
718             av_log(link->src, AV_LOG_ERROR, "Cannot select channel layout for"
719                    " the link between filters %s and %s.\n", link->src->name,
720                    link->dst->name);
721             if (!link->in_channel_layouts->all_counts)
722                 av_log(link->src, AV_LOG_ERROR, "Unknown channel layouts not "
723                        "supported, try specifying a channel layout using "
724                        "'aformat=channel_layouts=something'.\n");
725             return AVERROR(EINVAL);
726         }
727         link->in_channel_layouts->nb_channel_layouts = 1;
728         link->channel_layout = link->in_channel_layouts->channel_layouts[0];
729         if ((link->channels = FF_LAYOUT2COUNT(link->channel_layout)))
730             link->channel_layout = 0;
731         else
732             link->channels = av_get_channel_layout_nb_channels(link->channel_layout);
733     }
734
735     ff_formats_unref(&link->in_formats);
736     ff_formats_unref(&link->out_formats);
737     ff_formats_unref(&link->in_samplerates);
738     ff_formats_unref(&link->out_samplerates);
739     ff_channel_layouts_unref(&link->in_channel_layouts);
740     ff_channel_layouts_unref(&link->out_channel_layouts);
741
742     return 0;
743 }
744
745 #define REDUCE_FORMATS(fmt_type, list_type, list, var, nb, add_format, unref_format) \
746 do {                                                                   \
747     for (i = 0; i < filter->nb_inputs; i++) {                          \
748         AVFilterLink *link = filter->inputs[i];                        \
749         fmt_type fmt;                                                  \
750                                                                        \
751         if (!link->out_ ## list || link->out_ ## list->nb != 1)        \
752             continue;                                                  \
753         fmt = link->out_ ## list->var[0];                              \
754                                                                        \
755         for (j = 0; j < filter->nb_outputs; j++) {                     \
756             AVFilterLink *out_link = filter->outputs[j];               \
757             list_type *fmts;                                           \
758                                                                        \
759             if (link->type != out_link->type ||                        \
760                 out_link->in_ ## list->nb == 1)                        \
761                 continue;                                              \
762             fmts = out_link->in_ ## list;                              \
763                                                                        \
764             if (!out_link->in_ ## list->nb) {                          \
765                 if ((ret = add_format(&out_link->in_ ##list, fmt)) < 0)\
766                     return ret;                                        \
767                 ret = 1;                                               \
768                 break;                                                 \
769             }                                                          \
770                                                                        \
771             for (k = 0; k < out_link->in_ ## list->nb; k++)            \
772                 if (fmts->var[k] == fmt) {                             \
773                     fmts->var[0]  = fmt;                               \
774                     fmts->nb = 1;                                      \
775                     ret = 1;                                           \
776                     break;                                             \
777                 }                                                      \
778         }                                                              \
779     }                                                                  \
780 } while (0)
781
782 static int reduce_formats_on_filter(AVFilterContext *filter)
783 {
784     int i, j, k, ret = 0;
785
786     REDUCE_FORMATS(int,      AVFilterFormats,        formats,         formats,
787                    nb_formats, ff_add_format, ff_formats_unref);
788     REDUCE_FORMATS(int,      AVFilterFormats,        samplerates,     formats,
789                    nb_formats, ff_add_format, ff_formats_unref);
790
791     /* reduce channel layouts */
792     for (i = 0; i < filter->nb_inputs; i++) {
793         AVFilterLink *inlink = filter->inputs[i];
794         uint64_t fmt;
795
796         if (!inlink->out_channel_layouts ||
797             inlink->out_channel_layouts->nb_channel_layouts != 1)
798             continue;
799         fmt = inlink->out_channel_layouts->channel_layouts[0];
800
801         for (j = 0; j < filter->nb_outputs; j++) {
802             AVFilterLink *outlink = filter->outputs[j];
803             AVFilterChannelLayouts *fmts;
804
805             fmts = outlink->in_channel_layouts;
806             if (inlink->type != outlink->type || fmts->nb_channel_layouts == 1)
807                 continue;
808
809             if (fmts->all_layouts &&
810                 (!FF_LAYOUT2COUNT(fmt) || fmts->all_counts)) {
811                 /* Turn the infinite list into a singleton */
812                 fmts->all_layouts = fmts->all_counts  = 0;
813                 if (ff_add_channel_layout(&outlink->in_channel_layouts, fmt) < 0)
814                     ret = 1;
815                 break;
816             }
817
818             for (k = 0; k < outlink->in_channel_layouts->nb_channel_layouts; k++) {
819                 if (fmts->channel_layouts[k] == fmt) {
820                     fmts->channel_layouts[0]  = fmt;
821                     fmts->nb_channel_layouts = 1;
822                     ret = 1;
823                     break;
824                 }
825             }
826         }
827     }
828
829     return ret;
830 }
831
832 static int reduce_formats(AVFilterGraph *graph)
833 {
834     int i, reduced, ret;
835
836     do {
837         reduced = 0;
838
839         for (i = 0; i < graph->nb_filters; i++) {
840             if ((ret = reduce_formats_on_filter(graph->filters[i])) < 0)
841                 return ret;
842             reduced |= ret;
843         }
844     } while (reduced);
845
846     return 0;
847 }
848
849 static void swap_samplerates_on_filter(AVFilterContext *filter)
850 {
851     AVFilterLink *link = NULL;
852     int sample_rate;
853     int i, j;
854
855     for (i = 0; i < filter->nb_inputs; i++) {
856         link = filter->inputs[i];
857
858         if (link->type == AVMEDIA_TYPE_AUDIO &&
859             link->out_samplerates->nb_formats== 1)
860             break;
861     }
862     if (i == filter->nb_inputs)
863         return;
864
865     sample_rate = link->out_samplerates->formats[0];
866
867     for (i = 0; i < filter->nb_outputs; i++) {
868         AVFilterLink *outlink = filter->outputs[i];
869         int best_idx, best_diff = INT_MAX;
870
871         if (outlink->type != AVMEDIA_TYPE_AUDIO ||
872             outlink->in_samplerates->nb_formats < 2)
873             continue;
874
875         for (j = 0; j < outlink->in_samplerates->nb_formats; j++) {
876             int diff = abs(sample_rate - outlink->in_samplerates->formats[j]);
877
878             if (diff < best_diff) {
879                 best_diff = diff;
880                 best_idx  = j;
881             }
882         }
883         FFSWAP(int, outlink->in_samplerates->formats[0],
884                outlink->in_samplerates->formats[best_idx]);
885     }
886 }
887
888 static void swap_samplerates(AVFilterGraph *graph)
889 {
890     int i;
891
892     for (i = 0; i < graph->nb_filters; i++)
893         swap_samplerates_on_filter(graph->filters[i]);
894 }
895
896 #define CH_CENTER_PAIR (AV_CH_FRONT_LEFT_OF_CENTER | AV_CH_FRONT_RIGHT_OF_CENTER)
897 #define CH_FRONT_PAIR  (AV_CH_FRONT_LEFT           | AV_CH_FRONT_RIGHT)
898 #define CH_STEREO_PAIR (AV_CH_STEREO_LEFT          | AV_CH_STEREO_RIGHT)
899 #define CH_WIDE_PAIR   (AV_CH_WIDE_LEFT            | AV_CH_WIDE_RIGHT)
900 #define CH_SIDE_PAIR   (AV_CH_SIDE_LEFT            | AV_CH_SIDE_RIGHT)
901 #define CH_DIRECT_PAIR (AV_CH_SURROUND_DIRECT_LEFT | AV_CH_SURROUND_DIRECT_RIGHT)
902 #define CH_BACK_PAIR   (AV_CH_BACK_LEFT            | AV_CH_BACK_RIGHT)
903
904 /* allowable substitutions for channel pairs when comparing layouts,
905  * ordered by priority for both values */
906 static const uint64_t ch_subst[][2] = {
907     { CH_FRONT_PAIR,      CH_CENTER_PAIR     },
908     { CH_FRONT_PAIR,      CH_WIDE_PAIR       },
909     { CH_FRONT_PAIR,      AV_CH_FRONT_CENTER },
910     { CH_CENTER_PAIR,     CH_FRONT_PAIR      },
911     { CH_CENTER_PAIR,     CH_WIDE_PAIR       },
912     { CH_CENTER_PAIR,     AV_CH_FRONT_CENTER },
913     { CH_WIDE_PAIR,       CH_FRONT_PAIR      },
914     { CH_WIDE_PAIR,       CH_CENTER_PAIR     },
915     { CH_WIDE_PAIR,       AV_CH_FRONT_CENTER },
916     { AV_CH_FRONT_CENTER, CH_FRONT_PAIR      },
917     { AV_CH_FRONT_CENTER, CH_CENTER_PAIR     },
918     { AV_CH_FRONT_CENTER, CH_WIDE_PAIR       },
919     { CH_SIDE_PAIR,       CH_DIRECT_PAIR     },
920     { CH_SIDE_PAIR,       CH_BACK_PAIR       },
921     { CH_SIDE_PAIR,       AV_CH_BACK_CENTER  },
922     { CH_BACK_PAIR,       CH_DIRECT_PAIR     },
923     { CH_BACK_PAIR,       CH_SIDE_PAIR       },
924     { CH_BACK_PAIR,       AV_CH_BACK_CENTER  },
925     { AV_CH_BACK_CENTER,  CH_BACK_PAIR       },
926     { AV_CH_BACK_CENTER,  CH_DIRECT_PAIR     },
927     { AV_CH_BACK_CENTER,  CH_SIDE_PAIR       },
928 };
929
930 static void swap_channel_layouts_on_filter(AVFilterContext *filter)
931 {
932     AVFilterLink *link = NULL;
933     int i, j, k;
934
935     for (i = 0; i < filter->nb_inputs; i++) {
936         link = filter->inputs[i];
937
938         if (link->type == AVMEDIA_TYPE_AUDIO &&
939             link->out_channel_layouts->nb_channel_layouts == 1)
940             break;
941     }
942     if (i == filter->nb_inputs)
943         return;
944
945     for (i = 0; i < filter->nb_outputs; i++) {
946         AVFilterLink *outlink = filter->outputs[i];
947         int best_idx = -1, best_score = INT_MIN, best_count_diff = INT_MAX;
948
949         if (outlink->type != AVMEDIA_TYPE_AUDIO ||
950             outlink->in_channel_layouts->nb_channel_layouts < 2)
951             continue;
952
953         for (j = 0; j < outlink->in_channel_layouts->nb_channel_layouts; j++) {
954             uint64_t  in_chlayout = link->out_channel_layouts->channel_layouts[0];
955             uint64_t out_chlayout = outlink->in_channel_layouts->channel_layouts[j];
956             int  in_channels      = av_get_channel_layout_nb_channels(in_chlayout);
957             int out_channels      = av_get_channel_layout_nb_channels(out_chlayout);
958             int count_diff        = out_channels - in_channels;
959             int matched_channels, extra_channels;
960             int score = 100000;
961
962             if (FF_LAYOUT2COUNT(in_chlayout) || FF_LAYOUT2COUNT(out_chlayout)) {
963                 /* Compute score in case the input or output layout encodes
964                    a channel count; in this case the score is not altered by
965                    the computation afterwards, as in_chlayout and
966                    out_chlayout have both been set to 0 */
967                 if (FF_LAYOUT2COUNT(in_chlayout))
968                     in_channels = FF_LAYOUT2COUNT(in_chlayout);
969                 if (FF_LAYOUT2COUNT(out_chlayout))
970                     out_channels = FF_LAYOUT2COUNT(out_chlayout);
971                 score -= 10000 + FFABS(out_channels - in_channels) +
972                          (in_channels > out_channels ? 10000 : 0);
973                 in_chlayout = out_chlayout = 0;
974                 /* Let the remaining computation run, even if the score
975                    value is not altered */
976             }
977
978             /* channel substitution */
979             for (k = 0; k < FF_ARRAY_ELEMS(ch_subst); k++) {
980                 uint64_t cmp0 = ch_subst[k][0];
981                 uint64_t cmp1 = ch_subst[k][1];
982                 if (( in_chlayout & cmp0) && (!(out_chlayout & cmp0)) &&
983                     (out_chlayout & cmp1) && (!( in_chlayout & cmp1))) {
984                     in_chlayout  &= ~cmp0;
985                     out_chlayout &= ~cmp1;
986                     /* add score for channel match, minus a deduction for
987                        having to do the substitution */
988                     score += 10 * av_get_channel_layout_nb_channels(cmp1) - 2;
989                 }
990             }
991
992             /* no penalty for LFE channel mismatch */
993             if ( (in_chlayout & AV_CH_LOW_FREQUENCY) &&
994                 (out_chlayout & AV_CH_LOW_FREQUENCY))
995                 score += 10;
996             in_chlayout  &= ~AV_CH_LOW_FREQUENCY;
997             out_chlayout &= ~AV_CH_LOW_FREQUENCY;
998
999             matched_channels = av_get_channel_layout_nb_channels(in_chlayout &
1000                                                                  out_chlayout);
1001             extra_channels   = av_get_channel_layout_nb_channels(out_chlayout &
1002                                                                  (~in_chlayout));
1003             score += 10 * matched_channels - 5 * extra_channels;
1004
1005             if (score > best_score ||
1006                 (count_diff < best_count_diff && score == best_score)) {
1007                 best_score = score;
1008                 best_idx   = j;
1009                 best_count_diff = count_diff;
1010             }
1011         }
1012         av_assert0(best_idx >= 0);
1013         FFSWAP(uint64_t, outlink->in_channel_layouts->channel_layouts[0],
1014                outlink->in_channel_layouts->channel_layouts[best_idx]);
1015     }
1016
1017 }
1018
1019 static void swap_channel_layouts(AVFilterGraph *graph)
1020 {
1021     int i;
1022
1023     for (i = 0; i < graph->nb_filters; i++)
1024         swap_channel_layouts_on_filter(graph->filters[i]);
1025 }
1026
1027 static void swap_sample_fmts_on_filter(AVFilterContext *filter)
1028 {
1029     AVFilterLink *link = NULL;
1030     int format, bps;
1031     int i, j;
1032
1033     for (i = 0; i < filter->nb_inputs; i++) {
1034         link = filter->inputs[i];
1035
1036         if (link->type == AVMEDIA_TYPE_AUDIO &&
1037             link->out_formats->nb_formats == 1)
1038             break;
1039     }
1040     if (i == filter->nb_inputs)
1041         return;
1042
1043     format = link->out_formats->formats[0];
1044     bps    = av_get_bytes_per_sample(format);
1045
1046     for (i = 0; i < filter->nb_outputs; i++) {
1047         AVFilterLink *outlink = filter->outputs[i];
1048         int best_idx = -1, best_score = INT_MIN;
1049
1050         if (outlink->type != AVMEDIA_TYPE_AUDIO ||
1051             outlink->in_formats->nb_formats < 2)
1052             continue;
1053
1054         for (j = 0; j < outlink->in_formats->nb_formats; j++) {
1055             int out_format = outlink->in_formats->formats[j];
1056             int out_bps    = av_get_bytes_per_sample(out_format);
1057             int score;
1058
1059             if (av_get_packed_sample_fmt(out_format) == format ||
1060                 av_get_planar_sample_fmt(out_format) == format) {
1061                 best_idx   = j;
1062                 break;
1063             }
1064
1065             /* for s32 and float prefer double to prevent loss of information */
1066             if (bps == 4 && out_bps == 8) {
1067                 best_idx = j;
1068                 break;
1069             }
1070
1071             /* prefer closest higher or equal bps */
1072             score = -abs(out_bps - bps);
1073             if (out_bps >= bps)
1074                 score += INT_MAX/2;
1075
1076             if (score > best_score) {
1077                 best_score = score;
1078                 best_idx   = j;
1079             }
1080         }
1081         av_assert0(best_idx >= 0);
1082         FFSWAP(int, outlink->in_formats->formats[0],
1083                outlink->in_formats->formats[best_idx]);
1084     }
1085 }
1086
1087 static void swap_sample_fmts(AVFilterGraph *graph)
1088 {
1089     int i;
1090
1091     for (i = 0; i < graph->nb_filters; i++)
1092         swap_sample_fmts_on_filter(graph->filters[i]);
1093
1094 }
1095
1096 static int pick_formats(AVFilterGraph *graph)
1097 {
1098     int i, j, ret;
1099     int change;
1100
1101     do{
1102         change = 0;
1103         for (i = 0; i < graph->nb_filters; i++) {
1104             AVFilterContext *filter = graph->filters[i];
1105             if (filter->nb_inputs){
1106                 for (j = 0; j < filter->nb_inputs; j++){
1107                     if(filter->inputs[j]->in_formats && filter->inputs[j]->in_formats->nb_formats == 1) {
1108                         if ((ret = pick_format(filter->inputs[j], NULL)) < 0)
1109                             return ret;
1110                         change = 1;
1111                     }
1112                 }
1113             }
1114             if (filter->nb_outputs){
1115                 for (j = 0; j < filter->nb_outputs; j++){
1116                     if(filter->outputs[j]->in_formats && filter->outputs[j]->in_formats->nb_formats == 1) {
1117                         if ((ret = pick_format(filter->outputs[j], NULL)) < 0)
1118                             return ret;
1119                         change = 1;
1120                     }
1121                 }
1122             }
1123             if (filter->nb_inputs && filter->nb_outputs && filter->inputs[0]->format>=0) {
1124                 for (j = 0; j < filter->nb_outputs; j++) {
1125                     if(filter->outputs[j]->format<0) {
1126                         if ((ret = pick_format(filter->outputs[j], filter->inputs[0])) < 0)
1127                             return ret;
1128                         change = 1;
1129                     }
1130                 }
1131             }
1132         }
1133     }while(change);
1134
1135     for (i = 0; i < graph->nb_filters; i++) {
1136         AVFilterContext *filter = graph->filters[i];
1137
1138         for (j = 0; j < filter->nb_inputs; j++)
1139             if ((ret = pick_format(filter->inputs[j], NULL)) < 0)
1140                 return ret;
1141         for (j = 0; j < filter->nb_outputs; j++)
1142             if ((ret = pick_format(filter->outputs[j], NULL)) < 0)
1143                 return ret;
1144     }
1145     return 0;
1146 }
1147
1148 /**
1149  * Configure the formats of all the links in the graph.
1150  */
1151 static int graph_config_formats(AVFilterGraph *graph, AVClass *log_ctx)
1152 {
1153     int ret;
1154
1155     /* find supported formats from sub-filters, and merge along links */
1156     while ((ret = query_formats(graph, log_ctx)) == AVERROR(EAGAIN))
1157         av_log(graph, AV_LOG_DEBUG, "query_formats not finished\n");
1158     if (ret < 0)
1159         return ret;
1160
1161     /* Once everything is merged, it's possible that we'll still have
1162      * multiple valid media format choices. We try to minimize the amount
1163      * of format conversion inside filters */
1164     if ((ret = reduce_formats(graph)) < 0)
1165         return ret;
1166
1167     /* for audio filters, ensure the best format, sample rate and channel layout
1168      * is selected */
1169     swap_sample_fmts(graph);
1170     swap_samplerates(graph);
1171     swap_channel_layouts(graph);
1172
1173     if ((ret = pick_formats(graph)) < 0)
1174         return ret;
1175
1176     return 0;
1177 }
1178
1179 static int graph_config_pointers(AVFilterGraph *graph,
1180                                              AVClass *log_ctx)
1181 {
1182     unsigned i, j;
1183     int sink_links_count = 0, n = 0;
1184     AVFilterContext *f;
1185     AVFilterLink **sinks;
1186
1187     for (i = 0; i < graph->nb_filters; i++) {
1188         f = graph->filters[i];
1189         for (j = 0; j < f->nb_inputs; j++) {
1190             f->inputs[j]->graph     = graph;
1191             f->inputs[j]->age_index = -1;
1192         }
1193         for (j = 0; j < f->nb_outputs; j++) {
1194             f->outputs[j]->graph    = graph;
1195             f->outputs[j]->age_index= -1;
1196         }
1197         if (!f->nb_outputs) {
1198             if (f->nb_inputs > INT_MAX - sink_links_count)
1199                 return AVERROR(EINVAL);
1200             sink_links_count += f->nb_inputs;
1201         }
1202     }
1203     sinks = av_calloc(sink_links_count, sizeof(*sinks));
1204     if (!sinks)
1205         return AVERROR(ENOMEM);
1206     for (i = 0; i < graph->nb_filters; i++) {
1207         f = graph->filters[i];
1208         if (!f->nb_outputs) {
1209             for (j = 0; j < f->nb_inputs; j++) {
1210                 sinks[n] = f->inputs[j];
1211                 f->inputs[j]->age_index = n++;
1212             }
1213         }
1214     }
1215     av_assert0(n == sink_links_count);
1216     graph->sink_links       = sinks;
1217     graph->sink_links_count = sink_links_count;
1218     return 0;
1219 }
1220
1221 static int graph_insert_fifos(AVFilterGraph *graph, AVClass *log_ctx)
1222 {
1223     AVFilterContext *f;
1224     int i, j, ret;
1225     int fifo_count = 0;
1226
1227     for (i = 0; i < graph->nb_filters; i++) {
1228         f = graph->filters[i];
1229
1230         for (j = 0; j < f->nb_inputs; j++) {
1231             AVFilterLink *link = f->inputs[j];
1232             AVFilterContext *fifo_ctx;
1233             AVFilter *fifo;
1234             char name[32];
1235
1236             if (!link->dstpad->needs_fifo)
1237                 continue;
1238
1239             fifo = f->inputs[j]->type == AVMEDIA_TYPE_VIDEO ?
1240                    avfilter_get_by_name("fifo") :
1241                    avfilter_get_by_name("afifo");
1242
1243             snprintf(name, sizeof(name), "auto-inserted fifo %d", fifo_count++);
1244
1245             ret = avfilter_graph_create_filter(&fifo_ctx, fifo, name, NULL,
1246                                                NULL, graph);
1247             if (ret < 0)
1248                 return ret;
1249
1250             ret = avfilter_insert_filter(link, fifo_ctx, 0, 0);
1251             if (ret < 0)
1252                 return ret;
1253         }
1254     }
1255
1256     return 0;
1257 }
1258
1259 int avfilter_graph_config(AVFilterGraph *graphctx, void *log_ctx)
1260 {
1261     int ret;
1262
1263     if ((ret = graph_check_validity(graphctx, log_ctx)))
1264         return ret;
1265     if ((ret = graph_insert_fifos(graphctx, log_ctx)) < 0)
1266         return ret;
1267     if ((ret = graph_config_formats(graphctx, log_ctx)))
1268         return ret;
1269     if ((ret = graph_config_links(graphctx, log_ctx)))
1270         return ret;
1271     if ((ret = graph_config_pointers(graphctx, log_ctx)))
1272         return ret;
1273
1274     return 0;
1275 }
1276
1277 int avfilter_graph_send_command(AVFilterGraph *graph, const char *target, const char *cmd, const char *arg, char *res, int res_len, int flags)
1278 {
1279     int i, r = AVERROR(ENOSYS);
1280
1281     if (!graph)
1282         return r;
1283
1284     if ((flags & AVFILTER_CMD_FLAG_ONE) && !(flags & AVFILTER_CMD_FLAG_FAST)) {
1285         r = avfilter_graph_send_command(graph, target, cmd, arg, res, res_len, flags | AVFILTER_CMD_FLAG_FAST);
1286         if (r != AVERROR(ENOSYS))
1287             return r;
1288     }
1289
1290     if (res_len && res)
1291         res[0] = 0;
1292
1293     for (i = 0; i < graph->nb_filters; i++) {
1294         AVFilterContext *filter = graph->filters[i];
1295         if (!strcmp(target, "all") || (filter->name && !strcmp(target, filter->name)) || !strcmp(target, filter->filter->name)) {
1296             r = avfilter_process_command(filter, cmd, arg, res, res_len, flags);
1297             if (r != AVERROR(ENOSYS)) {
1298                 if ((flags & AVFILTER_CMD_FLAG_ONE) || r < 0)
1299                     return r;
1300             }
1301         }
1302     }
1303
1304     return r;
1305 }
1306
1307 int avfilter_graph_queue_command(AVFilterGraph *graph, const char *target, const char *command, const char *arg, int flags, double ts)
1308 {
1309     int i;
1310
1311     if(!graph)
1312         return 0;
1313
1314     for (i = 0; i < graph->nb_filters; i++) {
1315         AVFilterContext *filter = graph->filters[i];
1316         if(filter && (!strcmp(target, "all") || !strcmp(target, filter->name) || !strcmp(target, filter->filter->name))){
1317             AVFilterCommand **queue = &filter->command_queue, *next;
1318             while (*queue && (*queue)->time <= ts)
1319                 queue = &(*queue)->next;
1320             next = *queue;
1321             *queue = av_mallocz(sizeof(AVFilterCommand));
1322             (*queue)->command = av_strdup(command);
1323             (*queue)->arg     = av_strdup(arg);
1324             (*queue)->time    = ts;
1325             (*queue)->flags   = flags;
1326             (*queue)->next    = next;
1327             if(flags & AVFILTER_CMD_FLAG_ONE)
1328                 return 0;
1329         }
1330     }
1331
1332     return 0;
1333 }
1334
1335 static void heap_bubble_up(AVFilterGraph *graph,
1336                            AVFilterLink *link, int index)
1337 {
1338     AVFilterLink **links = graph->sink_links;
1339
1340     av_assert0(index >= 0);
1341
1342     while (index) {
1343         int parent = (index - 1) >> 1;
1344         if (links[parent]->current_pts_us >= link->current_pts_us)
1345             break;
1346         links[index] = links[parent];
1347         links[index]->age_index = index;
1348         index = parent;
1349     }
1350     links[index] = link;
1351     link->age_index = index;
1352 }
1353
1354 static void heap_bubble_down(AVFilterGraph *graph,
1355                              AVFilterLink *link, int index)
1356 {
1357     AVFilterLink **links = graph->sink_links;
1358
1359     av_assert0(index >= 0);
1360
1361     while (1) {
1362         int child = 2 * index + 1;
1363         if (child >= graph->sink_links_count)
1364             break;
1365         if (child + 1 < graph->sink_links_count &&
1366             links[child + 1]->current_pts_us < links[child]->current_pts_us)
1367             child++;
1368         if (link->current_pts_us < links[child]->current_pts_us)
1369             break;
1370         links[index] = links[child];
1371         links[index]->age_index = index;
1372         index = child;
1373     }
1374     links[index] = link;
1375     link->age_index = index;
1376 }
1377
1378 void ff_avfilter_graph_update_heap(AVFilterGraph *graph, AVFilterLink *link)
1379 {
1380     heap_bubble_up  (graph, link, link->age_index);
1381     heap_bubble_down(graph, link, link->age_index);
1382 }
1383
1384 int avfilter_graph_request_oldest(AVFilterGraph *graph)
1385 {
1386     AVFilterLink *oldest = graph->sink_links[0];
1387     int64_t frame_count;
1388     int r;
1389
1390     while (graph->sink_links_count) {
1391         oldest = graph->sink_links[0];
1392         r = ff_request_frame(oldest);
1393         if (r != AVERROR_EOF)
1394             break;
1395         av_log(oldest->dst, AV_LOG_DEBUG, "EOF on sink link %s:%s.\n",
1396                oldest->dst ? oldest->dst->name : "unknown",
1397                oldest->dstpad ? oldest->dstpad->name : "unknown");
1398         /* EOF: remove the link from the heap */
1399         if (oldest->age_index < --graph->sink_links_count)
1400             heap_bubble_down(graph, graph->sink_links[graph->sink_links_count],
1401                              oldest->age_index);
1402         oldest->age_index = -1;
1403     }
1404     if (!graph->sink_links_count)
1405         return AVERROR_EOF;
1406     av_assert1(oldest->age_index >= 0);
1407     frame_count = oldest->frame_count_out;
1408     while (frame_count == oldest->frame_count_out) {
1409         r = ff_filter_graph_run_once(graph);
1410         if (r < 0)
1411             return r;
1412     }
1413     return 0;
1414 }
1415
1416 int ff_filter_graph_run_once(AVFilterGraph *graph)
1417 {
1418     AVFilterContext *filter;
1419     unsigned i;
1420
1421     av_assert0(graph->nb_filters);
1422     filter = graph->filters[0];
1423     for (i = 1; i < graph->nb_filters; i++)
1424         if (graph->filters[i]->ready > filter->ready)
1425             filter = graph->filters[i];
1426     if (!filter->ready)
1427         return AVERROR(EAGAIN);
1428     return ff_filter_activate(filter);
1429 }