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