7f1ee1b6b91fc7da4206b0c74b3ca5febd317f1c
[ffmpeg.git] / ffmpeg_filter.c
1 /*
2  * ffmpeg filter configuration
3  *
4  * This file is part of FFmpeg.
5  *
6  * FFmpeg 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  * FFmpeg 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 FFmpeg; if not, write to the Free Software
18  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
19  */
20
21 #include <stdint.h>
22
23 #include "ffmpeg.h"
24
25 #include "libavfilter/avfilter.h"
26 #include "libavfilter/buffersink.h"
27
28 #include "libavresample/avresample.h"
29
30 #include "libavutil/avassert.h"
31 #include "libavutil/avstring.h"
32 #include "libavutil/bprint.h"
33 #include "libavutil/channel_layout.h"
34 #include "libavutil/display.h"
35 #include "libavutil/opt.h"
36 #include "libavutil/pixdesc.h"
37 #include "libavutil/pixfmt.h"
38 #include "libavutil/imgutils.h"
39 #include "libavutil/samplefmt.h"
40
41 enum AVPixelFormat choose_pixel_fmt(AVStream *st, AVCodecContext *enc_ctx, AVCodec *codec, enum AVPixelFormat target)
42 {
43     if (codec && codec->pix_fmts) {
44         const enum AVPixelFormat *p = codec->pix_fmts;
45         const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(target);
46         int has_alpha = desc ? desc->nb_components % 2 == 0 : 0;
47         enum AVPixelFormat best= AV_PIX_FMT_NONE;
48         static const enum AVPixelFormat mjpeg_formats[] =
49             { AV_PIX_FMT_YUVJ420P, AV_PIX_FMT_YUVJ422P, AV_PIX_FMT_YUVJ444P,
50               AV_PIX_FMT_YUV420P,  AV_PIX_FMT_YUV422P,  AV_PIX_FMT_YUV444P,
51               AV_PIX_FMT_NONE };
52         static const enum AVPixelFormat ljpeg_formats[] =
53             { AV_PIX_FMT_BGR24   , AV_PIX_FMT_BGRA    , AV_PIX_FMT_BGR0,
54               AV_PIX_FMT_YUVJ420P, AV_PIX_FMT_YUVJ444P, AV_PIX_FMT_YUVJ422P,
55               AV_PIX_FMT_YUV420P , AV_PIX_FMT_YUV444P , AV_PIX_FMT_YUV422P,
56               AV_PIX_FMT_NONE};
57
58         if (enc_ctx->strict_std_compliance <= FF_COMPLIANCE_UNOFFICIAL) {
59             if (enc_ctx->codec_id == AV_CODEC_ID_MJPEG) {
60                 p = mjpeg_formats;
61             } else if (enc_ctx->codec_id == AV_CODEC_ID_LJPEG) {
62                 p =ljpeg_formats;
63             }
64         }
65         for (; *p != AV_PIX_FMT_NONE; p++) {
66             best= avcodec_find_best_pix_fmt_of_2(best, *p, target, has_alpha, NULL);
67             if (*p == target)
68                 break;
69         }
70         if (*p == AV_PIX_FMT_NONE) {
71             if (target != AV_PIX_FMT_NONE)
72                 av_log(NULL, AV_LOG_WARNING,
73                        "Incompatible pixel format '%s' for codec '%s', auto-selecting format '%s'\n",
74                        av_get_pix_fmt_name(target),
75                        codec->name,
76                        av_get_pix_fmt_name(best));
77             return best;
78         }
79     }
80     return target;
81 }
82
83 void choose_sample_fmt(AVStream *st, AVCodec *codec)
84 {
85     if (codec && codec->sample_fmts) {
86         const enum AVSampleFormat *p = codec->sample_fmts;
87         for (; *p != -1; p++) {
88             if (*p == st->codec->sample_fmt)
89                 break;
90         }
91         if (*p == -1) {
92             if((codec->capabilities & AV_CODEC_CAP_LOSSLESS) && av_get_sample_fmt_name(st->codec->sample_fmt) > av_get_sample_fmt_name(codec->sample_fmts[0]))
93                 av_log(NULL, AV_LOG_ERROR, "Conversion will not be lossless.\n");
94             if(av_get_sample_fmt_name(st->codec->sample_fmt))
95             av_log(NULL, AV_LOG_WARNING,
96                    "Incompatible sample format '%s' for codec '%s', auto-selecting format '%s'\n",
97                    av_get_sample_fmt_name(st->codec->sample_fmt),
98                    codec->name,
99                    av_get_sample_fmt_name(codec->sample_fmts[0]));
100             st->codec->sample_fmt = codec->sample_fmts[0];
101         }
102     }
103 }
104
105 static char *choose_pix_fmts(OutputStream *ost)
106 {
107     AVDictionaryEntry *strict_dict = av_dict_get(ost->encoder_opts, "strict", NULL, 0);
108     if (strict_dict)
109         // used by choose_pixel_fmt() and below
110         av_opt_set(ost->enc_ctx, "strict", strict_dict->value, 0);
111
112      if (ost->keep_pix_fmt) {
113         if (ost->filter)
114             avfilter_graph_set_auto_convert(ost->filter->graph->graph,
115                                             AVFILTER_AUTO_CONVERT_NONE);
116         if (ost->enc_ctx->pix_fmt == AV_PIX_FMT_NONE)
117             return NULL;
118         return av_strdup(av_get_pix_fmt_name(ost->enc_ctx->pix_fmt));
119     }
120     if (ost->enc_ctx->pix_fmt != AV_PIX_FMT_NONE) {
121         return av_strdup(av_get_pix_fmt_name(choose_pixel_fmt(ost->st, ost->enc_ctx, ost->enc, ost->enc_ctx->pix_fmt)));
122     } else if (ost->enc && ost->enc->pix_fmts) {
123         const enum AVPixelFormat *p;
124         AVIOContext *s = NULL;
125         uint8_t *ret;
126         int len;
127
128         if (avio_open_dyn_buf(&s) < 0)
129             exit_program(1);
130
131         p = ost->enc->pix_fmts;
132         if (ost->enc_ctx->strict_std_compliance <= FF_COMPLIANCE_UNOFFICIAL) {
133             if (ost->enc_ctx->codec_id == AV_CODEC_ID_MJPEG) {
134                 p = (const enum AVPixelFormat[]) { AV_PIX_FMT_YUVJ420P, AV_PIX_FMT_YUVJ422P, AV_PIX_FMT_YUV420P, AV_PIX_FMT_YUV422P, AV_PIX_FMT_NONE };
135             } else if (ost->enc_ctx->codec_id == AV_CODEC_ID_LJPEG) {
136                 p = (const enum AVPixelFormat[]) { AV_PIX_FMT_YUVJ420P, AV_PIX_FMT_YUVJ422P, AV_PIX_FMT_YUVJ444P, AV_PIX_FMT_YUV420P,
137                                                     AV_PIX_FMT_YUV422P, AV_PIX_FMT_YUV444P, AV_PIX_FMT_BGRA, AV_PIX_FMT_NONE };
138             }
139         }
140
141         for (; *p != AV_PIX_FMT_NONE; p++) {
142             const char *name = av_get_pix_fmt_name(*p);
143             avio_printf(s, "%s|", name);
144         }
145         len = avio_close_dyn_buf(s, &ret);
146         ret[len - 1] = 0;
147         return ret;
148     } else
149         return NULL;
150 }
151
152 /* Define a function for building a string containing a list of
153  * allowed formats. */
154 #define DEF_CHOOSE_FORMAT(type, var, supported_list, none, get_name)           \
155 static char *choose_ ## var ## s(OutputStream *ost)                            \
156 {                                                                              \
157     if (ost->enc_ctx->var != none) {                                           \
158         get_name(ost->enc_ctx->var);                                           \
159         return av_strdup(name);                                                \
160     } else if (ost->enc && ost->enc->supported_list) {                         \
161         const type *p;                                                         \
162         AVIOContext *s = NULL;                                                 \
163         uint8_t *ret;                                                          \
164         int len;                                                               \
165                                                                                \
166         if (avio_open_dyn_buf(&s) < 0)                                         \
167             exit_program(1);                                                           \
168                                                                                \
169         for (p = ost->enc->supported_list; *p != none; p++) {                  \
170             get_name(*p);                                                      \
171             avio_printf(s, "%s|", name);                                       \
172         }                                                                      \
173         len = avio_close_dyn_buf(s, &ret);                                     \
174         ret[len - 1] = 0;                                                      \
175         return ret;                                                            \
176     } else                                                                     \
177         return NULL;                                                           \
178 }
179
180 // DEF_CHOOSE_FORMAT(enum AVPixelFormat, pix_fmt, pix_fmts, AV_PIX_FMT_NONE,
181 //                   GET_PIX_FMT_NAME)
182
183 DEF_CHOOSE_FORMAT(enum AVSampleFormat, sample_fmt, sample_fmts,
184                   AV_SAMPLE_FMT_NONE, GET_SAMPLE_FMT_NAME)
185
186 DEF_CHOOSE_FORMAT(int, sample_rate, supported_samplerates, 0,
187                   GET_SAMPLE_RATE_NAME)
188
189 DEF_CHOOSE_FORMAT(uint64_t, channel_layout, channel_layouts, 0,
190                   GET_CH_LAYOUT_NAME)
191
192 FilterGraph *init_simple_filtergraph(InputStream *ist, OutputStream *ost)
193 {
194     FilterGraph *fg = av_mallocz(sizeof(*fg));
195
196     if (!fg)
197         exit_program(1);
198     fg->index = nb_filtergraphs;
199
200     GROW_ARRAY(fg->outputs, fg->nb_outputs);
201     if (!(fg->outputs[0] = av_mallocz(sizeof(*fg->outputs[0]))))
202         exit_program(1);
203     fg->outputs[0]->ost   = ost;
204     fg->outputs[0]->graph = fg;
205
206     ost->filter = fg->outputs[0];
207
208     GROW_ARRAY(fg->inputs, fg->nb_inputs);
209     if (!(fg->inputs[0] = av_mallocz(sizeof(*fg->inputs[0]))))
210         exit_program(1);
211     fg->inputs[0]->ist   = ist;
212     fg->inputs[0]->graph = fg;
213
214     GROW_ARRAY(ist->filters, ist->nb_filters);
215     ist->filters[ist->nb_filters - 1] = fg->inputs[0];
216
217     GROW_ARRAY(filtergraphs, nb_filtergraphs);
218     filtergraphs[nb_filtergraphs - 1] = fg;
219
220     return fg;
221 }
222
223 static void init_input_filter(FilterGraph *fg, AVFilterInOut *in)
224 {
225     InputStream *ist = NULL;
226     enum AVMediaType type = avfilter_pad_get_type(in->filter_ctx->input_pads, in->pad_idx);
227     int i;
228
229     // TODO: support other filter types
230     if (type != AVMEDIA_TYPE_VIDEO && type != AVMEDIA_TYPE_AUDIO) {
231         av_log(NULL, AV_LOG_FATAL, "Only video and audio filters supported "
232                "currently.\n");
233         exit_program(1);
234     }
235
236     if (in->name) {
237         AVFormatContext *s;
238         AVStream       *st = NULL;
239         char *p;
240         int file_idx = strtol(in->name, &p, 0);
241
242         if (file_idx < 0 || file_idx >= nb_input_files) {
243             av_log(NULL, AV_LOG_FATAL, "Invalid file index %d in filtergraph description %s.\n",
244                    file_idx, fg->graph_desc);
245             exit_program(1);
246         }
247         s = input_files[file_idx]->ctx;
248
249         for (i = 0; i < s->nb_streams; i++) {
250             enum AVMediaType stream_type = s->streams[i]->codec->codec_type;
251             if (stream_type != type &&
252                 !(stream_type == AVMEDIA_TYPE_SUBTITLE &&
253                   type == AVMEDIA_TYPE_VIDEO /* sub2video hack */))
254                 continue;
255             if (check_stream_specifier(s, s->streams[i], *p == ':' ? p + 1 : p) == 1) {
256                 st = s->streams[i];
257                 break;
258             }
259         }
260         if (!st) {
261             av_log(NULL, AV_LOG_FATAL, "Stream specifier '%s' in filtergraph description %s "
262                    "matches no streams.\n", p, fg->graph_desc);
263             exit_program(1);
264         }
265         ist = input_streams[input_files[file_idx]->ist_index + st->index];
266     } else {
267         /* find the first unused stream of corresponding type */
268         for (i = 0; i < nb_input_streams; i++) {
269             ist = input_streams[i];
270             if (ist->dec_ctx->codec_type == type && ist->discard)
271                 break;
272         }
273         if (i == nb_input_streams) {
274             av_log(NULL, AV_LOG_FATAL, "Cannot find a matching stream for "
275                    "unlabeled input pad %d on filter %s\n", in->pad_idx,
276                    in->filter_ctx->name);
277             exit_program(1);
278         }
279     }
280     av_assert0(ist);
281
282     ist->discard         = 0;
283     ist->decoding_needed |= DECODING_FOR_FILTER;
284     ist->st->discard = AVDISCARD_NONE;
285
286     GROW_ARRAY(fg->inputs, fg->nb_inputs);
287     if (!(fg->inputs[fg->nb_inputs - 1] = av_mallocz(sizeof(*fg->inputs[0]))))
288         exit_program(1);
289     fg->inputs[fg->nb_inputs - 1]->ist   = ist;
290     fg->inputs[fg->nb_inputs - 1]->graph = fg;
291
292     GROW_ARRAY(ist->filters, ist->nb_filters);
293     ist->filters[ist->nb_filters - 1] = fg->inputs[fg->nb_inputs - 1];
294 }
295
296 int init_complex_filtergraph(FilterGraph *fg)
297 {
298     AVFilterInOut *inputs, *outputs, *cur;
299     AVFilterGraph *graph;
300     int ret = 0;
301
302     /* this graph is only used for determining the kinds of inputs
303      * and outputs we have, and is discarded on exit from this function */
304     graph = avfilter_graph_alloc();
305     if (!graph)
306         return AVERROR(ENOMEM);
307
308     ret = avfilter_graph_parse2(graph, fg->graph_desc, &inputs, &outputs);
309     if (ret < 0)
310         goto fail;
311
312     for (cur = inputs; cur; cur = cur->next)
313         init_input_filter(fg, cur);
314
315     for (cur = outputs; cur;) {
316         GROW_ARRAY(fg->outputs, fg->nb_outputs);
317         fg->outputs[fg->nb_outputs - 1] = av_mallocz(sizeof(*fg->outputs[0]));
318         if (!fg->outputs[fg->nb_outputs - 1])
319             exit_program(1);
320
321         fg->outputs[fg->nb_outputs - 1]->graph   = fg;
322         fg->outputs[fg->nb_outputs - 1]->out_tmp = cur;
323         fg->outputs[fg->nb_outputs - 1]->type    = avfilter_pad_get_type(cur->filter_ctx->output_pads,
324                                                                          cur->pad_idx);
325         cur = cur->next;
326         fg->outputs[fg->nb_outputs - 1]->out_tmp->next = NULL;
327     }
328
329 fail:
330     avfilter_inout_free(&inputs);
331     avfilter_graph_free(&graph);
332     return ret;
333 }
334
335 static int insert_trim(int64_t start_time, int64_t duration,
336                        AVFilterContext **last_filter, int *pad_idx,
337                        const char *filter_name)
338 {
339     AVFilterGraph *graph = (*last_filter)->graph;
340     AVFilterContext *ctx;
341     const AVFilter *trim;
342     enum AVMediaType type = avfilter_pad_get_type((*last_filter)->output_pads, *pad_idx);
343     const char *name = (type == AVMEDIA_TYPE_VIDEO) ? "trim" : "atrim";
344     int ret = 0;
345
346     if (duration == INT64_MAX && start_time == AV_NOPTS_VALUE)
347         return 0;
348
349     trim = avfilter_get_by_name(name);
350     if (!trim) {
351         av_log(NULL, AV_LOG_ERROR, "%s filter not present, cannot limit "
352                "recording time.\n", name);
353         return AVERROR_FILTER_NOT_FOUND;
354     }
355
356     ctx = avfilter_graph_alloc_filter(graph, trim, filter_name);
357     if (!ctx)
358         return AVERROR(ENOMEM);
359
360     if (duration != INT64_MAX) {
361         ret = av_opt_set_int(ctx, "durationi", duration,
362                                 AV_OPT_SEARCH_CHILDREN);
363     }
364     if (ret >= 0 && start_time != AV_NOPTS_VALUE) {
365         ret = av_opt_set_int(ctx, "starti", start_time,
366                                 AV_OPT_SEARCH_CHILDREN);
367     }
368     if (ret < 0) {
369         av_log(ctx, AV_LOG_ERROR, "Error configuring the %s filter", name);
370         return ret;
371     }
372
373     ret = avfilter_init_str(ctx, NULL);
374     if (ret < 0)
375         return ret;
376
377     ret = avfilter_link(*last_filter, *pad_idx, ctx, 0);
378     if (ret < 0)
379         return ret;
380
381     *last_filter = ctx;
382     *pad_idx     = 0;
383     return 0;
384 }
385
386 static int insert_filter(AVFilterContext **last_filter, int *pad_idx,
387                          const char *filter_name, const char *args)
388 {
389     AVFilterGraph *graph = (*last_filter)->graph;
390     AVFilterContext *ctx;
391     int ret;
392
393     ret = avfilter_graph_create_filter(&ctx,
394                                        avfilter_get_by_name(filter_name),
395                                        filter_name, args, NULL, graph);
396     if (ret < 0)
397         return ret;
398
399     ret = avfilter_link(*last_filter, *pad_idx, ctx, 0);
400     if (ret < 0)
401         return ret;
402
403     *last_filter = ctx;
404     *pad_idx     = 0;
405     return 0;
406 }
407
408 static int configure_output_video_filter(FilterGraph *fg, OutputFilter *ofilter, AVFilterInOut *out)
409 {
410     char *pix_fmts;
411     OutputStream *ost = ofilter->ost;
412     OutputFile    *of = output_files[ost->file_index];
413     AVCodecContext *codec = ost->enc_ctx;
414     AVFilterContext *last_filter = out->filter_ctx;
415     int pad_idx = out->pad_idx;
416     int ret;
417     char name[255];
418
419     snprintf(name, sizeof(name), "output stream %d:%d", ost->file_index, ost->index);
420     ret = avfilter_graph_create_filter(&ofilter->filter,
421                                        avfilter_get_by_name("buffersink"),
422                                        name, NULL, NULL, fg->graph);
423
424     if (ret < 0)
425         return ret;
426
427     if (codec->width || codec->height) {
428         char args[255];
429         AVFilterContext *filter;
430         AVDictionaryEntry *e = NULL;
431
432         snprintf(args, sizeof(args), "%d:%d",
433                  codec->width,
434                  codec->height);
435
436         while ((e = av_dict_get(ost->sws_dict, "", e,
437                                 AV_DICT_IGNORE_SUFFIX))) {
438             av_strlcatf(args, sizeof(args), ":%s=%s", e->key, e->value);
439         }
440
441         snprintf(name, sizeof(name), "scaler for output stream %d:%d",
442                  ost->file_index, ost->index);
443         if ((ret = avfilter_graph_create_filter(&filter, avfilter_get_by_name("scale"),
444                                                 name, args, NULL, fg->graph)) < 0)
445             return ret;
446         if ((ret = avfilter_link(last_filter, pad_idx, filter, 0)) < 0)
447             return ret;
448
449         last_filter = filter;
450         pad_idx = 0;
451     }
452
453     if ((pix_fmts = choose_pix_fmts(ost))) {
454         AVFilterContext *filter;
455         snprintf(name, sizeof(name), "pixel format for output stream %d:%d",
456                  ost->file_index, ost->index);
457         ret = avfilter_graph_create_filter(&filter,
458                                            avfilter_get_by_name("format"),
459                                            "format", pix_fmts, NULL, fg->graph);
460         av_freep(&pix_fmts);
461         if (ret < 0)
462             return ret;
463         if ((ret = avfilter_link(last_filter, pad_idx, filter, 0)) < 0)
464             return ret;
465
466         last_filter = filter;
467         pad_idx     = 0;
468     }
469
470     if (ost->frame_rate.num && 0) {
471         AVFilterContext *fps;
472         char args[255];
473
474         snprintf(args, sizeof(args), "fps=%d/%d", ost->frame_rate.num,
475                  ost->frame_rate.den);
476         snprintf(name, sizeof(name), "fps for output stream %d:%d",
477                  ost->file_index, ost->index);
478         ret = avfilter_graph_create_filter(&fps, avfilter_get_by_name("fps"),
479                                            name, args, NULL, fg->graph);
480         if (ret < 0)
481             return ret;
482
483         ret = avfilter_link(last_filter, pad_idx, fps, 0);
484         if (ret < 0)
485             return ret;
486         last_filter = fps;
487         pad_idx = 0;
488     }
489
490     snprintf(name, sizeof(name), "trim for output stream %d:%d",
491              ost->file_index, ost->index);
492     ret = insert_trim(of->start_time, of->recording_time,
493                       &last_filter, &pad_idx, name);
494     if (ret < 0)
495         return ret;
496
497
498     if ((ret = avfilter_link(last_filter, pad_idx, ofilter->filter, 0)) < 0)
499         return ret;
500
501     return 0;
502 }
503
504 static int configure_output_audio_filter(FilterGraph *fg, OutputFilter *ofilter, AVFilterInOut *out)
505 {
506     OutputStream *ost = ofilter->ost;
507     OutputFile    *of = output_files[ost->file_index];
508     AVCodecContext *codec  = ost->enc_ctx;
509     AVFilterContext *last_filter = out->filter_ctx;
510     int pad_idx = out->pad_idx;
511     char *sample_fmts, *sample_rates, *channel_layouts;
512     char name[255];
513     int ret;
514
515     snprintf(name, sizeof(name), "output stream %d:%d", ost->file_index, ost->index);
516     ret = avfilter_graph_create_filter(&ofilter->filter,
517                                        avfilter_get_by_name("abuffersink"),
518                                        name, NULL, NULL, fg->graph);
519     if (ret < 0)
520         return ret;
521     if ((ret = av_opt_set_int(ofilter->filter, "all_channel_counts", 1, AV_OPT_SEARCH_CHILDREN)) < 0)
522         return ret;
523
524 #define AUTO_INSERT_FILTER(opt_name, filter_name, arg) do {                 \
525     AVFilterContext *filt_ctx;                                              \
526                                                                             \
527     av_log(NULL, AV_LOG_INFO, opt_name " is forwarded to lavfi "            \
528            "similarly to -af " filter_name "=%s.\n", arg);                  \
529                                                                             \
530     ret = avfilter_graph_create_filter(&filt_ctx,                           \
531                                        avfilter_get_by_name(filter_name),   \
532                                        filter_name, arg, NULL, fg->graph);  \
533     if (ret < 0)                                                            \
534         return ret;                                                         \
535                                                                             \
536     ret = avfilter_link(last_filter, pad_idx, filt_ctx, 0);                 \
537     if (ret < 0)                                                            \
538         return ret;                                                         \
539                                                                             \
540     last_filter = filt_ctx;                                                 \
541     pad_idx = 0;                                                            \
542 } while (0)
543     if (ost->audio_channels_mapped) {
544         int i;
545         AVBPrint pan_buf;
546         av_bprint_init(&pan_buf, 256, 8192);
547         av_bprintf(&pan_buf, "0x%"PRIx64,
548                    av_get_default_channel_layout(ost->audio_channels_mapped));
549         for (i = 0; i < ost->audio_channels_mapped; i++)
550             if (ost->audio_channels_map[i] != -1)
551                 av_bprintf(&pan_buf, "|c%d=c%d", i, ost->audio_channels_map[i]);
552
553         AUTO_INSERT_FILTER("-map_channel", "pan", pan_buf.str);
554         av_bprint_finalize(&pan_buf, NULL);
555     }
556
557     if (codec->channels && !codec->channel_layout)
558         codec->channel_layout = av_get_default_channel_layout(codec->channels);
559
560     sample_fmts     = choose_sample_fmts(ost);
561     sample_rates    = choose_sample_rates(ost);
562     channel_layouts = choose_channel_layouts(ost);
563     if (sample_fmts || sample_rates || channel_layouts) {
564         AVFilterContext *format;
565         char args[256];
566         args[0] = 0;
567
568         if (sample_fmts)
569             av_strlcatf(args, sizeof(args), "sample_fmts=%s:",
570                             sample_fmts);
571         if (sample_rates)
572             av_strlcatf(args, sizeof(args), "sample_rates=%s:",
573                             sample_rates);
574         if (channel_layouts)
575             av_strlcatf(args, sizeof(args), "channel_layouts=%s:",
576                             channel_layouts);
577
578         av_freep(&sample_fmts);
579         av_freep(&sample_rates);
580         av_freep(&channel_layouts);
581
582         snprintf(name, sizeof(name), "audio format for output stream %d:%d",
583                  ost->file_index, ost->index);
584         ret = avfilter_graph_create_filter(&format,
585                                            avfilter_get_by_name("aformat"),
586                                            name, args, NULL, fg->graph);
587         if (ret < 0)
588             return ret;
589
590         ret = avfilter_link(last_filter, pad_idx, format, 0);
591         if (ret < 0)
592             return ret;
593
594         last_filter = format;
595         pad_idx = 0;
596     }
597
598     if (audio_volume != 256 && 0) {
599         char args[256];
600
601         snprintf(args, sizeof(args), "%f", audio_volume / 256.);
602         AUTO_INSERT_FILTER("-vol", "volume", args);
603     }
604
605     if (ost->apad && of->shortest) {
606         char args[256];
607         int i;
608
609         for (i=0; i<of->ctx->nb_streams; i++)
610             if (of->ctx->streams[i]->codec->codec_type == AVMEDIA_TYPE_VIDEO)
611                 break;
612
613         if (i<of->ctx->nb_streams) {
614             snprintf(args, sizeof(args), "%s", ost->apad);
615             AUTO_INSERT_FILTER("-apad", "apad", args);
616         }
617     }
618
619     snprintf(name, sizeof(name), "trim for output stream %d:%d",
620              ost->file_index, ost->index);
621     ret = insert_trim(of->start_time, of->recording_time,
622                       &last_filter, &pad_idx, name);
623     if (ret < 0)
624         return ret;
625
626     if ((ret = avfilter_link(last_filter, pad_idx, ofilter->filter, 0)) < 0)
627         return ret;
628
629     return 0;
630 }
631
632 #define DESCRIBE_FILTER_LINK(f, inout, in)                         \
633 {                                                                  \
634     AVFilterContext *ctx = inout->filter_ctx;                      \
635     AVFilterPad *pads = in ? ctx->input_pads  : ctx->output_pads;  \
636     int       nb_pads = in ? ctx->nb_inputs   : ctx->nb_outputs;   \
637     AVIOContext *pb;                                               \
638                                                                    \
639     if (avio_open_dyn_buf(&pb) < 0)                                \
640         exit_program(1);                                           \
641                                                                    \
642     avio_printf(pb, "%s", ctx->filter->name);                      \
643     if (nb_pads > 1)                                               \
644         avio_printf(pb, ":%s", avfilter_pad_get_name(pads, inout->pad_idx));\
645     avio_w8(pb, 0);                                                \
646     avio_close_dyn_buf(pb, &f->name);                              \
647 }
648
649 int configure_output_filter(FilterGraph *fg, OutputFilter *ofilter, AVFilterInOut *out)
650 {
651     av_freep(&ofilter->name);
652     DESCRIBE_FILTER_LINK(ofilter, out, 0);
653
654     if (!ofilter->ost) {
655         av_log(NULL, AV_LOG_FATAL, "Filter %s has a unconnected output\n", ofilter->name);
656         exit_program(1);
657     }
658
659     switch (avfilter_pad_get_type(out->filter_ctx->output_pads, out->pad_idx)) {
660     case AVMEDIA_TYPE_VIDEO: return configure_output_video_filter(fg, ofilter, out);
661     case AVMEDIA_TYPE_AUDIO: return configure_output_audio_filter(fg, ofilter, out);
662     default: av_assert0(0);
663     }
664 }
665
666 static int sub2video_prepare(InputStream *ist)
667 {
668     AVFormatContext *avf = input_files[ist->file_index]->ctx;
669     int i, w, h;
670
671     /* Compute the size of the canvas for the subtitles stream.
672        If the subtitles codec has set a size, use it. Otherwise use the
673        maximum dimensions of the video streams in the same file. */
674     w = ist->dec_ctx->width;
675     h = ist->dec_ctx->height;
676     if (!(w && h)) {
677         for (i = 0; i < avf->nb_streams; i++) {
678             if (avf->streams[i]->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
679                 w = FFMAX(w, avf->streams[i]->codec->width);
680                 h = FFMAX(h, avf->streams[i]->codec->height);
681             }
682         }
683         if (!(w && h)) {
684             w = FFMAX(w, 720);
685             h = FFMAX(h, 576);
686         }
687         av_log(avf, AV_LOG_INFO, "sub2video: using %dx%d canvas\n", w, h);
688     }
689     ist->sub2video.w = ist->resample_width  = w;
690     ist->sub2video.h = ist->resample_height = h;
691
692     /* rectangles are AV_PIX_FMT_PAL8, but we have no guarantee that the
693        palettes for all rectangles are identical or compatible */
694     ist->resample_pix_fmt = ist->dec_ctx->pix_fmt = AV_PIX_FMT_RGB32;
695
696     ist->sub2video.frame = av_frame_alloc();
697     if (!ist->sub2video.frame)
698         return AVERROR(ENOMEM);
699     ist->sub2video.last_pts = INT64_MIN;
700     return 0;
701 }
702
703 static int configure_input_video_filter(FilterGraph *fg, InputFilter *ifilter,
704                                         AVFilterInOut *in)
705 {
706     AVFilterContext *last_filter;
707     const AVFilter *buffer_filt = avfilter_get_by_name("buffer");
708     InputStream *ist = ifilter->ist;
709     InputFile     *f = input_files[ist->file_index];
710     AVRational tb = ist->framerate.num ? av_inv_q(ist->framerate) :
711                                          ist->st->time_base;
712     AVRational fr = ist->framerate;
713     AVRational sar;
714     AVBPrint args;
715     char name[255];
716     int ret, pad_idx = 0;
717     int64_t tsoffset = 0;
718
719     if (ist->dec_ctx->codec_type == AVMEDIA_TYPE_AUDIO) {
720         av_log(NULL, AV_LOG_ERROR, "Cannot connect video filter to audio input\n");
721         return AVERROR(EINVAL);
722     }
723
724     if (!fr.num)
725         fr = av_guess_frame_rate(input_files[ist->file_index]->ctx, ist->st, NULL);
726
727     if (ist->dec_ctx->codec_type == AVMEDIA_TYPE_SUBTITLE) {
728         ret = sub2video_prepare(ist);
729         if (ret < 0)
730             return ret;
731     }
732
733     sar = ist->st->sample_aspect_ratio.num ?
734           ist->st->sample_aspect_ratio :
735           ist->dec_ctx->sample_aspect_ratio;
736     if(!sar.den)
737         sar = (AVRational){0,1};
738     av_bprint_init(&args, 0, 1);
739     av_bprintf(&args,
740              "video_size=%dx%d:pix_fmt=%d:time_base=%d/%d:"
741              "pixel_aspect=%d/%d:sws_param=flags=%d", ist->resample_width,
742              ist->resample_height,
743              ist->hwaccel_retrieve_data ? ist->hwaccel_retrieved_pix_fmt : ist->resample_pix_fmt,
744              tb.num, tb.den, sar.num, sar.den,
745              SWS_BILINEAR + ((ist->dec_ctx->flags&AV_CODEC_FLAG_BITEXACT) ? SWS_BITEXACT:0));
746     if (fr.num && fr.den)
747         av_bprintf(&args, ":frame_rate=%d/%d", fr.num, fr.den);
748     snprintf(name, sizeof(name), "graph %d input from stream %d:%d", fg->index,
749              ist->file_index, ist->st->index);
750
751     if ((ret = avfilter_graph_create_filter(&ifilter->filter, buffer_filt, name,
752                                             args.str, NULL, fg->graph)) < 0)
753         return ret;
754     last_filter = ifilter->filter;
755
756     if (ist->autorotate) {
757         double theta = get_rotation(ist->st);
758
759         if (fabs(theta - 90) < 1.0) {
760             ret = insert_filter(&last_filter, &pad_idx, "transpose", "clock");
761         } else if (fabs(theta - 180) < 1.0) {
762             ret = insert_filter(&last_filter, &pad_idx, "hflip", NULL);
763             if (ret < 0)
764                 return ret;
765             ret = insert_filter(&last_filter, &pad_idx, "vflip", NULL);
766         } else if (fabs(theta - 270) < 1.0) {
767             ret = insert_filter(&last_filter, &pad_idx, "transpose", "cclock");
768         } else if (fabs(theta) > 1.0) {
769             char rotate_buf[64];
770             snprintf(rotate_buf, sizeof(rotate_buf), "%f*PI/180", theta);
771             ret = insert_filter(&last_filter, &pad_idx, "rotate", rotate_buf);
772         }
773         if (ret < 0)
774             return ret;
775     }
776
777     if (ist->framerate.num) {
778         AVFilterContext *setpts;
779
780         snprintf(name, sizeof(name), "force CFR for input from stream %d:%d",
781                  ist->file_index, ist->st->index);
782         if ((ret = avfilter_graph_create_filter(&setpts,
783                                                 avfilter_get_by_name("setpts"),
784                                                 name, "N", NULL,
785                                                 fg->graph)) < 0)
786             return ret;
787
788         if ((ret = avfilter_link(last_filter, 0, setpts, 0)) < 0)
789             return ret;
790
791         last_filter = setpts;
792     }
793
794     if (do_deinterlace) {
795         AVFilterContext *yadif;
796
797         snprintf(name, sizeof(name), "deinterlace input from stream %d:%d",
798                  ist->file_index, ist->st->index);
799         if ((ret = avfilter_graph_create_filter(&yadif,
800                                                 avfilter_get_by_name("yadif"),
801                                                 name, "", NULL,
802                                                 fg->graph)) < 0)
803             return ret;
804
805         if ((ret = avfilter_link(last_filter, 0, yadif, 0)) < 0)
806             return ret;
807
808         last_filter = yadif;
809     }
810
811     snprintf(name, sizeof(name), "trim for input stream %d:%d",
812              ist->file_index, ist->st->index);
813     if (copy_ts) {
814         tsoffset = f->start_time == AV_NOPTS_VALUE ? 0 : f->start_time;
815         if (!start_at_zero && f->ctx->start_time != AV_NOPTS_VALUE)
816             tsoffset += f->ctx->start_time;
817     }
818     ret = insert_trim(((f->start_time == AV_NOPTS_VALUE) || !f->accurate_seek) ?
819                       AV_NOPTS_VALUE : tsoffset, f->recording_time,
820                       &last_filter, &pad_idx, name);
821     if (ret < 0)
822         return ret;
823
824     if ((ret = avfilter_link(last_filter, 0, in->filter_ctx, in->pad_idx)) < 0)
825         return ret;
826     return 0;
827 }
828
829 static int configure_input_audio_filter(FilterGraph *fg, InputFilter *ifilter,
830                                         AVFilterInOut *in)
831 {
832     AVFilterContext *last_filter;
833     const AVFilter *abuffer_filt = avfilter_get_by_name("abuffer");
834     InputStream *ist = ifilter->ist;
835     InputFile     *f = input_files[ist->file_index];
836     AVBPrint args;
837     char name[255];
838     int ret, pad_idx = 0;
839     int64_t tsoffset = 0;
840
841     if (ist->dec_ctx->codec_type != AVMEDIA_TYPE_AUDIO) {
842         av_log(NULL, AV_LOG_ERROR, "Cannot connect audio filter to non audio input\n");
843         return AVERROR(EINVAL);
844     }
845
846     av_bprint_init(&args, 0, AV_BPRINT_SIZE_AUTOMATIC);
847     av_bprintf(&args, "time_base=%d/%d:sample_rate=%d:sample_fmt=%s",
848              1, ist->dec_ctx->sample_rate,
849              ist->dec_ctx->sample_rate,
850              av_get_sample_fmt_name(ist->dec_ctx->sample_fmt));
851     if (ist->dec_ctx->channel_layout)
852         av_bprintf(&args, ":channel_layout=0x%"PRIx64,
853                    ist->dec_ctx->channel_layout);
854     else
855         av_bprintf(&args, ":channels=%d", ist->dec_ctx->channels);
856     snprintf(name, sizeof(name), "graph %d input from stream %d:%d", fg->index,
857              ist->file_index, ist->st->index);
858
859     if ((ret = avfilter_graph_create_filter(&ifilter->filter, abuffer_filt,
860                                             name, args.str, NULL,
861                                             fg->graph)) < 0)
862         return ret;
863     last_filter = ifilter->filter;
864
865 #define AUTO_INSERT_FILTER_INPUT(opt_name, filter_name, arg) do {                 \
866     AVFilterContext *filt_ctx;                                              \
867                                                                             \
868     av_log(NULL, AV_LOG_INFO, opt_name " is forwarded to lavfi "            \
869            "similarly to -af " filter_name "=%s.\n", arg);                  \
870                                                                             \
871     snprintf(name, sizeof(name), "graph %d %s for input stream %d:%d",      \
872                 fg->index, filter_name, ist->file_index, ist->st->index);   \
873     ret = avfilter_graph_create_filter(&filt_ctx,                           \
874                                        avfilter_get_by_name(filter_name),   \
875                                        name, arg, NULL, fg->graph);         \
876     if (ret < 0)                                                            \
877         return ret;                                                         \
878                                                                             \
879     ret = avfilter_link(last_filter, 0, filt_ctx, 0);                       \
880     if (ret < 0)                                                            \
881         return ret;                                                         \
882                                                                             \
883     last_filter = filt_ctx;                                                 \
884 } while (0)
885
886     if (audio_sync_method > 0) {
887         char args[256] = {0};
888
889         av_strlcatf(args, sizeof(args), "async=%d", audio_sync_method);
890         if (audio_drift_threshold != 0.1)
891             av_strlcatf(args, sizeof(args), ":min_hard_comp=%f", audio_drift_threshold);
892         if (!fg->reconfiguration)
893             av_strlcatf(args, sizeof(args), ":first_pts=0");
894         AUTO_INSERT_FILTER_INPUT("-async", "aresample", args);
895     }
896
897 //     if (ost->audio_channels_mapped) {
898 //         int i;
899 //         AVBPrint pan_buf;
900 //         av_bprint_init(&pan_buf, 256, 8192);
901 //         av_bprintf(&pan_buf, "0x%"PRIx64,
902 //                    av_get_default_channel_layout(ost->audio_channels_mapped));
903 //         for (i = 0; i < ost->audio_channels_mapped; i++)
904 //             if (ost->audio_channels_map[i] != -1)
905 //                 av_bprintf(&pan_buf, ":c%d=c%d", i, ost->audio_channels_map[i]);
906 //         AUTO_INSERT_FILTER_INPUT("-map_channel", "pan", pan_buf.str);
907 //         av_bprint_finalize(&pan_buf, NULL);
908 //     }
909
910     if (audio_volume != 256) {
911         char args[256];
912
913         av_log(NULL, AV_LOG_WARNING, "-vol has been deprecated. Use the volume "
914                "audio filter instead.\n");
915
916         snprintf(args, sizeof(args), "%f", audio_volume / 256.);
917         AUTO_INSERT_FILTER_INPUT("-vol", "volume", args);
918     }
919
920     snprintf(name, sizeof(name), "trim for input stream %d:%d",
921              ist->file_index, ist->st->index);
922     if (copy_ts) {
923         tsoffset = f->start_time == AV_NOPTS_VALUE ? 0 : f->start_time;
924         if (!start_at_zero && f->ctx->start_time != AV_NOPTS_VALUE)
925             tsoffset += f->ctx->start_time;
926     }
927     ret = insert_trim(((f->start_time == AV_NOPTS_VALUE) || !f->accurate_seek) ?
928                       AV_NOPTS_VALUE : tsoffset, f->recording_time,
929                       &last_filter, &pad_idx, name);
930     if (ret < 0)
931         return ret;
932
933     if ((ret = avfilter_link(last_filter, 0, in->filter_ctx, in->pad_idx)) < 0)
934         return ret;
935
936     return 0;
937 }
938
939 static int configure_input_filter(FilterGraph *fg, InputFilter *ifilter,
940                                   AVFilterInOut *in)
941 {
942     av_freep(&ifilter->name);
943     DESCRIBE_FILTER_LINK(ifilter, in, 1);
944
945     if (!ifilter->ist->dec) {
946         av_log(NULL, AV_LOG_ERROR,
947                "No decoder for stream #%d:%d, filtering impossible\n",
948                ifilter->ist->file_index, ifilter->ist->st->index);
949         return AVERROR_DECODER_NOT_FOUND;
950     }
951     switch (avfilter_pad_get_type(in->filter_ctx->input_pads, in->pad_idx)) {
952     case AVMEDIA_TYPE_VIDEO: return configure_input_video_filter(fg, ifilter, in);
953     case AVMEDIA_TYPE_AUDIO: return configure_input_audio_filter(fg, ifilter, in);
954     default: av_assert0(0);
955     }
956 }
957
958 int configure_filtergraph(FilterGraph *fg)
959 {
960     AVFilterInOut *inputs, *outputs, *cur;
961     int ret, i, simple = !fg->graph_desc;
962     const char *graph_desc = simple ? fg->outputs[0]->ost->avfilter :
963                                       fg->graph_desc;
964
965     avfilter_graph_free(&fg->graph);
966     if (!(fg->graph = avfilter_graph_alloc()))
967         return AVERROR(ENOMEM);
968
969     if (simple) {
970         OutputStream *ost = fg->outputs[0]->ost;
971         char args[512];
972         AVDictionaryEntry *e = NULL;
973
974         args[0] = 0;
975         while ((e = av_dict_get(ost->sws_dict, "", e,
976                                 AV_DICT_IGNORE_SUFFIX))) {
977             av_strlcatf(args, sizeof(args), "%s=%s:", e->key, e->value);
978         }
979         if (strlen(args))
980             args[strlen(args)-1] = 0;
981         fg->graph->scale_sws_opts = av_strdup(args);
982
983         args[0] = 0;
984         while ((e = av_dict_get(ost->swr_opts, "", e,
985                                 AV_DICT_IGNORE_SUFFIX))) {
986             av_strlcatf(args, sizeof(args), "%s=%s:", e->key, e->value);
987         }
988         if (strlen(args))
989             args[strlen(args)-1] = 0;
990         av_opt_set(fg->graph, "aresample_swr_opts", args, 0);
991
992         args[0] = '\0';
993         while ((e = av_dict_get(fg->outputs[0]->ost->resample_opts, "", e,
994                                 AV_DICT_IGNORE_SUFFIX))) {
995             av_strlcatf(args, sizeof(args), "%s=%s:", e->key, e->value);
996         }
997         if (strlen(args))
998             args[strlen(args) - 1] = '\0';
999         fg->graph->resample_lavr_opts = av_strdup(args);
1000
1001         e = av_dict_get(ost->encoder_opts, "threads", NULL, 0);
1002         if (e)
1003             av_opt_set(fg->graph, "threads", e->value, 0);
1004     }
1005
1006     if ((ret = avfilter_graph_parse2(fg->graph, graph_desc, &inputs, &outputs)) < 0)
1007         return ret;
1008
1009     if (simple && (!inputs || inputs->next || !outputs || outputs->next)) {
1010         const char *num_inputs;
1011         const char *num_outputs;
1012         if (!outputs) {
1013             num_outputs = "0";
1014         } else if (outputs->next) {
1015             num_outputs = ">1";
1016         } else {
1017             num_outputs = "1";
1018         }
1019         if (!inputs) {
1020             num_inputs = "0";
1021         } else if (inputs->next) {
1022             num_inputs = ">1";
1023         } else {
1024             num_inputs = "1";
1025         }
1026         av_log(NULL, AV_LOG_ERROR, "Simple filtergraph '%s' was expected "
1027                "to have exactly 1 input and 1 output."
1028                " However, it had %s input(s) and %s output(s)."
1029                " Please adjust, or use a complex filtergraph (-filter_complex) instead.\n",
1030                graph_desc, num_inputs, num_outputs);
1031         return AVERROR(EINVAL);
1032     }
1033
1034     for (cur = inputs, i = 0; cur; cur = cur->next, i++)
1035         if ((ret = configure_input_filter(fg, fg->inputs[i], cur)) < 0) {
1036             avfilter_inout_free(&inputs);
1037             avfilter_inout_free(&outputs);
1038             return ret;
1039         }
1040     avfilter_inout_free(&inputs);
1041
1042     for (cur = outputs, i = 0; cur; cur = cur->next, i++)
1043         configure_output_filter(fg, fg->outputs[i], cur);
1044     avfilter_inout_free(&outputs);
1045
1046     if ((ret = avfilter_graph_config(fg->graph, NULL)) < 0)
1047         return ret;
1048
1049     fg->reconfiguration = 1;
1050
1051     for (i = 0; i < fg->nb_outputs; i++) {
1052         OutputStream *ost = fg->outputs[i]->ost;
1053         if (!ost->enc) {
1054             /* identical to the same check in ffmpeg.c, needed because
1055                complex filter graphs are initialized earlier */
1056             av_log(NULL, AV_LOG_ERROR, "Encoder (codec %s) not found for output stream #%d:%d\n",
1057                      avcodec_get_name(ost->st->codec->codec_id), ost->file_index, ost->index);
1058             return AVERROR(EINVAL);
1059         }
1060         if (ost->enc->type == AVMEDIA_TYPE_AUDIO &&
1061             !(ost->enc->capabilities & AV_CODEC_CAP_VARIABLE_FRAME_SIZE))
1062             av_buffersink_set_frame_size(ost->filter->filter,
1063                                          ost->enc_ctx->frame_size);
1064     }
1065
1066     return 0;
1067 }
1068
1069 int ist_in_filtergraph(FilterGraph *fg, InputStream *ist)
1070 {
1071     int i;
1072     for (i = 0; i < fg->nb_inputs; i++)
1073         if (fg->inputs[i]->ist == ist)
1074             return 1;
1075     return 0;
1076 }
1077