avconv: update to the new options syntax.
[ffmpeg.git] / avconv_filter.c
1 /*
2  * avconv filter configuration
3  *
4  * This file is part of Libav.
5  *
6  * Libav is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU Lesser General Public
8  * License as published by the Free Software Foundation; either
9  * version 2.1 of the License, or (at your option) any later version.
10  *
11  * Libav is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14  * Lesser General Public License for more details.
15  *
16  * You should have received a copy of the GNU Lesser General Public
17  * License along with Libav; if not, write to the Free Software
18  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
19  */
20
21 #include "avconv.h"
22
23 #include "libavfilter/avfilter.h"
24
25 #include "libavresample/avresample.h"
26
27 #include "libavutil/avassert.h"
28 #include "libavutil/avstring.h"
29 #include "libavutil/channel_layout.h"
30 #include "libavutil/opt.h"
31 #include "libavutil/pixdesc.h"
32 #include "libavutil/pixfmt.h"
33 #include "libavutil/samplefmt.h"
34
35 /* Define a function for building a string containing a list of
36  * allowed formats. */
37 #define DEF_CHOOSE_FORMAT(type, var, supported_list, none, get_name)           \
38 static char *choose_ ## var ## s(OutputStream *ost)                            \
39 {                                                                              \
40     if (ost->st->codec->var != none) {                                         \
41         get_name(ost->st->codec->var);                                         \
42         return av_strdup(name);                                                \
43     } else if (ost->enc && ost->enc->supported_list) {                         \
44         const type *p;                                                         \
45         AVIOContext *s = NULL;                                                 \
46         uint8_t *ret;                                                          \
47         int len;                                                               \
48                                                                                \
49         if (avio_open_dyn_buf(&s) < 0)                                         \
50             exit(1);                                                           \
51                                                                                \
52         for (p = ost->enc->supported_list; *p != none; p++) {                  \
53             get_name(*p);                                                      \
54             avio_printf(s, "%s|", name);                                       \
55         }                                                                      \
56         len = avio_close_dyn_buf(s, &ret);                                     \
57         ret[len - 1] = 0;                                                      \
58         return ret;                                                            \
59     } else                                                                     \
60         return NULL;                                                           \
61 }
62
63 DEF_CHOOSE_FORMAT(enum AVPixelFormat, pix_fmt, pix_fmts, AV_PIX_FMT_NONE,
64                   GET_PIX_FMT_NAME)
65
66 DEF_CHOOSE_FORMAT(enum AVSampleFormat, sample_fmt, sample_fmts,
67                   AV_SAMPLE_FMT_NONE, GET_SAMPLE_FMT_NAME)
68
69 DEF_CHOOSE_FORMAT(int, sample_rate, supported_samplerates, 0,
70                   GET_SAMPLE_RATE_NAME)
71
72 DEF_CHOOSE_FORMAT(uint64_t, channel_layout, channel_layouts, 0,
73                   GET_CH_LAYOUT_NAME)
74
75 FilterGraph *init_simple_filtergraph(InputStream *ist, OutputStream *ost)
76 {
77     FilterGraph *fg = av_mallocz(sizeof(*fg));
78
79     if (!fg)
80         exit(1);
81     fg->index = nb_filtergraphs;
82
83     GROW_ARRAY(fg->outputs, fg->nb_outputs);
84     if (!(fg->outputs[0] = av_mallocz(sizeof(*fg->outputs[0]))))
85         exit(1);
86     fg->outputs[0]->ost   = ost;
87     fg->outputs[0]->graph = fg;
88
89     ost->filter = fg->outputs[0];
90
91     GROW_ARRAY(fg->inputs, fg->nb_inputs);
92     if (!(fg->inputs[0] = av_mallocz(sizeof(*fg->inputs[0]))))
93         exit(1);
94     fg->inputs[0]->ist   = ist;
95     fg->inputs[0]->graph = fg;
96
97     GROW_ARRAY(ist->filters, ist->nb_filters);
98     ist->filters[ist->nb_filters - 1] = fg->inputs[0];
99
100     GROW_ARRAY(filtergraphs, nb_filtergraphs);
101     filtergraphs[nb_filtergraphs - 1] = fg;
102
103     return fg;
104 }
105
106 static void init_input_filter(FilterGraph *fg, AVFilterInOut *in)
107 {
108     InputStream *ist = NULL;
109     enum AVMediaType type = avfilter_pad_get_type(in->filter_ctx->input_pads, in->pad_idx);
110     int i;
111
112     // TODO: support other filter types
113     if (type != AVMEDIA_TYPE_VIDEO && type != AVMEDIA_TYPE_AUDIO) {
114         av_log(NULL, AV_LOG_FATAL, "Only video and audio filters supported "
115                "currently.\n");
116         exit(1);
117     }
118
119     if (in->name) {
120         AVFormatContext *s;
121         AVStream       *st = NULL;
122         char *p;
123         int file_idx = strtol(in->name, &p, 0);
124
125         if (file_idx < 0 || file_idx >= nb_input_files) {
126             av_log(NULL, AV_LOG_FATAL, "Invalid file index %d in filtegraph description %s.\n",
127                    file_idx, fg->graph_desc);
128             exit(1);
129         }
130         s = input_files[file_idx]->ctx;
131
132         for (i = 0; i < s->nb_streams; i++) {
133             if (s->streams[i]->codec->codec_type != type)
134                 continue;
135             if (check_stream_specifier(s, s->streams[i], *p == ':' ? p + 1 : p) == 1) {
136                 st = s->streams[i];
137                 break;
138             }
139         }
140         if (!st) {
141             av_log(NULL, AV_LOG_FATAL, "Stream specifier '%s' in filtergraph description %s "
142                    "matches no streams.\n", p, fg->graph_desc);
143             exit(1);
144         }
145         ist = input_streams[input_files[file_idx]->ist_index + st->index];
146     } else {
147         /* find the first unused stream of corresponding type */
148         for (i = 0; i < nb_input_streams; i++) {
149             ist = input_streams[i];
150             if (ist->st->codec->codec_type == type && ist->discard)
151                 break;
152         }
153         if (i == nb_input_streams) {
154             av_log(NULL, AV_LOG_FATAL, "Cannot find a matching stream for "
155                    "unlabeled input pad %d on filter %s", in->pad_idx,
156                    in->filter_ctx->name);
157             exit(1);
158         }
159     }
160     av_assert0(ist);
161
162     ist->discard         = 0;
163     ist->decoding_needed = 1;
164     ist->st->discard = AVDISCARD_NONE;
165
166     GROW_ARRAY(fg->inputs, fg->nb_inputs);
167     if (!(fg->inputs[fg->nb_inputs - 1] = av_mallocz(sizeof(*fg->inputs[0]))))
168         exit(1);
169     fg->inputs[fg->nb_inputs - 1]->ist   = ist;
170     fg->inputs[fg->nb_inputs - 1]->graph = fg;
171
172     GROW_ARRAY(ist->filters, ist->nb_filters);
173     ist->filters[ist->nb_filters - 1] = fg->inputs[fg->nb_inputs - 1];
174 }
175
176 static int configure_output_video_filter(FilterGraph *fg, OutputFilter *ofilter, AVFilterInOut *out)
177 {
178     char *pix_fmts;
179     OutputStream *ost = ofilter->ost;
180     AVCodecContext *codec = ost->st->codec;
181     AVFilterContext *last_filter = out->filter_ctx;
182     int pad_idx = out->pad_idx;
183     int ret;
184     char name[255];
185
186     snprintf(name, sizeof(name), "output stream %d:%d", ost->file_index, ost->index);
187     ret = avfilter_graph_create_filter(&ofilter->filter,
188                                        avfilter_get_by_name("buffersink"),
189                                        name, NULL, NULL, fg->graph);
190     if (ret < 0)
191         return ret;
192
193     if (codec->width || codec->height) {
194         char args[255];
195         AVFilterContext *filter;
196
197         snprintf(args, sizeof(args), "%d:%d:flags=0x%X",
198                  codec->width,
199                  codec->height,
200                  (unsigned)ost->sws_flags);
201         snprintf(name, sizeof(name), "scaler for output stream %d:%d",
202                  ost->file_index, ost->index);
203         if ((ret = avfilter_graph_create_filter(&filter, avfilter_get_by_name("scale"),
204                                                 name, args, NULL, fg->graph)) < 0)
205             return ret;
206         if ((ret = avfilter_link(last_filter, pad_idx, filter, 0)) < 0)
207             return ret;
208
209         last_filter = filter;
210         pad_idx = 0;
211     }
212
213     if ((pix_fmts = choose_pix_fmts(ost))) {
214         AVFilterContext *filter;
215         snprintf(name, sizeof(name), "pixel format for output stream %d:%d",
216                  ost->file_index, ost->index);
217         if ((ret = avfilter_graph_create_filter(&filter,
218                                                 avfilter_get_by_name("format"),
219                                                 "format", pix_fmts, NULL,
220                                                 fg->graph)) < 0)
221             return ret;
222         if ((ret = avfilter_link(last_filter, pad_idx, filter, 0)) < 0)
223             return ret;
224
225         last_filter = filter;
226         pad_idx     = 0;
227         av_freep(&pix_fmts);
228     }
229
230     if (ost->frame_rate.num) {
231         AVFilterContext *fps;
232         char args[255];
233
234         snprintf(args, sizeof(args), "fps=%d/%d", ost->frame_rate.num,
235                  ost->frame_rate.den);
236         snprintf(name, sizeof(name), "fps for output stream %d:%d",
237                  ost->file_index, ost->index);
238         ret = avfilter_graph_create_filter(&fps, avfilter_get_by_name("fps"),
239                                            name, args, NULL, fg->graph);
240         if (ret < 0)
241             return ret;
242
243         ret = avfilter_link(last_filter, pad_idx, fps, 0);
244         if (ret < 0)
245             return ret;
246         last_filter = fps;
247         pad_idx = 0;
248     }
249
250     if ((ret = avfilter_link(last_filter, pad_idx, ofilter->filter, 0)) < 0)
251         return ret;
252
253     return 0;
254 }
255
256 static int configure_output_audio_filter(FilterGraph *fg, OutputFilter *ofilter, AVFilterInOut *out)
257 {
258     OutputStream *ost = ofilter->ost;
259     AVCodecContext *codec  = ost->st->codec;
260     AVFilterContext *last_filter = out->filter_ctx;
261     int pad_idx = out->pad_idx;
262     char *sample_fmts, *sample_rates, *channel_layouts;
263     char name[255];
264     int ret;
265
266
267     snprintf(name, sizeof(name), "output stream %d:%d", ost->file_index, ost->index);
268     ret = avfilter_graph_create_filter(&ofilter->filter,
269                                        avfilter_get_by_name("abuffersink"),
270                                        name, NULL, NULL, fg->graph);
271     if (ret < 0)
272         return ret;
273
274     if (codec->channels && !codec->channel_layout)
275         codec->channel_layout = av_get_default_channel_layout(codec->channels);
276
277     sample_fmts     = choose_sample_fmts(ost);
278     sample_rates    = choose_sample_rates(ost);
279     channel_layouts = choose_channel_layouts(ost);
280     if (sample_fmts || sample_rates || channel_layouts) {
281         AVFilterContext *format;
282         char args[256];
283         int len = 0;
284
285         if (sample_fmts)
286             len += snprintf(args + len, sizeof(args) - len, "sample_fmts=%s:",
287                             sample_fmts);
288         if (sample_rates)
289             len += snprintf(args + len, sizeof(args) - len, "sample_rates=%s:",
290                             sample_rates);
291         if (channel_layouts)
292             len += snprintf(args + len, sizeof(args) - len, "channel_layouts=%s:",
293                             channel_layouts);
294         args[len - 1] = 0;
295
296         av_freep(&sample_fmts);
297         av_freep(&sample_rates);
298         av_freep(&channel_layouts);
299
300         snprintf(name, sizeof(name), "audio format for output stream %d:%d",
301                  ost->file_index, ost->index);
302         ret = avfilter_graph_create_filter(&format,
303                                            avfilter_get_by_name("aformat"),
304                                            name, args, NULL, fg->graph);
305         if (ret < 0)
306             return ret;
307
308         ret = avfilter_link(last_filter, pad_idx, format, 0);
309         if (ret < 0)
310             return ret;
311
312         last_filter = format;
313         pad_idx = 0;
314     }
315
316     if ((ret = avfilter_link(last_filter, pad_idx, ofilter->filter, 0)) < 0)
317         return ret;
318
319     return 0;
320 }
321
322 #define DESCRIBE_FILTER_LINK(f, inout, in)                         \
323 {                                                                  \
324     AVFilterContext *ctx = inout->filter_ctx;                      \
325     AVFilterPad *pads = in ? ctx->input_pads  : ctx->output_pads;  \
326     int       nb_pads = in ? ctx->input_count : ctx->output_count; \
327     AVIOContext *pb;                                               \
328                                                                    \
329     if (avio_open_dyn_buf(&pb) < 0)                                \
330         exit(1);                                                   \
331                                                                    \
332     avio_printf(pb, "%s", ctx->filter->name);                      \
333     if (nb_pads > 1)                                               \
334         avio_printf(pb, ":%s", avfilter_pad_get_name(pads, inout->pad_idx));\
335     avio_w8(pb, 0);                                                \
336     avio_close_dyn_buf(pb, &f->name);                              \
337 }
338
339 int configure_output_filter(FilterGraph *fg, OutputFilter *ofilter, AVFilterInOut *out)
340 {
341     av_freep(&ofilter->name);
342     DESCRIBE_FILTER_LINK(ofilter, out, 0);
343
344     switch (avfilter_pad_get_type(out->filter_ctx->output_pads, out->pad_idx)) {
345     case AVMEDIA_TYPE_VIDEO: return configure_output_video_filter(fg, ofilter, out);
346     case AVMEDIA_TYPE_AUDIO: return configure_output_audio_filter(fg, ofilter, out);
347     default: av_assert0(0);
348     }
349 }
350
351 static int configure_input_video_filter(FilterGraph *fg, InputFilter *ifilter,
352                                         AVFilterInOut *in)
353 {
354     AVFilterContext *first_filter = in->filter_ctx;
355     AVFilter *filter = avfilter_get_by_name("buffer");
356     InputStream *ist = ifilter->ist;
357     AVRational tb = ist->framerate.num ? av_inv_q(ist->framerate) :
358                                          ist->st->time_base;
359     AVRational sar;
360     char args[255], name[255];
361     int pad_idx = in->pad_idx;
362     int ret;
363
364     sar = ist->st->sample_aspect_ratio.num ?
365           ist->st->sample_aspect_ratio :
366           ist->st->codec->sample_aspect_ratio;
367     snprintf(args, sizeof(args), "%d:%d:%d:%d:%d:%d:%d", ist->st->codec->width,
368              ist->st->codec->height, ist->st->codec->pix_fmt,
369              tb.num, tb.den, sar.num, sar.den);
370     snprintf(name, sizeof(name), "graph %d input from stream %d:%d", fg->index,
371              ist->file_index, ist->st->index);
372
373     if ((ret = avfilter_graph_create_filter(&ifilter->filter, filter, name,
374                                             args, NULL, fg->graph)) < 0)
375         return ret;
376
377     if (ist->framerate.num) {
378         AVFilterContext *setpts;
379
380         snprintf(name, sizeof(name), "force CFR for input from stream %d:%d",
381                  ist->file_index, ist->st->index);
382         if ((ret = avfilter_graph_create_filter(&setpts,
383                                                 avfilter_get_by_name("setpts"),
384                                                 name, "N", NULL,
385                                                 fg->graph)) < 0)
386             return ret;
387
388         if ((ret = avfilter_link(setpts, 0, first_filter, pad_idx)) < 0)
389             return ret;
390
391         first_filter = setpts;
392         pad_idx = 0;
393     }
394
395     if ((ret = avfilter_link(ifilter->filter, 0, first_filter, pad_idx)) < 0)
396         return ret;
397     return 0;
398 }
399
400 static int configure_input_audio_filter(FilterGraph *fg, InputFilter *ifilter,
401                                         AVFilterInOut *in)
402 {
403     AVFilterContext *first_filter = in->filter_ctx;
404     AVFilter *filter = avfilter_get_by_name("abuffer");
405     InputStream *ist = ifilter->ist;
406     int pad_idx = in->pad_idx;
407     char args[255], name[255];
408     int ret;
409
410     snprintf(args, sizeof(args), "time_base=%d/%d:sample_rate=%d:sample_fmt=%s"
411              ":channel_layout=0x%"PRIx64,
412              1, ist->st->codec->sample_rate,
413              ist->st->codec->sample_rate,
414              av_get_sample_fmt_name(ist->st->codec->sample_fmt),
415              ist->st->codec->channel_layout);
416     snprintf(name, sizeof(name), "graph %d input from stream %d:%d", fg->index,
417              ist->file_index, ist->st->index);
418
419     if ((ret = avfilter_graph_create_filter(&ifilter->filter, filter,
420                                             name, args, NULL,
421                                             fg->graph)) < 0)
422         return ret;
423
424     if (audio_sync_method > 0) {
425         AVFilterContext *async;
426         int  len = 0;
427
428         av_log(NULL, AV_LOG_WARNING, "-async has been deprecated. Used the "
429                "asyncts audio filter instead.\n");
430
431         if (audio_sync_method > 1)
432             len += snprintf(args + len, sizeof(args) - len, "compensate=1:"
433                             "max_comp=%d:", audio_sync_method);
434         snprintf(args + len, sizeof(args) - len, "min_delta=%f",
435                  audio_drift_threshold);
436
437         snprintf(name, sizeof(name), "graph %d audio sync for input stream %d:%d",
438                  fg->index, ist->file_index, ist->st->index);
439         ret = avfilter_graph_create_filter(&async,
440                                            avfilter_get_by_name("asyncts"),
441                                            name, args, NULL, fg->graph);
442         if (ret < 0)
443             return ret;
444
445         ret = avfilter_link(async, 0, first_filter, pad_idx);
446         if (ret < 0)
447             return ret;
448
449         first_filter = async;
450         pad_idx = 0;
451     }
452     if (audio_volume != 256) {
453         AVFilterContext *volume;
454
455         av_log(NULL, AV_LOG_WARNING, "-vol has been deprecated. Use the volume "
456                "audio filter instead.\n");
457
458         snprintf(args, sizeof(args), "volume=%f", audio_volume / 256.0);
459
460         snprintf(name, sizeof(name), "graph %d volume for input stream %d:%d",
461                  fg->index, ist->file_index, ist->st->index);
462         ret = avfilter_graph_create_filter(&volume,
463                                            avfilter_get_by_name("volume"),
464                                            name, args, NULL, fg->graph);
465         if (ret < 0)
466             return ret;
467
468         ret = avfilter_link(volume, 0, first_filter, pad_idx);
469         if (ret < 0)
470             return ret;
471
472         first_filter = volume;
473         pad_idx = 0;
474     }
475     if ((ret = avfilter_link(ifilter->filter, 0, first_filter, pad_idx)) < 0)
476         return ret;
477
478     return 0;
479 }
480
481 static int configure_input_filter(FilterGraph *fg, InputFilter *ifilter,
482                                   AVFilterInOut *in)
483 {
484     av_freep(&ifilter->name);
485     DESCRIBE_FILTER_LINK(ifilter, in, 1);
486
487     switch (avfilter_pad_get_type(in->filter_ctx->input_pads, in->pad_idx)) {
488     case AVMEDIA_TYPE_VIDEO: return configure_input_video_filter(fg, ifilter, in);
489     case AVMEDIA_TYPE_AUDIO: return configure_input_audio_filter(fg, ifilter, in);
490     default: av_assert0(0);
491     }
492 }
493
494 int configure_filtergraph(FilterGraph *fg)
495 {
496     AVFilterInOut *inputs, *outputs, *cur;
497     int ret, i, init = !fg->graph, simple = !fg->graph_desc;
498     const char *graph_desc = simple ? fg->outputs[0]->ost->avfilter :
499                                       fg->graph_desc;
500
501     avfilter_graph_free(&fg->graph);
502     if (!(fg->graph = avfilter_graph_alloc()))
503         return AVERROR(ENOMEM);
504
505     if (simple) {
506         OutputStream *ost = fg->outputs[0]->ost;
507         char args[512];
508         AVDictionaryEntry *e = NULL;
509
510         snprintf(args, sizeof(args), "flags=0x%X", (unsigned)ost->sws_flags);
511         fg->graph->scale_sws_opts = av_strdup(args);
512
513         args[0] = '\0';
514         while ((e = av_dict_get(fg->outputs[0]->ost->resample_opts, "", e,
515                                 AV_DICT_IGNORE_SUFFIX))) {
516             av_strlcatf(args, sizeof(args), "%s=%s:", e->key, e->value);
517         }
518         if (strlen(args))
519             args[strlen(args) - 1] = '\0';
520         fg->graph->resample_lavr_opts = av_strdup(args);
521     }
522
523     if ((ret = avfilter_graph_parse2(fg->graph, graph_desc, &inputs, &outputs)) < 0)
524         return ret;
525
526     if (simple && (!inputs || inputs->next || !outputs || outputs->next)) {
527         av_log(NULL, AV_LOG_ERROR, "Simple filtergraph '%s' does not have "
528                "exactly one input and output.\n", graph_desc);
529         return AVERROR(EINVAL);
530     }
531
532     for (cur = inputs; !simple && init && cur; cur = cur->next)
533         init_input_filter(fg, cur);
534
535     for (cur = inputs, i = 0; cur; cur = cur->next, i++)
536         if ((ret = configure_input_filter(fg, fg->inputs[i], cur)) < 0)
537             return ret;
538     avfilter_inout_free(&inputs);
539
540     if (!init || simple) {
541         /* we already know the mappings between lavfi outputs and output streams,
542          * so we can finish the setup */
543         for (cur = outputs, i = 0; cur; cur = cur->next, i++)
544             configure_output_filter(fg, fg->outputs[i], cur);
545         avfilter_inout_free(&outputs);
546
547         if ((ret = avfilter_graph_config(fg->graph, NULL)) < 0)
548             return ret;
549     } else {
550         /* wait until output mappings are processed */
551         for (cur = outputs; cur;) {
552             GROW_ARRAY(fg->outputs, fg->nb_outputs);
553             if (!(fg->outputs[fg->nb_outputs - 1] = av_mallocz(sizeof(*fg->outputs[0]))))
554                 exit(1);
555             fg->outputs[fg->nb_outputs - 1]->graph   = fg;
556             fg->outputs[fg->nb_outputs - 1]->out_tmp = cur;
557             cur = cur->next;
558             fg->outputs[fg->nb_outputs - 1]->out_tmp->next = NULL;
559         }
560     }
561
562     return 0;
563 }
564
565 int ist_in_filtergraph(FilterGraph *fg, InputStream *ist)
566 {
567     int i;
568     for (i = 0; i < fg->nb_inputs; i++)
569         if (fg->inputs[i]->ist == ist)
570             return 1;
571     return 0;
572 }
573