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