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