]> git.sesse.net Git - ffmpeg/blob - ffmpeg_filter.c
ffv1dec: remove redundant error message.
[ffmpeg] / 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 configure_output_video_filter(FilterGraph *fg, OutputFilter *ofilter, AVFilterInOut *out)
280 {
281     char *pix_fmts;
282     OutputStream *ost = ofilter->ost;
283     AVCodecContext *codec = ost->st->codec;
284     AVFilterContext *last_filter = out->filter_ctx;
285     int pad_idx = out->pad_idx;
286     int ret;
287     char name[255];
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("buffersink"),
292                                        name, NULL, NULL, fg->graph);
293
294     if (ret < 0)
295         return ret;
296
297     if (codec->width || codec->height) {
298         char args[255];
299         AVFilterContext *filter;
300
301         snprintf(args, sizeof(args), "%d:%d:flags=0x%X",
302                  codec->width,
303                  codec->height,
304                  (unsigned)ost->sws_flags);
305         snprintf(name, sizeof(name), "scaler for output stream %d:%d",
306                  ost->file_index, ost->index);
307         if ((ret = avfilter_graph_create_filter(&filter, avfilter_get_by_name("scale"),
308                                                 name, args, NULL, fg->graph)) < 0)
309             return ret;
310         if ((ret = avfilter_link(last_filter, pad_idx, filter, 0)) < 0)
311             return ret;
312
313         last_filter = filter;
314         pad_idx = 0;
315     }
316
317     if ((pix_fmts = choose_pix_fmts(ost))) {
318         AVFilterContext *filter;
319         snprintf(name, sizeof(name), "pixel format for output stream %d:%d",
320                  ost->file_index, ost->index);
321         ret = avfilter_graph_create_filter(&filter,
322                                                 avfilter_get_by_name("format"),
323                                                 "format", pix_fmts, NULL,
324                                                 fg->graph);
325         av_freep(&pix_fmts);
326         if (ret < 0)
327             return ret;
328         if ((ret = avfilter_link(last_filter, pad_idx, filter, 0)) < 0)
329             return ret;
330
331         last_filter = filter;
332         pad_idx     = 0;
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     snprintf(name, sizeof(name), "output stream %d:%d", ost->file_index, ost->index);
372     ret = avfilter_graph_create_filter(&ofilter->filter,
373                                        avfilter_get_by_name("abuffersink"),
374                                        name, NULL, NULL, fg->graph);
375     if (ret < 0)
376         return ret;
377     if ((ret = av_opt_set_int(ofilter->filter, "all_channel_counts", 1, AV_OPT_SEARCH_CHILDREN)) < 0)
378         return ret;
379
380 #define AUTO_INSERT_FILTER(opt_name, filter_name, arg) do {                 \
381     AVFilterContext *filt_ctx;                                              \
382                                                                             \
383     av_log(NULL, AV_LOG_INFO, opt_name " is forwarded to lavfi "            \
384            "similarly to -af " filter_name "=%s.\n", arg);                  \
385                                                                             \
386     ret = avfilter_graph_create_filter(&filt_ctx,                           \
387                                        avfilter_get_by_name(filter_name),   \
388                                        filter_name, arg, NULL, fg->graph);  \
389     if (ret < 0)                                                            \
390         return ret;                                                         \
391                                                                             \
392     ret = avfilter_link(last_filter, pad_idx, filt_ctx, 0);                 \
393     if (ret < 0)                                                            \
394         return ret;                                                         \
395                                                                             \
396     last_filter = filt_ctx;                                                 \
397     pad_idx = 0;                                                            \
398 } while (0)
399     if (ost->audio_channels_mapped) {
400         int i;
401         AVBPrint pan_buf;
402         av_bprint_init(&pan_buf, 256, 8192);
403         av_bprintf(&pan_buf, "0x%"PRIx64,
404                    av_get_default_channel_layout(ost->audio_channels_mapped));
405         for (i = 0; i < ost->audio_channels_mapped; i++)
406             if (ost->audio_channels_map[i] != -1)
407                 av_bprintf(&pan_buf, ":c%d=c%d", i, ost->audio_channels_map[i]);
408
409         AUTO_INSERT_FILTER("-map_channel", "pan", pan_buf.str);
410         av_bprint_finalize(&pan_buf, NULL);
411     }
412
413     if (codec->channels && !codec->channel_layout)
414         codec->channel_layout = av_get_default_channel_layout(codec->channels);
415
416     sample_fmts     = choose_sample_fmts(ost);
417     sample_rates    = choose_sample_rates(ost);
418     channel_layouts = choose_channel_layouts(ost);
419     if (sample_fmts || sample_rates || channel_layouts) {
420         AVFilterContext *format;
421         char args[256];
422         args[0] = 0;
423
424         if (sample_fmts)
425             av_strlcatf(args, sizeof(args), "sample_fmts=%s:",
426                             sample_fmts);
427         if (sample_rates)
428             av_strlcatf(args, sizeof(args), "sample_rates=%s:",
429                             sample_rates);
430         if (channel_layouts)
431             av_strlcatf(args, sizeof(args), "channel_layouts=%s:",
432                             channel_layouts);
433
434         av_freep(&sample_fmts);
435         av_freep(&sample_rates);
436         av_freep(&channel_layouts);
437
438         snprintf(name, sizeof(name), "audio format for output stream %d:%d",
439                  ost->file_index, ost->index);
440         ret = avfilter_graph_create_filter(&format,
441                                            avfilter_get_by_name("aformat"),
442                                            name, args, NULL, fg->graph);
443         if (ret < 0)
444             return ret;
445
446         ret = avfilter_link(last_filter, pad_idx, format, 0);
447         if (ret < 0)
448             return ret;
449
450         last_filter = format;
451         pad_idx = 0;
452     }
453
454     if (audio_volume != 256 && 0) {
455         char args[256];
456
457         snprintf(args, sizeof(args), "%f", audio_volume / 256.);
458         AUTO_INSERT_FILTER("-vol", "volume", args);
459     }
460
461     if ((ret = avfilter_link(last_filter, pad_idx, ofilter->filter, 0)) < 0)
462         return ret;
463
464     return 0;
465 }
466
467 #define DESCRIBE_FILTER_LINK(f, inout, in)                         \
468 {                                                                  \
469     AVFilterContext *ctx = inout->filter_ctx;                      \
470     AVFilterPad *pads = in ? ctx->input_pads  : ctx->output_pads;  \
471     int       nb_pads = in ? ctx->input_count : ctx->output_count; \
472     AVIOContext *pb;                                               \
473                                                                    \
474     if (avio_open_dyn_buf(&pb) < 0)                                \
475         exit(1);                                                   \
476                                                                    \
477     avio_printf(pb, "%s", ctx->filter->name);                      \
478     if (nb_pads > 1)                                               \
479         avio_printf(pb, ":%s", avfilter_pad_get_name(pads, inout->pad_idx));\
480     avio_w8(pb, 0);                                                \
481     avio_close_dyn_buf(pb, &f->name);                              \
482 }
483
484 int configure_output_filter(FilterGraph *fg, OutputFilter *ofilter, AVFilterInOut *out)
485 {
486     av_freep(&ofilter->name);
487     DESCRIBE_FILTER_LINK(ofilter, out, 0);
488
489     switch (avfilter_pad_get_type(out->filter_ctx->output_pads, out->pad_idx)) {
490     case AVMEDIA_TYPE_VIDEO: return configure_output_video_filter(fg, ofilter, out);
491     case AVMEDIA_TYPE_AUDIO: return configure_output_audio_filter(fg, ofilter, out);
492     default: av_assert0(0);
493     }
494 }
495
496 static int sub2video_prepare(InputStream *ist)
497 {
498     AVFormatContext *avf = input_files[ist->file_index]->ctx;
499     int i, w, h;
500
501     /* Compute the size of the canvas for the subtitles stream.
502        If the subtitles codec has set a size, use it. Otherwise use the
503        maximum dimensions of the video streams in the same file. */
504     w = ist->st->codec->width;
505     h = ist->st->codec->height;
506     if (!(w && h)) {
507         for (i = 0; i < avf->nb_streams; i++) {
508             if (avf->streams[i]->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
509                 w = FFMAX(w, avf->streams[i]->codec->width);
510                 h = FFMAX(h, avf->streams[i]->codec->height);
511             }
512         }
513         if (!(w && h)) {
514             w = FFMAX(w, 720);
515             h = FFMAX(h, 576);
516         }
517         av_log(avf, AV_LOG_INFO, "sub2video: using %dx%d canvas\n", w, h);
518     }
519     ist->sub2video.w = ist->st->codec->width  = ist->resample_width  = w;
520     ist->sub2video.h = ist->st->codec->height = ist->resample_height = h;
521
522     /* rectangles are AV_PIX_FMT_PAL8, but we have no guarantee that the
523        palettes for all rectangles are identical or compatible */
524     ist->resample_pix_fmt = ist->st->codec->pix_fmt = AV_PIX_FMT_RGB32;
525
526     ist->sub2video.frame = av_frame_alloc();
527     if (!ist->sub2video.frame)
528         return AVERROR(ENOMEM);
529     return 0;
530 }
531
532 static int configure_input_video_filter(FilterGraph *fg, InputFilter *ifilter,
533                                         AVFilterInOut *in)
534 {
535     AVFilterContext *first_filter = in->filter_ctx;
536     AVFilter *filter = avfilter_get_by_name("buffer");
537     InputStream *ist = ifilter->ist;
538     AVRational tb = ist->framerate.num ? av_inv_q(ist->framerate) :
539                                          ist->st->time_base;
540     AVRational fr = ist->framerate;
541     AVRational sar;
542     AVBPrint args;
543     char name[255];
544     int pad_idx = in->pad_idx;
545     int ret;
546
547     if (!fr.num)
548         fr = av_guess_frame_rate(input_files[ist->file_index]->ctx, ist->st, NULL);
549
550     if (ist->st->codec->codec_type == AVMEDIA_TYPE_SUBTITLE) {
551         ret = sub2video_prepare(ist);
552         if (ret < 0)
553             return ret;
554     }
555
556     sar = ist->st->sample_aspect_ratio.num ?
557           ist->st->sample_aspect_ratio :
558           ist->st->codec->sample_aspect_ratio;
559     if(!sar.den)
560         sar = (AVRational){0,1};
561     av_bprint_init(&args, 0, 1);
562     av_bprintf(&args,
563              "video_size=%dx%d:pix_fmt=%d:time_base=%d/%d:"
564              "pixel_aspect=%d/%d:sws_param=flags=%d", ist->resample_width,
565              ist->resample_height, ist->resample_pix_fmt,
566              tb.num, tb.den, sar.num, sar.den,
567              SWS_BILINEAR + ((ist->st->codec->flags&CODEC_FLAG_BITEXACT) ? SWS_BITEXACT:0));
568     if (fr.num && fr.den)
569         av_bprintf(&args, ":frame_rate=%d/%d", fr.num, fr.den);
570     snprintf(name, sizeof(name), "graph %d input from stream %d:%d", fg->index,
571              ist->file_index, ist->st->index);
572
573     if ((ret = avfilter_graph_create_filter(&ifilter->filter, filter, name,
574                                             args.str, NULL, fg->graph)) < 0)
575         return ret;
576
577     if (ist->framerate.num) {
578         AVFilterContext *setpts;
579
580         snprintf(name, sizeof(name), "force CFR for input from stream %d:%d",
581                  ist->file_index, ist->st->index);
582         if ((ret = avfilter_graph_create_filter(&setpts,
583                                                 avfilter_get_by_name("setpts"),
584                                                 name, "N", NULL,
585                                                 fg->graph)) < 0)
586             return ret;
587
588         if ((ret = avfilter_link(setpts, 0, first_filter, pad_idx)) < 0)
589             return ret;
590
591         first_filter = setpts;
592         pad_idx = 0;
593     }
594
595     if (do_deinterlace) {
596         AVFilterContext *yadif;
597
598         snprintf(name, sizeof(name), "deinterlace input from stream %d:%d",
599                  ist->file_index, ist->st->index);
600         if ((ret = avfilter_graph_create_filter(&yadif,
601                                                 avfilter_get_by_name("yadif"),
602                                                 name, "", NULL,
603                                                 fg->graph)) < 0)
604             return ret;
605
606         if ((ret = avfilter_link(yadif, 0, first_filter, pad_idx)) < 0)
607             return ret;
608
609         first_filter = yadif;
610         pad_idx = 0;
611     }
612
613     if ((ret = avfilter_link(ifilter->filter, 0, first_filter, pad_idx)) < 0)
614         return ret;
615     return 0;
616 }
617
618 static int configure_input_audio_filter(FilterGraph *fg, InputFilter *ifilter,
619                                         AVFilterInOut *in)
620 {
621     AVFilterContext *first_filter = in->filter_ctx;
622     AVFilter *filter = avfilter_get_by_name("abuffer");
623     InputStream *ist = ifilter->ist;
624     int pad_idx = in->pad_idx;
625     AVBPrint args;
626     char name[255];
627     int ret;
628
629     av_bprint_init(&args, 0, AV_BPRINT_SIZE_AUTOMATIC);
630     av_bprintf(&args, "time_base=%d/%d:sample_rate=%d:sample_fmt=%s",
631              1, ist->st->codec->sample_rate,
632              ist->st->codec->sample_rate,
633              av_get_sample_fmt_name(ist->st->codec->sample_fmt));
634     if (ist->st->codec->channel_layout)
635         av_bprintf(&args, ":channel_layout=0x%"PRIx64,
636                    ist->st->codec->channel_layout);
637     else
638         av_bprintf(&args, ":channels=%d", ist->st->codec->channels);
639     snprintf(name, sizeof(name), "graph %d input from stream %d:%d", fg->index,
640              ist->file_index, ist->st->index);
641
642     if ((ret = avfilter_graph_create_filter(&ifilter->filter, filter,
643                                             name, args.str, NULL,
644                                             fg->graph)) < 0)
645         return ret;
646
647 #define AUTO_INSERT_FILTER_INPUT(opt_name, filter_name, arg) do {                 \
648     AVFilterContext *filt_ctx;                                              \
649                                                                             \
650     av_log(NULL, AV_LOG_INFO, opt_name " is forwarded to lavfi "            \
651            "similarly to -af " filter_name "=%s.\n", arg);                  \
652                                                                             \
653     snprintf(name, sizeof(name), "graph %d %s for input stream %d:%d",      \
654                 fg->index, filter_name, ist->file_index, ist->st->index);   \
655     ret = avfilter_graph_create_filter(&filt_ctx,                           \
656                                        avfilter_get_by_name(filter_name),   \
657                                        name, arg, NULL, fg->graph);         \
658     if (ret < 0)                                                            \
659         return ret;                                                         \
660                                                                             \
661     ret = avfilter_link(filt_ctx, 0, first_filter, pad_idx);                \
662     if (ret < 0)                                                            \
663         return ret;                                                         \
664                                                                             \
665     first_filter = filt_ctx;                                                  \
666 } while (0)
667
668     if (audio_sync_method > 0) {
669         char args[256] = {0};
670
671         av_strlcatf(args, sizeof(args), "async=%d", audio_sync_method);
672         if (audio_drift_threshold != 0.1)
673             av_strlcatf(args, sizeof(args), ":min_hard_comp=%f", audio_drift_threshold);
674         if (!fg->reconfiguration)
675             av_strlcatf(args, sizeof(args), ":first_pts=0");
676         AUTO_INSERT_FILTER_INPUT("-async", "aresample", args);
677     }
678
679 //     if (ost->audio_channels_mapped) {
680 //         int i;
681 //         AVBPrint pan_buf;
682 //         av_bprint_init(&pan_buf, 256, 8192);
683 //         av_bprintf(&pan_buf, "0x%"PRIx64,
684 //                    av_get_default_channel_layout(ost->audio_channels_mapped));
685 //         for (i = 0; i < ost->audio_channels_mapped; i++)
686 //             if (ost->audio_channels_map[i] != -1)
687 //                 av_bprintf(&pan_buf, ":c%d=c%d", i, ost->audio_channels_map[i]);
688 //         AUTO_INSERT_FILTER_INPUT("-map_channel", "pan", pan_buf.str);
689 //         av_bprint_finalize(&pan_buf, NULL);
690 //     }
691
692     if (audio_volume != 256) {
693         char args[256];
694
695         av_log(NULL, AV_LOG_WARNING, "-vol has been deprecated. Use the volume "
696                "audio filter instead.\n");
697
698         snprintf(args, sizeof(args), "%f", audio_volume / 256.);
699         AUTO_INSERT_FILTER_INPUT("-vol", "volume", args);
700     }
701     if ((ret = avfilter_link(ifilter->filter, 0, first_filter, pad_idx)) < 0)
702         return ret;
703
704     return 0;
705 }
706
707 static int configure_input_filter(FilterGraph *fg, InputFilter *ifilter,
708                                   AVFilterInOut *in)
709 {
710     av_freep(&ifilter->name);
711     DESCRIBE_FILTER_LINK(ifilter, in, 1);
712
713     switch (avfilter_pad_get_type(in->filter_ctx->input_pads, in->pad_idx)) {
714     case AVMEDIA_TYPE_VIDEO: return configure_input_video_filter(fg, ifilter, in);
715     case AVMEDIA_TYPE_AUDIO: return configure_input_audio_filter(fg, ifilter, in);
716     default: av_assert0(0);
717     }
718 }
719
720 int configure_filtergraph(FilterGraph *fg)
721 {
722     AVFilterInOut *inputs, *outputs, *cur;
723     int ret, i, init = !fg->graph, simple = !fg->graph_desc;
724     const char *graph_desc = simple ? fg->outputs[0]->ost->avfilter :
725                                       fg->graph_desc;
726
727     avfilter_graph_free(&fg->graph);
728     if (!(fg->graph = avfilter_graph_alloc()))
729         return AVERROR(ENOMEM);
730
731     if (simple) {
732         OutputStream *ost = fg->outputs[0]->ost;
733         char args[512];
734         AVDictionaryEntry *e = NULL;
735
736         snprintf(args, sizeof(args), "flags=0x%X", (unsigned)ost->sws_flags);
737         fg->graph->scale_sws_opts = av_strdup(args);
738
739         args[0] = 0;
740         while ((e = av_dict_get(ost->swr_opts, "", e,
741                                 AV_DICT_IGNORE_SUFFIX))) {
742             av_strlcatf(args, sizeof(args), "%s=%s:", e->key, e->value);
743         }
744         if (strlen(args))
745             args[strlen(args)-1] = 0;
746         av_opt_set(fg->graph, "aresample_swr_opts", args, 0);
747
748         args[0] = '\0';
749         while ((e = av_dict_get(fg->outputs[0]->ost->resample_opts, "", e,
750                                 AV_DICT_IGNORE_SUFFIX))) {
751             av_strlcatf(args, sizeof(args), "%s=%s:", e->key, e->value);
752         }
753         if (strlen(args))
754             args[strlen(args) - 1] = '\0';
755         fg->graph->resample_lavr_opts = av_strdup(args);
756     }
757
758     if ((ret = avfilter_graph_parse2(fg->graph, graph_desc, &inputs, &outputs)) < 0)
759         return ret;
760
761     if (simple && (!inputs || inputs->next || !outputs || outputs->next)) {
762         av_log(NULL, AV_LOG_ERROR, "Simple filtergraph '%s' does not have "
763                "exactly one input and output.\n", graph_desc);
764         return AVERROR(EINVAL);
765     }
766
767     for (cur = inputs; !simple && init && cur; cur = cur->next)
768         init_input_filter(fg, cur);
769
770     for (cur = inputs, i = 0; cur; cur = cur->next, i++)
771         if ((ret = configure_input_filter(fg, fg->inputs[i], cur)) < 0)
772             return ret;
773     avfilter_inout_free(&inputs);
774
775     if (!init || simple) {
776         /* we already know the mappings between lavfi outputs and output streams,
777          * so we can finish the setup */
778         for (cur = outputs, i = 0; cur; cur = cur->next, i++)
779             configure_output_filter(fg, fg->outputs[i], cur);
780         avfilter_inout_free(&outputs);
781
782         if ((ret = avfilter_graph_config(fg->graph, NULL)) < 0)
783             return ret;
784     } else {
785         /* wait until output mappings are processed */
786         for (cur = outputs; cur;) {
787             GROW_ARRAY(fg->outputs, fg->nb_outputs);
788             if (!(fg->outputs[fg->nb_outputs - 1] = av_mallocz(sizeof(*fg->outputs[0]))))
789                 exit(1);
790             fg->outputs[fg->nb_outputs - 1]->graph   = fg;
791             fg->outputs[fg->nb_outputs - 1]->out_tmp = cur;
792             cur = cur->next;
793             fg->outputs[fg->nb_outputs - 1]->out_tmp->next = NULL;
794         }
795     }
796
797     fg->reconfiguration = 1;
798     return 0;
799 }
800
801 int ist_in_filtergraph(FilterGraph *fg, InputStream *ist)
802 {
803     int i;
804     for (i = 0; i < fg->nb_inputs; i++)
805         if (fg->inputs[i]->ist == ist)
806             return 1;
807     return 0;
808 }
809