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