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