b9f01645d0ee9622d55d535896ce6ad67e51df78
[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 Libav.
7  *
8  * Libav 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  * Libav 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 Libav; if not, write to the Free Software
20  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
21  */
22
23 #include <ctype.h>
24 #include <string.h>
25
26 #include "avfilter.h"
27 #include "avfiltergraph.h"
28 #include "formats.h"
29 #include "internal.h"
30
31 #include "libavutil/audioconvert.h"
32 #include "libavutil/log.h"
33
34 static const AVClass filtergraph_class = {
35     .class_name = "AVFilterGraph",
36     .item_name  = av_default_item_name,
37     .version    = LIBAVUTIL_VERSION_INT,
38 };
39
40 AVFilterGraph *avfilter_graph_alloc(void)
41 {
42     AVFilterGraph *ret = av_mallocz(sizeof(AVFilterGraph));
43     if (!ret)
44         return NULL;
45     ret->av_class = &filtergraph_class;
46     return ret;
47 }
48
49 void avfilter_graph_free(AVFilterGraph **graph)
50 {
51     if (!*graph)
52         return;
53     for (; (*graph)->filter_count > 0; (*graph)->filter_count--)
54         avfilter_free((*graph)->filters[(*graph)->filter_count - 1]);
55     av_freep(&(*graph)->scale_sws_opts);
56     av_freep(&(*graph)->filters);
57     av_freep(graph);
58 }
59
60 int avfilter_graph_add_filter(AVFilterGraph *graph, AVFilterContext *filter)
61 {
62     AVFilterContext **filters = av_realloc(graph->filters,
63                                            sizeof(AVFilterContext*) * (graph->filter_count+1));
64     if (!filters)
65         return AVERROR(ENOMEM);
66
67     graph->filters = filters;
68     graph->filters[graph->filter_count++] = filter;
69
70     return 0;
71 }
72
73 int avfilter_graph_create_filter(AVFilterContext **filt_ctx, AVFilter *filt,
74                                  const char *name, const char *args, void *opaque,
75                                  AVFilterGraph *graph_ctx)
76 {
77     int ret;
78
79     if ((ret = avfilter_open(filt_ctx, filt, name)) < 0)
80         goto fail;
81     if ((ret = avfilter_init_filter(*filt_ctx, args, opaque)) < 0)
82         goto fail;
83     if ((ret = avfilter_graph_add_filter(graph_ctx, *filt_ctx)) < 0)
84         goto fail;
85     return 0;
86
87 fail:
88     if (*filt_ctx)
89         avfilter_free(*filt_ctx);
90     *filt_ctx = NULL;
91     return ret;
92 }
93
94 /**
95  * Check for the validity of graph.
96  *
97  * A graph is considered valid if all its input and output pads are
98  * connected.
99  *
100  * @return 0 in case of success, a negative value otherwise
101  */
102 static int graph_check_validity(AVFilterGraph *graph, AVClass *log_ctx)
103 {
104     AVFilterContext *filt;
105     int i, j;
106
107     for (i = 0; i < graph->filter_count; i++) {
108         filt = graph->filters[i];
109
110         for (j = 0; j < filt->nb_inputs; j++) {
111             if (!filt->inputs[j] || !filt->inputs[j]->src) {
112                 av_log(log_ctx, AV_LOG_ERROR,
113                        "Input pad \"%s\" for the filter \"%s\" of type \"%s\" not connected to any source\n",
114                        filt->input_pads[j].name, filt->name, filt->filter->name);
115                 return AVERROR(EINVAL);
116             }
117         }
118
119         for (j = 0; j < filt->nb_outputs; j++) {
120             if (!filt->outputs[j] || !filt->outputs[j]->dst) {
121                 av_log(log_ctx, AV_LOG_ERROR,
122                        "Output pad \"%s\" for the filter \"%s\" of type \"%s\" not connected to any destination\n",
123                        filt->output_pads[j].name, filt->name, filt->filter->name);
124                 return AVERROR(EINVAL);
125             }
126         }
127     }
128
129     return 0;
130 }
131
132 /**
133  * Configure all the links of graphctx.
134  *
135  * @return 0 in case of success, a negative value otherwise
136  */
137 static int graph_config_links(AVFilterGraph *graph, AVClass *log_ctx)
138 {
139     AVFilterContext *filt;
140     int i, ret;
141
142     for (i=0; i < graph->filter_count; i++) {
143         filt = graph->filters[i];
144
145         if (!filt->nb_outputs) {
146             if ((ret = avfilter_config_links(filt)))
147                 return ret;
148         }
149     }
150
151     return 0;
152 }
153
154 AVFilterContext *avfilter_graph_get_filter(AVFilterGraph *graph, char *name)
155 {
156     int i;
157
158     for (i = 0; i < graph->filter_count; i++)
159         if (graph->filters[i]->name && !strcmp(name, graph->filters[i]->name))
160             return graph->filters[i];
161
162     return NULL;
163 }
164
165 static int query_formats(AVFilterGraph *graph, AVClass *log_ctx)
166 {
167     int i, j, ret;
168     int scaler_count = 0, resampler_count = 0;
169
170     /* ask all the sub-filters for their supported media formats */
171     for (i = 0; i < graph->filter_count; i++) {
172         if (graph->filters[i]->filter->query_formats)
173             graph->filters[i]->filter->query_formats(graph->filters[i]);
174         else
175             ff_default_query_formats(graph->filters[i]);
176     }
177
178     /* go through and merge as many format lists as possible */
179     for (i = 0; i < graph->filter_count; i++) {
180         AVFilterContext *filter = graph->filters[i];
181
182         for (j = 0; j < filter->nb_inputs; j++) {
183             AVFilterLink *link = filter->inputs[j];
184             int convert_needed = 0;
185
186             if (!link)
187                 continue;
188
189             if (link->in_formats != link->out_formats &&
190                 !ff_merge_formats(link->in_formats,
191                                         link->out_formats))
192                 convert_needed = 1;
193             if (link->type == AVMEDIA_TYPE_AUDIO) {
194                 if (link->in_channel_layouts != link->out_channel_layouts &&
195                     !ff_merge_channel_layouts(link->in_channel_layouts,
196                                               link->out_channel_layouts))
197                     convert_needed = 1;
198                 if (link->in_samplerates != link->out_samplerates &&
199                     !ff_merge_samplerates(link->in_samplerates,
200                                           link->out_samplerates))
201                     convert_needed = 1;
202             }
203
204             if (convert_needed) {
205                 AVFilterContext *convert;
206                 AVFilter *filter;
207                 AVFilterLink *inlink, *outlink;
208                 char scale_args[256];
209                 char inst_name[30];
210
211                 /* couldn't merge format lists. auto-insert conversion filter */
212                 switch (link->type) {
213                 case AVMEDIA_TYPE_VIDEO:
214                     if (!(filter = avfilter_get_by_name("scale"))) {
215                         av_log(log_ctx, AV_LOG_ERROR, "'scale' filter "
216                                "not present, cannot convert pixel formats.\n");
217                         return AVERROR(EINVAL);
218                     }
219
220                     snprintf(inst_name, sizeof(inst_name), "auto-inserted scaler %d",
221                              scaler_count++);
222                     snprintf(scale_args, sizeof(scale_args), "0:0:%s", graph->scale_sws_opts);
223                     if ((ret = avfilter_graph_create_filter(&convert, filter,
224                                                             inst_name, scale_args, NULL,
225                                                             graph)) < 0)
226                         return ret;
227                     break;
228                 case AVMEDIA_TYPE_AUDIO:
229                     if (!(filter = avfilter_get_by_name("resample"))) {
230                         av_log(log_ctx, AV_LOG_ERROR, "'resample' filter "
231                                "not present, cannot convert audio formats.\n");
232                         return AVERROR(EINVAL);
233                     }
234
235                     snprintf(inst_name, sizeof(inst_name), "auto-inserted resampler %d",
236                              resampler_count++);
237                     if ((ret = avfilter_graph_create_filter(&convert, filter,
238                                                             inst_name, NULL, NULL, graph)) < 0)
239                         return ret;
240                     break;
241                 default:
242                     return AVERROR(EINVAL);
243                 }
244
245                 if ((ret = avfilter_insert_filter(link, convert, 0, 0)) < 0)
246                     return ret;
247
248                 convert->filter->query_formats(convert);
249                 inlink  = convert->inputs[0];
250                 outlink = convert->outputs[0];
251                 if (!ff_merge_formats( inlink->in_formats,  inlink->out_formats) ||
252                     !ff_merge_formats(outlink->in_formats, outlink->out_formats))
253                     ret |= AVERROR(ENOSYS);
254                 if (inlink->type == AVMEDIA_TYPE_AUDIO &&
255                     (!ff_merge_samplerates(inlink->in_samplerates,
256                                            inlink->out_samplerates) ||
257                      !ff_merge_channel_layouts(inlink->in_channel_layouts,
258                                                inlink->out_channel_layouts)))
259                     ret |= AVERROR(ENOSYS);
260                 if (outlink->type == AVMEDIA_TYPE_AUDIO &&
261                     (!ff_merge_samplerates(outlink->in_samplerates,
262                                            outlink->out_samplerates) ||
263                      !ff_merge_channel_layouts(outlink->in_channel_layouts,
264                                                outlink->out_channel_layouts)))
265                     ret |= AVERROR(ENOSYS);
266
267                 if (ret < 0) {
268                     av_log(log_ctx, AV_LOG_ERROR,
269                            "Impossible to convert between the formats supported by the filter "
270                            "'%s' and the filter '%s'\n", link->src->name, link->dst->name);
271                     return ret;
272                 }
273             }
274         }
275     }
276
277     return 0;
278 }
279
280 static int pick_format(AVFilterLink *link)
281 {
282     if (!link || !link->in_formats)
283         return 0;
284
285     link->in_formats->format_count = 1;
286     link->format = link->in_formats->formats[0];
287
288     if (link->type == AVMEDIA_TYPE_AUDIO) {
289         if (!link->in_samplerates->format_count) {
290             av_log(link->src, AV_LOG_ERROR, "Cannot select sample rate for"
291                    " the link between filters %s and %s.\n", link->src->name,
292                    link->dst->name);
293             return AVERROR(EINVAL);
294         }
295         link->in_samplerates->format_count = 1;
296         link->sample_rate = link->in_samplerates->formats[0];
297
298         if (!link->in_channel_layouts->nb_channel_layouts) {
299             av_log(link->src, AV_LOG_ERROR, "Cannot select channel layout for"
300                    "the link between filters %s and %s.\n", link->src->name,
301                    link->dst->name);
302             return AVERROR(EINVAL);
303         }
304         link->in_channel_layouts->nb_channel_layouts = 1;
305         link->channel_layout = link->in_channel_layouts->channel_layouts[0];
306     }
307
308     ff_formats_unref(&link->in_formats);
309     ff_formats_unref(&link->out_formats);
310     ff_formats_unref(&link->in_samplerates);
311     ff_formats_unref(&link->out_samplerates);
312     ff_channel_layouts_unref(&link->in_channel_layouts);
313     ff_channel_layouts_unref(&link->out_channel_layouts);
314
315     return 0;
316 }
317
318 #define REDUCE_FORMATS(fmt_type, list_type, list, var, nb, add_format) \
319 do {                                                                   \
320     for (i = 0; i < filter->nb_inputs; i++) {                          \
321         AVFilterLink *link = filter->inputs[i];                        \
322         fmt_type fmt;                                                  \
323                                                                        \
324         if (!link->out_ ## list || link->out_ ## list->nb != 1)        \
325             continue;                                                  \
326         fmt = link->out_ ## list->var[0];                              \
327                                                                        \
328         for (j = 0; j < filter->nb_outputs; j++) {                     \
329             AVFilterLink *out_link = filter->outputs[j];               \
330             list_type *fmts;                                           \
331                                                                        \
332             if (link->type != out_link->type ||                        \
333                 out_link->in_ ## list->nb == 1)                        \
334                 continue;                                              \
335             fmts = out_link->in_ ## list;                              \
336                                                                        \
337             if (!out_link->in_ ## list->nb) {                          \
338                 add_format(&out_link->in_ ##list, fmt);                \
339                 break;                                                 \
340             }                                                          \
341                                                                        \
342             for (k = 0; k < out_link->in_ ## list->nb; k++)            \
343                 if (fmts->var[k] == fmt) {                             \
344                     fmts->var[0]  = fmt;                               \
345                     fmts->nb = 1;                                      \
346                     ret = 1;                                           \
347                     break;                                             \
348                 }                                                      \
349         }                                                              \
350     }                                                                  \
351 } while (0)
352
353 static int reduce_formats_on_filter(AVFilterContext *filter)
354 {
355     int i, j, k, ret = 0;
356
357     REDUCE_FORMATS(int,      AVFilterFormats,        formats,         formats,
358                    format_count, ff_add_format);
359     REDUCE_FORMATS(int,      AVFilterFormats,        samplerates,     formats,
360                    format_count, ff_add_format);
361     REDUCE_FORMATS(uint64_t, AVFilterChannelLayouts, channel_layouts,
362                    channel_layouts, nb_channel_layouts, ff_add_channel_layout);
363
364     return ret;
365 }
366
367 static void reduce_formats(AVFilterGraph *graph)
368 {
369     int i, reduced;
370
371     do {
372         reduced = 0;
373
374         for (i = 0; i < graph->filter_count; i++)
375             reduced |= reduce_formats_on_filter(graph->filters[i]);
376     } while (reduced);
377 }
378
379 static void swap_samplerates_on_filter(AVFilterContext *filter)
380 {
381     AVFilterLink *link = NULL;
382     int sample_rate;
383     int i, j;
384
385     for (i = 0; i < filter->nb_inputs; i++) {
386         link = filter->inputs[i];
387
388         if (link->type == AVMEDIA_TYPE_AUDIO &&
389             link->out_samplerates->format_count == 1)
390             break;
391     }
392     if (i == filter->nb_inputs)
393         return;
394
395     sample_rate = link->out_samplerates->formats[0];
396
397     for (i = 0; i < filter->nb_outputs; i++) {
398         AVFilterLink *outlink = filter->outputs[i];
399         int best_idx, best_diff = INT_MAX;
400
401         if (outlink->type != AVMEDIA_TYPE_AUDIO ||
402             outlink->in_samplerates->format_count < 2)
403             continue;
404
405         for (j = 0; j < outlink->in_samplerates->format_count; j++) {
406             int diff = abs(sample_rate - outlink->in_samplerates->formats[j]);
407
408             if (diff < best_diff) {
409                 best_diff = diff;
410                 best_idx  = j;
411             }
412         }
413         FFSWAP(int, outlink->in_samplerates->formats[0],
414                outlink->in_samplerates->formats[best_idx]);
415     }
416 }
417
418 static void swap_samplerates(AVFilterGraph *graph)
419 {
420     int i;
421
422     for (i = 0; i < graph->filter_count; i++)
423         swap_samplerates_on_filter(graph->filters[i]);
424 }
425
426 static void swap_channel_layouts_on_filter(AVFilterContext *filter)
427 {
428     AVFilterLink *link = NULL;
429     uint64_t chlayout;
430     int i, j;
431
432     for (i = 0; i < filter->nb_inputs; i++) {
433         link = filter->inputs[i];
434
435         if (link->type == AVMEDIA_TYPE_AUDIO &&
436             link->out_channel_layouts->nb_channel_layouts == 1)
437             break;
438     }
439     if (i == filter->nb_inputs)
440         return;
441
442     chlayout = link->out_channel_layouts->channel_layouts[0];
443
444     for (i = 0; i < filter->nb_outputs; i++) {
445         AVFilterLink *outlink = filter->outputs[i];
446         int best_idx, best_score = INT_MIN;
447
448         if (outlink->type != AVMEDIA_TYPE_AUDIO ||
449             outlink->in_channel_layouts->nb_channel_layouts < 2)
450             continue;
451
452         for (j = 0; j < outlink->in_channel_layouts->nb_channel_layouts; j++) {
453             uint64_t out_chlayout = outlink->in_channel_layouts->channel_layouts[j];
454             int matched_channels  = av_get_channel_layout_nb_channels(chlayout &
455                                                                       out_chlayout);
456             int extra_channels     = av_get_channel_layout_nb_channels(out_chlayout &
457                                                                        (~chlayout));
458             int score = matched_channels - extra_channels;
459
460             if (score > best_score) {
461                 best_score = score;
462                 best_idx   = j;
463             }
464         }
465         FFSWAP(uint64_t, outlink->in_channel_layouts->channel_layouts[0],
466                outlink->in_channel_layouts->channel_layouts[best_idx]);
467     }
468
469 }
470
471 static void swap_channel_layouts(AVFilterGraph *graph)
472 {
473     int i;
474
475     for (i = 0; i < graph->filter_count; i++)
476         swap_channel_layouts_on_filter(graph->filters[i]);
477 }
478
479 static void swap_sample_fmts_on_filter(AVFilterContext *filter)
480 {
481     AVFilterLink *link = NULL;
482     int format, bps;
483     int i, j;
484
485     for (i = 0; i < filter->nb_inputs; i++) {
486         link = filter->inputs[i];
487
488         if (link->type == AVMEDIA_TYPE_AUDIO &&
489             link->out_formats->format_count == 1)
490             break;
491     }
492     if (i == filter->nb_inputs)
493         return;
494
495     format = link->out_formats->formats[0];
496     bps    = av_get_bytes_per_sample(format);
497
498     for (i = 0; i < filter->nb_outputs; i++) {
499         AVFilterLink *outlink = filter->outputs[i];
500         int best_idx, best_score = INT_MIN;
501
502         if (outlink->type != AVMEDIA_TYPE_AUDIO ||
503             outlink->in_formats->format_count < 2)
504             continue;
505
506         for (j = 0; j < outlink->in_formats->format_count; j++) {
507             int out_format = outlink->in_formats->formats[j];
508             int out_bps    = av_get_bytes_per_sample(out_format);
509             int score;
510
511             if (av_get_packed_sample_fmt(out_format) == format ||
512                 av_get_planar_sample_fmt(out_format) == format) {
513                 best_idx   = j;
514                 break;
515             }
516
517             /* for s32 and float prefer double to prevent loss of information */
518             if (bps == 4 && out_bps == 8) {
519                 best_idx = j;
520                 break;
521             }
522
523             /* prefer closest higher or equal bps */
524             score = -abs(out_bps - bps);
525             if (out_bps >= bps)
526                 score += INT_MAX/2;
527
528             if (score > best_score) {
529                 best_score = score;
530                 best_idx   = j;
531             }
532         }
533         FFSWAP(int, outlink->in_formats->formats[0],
534                outlink->in_formats->formats[best_idx]);
535     }
536 }
537
538 static void swap_sample_fmts(AVFilterGraph *graph)
539 {
540     int i;
541
542     for (i = 0; i < graph->filter_count; i++)
543         swap_sample_fmts_on_filter(graph->filters[i]);
544
545 }
546
547 static int pick_formats(AVFilterGraph *graph)
548 {
549     int i, j, ret;
550
551     for (i = 0; i < graph->filter_count; i++) {
552         AVFilterContext *filter = graph->filters[i];
553
554         for (j = 0; j < filter->nb_inputs; j++)
555             if ((ret = pick_format(filter->inputs[j])) < 0)
556                 return ret;
557         for (j = 0; j < filter->nb_outputs; j++)
558             if ((ret = pick_format(filter->outputs[j])) < 0)
559                 return ret;
560     }
561     return 0;
562 }
563
564 /**
565  * Configure the formats of all the links in the graph.
566  */
567 static int graph_config_formats(AVFilterGraph *graph, AVClass *log_ctx)
568 {
569     int ret;
570
571     /* find supported formats from sub-filters, and merge along links */
572     if ((ret = query_formats(graph, log_ctx)) < 0)
573         return ret;
574
575     /* Once everything is merged, it's possible that we'll still have
576      * multiple valid media format choices. We try to minimize the amount
577      * of format conversion inside filters */
578     reduce_formats(graph);
579
580     /* for audio filters, ensure the best format, sample rate and channel layout
581      * is selected */
582     swap_sample_fmts(graph);
583     swap_samplerates(graph);
584     swap_channel_layouts(graph);
585
586     if ((ret = pick_formats(graph)) < 0)
587         return ret;
588
589     return 0;
590 }
591
592 static int graph_insert_fifos(AVFilterGraph *graph, AVClass *log_ctx)
593 {
594     AVFilterContext *f;
595     int i, j, ret;
596     int fifo_count = 0;
597
598     for (i = 0; i < graph->filter_count; i++) {
599         f = graph->filters[i];
600
601         for (j = 0; j < f->nb_inputs; j++) {
602             AVFilterLink *link = f->inputs[j];
603             AVFilterContext *fifo_ctx;
604             AVFilter *fifo;
605             char name[32];
606
607             if (!link->dstpad->needs_fifo)
608                 continue;
609
610             fifo = f->inputs[j]->type == AVMEDIA_TYPE_VIDEO ?
611                    avfilter_get_by_name("fifo") :
612                    avfilter_get_by_name("afifo");
613
614             snprintf(name, sizeof(name), "auto-inserted fifo %d", fifo_count++);
615
616             ret = avfilter_graph_create_filter(&fifo_ctx, fifo, name, NULL,
617                                                NULL, graph);
618             if (ret < 0)
619                 return ret;
620
621             ret = avfilter_insert_filter(link, fifo_ctx, 0, 0);
622             if (ret < 0)
623                 return ret;
624         }
625     }
626
627     return 0;
628 }
629
630 int avfilter_graph_config(AVFilterGraph *graphctx, void *log_ctx)
631 {
632     int ret;
633
634     if ((ret = graph_check_validity(graphctx, log_ctx)))
635         return ret;
636     if ((ret = graph_insert_fifos(graphctx, log_ctx)) < 0)
637         return ret;
638     if ((ret = graph_config_formats(graphctx, log_ctx)))
639         return ret;
640     if ((ret = graph_config_links(graphctx, log_ctx)))
641         return ret;
642
643     return 0;
644 }