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