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