Merge commit 'a83c0da539fb07260310bc3b34056239d2b138b2'
[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 "ffmpeg.h"
22
23 #include "libavfilter/avfilter.h"
24 #include "libavfilter/buffersink.h"
25
26 #include "libavresample/avresample.h"
27
28 #include "libavutil/avassert.h"
29 #include "libavutil/avstring.h"
30 #include "libavutil/bprint.h"
31 #include "libavutil/channel_layout.h"
32 #include "libavutil/opt.h"
33 #include "libavutil/pixdesc.h"
34 #include "libavutil/pixfmt.h"
35 #include "libavutil/imgutils.h"
36 #include "libavutil/samplefmt.h"
37
38 enum AVPixelFormat choose_pixel_fmt(AVStream *st, AVCodec *codec, enum AVPixelFormat target)
39 {
40     if (codec && codec->pix_fmts) {
41         const enum AVPixelFormat *p = codec->pix_fmts;
42         const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(target);
43         int has_alpha = desc ? desc->nb_components % 2 == 0 : 0;
44         enum AVPixelFormat best= AV_PIX_FMT_NONE;
45         if (st->codec->strict_std_compliance <= FF_COMPLIANCE_UNOFFICIAL) {
46             if (st->codec->codec_id == AV_CODEC_ID_MJPEG) {
47                 p = (const enum AVPixelFormat[]) { AV_PIX_FMT_YUVJ420P, AV_PIX_FMT_YUVJ422P, AV_PIX_FMT_YUV420P, AV_PIX_FMT_YUV422P, AV_PIX_FMT_NONE };
48             } else if (st->codec->codec_id == AV_CODEC_ID_LJPEG) {
49                 p = (const enum AVPixelFormat[]) { AV_PIX_FMT_YUVJ420P, AV_PIX_FMT_YUVJ422P, AV_PIX_FMT_YUVJ444P, AV_PIX_FMT_YUV420P,
50                                                  AV_PIX_FMT_YUV422P, AV_PIX_FMT_YUV444P, AV_PIX_FMT_BGRA, AV_PIX_FMT_NONE };
51             }
52         }
53         for (; *p != AV_PIX_FMT_NONE; p++) {
54             best= avcodec_find_best_pix_fmt_of_2(best, *p, target, has_alpha, NULL);
55             if (*p == target)
56                 break;
57         }
58         if (*p == AV_PIX_FMT_NONE) {
59             if (target != AV_PIX_FMT_NONE)
60                 av_log(NULL, AV_LOG_WARNING,
61                        "Incompatible pixel format '%s' for codec '%s', auto-selecting format '%s'\n",
62                        av_get_pix_fmt_name(target),
63                        codec->name,
64                        av_get_pix_fmt_name(best));
65             return best;
66         }
67     }
68     return target;
69 }
70
71 void choose_sample_fmt(AVStream *st, AVCodec *codec)
72 {
73     if (codec && codec->sample_fmts) {
74         const enum AVSampleFormat *p = codec->sample_fmts;
75         for (; *p != -1; p++) {
76             if (*p == st->codec->sample_fmt)
77                 break;
78         }
79         if (*p == -1) {
80             if((codec->capabilities & CODEC_CAP_LOSSLESS) && av_get_sample_fmt_name(st->codec->sample_fmt) > av_get_sample_fmt_name(codec->sample_fmts[0]))
81                 av_log(NULL, AV_LOG_ERROR, "Conversion will not be lossless.\n");
82             if(av_get_sample_fmt_name(st->codec->sample_fmt))
83             av_log(NULL, AV_LOG_WARNING,
84                    "Incompatible sample format '%s' for codec '%s', auto-selecting format '%s'\n",
85                    av_get_sample_fmt_name(st->codec->sample_fmt),
86                    codec->name,
87                    av_get_sample_fmt_name(codec->sample_fmts[0]));
88             st->codec->sample_fmt = codec->sample_fmts[0];
89         }
90     }
91 }
92
93 static char *choose_pix_fmts(OutputStream *ost)
94 {
95      if (ost->keep_pix_fmt) {
96         if (ost->filter)
97             avfilter_graph_set_auto_convert(ost->filter->graph->graph,
98                                             AVFILTER_AUTO_CONVERT_NONE);
99         if (ost->st->codec->pix_fmt == AV_PIX_FMT_NONE)
100             return NULL;
101         return av_strdup(av_get_pix_fmt_name(ost->st->codec->pix_fmt));
102     }
103     if (ost->st->codec->pix_fmt != AV_PIX_FMT_NONE) {
104         return av_strdup(av_get_pix_fmt_name(choose_pixel_fmt(ost->st, ost->enc, ost->st->codec->pix_fmt)));
105     } else if (ost->enc && ost->enc->pix_fmts) {
106         const enum AVPixelFormat *p;
107         AVIOContext *s = NULL;
108         uint8_t *ret;
109         int len;
110
111         if (avio_open_dyn_buf(&s) < 0)
112             exit(1);
113
114         p = ost->enc->pix_fmts;
115         if (ost->st->codec->strict_std_compliance <= FF_COMPLIANCE_UNOFFICIAL) {
116             if (ost->st->codec->codec_id == AV_CODEC_ID_MJPEG) {
117                 p = (const enum AVPixelFormat[]) { AV_PIX_FMT_YUVJ420P, AV_PIX_FMT_YUVJ422P, AV_PIX_FMT_YUV420P, AV_PIX_FMT_YUV422P, AV_PIX_FMT_NONE };
118             } else if (ost->st->codec->codec_id == AV_CODEC_ID_LJPEG) {
119                 p = (const enum AVPixelFormat[]) { AV_PIX_FMT_YUVJ420P, AV_PIX_FMT_YUVJ422P, AV_PIX_FMT_YUVJ444P, AV_PIX_FMT_YUV420P,
120                                                     AV_PIX_FMT_YUV422P, AV_PIX_FMT_YUV444P, AV_PIX_FMT_BGRA, AV_PIX_FMT_NONE };
121             }
122         }
123
124         for (; *p != AV_PIX_FMT_NONE; p++) {
125             const char *name = av_get_pix_fmt_name(*p);
126             avio_printf(s, "%s|", name);
127         }
128         len = avio_close_dyn_buf(s, &ret);
129         ret[len - 1] = 0;
130         return ret;
131     } else
132         return NULL;
133 }
134
135 /* Define a function for building a string containing a list of
136  * allowed formats. */
137 #define DEF_CHOOSE_FORMAT(type, var, supported_list, none, get_name)           \
138 static char *choose_ ## var ## s(OutputStream *ost)                            \
139 {                                                                              \
140     if (ost->st->codec->var != none) {                                         \
141         get_name(ost->st->codec->var);                                         \
142         return av_strdup(name);                                                \
143     } else if (ost->enc && ost->enc->supported_list) {                         \
144         const type *p;                                                         \
145         AVIOContext *s = NULL;                                                 \
146         uint8_t *ret;                                                          \
147         int len;                                                               \
148                                                                                \
149         if (avio_open_dyn_buf(&s) < 0)                                         \
150             exit(1);                                                           \
151                                                                                \
152         for (p = ost->enc->supported_list; *p != none; p++) {                  \
153             get_name(*p);                                                      \
154             avio_printf(s, "%s|", name);                                       \
155         }                                                                      \
156         len = avio_close_dyn_buf(s, &ret);                                     \
157         ret[len - 1] = 0;                                                      \
158         return ret;                                                            \
159     } else                                                                     \
160         return NULL;                                                           \
161 }
162
163 // DEF_CHOOSE_FORMAT(enum AVPixelFormat, pix_fmt, pix_fmts, AV_PIX_FMT_NONE,
164 //                   GET_PIX_FMT_NAME)
165
166 DEF_CHOOSE_FORMAT(enum AVSampleFormat, sample_fmt, sample_fmts,
167                   AV_SAMPLE_FMT_NONE, GET_SAMPLE_FMT_NAME)
168
169 DEF_CHOOSE_FORMAT(int, sample_rate, supported_samplerates, 0,
170                   GET_SAMPLE_RATE_NAME)
171
172 DEF_CHOOSE_FORMAT(uint64_t, channel_layout, channel_layouts, 0,
173                   GET_CH_LAYOUT_NAME)
174
175 FilterGraph *init_simple_filtergraph(InputStream *ist, OutputStream *ost)
176 {
177     FilterGraph *fg = av_mallocz(sizeof(*fg));
178
179     if (!fg)
180         exit(1);
181     fg->index = nb_filtergraphs;
182
183     GROW_ARRAY(fg->outputs, fg->nb_outputs);
184     if (!(fg->outputs[0] = av_mallocz(sizeof(*fg->outputs[0]))))
185         exit(1);
186     fg->outputs[0]->ost   = ost;
187     fg->outputs[0]->graph = fg;
188
189     ost->filter = fg->outputs[0];
190
191     GROW_ARRAY(fg->inputs, fg->nb_inputs);
192     if (!(fg->inputs[0] = av_mallocz(sizeof(*fg->inputs[0]))))
193         exit(1);
194     fg->inputs[0]->ist   = ist;
195     fg->inputs[0]->graph = fg;
196
197     GROW_ARRAY(ist->filters, ist->nb_filters);
198     ist->filters[ist->nb_filters - 1] = fg->inputs[0];
199
200     GROW_ARRAY(filtergraphs, nb_filtergraphs);
201     filtergraphs[nb_filtergraphs - 1] = fg;
202
203     return fg;
204 }
205
206 static void init_input_filter(FilterGraph *fg, AVFilterInOut *in)
207 {
208     InputStream *ist = NULL;
209     enum AVMediaType type = avfilter_pad_get_type(in->filter_ctx->input_pads, in->pad_idx);
210     int i;
211
212     // TODO: support other filter types
213     if (type != AVMEDIA_TYPE_VIDEO && type != AVMEDIA_TYPE_AUDIO) {
214         av_log(NULL, AV_LOG_FATAL, "Only video and audio filters supported "
215                "currently.\n");
216         exit(1);
217     }
218
219     if (in->name) {
220         AVFormatContext *s;
221         AVStream       *st = NULL;
222         char *p;
223         int file_idx = strtol(in->name, &p, 0);
224
225         if (file_idx < 0 || file_idx >= nb_input_files) {
226             av_log(NULL, AV_LOG_FATAL, "Invalid file index %d in filtergraph description %s.\n",
227                    file_idx, fg->graph_desc);
228             exit(1);
229         }
230         s = input_files[file_idx]->ctx;
231
232         for (i = 0; i < s->nb_streams; i++) {
233             enum AVMediaType stream_type = s->streams[i]->codec->codec_type;
234             if (stream_type != type &&
235                 !(stream_type == AVMEDIA_TYPE_SUBTITLE &&
236                   type == AVMEDIA_TYPE_VIDEO /* sub2video hack */))
237                 continue;
238             if (check_stream_specifier(s, s->streams[i], *p == ':' ? p + 1 : p) == 1) {
239                 st = s->streams[i];
240                 break;
241             }
242         }
243         if (!st) {
244             av_log(NULL, AV_LOG_FATAL, "Stream specifier '%s' in filtergraph description %s "
245                    "matches no streams.\n", p, fg->graph_desc);
246             exit(1);
247         }
248         ist = input_streams[input_files[file_idx]->ist_index + st->index];
249     } else {
250         /* find the first unused stream of corresponding type */
251         for (i = 0; i < nb_input_streams; i++) {
252             ist = input_streams[i];
253             if (ist->st->codec->codec_type == type && ist->discard)
254                 break;
255         }
256         if (i == nb_input_streams) {
257             av_log(NULL, AV_LOG_FATAL, "Cannot find a matching stream for "
258                    "unlabeled input pad %d on filter %s\n", in->pad_idx,
259                    in->filter_ctx->name);
260             exit(1);
261         }
262     }
263     av_assert0(ist);
264
265     ist->discard         = 0;
266     ist->decoding_needed++;
267     ist->st->discard = AVDISCARD_NONE;
268
269     GROW_ARRAY(fg->inputs, fg->nb_inputs);
270     if (!(fg->inputs[fg->nb_inputs - 1] = av_mallocz(sizeof(*fg->inputs[0]))))
271         exit(1);
272     fg->inputs[fg->nb_inputs - 1]->ist   = ist;
273     fg->inputs[fg->nb_inputs - 1]->graph = fg;
274
275     GROW_ARRAY(ist->filters, ist->nb_filters);
276     ist->filters[ist->nb_filters - 1] = fg->inputs[fg->nb_inputs - 1];
277 }
278
279 static int insert_trim(OutputStream *ost, AVFilterContext **last_filter, int *pad_idx)
280 {
281     OutputFile *of = output_files[ost->file_index];
282     AVFilterGraph *graph = (*last_filter)->graph;
283     AVFilterContext *ctx;
284     const AVFilter *trim;
285     const char *name = ost->st->codec->codec_type == AVMEDIA_TYPE_VIDEO ? "trim" : "atrim";
286     char filter_name[128];
287     int ret = 0;
288
289     if (of->recording_time == INT64_MAX)
290         return 0;
291
292     return 0;
293
294     trim = avfilter_get_by_name(name);
295     if (!trim) {
296         av_log(NULL, AV_LOG_ERROR, "%s filter not present, cannot limit "
297                "recording time.\n", name);
298         return AVERROR_FILTER_NOT_FOUND;
299     }
300
301     snprintf(filter_name, sizeof(filter_name), "%s for output stream %d:%d",
302              name, ost->file_index, ost->index);
303     ctx = avfilter_graph_alloc_filter(graph, trim, filter_name);
304     if (!ctx)
305         return AVERROR(ENOMEM);
306
307     ret = av_opt_set_double(ctx, "duration", (double)of->recording_time / 1e6,
308                             AV_OPT_SEARCH_CHILDREN);
309     if (ret < 0) {
310         av_log(ctx, AV_LOG_ERROR, "Error configuring the %s filter", name);
311         return ret;
312     }
313
314     ret = avfilter_init_str(ctx, NULL);
315     if (ret < 0)
316         return ret;
317
318     ret = avfilter_link(*last_filter, *pad_idx, ctx, 0);
319     if (ret < 0)
320         return ret;
321
322     *last_filter = ctx;
323     *pad_idx     = 0;
324     return 0;
325 }
326
327 static int configure_output_video_filter(FilterGraph *fg, OutputFilter *ofilter, AVFilterInOut *out)
328 {
329     char *pix_fmts;
330     OutputStream *ost = ofilter->ost;
331     AVCodecContext *codec = ost->st->codec;
332     AVFilterContext *last_filter = out->filter_ctx;
333     int pad_idx = out->pad_idx;
334     int ret;
335     char name[255];
336
337     snprintf(name, sizeof(name), "output stream %d:%d", ost->file_index, ost->index);
338     ret = avfilter_graph_create_filter(&ofilter->filter,
339                                        avfilter_get_by_name("buffersink"),
340                                        name, NULL, NULL, fg->graph);
341
342     if (ret < 0)
343         return ret;
344
345     if (codec->width || codec->height) {
346         char args[255];
347         AVFilterContext *filter;
348
349         snprintf(args, sizeof(args), "%d:%d:flags=0x%X",
350                  codec->width,
351                  codec->height,
352                  (unsigned)ost->sws_flags);
353         snprintf(name, sizeof(name), "scaler for output stream %d:%d",
354                  ost->file_index, ost->index);
355         if ((ret = avfilter_graph_create_filter(&filter, avfilter_get_by_name("scale"),
356                                                 name, args, NULL, fg->graph)) < 0)
357             return ret;
358         if ((ret = avfilter_link(last_filter, pad_idx, filter, 0)) < 0)
359             return ret;
360
361         last_filter = filter;
362         pad_idx = 0;
363     }
364
365     if ((pix_fmts = choose_pix_fmts(ost))) {
366         AVFilterContext *filter;
367         snprintf(name, sizeof(name), "pixel format for output stream %d:%d",
368                  ost->file_index, ost->index);
369         ret = avfilter_graph_create_filter(&filter,
370                                                 avfilter_get_by_name("format"),
371                                                 "format", pix_fmts, NULL,
372                                                 fg->graph);
373         av_freep(&pix_fmts);
374         if (ret < 0)
375             return ret;
376         if ((ret = avfilter_link(last_filter, pad_idx, filter, 0)) < 0)
377             return ret;
378
379         last_filter = filter;
380         pad_idx     = 0;
381     }
382
383     if (ost->frame_rate.num && 0) {
384         AVFilterContext *fps;
385         char args[255];
386
387         snprintf(args, sizeof(args), "fps=%d/%d", ost->frame_rate.num,
388                  ost->frame_rate.den);
389         snprintf(name, sizeof(name), "fps for output stream %d:%d",
390                  ost->file_index, ost->index);
391         ret = avfilter_graph_create_filter(&fps, avfilter_get_by_name("fps"),
392                                            name, args, NULL, fg->graph);
393         if (ret < 0)
394             return ret;
395
396         ret = avfilter_link(last_filter, pad_idx, fps, 0);
397         if (ret < 0)
398             return ret;
399         last_filter = fps;
400         pad_idx = 0;
401     }
402
403     ret = insert_trim(ost, &last_filter, &pad_idx);
404     if (ret < 0)
405         return ret;
406
407
408     if ((ret = avfilter_link(last_filter, pad_idx, ofilter->filter, 0)) < 0)
409         return ret;
410
411     return 0;
412 }
413
414 static int configure_output_audio_filter(FilterGraph *fg, OutputFilter *ofilter, AVFilterInOut *out)
415 {
416     OutputStream *ost = ofilter->ost;
417     AVCodecContext *codec  = ost->st->codec;
418     AVFilterContext *last_filter = out->filter_ctx;
419     int pad_idx = out->pad_idx;
420     char *sample_fmts, *sample_rates, *channel_layouts;
421     char name[255];
422     int ret;
423
424     snprintf(name, sizeof(name), "output stream %d:%d", ost->file_index, ost->index);
425     ret = avfilter_graph_create_filter(&ofilter->filter,
426                                        avfilter_get_by_name("abuffersink"),
427                                        name, NULL, NULL, fg->graph);
428     if (ret < 0)
429         return ret;
430     if ((ret = av_opt_set_int(ofilter->filter, "all_channel_counts", 1, AV_OPT_SEARCH_CHILDREN)) < 0)
431         return ret;
432
433 #define AUTO_INSERT_FILTER(opt_name, filter_name, arg) do {                 \
434     AVFilterContext *filt_ctx;                                              \
435                                                                             \
436     av_log(NULL, AV_LOG_INFO, opt_name " is forwarded to lavfi "            \
437            "similarly to -af " filter_name "=%s.\n", arg);                  \
438                                                                             \
439     ret = avfilter_graph_create_filter(&filt_ctx,                           \
440                                        avfilter_get_by_name(filter_name),   \
441                                        filter_name, arg, NULL, fg->graph);  \
442     if (ret < 0)                                                            \
443         return ret;                                                         \
444                                                                             \
445     ret = avfilter_link(last_filter, pad_idx, filt_ctx, 0);                 \
446     if (ret < 0)                                                            \
447         return ret;                                                         \
448                                                                             \
449     last_filter = filt_ctx;                                                 \
450     pad_idx = 0;                                                            \
451 } while (0)
452     if (ost->audio_channels_mapped) {
453         int i;
454         AVBPrint pan_buf;
455         av_bprint_init(&pan_buf, 256, 8192);
456         av_bprintf(&pan_buf, "0x%"PRIx64,
457                    av_get_default_channel_layout(ost->audio_channels_mapped));
458         for (i = 0; i < ost->audio_channels_mapped; i++)
459             if (ost->audio_channels_map[i] != -1)
460                 av_bprintf(&pan_buf, ":c%d=c%d", i, ost->audio_channels_map[i]);
461
462         AUTO_INSERT_FILTER("-map_channel", "pan", pan_buf.str);
463         av_bprint_finalize(&pan_buf, NULL);
464     }
465
466     if (codec->channels && !codec->channel_layout)
467         codec->channel_layout = av_get_default_channel_layout(codec->channels);
468
469     sample_fmts     = choose_sample_fmts(ost);
470     sample_rates    = choose_sample_rates(ost);
471     channel_layouts = choose_channel_layouts(ost);
472     if (sample_fmts || sample_rates || channel_layouts) {
473         AVFilterContext *format;
474         char args[256];
475         args[0] = 0;
476
477         if (sample_fmts)
478             av_strlcatf(args, sizeof(args), "sample_fmts=%s:",
479                             sample_fmts);
480         if (sample_rates)
481             av_strlcatf(args, sizeof(args), "sample_rates=%s:",
482                             sample_rates);
483         if (channel_layouts)
484             av_strlcatf(args, sizeof(args), "channel_layouts=%s:",
485                             channel_layouts);
486
487         av_freep(&sample_fmts);
488         av_freep(&sample_rates);
489         av_freep(&channel_layouts);
490
491         snprintf(name, sizeof(name), "audio format for output stream %d:%d",
492                  ost->file_index, ost->index);
493         ret = avfilter_graph_create_filter(&format,
494                                            avfilter_get_by_name("aformat"),
495                                            name, args, NULL, fg->graph);
496         if (ret < 0)
497             return ret;
498
499         ret = avfilter_link(last_filter, pad_idx, format, 0);
500         if (ret < 0)
501             return ret;
502
503         last_filter = format;
504         pad_idx = 0;
505     }
506
507     if (audio_volume != 256 && 0) {
508         char args[256];
509
510         snprintf(args, sizeof(args), "%f", audio_volume / 256.);
511         AUTO_INSERT_FILTER("-vol", "volume", args);
512     }
513
514     ret = insert_trim(ost, &last_filter, &pad_idx);
515     if (ret < 0)
516         return ret;
517
518     if ((ret = avfilter_link(last_filter, pad_idx, ofilter->filter, 0)) < 0)
519         return ret;
520
521     return 0;
522 }
523
524 #define DESCRIBE_FILTER_LINK(f, inout, in)                         \
525 {                                                                  \
526     AVFilterContext *ctx = inout->filter_ctx;                      \
527     AVFilterPad *pads = in ? ctx->input_pads  : ctx->output_pads;  \
528     int       nb_pads = in ? ctx->input_count : ctx->output_count; \
529     AVIOContext *pb;                                               \
530                                                                    \
531     if (avio_open_dyn_buf(&pb) < 0)                                \
532         exit(1);                                                   \
533                                                                    \
534     avio_printf(pb, "%s", ctx->filter->name);                      \
535     if (nb_pads > 1)                                               \
536         avio_printf(pb, ":%s", avfilter_pad_get_name(pads, inout->pad_idx));\
537     avio_w8(pb, 0);                                                \
538     avio_close_dyn_buf(pb, &f->name);                              \
539 }
540
541 int configure_output_filter(FilterGraph *fg, OutputFilter *ofilter, AVFilterInOut *out)
542 {
543     av_freep(&ofilter->name);
544     DESCRIBE_FILTER_LINK(ofilter, out, 0);
545
546     switch (avfilter_pad_get_type(out->filter_ctx->output_pads, out->pad_idx)) {
547     case AVMEDIA_TYPE_VIDEO: return configure_output_video_filter(fg, ofilter, out);
548     case AVMEDIA_TYPE_AUDIO: return configure_output_audio_filter(fg, ofilter, out);
549     default: av_assert0(0);
550     }
551 }
552
553 static int sub2video_prepare(InputStream *ist)
554 {
555     AVFormatContext *avf = input_files[ist->file_index]->ctx;
556     int i, w, h;
557
558     /* Compute the size of the canvas for the subtitles stream.
559        If the subtitles codec has set a size, use it. Otherwise use the
560        maximum dimensions of the video streams in the same file. */
561     w = ist->st->codec->width;
562     h = ist->st->codec->height;
563     if (!(w && h)) {
564         for (i = 0; i < avf->nb_streams; i++) {
565             if (avf->streams[i]->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
566                 w = FFMAX(w, avf->streams[i]->codec->width);
567                 h = FFMAX(h, avf->streams[i]->codec->height);
568             }
569         }
570         if (!(w && h)) {
571             w = FFMAX(w, 720);
572             h = FFMAX(h, 576);
573         }
574         av_log(avf, AV_LOG_INFO, "sub2video: using %dx%d canvas\n", w, h);
575     }
576     ist->sub2video.w = ist->st->codec->width  = ist->resample_width  = w;
577     ist->sub2video.h = ist->st->codec->height = ist->resample_height = h;
578
579     /* rectangles are AV_PIX_FMT_PAL8, but we have no guarantee that the
580        palettes for all rectangles are identical or compatible */
581     ist->resample_pix_fmt = ist->st->codec->pix_fmt = AV_PIX_FMT_RGB32;
582
583     ist->sub2video.frame = av_frame_alloc();
584     if (!ist->sub2video.frame)
585         return AVERROR(ENOMEM);
586     return 0;
587 }
588
589 static int configure_input_video_filter(FilterGraph *fg, InputFilter *ifilter,
590                                         AVFilterInOut *in)
591 {
592     AVFilterContext *first_filter = in->filter_ctx;
593     AVFilter *filter = avfilter_get_by_name("buffer");
594     InputStream *ist = ifilter->ist;
595     AVRational tb = ist->framerate.num ? av_inv_q(ist->framerate) :
596                                          ist->st->time_base;
597     AVRational fr = ist->framerate;
598     AVRational sar;
599     AVBPrint args;
600     char name[255];
601     int pad_idx = in->pad_idx;
602     int ret;
603
604     if (!fr.num)
605         fr = av_guess_frame_rate(input_files[ist->file_index]->ctx, ist->st, NULL);
606
607     if (ist->st->codec->codec_type == AVMEDIA_TYPE_SUBTITLE) {
608         ret = sub2video_prepare(ist);
609         if (ret < 0)
610             return ret;
611     }
612
613     sar = ist->st->sample_aspect_ratio.num ?
614           ist->st->sample_aspect_ratio :
615           ist->st->codec->sample_aspect_ratio;
616     if(!sar.den)
617         sar = (AVRational){0,1};
618     av_bprint_init(&args, 0, 1);
619     av_bprintf(&args,
620              "video_size=%dx%d:pix_fmt=%d:time_base=%d/%d:"
621              "pixel_aspect=%d/%d:sws_param=flags=%d", ist->resample_width,
622              ist->resample_height, ist->resample_pix_fmt,
623              tb.num, tb.den, sar.num, sar.den,
624              SWS_BILINEAR + ((ist->st->codec->flags&CODEC_FLAG_BITEXACT) ? SWS_BITEXACT:0));
625     if (fr.num && fr.den)
626         av_bprintf(&args, ":frame_rate=%d/%d", fr.num, fr.den);
627     snprintf(name, sizeof(name), "graph %d input from stream %d:%d", fg->index,
628              ist->file_index, ist->st->index);
629
630     if ((ret = avfilter_graph_create_filter(&ifilter->filter, filter, name,
631                                             args.str, NULL, fg->graph)) < 0)
632         return ret;
633
634     if (ist->framerate.num) {
635         AVFilterContext *setpts;
636
637         snprintf(name, sizeof(name), "force CFR for input from stream %d:%d",
638                  ist->file_index, ist->st->index);
639         if ((ret = avfilter_graph_create_filter(&setpts,
640                                                 avfilter_get_by_name("setpts"),
641                                                 name, "N", NULL,
642                                                 fg->graph)) < 0)
643             return ret;
644
645         if ((ret = avfilter_link(setpts, 0, first_filter, pad_idx)) < 0)
646             return ret;
647
648         first_filter = setpts;
649         pad_idx = 0;
650     }
651
652     if (do_deinterlace) {
653         AVFilterContext *yadif;
654
655         snprintf(name, sizeof(name), "deinterlace input from stream %d:%d",
656                  ist->file_index, ist->st->index);
657         if ((ret = avfilter_graph_create_filter(&yadif,
658                                                 avfilter_get_by_name("yadif"),
659                                                 name, "", NULL,
660                                                 fg->graph)) < 0)
661             return ret;
662
663         if ((ret = avfilter_link(yadif, 0, first_filter, pad_idx)) < 0)
664             return ret;
665
666         first_filter = yadif;
667         pad_idx = 0;
668     }
669
670     if ((ret = avfilter_link(ifilter->filter, 0, first_filter, pad_idx)) < 0)
671         return ret;
672     return 0;
673 }
674
675 static int configure_input_audio_filter(FilterGraph *fg, InputFilter *ifilter,
676                                         AVFilterInOut *in)
677 {
678     AVFilterContext *first_filter = in->filter_ctx;
679     AVFilter *filter = avfilter_get_by_name("abuffer");
680     InputStream *ist = ifilter->ist;
681     int pad_idx = in->pad_idx;
682     AVBPrint args;
683     char name[255];
684     int ret;
685
686     av_bprint_init(&args, 0, AV_BPRINT_SIZE_AUTOMATIC);
687     av_bprintf(&args, "time_base=%d/%d:sample_rate=%d:sample_fmt=%s",
688              1, ist->st->codec->sample_rate,
689              ist->st->codec->sample_rate,
690              av_get_sample_fmt_name(ist->st->codec->sample_fmt));
691     if (ist->st->codec->channel_layout)
692         av_bprintf(&args, ":channel_layout=0x%"PRIx64,
693                    ist->st->codec->channel_layout);
694     else
695         av_bprintf(&args, ":channels=%d", ist->st->codec->channels);
696     snprintf(name, sizeof(name), "graph %d input from stream %d:%d", fg->index,
697              ist->file_index, ist->st->index);
698
699     if ((ret = avfilter_graph_create_filter(&ifilter->filter, filter,
700                                             name, args.str, NULL,
701                                             fg->graph)) < 0)
702         return ret;
703
704 #define AUTO_INSERT_FILTER_INPUT(opt_name, filter_name, arg) do {                 \
705     AVFilterContext *filt_ctx;                                              \
706                                                                             \
707     av_log(NULL, AV_LOG_INFO, opt_name " is forwarded to lavfi "            \
708            "similarly to -af " filter_name "=%s.\n", arg);                  \
709                                                                             \
710     snprintf(name, sizeof(name), "graph %d %s for input stream %d:%d",      \
711                 fg->index, filter_name, ist->file_index, ist->st->index);   \
712     ret = avfilter_graph_create_filter(&filt_ctx,                           \
713                                        avfilter_get_by_name(filter_name),   \
714                                        name, arg, NULL, fg->graph);         \
715     if (ret < 0)                                                            \
716         return ret;                                                         \
717                                                                             \
718     ret = avfilter_link(filt_ctx, 0, first_filter, pad_idx);                \
719     if (ret < 0)                                                            \
720         return ret;                                                         \
721                                                                             \
722     first_filter = filt_ctx;                                                  \
723 } while (0)
724
725     if (audio_sync_method > 0) {
726         char args[256] = {0};
727
728         av_strlcatf(args, sizeof(args), "async=%d", audio_sync_method);
729         if (audio_drift_threshold != 0.1)
730             av_strlcatf(args, sizeof(args), ":min_hard_comp=%f", audio_drift_threshold);
731         if (!fg->reconfiguration)
732             av_strlcatf(args, sizeof(args), ":first_pts=0");
733         AUTO_INSERT_FILTER_INPUT("-async", "aresample", args);
734     }
735
736 //     if (ost->audio_channels_mapped) {
737 //         int i;
738 //         AVBPrint pan_buf;
739 //         av_bprint_init(&pan_buf, 256, 8192);
740 //         av_bprintf(&pan_buf, "0x%"PRIx64,
741 //                    av_get_default_channel_layout(ost->audio_channels_mapped));
742 //         for (i = 0; i < ost->audio_channels_mapped; i++)
743 //             if (ost->audio_channels_map[i] != -1)
744 //                 av_bprintf(&pan_buf, ":c%d=c%d", i, ost->audio_channels_map[i]);
745 //         AUTO_INSERT_FILTER_INPUT("-map_channel", "pan", pan_buf.str);
746 //         av_bprint_finalize(&pan_buf, NULL);
747 //     }
748
749     if (audio_volume != 256) {
750         char args[256];
751
752         av_log(NULL, AV_LOG_WARNING, "-vol has been deprecated. Use the volume "
753                "audio filter instead.\n");
754
755         snprintf(args, sizeof(args), "%f", audio_volume / 256.);
756         AUTO_INSERT_FILTER_INPUT("-vol", "volume", args);
757     }
758     if ((ret = avfilter_link(ifilter->filter, 0, first_filter, pad_idx)) < 0)
759         return ret;
760
761     return 0;
762 }
763
764 static int configure_input_filter(FilterGraph *fg, InputFilter *ifilter,
765                                   AVFilterInOut *in)
766 {
767     av_freep(&ifilter->name);
768     DESCRIBE_FILTER_LINK(ifilter, in, 1);
769
770     switch (avfilter_pad_get_type(in->filter_ctx->input_pads, in->pad_idx)) {
771     case AVMEDIA_TYPE_VIDEO: return configure_input_video_filter(fg, ifilter, in);
772     case AVMEDIA_TYPE_AUDIO: return configure_input_audio_filter(fg, ifilter, in);
773     default: av_assert0(0);
774     }
775 }
776
777 int configure_filtergraph(FilterGraph *fg)
778 {
779     AVFilterInOut *inputs, *outputs, *cur;
780     int ret, i, init = !fg->graph, simple = !fg->graph_desc;
781     const char *graph_desc = simple ? fg->outputs[0]->ost->avfilter :
782                                       fg->graph_desc;
783
784     avfilter_graph_free(&fg->graph);
785     if (!(fg->graph = avfilter_graph_alloc()))
786         return AVERROR(ENOMEM);
787
788     if (simple) {
789         OutputStream *ost = fg->outputs[0]->ost;
790         char args[512];
791         AVDictionaryEntry *e = NULL;
792
793         snprintf(args, sizeof(args), "flags=0x%X", (unsigned)ost->sws_flags);
794         fg->graph->scale_sws_opts = av_strdup(args);
795
796         args[0] = 0;
797         while ((e = av_dict_get(ost->swr_opts, "", e,
798                                 AV_DICT_IGNORE_SUFFIX))) {
799             av_strlcatf(args, sizeof(args), "%s=%s:", e->key, e->value);
800         }
801         if (strlen(args))
802             args[strlen(args)-1] = 0;
803         av_opt_set(fg->graph, "aresample_swr_opts", args, 0);
804
805         args[0] = '\0';
806         while ((e = av_dict_get(fg->outputs[0]->ost->resample_opts, "", e,
807                                 AV_DICT_IGNORE_SUFFIX))) {
808             av_strlcatf(args, sizeof(args), "%s=%s:", e->key, e->value);
809         }
810         if (strlen(args))
811             args[strlen(args) - 1] = '\0';
812         fg->graph->resample_lavr_opts = av_strdup(args);
813     }
814
815     if ((ret = avfilter_graph_parse2(fg->graph, graph_desc, &inputs, &outputs)) < 0)
816         return ret;
817
818     if (simple && (!inputs || inputs->next || !outputs || outputs->next)) {
819         av_log(NULL, AV_LOG_ERROR, "Simple filtergraph '%s' does not have "
820                "exactly one input and output.\n", graph_desc);
821         return AVERROR(EINVAL);
822     }
823
824     for (cur = inputs; !simple && init && cur; cur = cur->next)
825         init_input_filter(fg, cur);
826
827     for (cur = inputs, i = 0; cur; cur = cur->next, i++)
828         if ((ret = configure_input_filter(fg, fg->inputs[i], cur)) < 0)
829             return ret;
830     avfilter_inout_free(&inputs);
831
832     if (!init || simple) {
833         /* we already know the mappings between lavfi outputs and output streams,
834          * so we can finish the setup */
835         for (cur = outputs, i = 0; cur; cur = cur->next, i++)
836             configure_output_filter(fg, fg->outputs[i], cur);
837         avfilter_inout_free(&outputs);
838
839         if ((ret = avfilter_graph_config(fg->graph, NULL)) < 0)
840             return ret;
841     } else {
842         /* wait until output mappings are processed */
843         for (cur = outputs; cur;) {
844             GROW_ARRAY(fg->outputs, fg->nb_outputs);
845             if (!(fg->outputs[fg->nb_outputs - 1] = av_mallocz(sizeof(*fg->outputs[0]))))
846                 exit(1);
847             fg->outputs[fg->nb_outputs - 1]->graph   = fg;
848             fg->outputs[fg->nb_outputs - 1]->out_tmp = cur;
849             cur = cur->next;
850             fg->outputs[fg->nb_outputs - 1]->out_tmp->next = NULL;
851         }
852     }
853
854     fg->reconfiguration = 1;
855     return 0;
856 }
857
858 int ist_in_filtergraph(FilterGraph *fg, InputStream *ist)
859 {
860     int i;
861     for (i = 0; i < fg->nb_inputs; i++)
862         if (fg->inputs[i]->ist == ist)
863             return 1;
864     return 0;
865 }
866