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