6a891d3d10022b9d1a899277ddc0dec91a4281a5
[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 <stdint.h>
22
23 #include "ffmpeg.h"
24
25 #include "libavfilter/avfilter.h"
26 #include "libavfilter/buffersink.h"
27
28 #include "libavresample/avresample.h"
29
30 #include "libavutil/avassert.h"
31 #include "libavutil/avstring.h"
32 #include "libavutil/bprint.h"
33 #include "libavutil/channel_layout.h"
34 #include "libavutil/display.h"
35 #include "libavutil/opt.h"
36 #include "libavutil/pixdesc.h"
37 #include "libavutil/pixfmt.h"
38 #include "libavutil/imgutils.h"
39 #include "libavutil/samplefmt.h"
40
41 enum AVPixelFormat choose_pixel_fmt(AVStream *st, AVCodecContext *enc_ctx, AVCodec *codec, enum AVPixelFormat target)
42 {
43     if (codec && codec->pix_fmts) {
44         const enum AVPixelFormat *p = codec->pix_fmts;
45         const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(target);
46         int has_alpha = desc ? desc->nb_components % 2 == 0 : 0;
47         enum AVPixelFormat best= AV_PIX_FMT_NONE;
48         static const enum AVPixelFormat mjpeg_formats[] =
49             { AV_PIX_FMT_YUVJ420P, AV_PIX_FMT_YUVJ422P, AV_PIX_FMT_YUV420P, AV_PIX_FMT_YUV422P, AV_PIX_FMT_NONE };
50         static const enum AVPixelFormat ljpeg_formats[] =
51             { AV_PIX_FMT_YUVJ420P, AV_PIX_FMT_YUVJ422P, AV_PIX_FMT_YUVJ444P, AV_PIX_FMT_YUV420P,
52               AV_PIX_FMT_YUV422P, AV_PIX_FMT_YUV444P, AV_PIX_FMT_BGRA, AV_PIX_FMT_NONE };
53
54         if (enc_ctx->strict_std_compliance <= FF_COMPLIANCE_UNOFFICIAL) {
55             if (enc_ctx->codec_id == AV_CODEC_ID_MJPEG) {
56                 p = mjpeg_formats;
57             } else if (enc_ctx->codec_id == AV_CODEC_ID_LJPEG) {
58                 p =ljpeg_formats;
59             }
60         }
61         for (; *p != AV_PIX_FMT_NONE; p++) {
62             best= avcodec_find_best_pix_fmt_of_2(best, *p, target, has_alpha, NULL);
63             if (*p == target)
64                 break;
65         }
66         if (*p == AV_PIX_FMT_NONE) {
67             if (target != AV_PIX_FMT_NONE)
68                 av_log(NULL, AV_LOG_WARNING,
69                        "Incompatible pixel format '%s' for codec '%s', auto-selecting format '%s'\n",
70                        av_get_pix_fmt_name(target),
71                        codec->name,
72                        av_get_pix_fmt_name(best));
73             return best;
74         }
75     }
76     return target;
77 }
78
79 void choose_sample_fmt(AVStream *st, AVCodec *codec)
80 {
81     if (codec && codec->sample_fmts) {
82         const enum AVSampleFormat *p = codec->sample_fmts;
83         for (; *p != -1; p++) {
84             if (*p == st->codec->sample_fmt)
85                 break;
86         }
87         if (*p == -1) {
88             if((codec->capabilities & CODEC_CAP_LOSSLESS) && av_get_sample_fmt_name(st->codec->sample_fmt) > av_get_sample_fmt_name(codec->sample_fmts[0]))
89                 av_log(NULL, AV_LOG_ERROR, "Conversion will not be lossless.\n");
90             if(av_get_sample_fmt_name(st->codec->sample_fmt))
91             av_log(NULL, AV_LOG_WARNING,
92                    "Incompatible sample format '%s' for codec '%s', auto-selecting format '%s'\n",
93                    av_get_sample_fmt_name(st->codec->sample_fmt),
94                    codec->name,
95                    av_get_sample_fmt_name(codec->sample_fmts[0]));
96             st->codec->sample_fmt = codec->sample_fmts[0];
97         }
98     }
99 }
100
101 static char *choose_pix_fmts(OutputStream *ost)
102 {
103     AVDictionaryEntry *strict_dict = av_dict_get(ost->encoder_opts, "strict", NULL, 0);
104     if (strict_dict)
105         // used by choose_pixel_fmt() and below
106         av_opt_set(ost->enc_ctx, "strict", strict_dict->value, 0);
107
108      if (ost->keep_pix_fmt) {
109         if (ost->filter)
110             avfilter_graph_set_auto_convert(ost->filter->graph->graph,
111                                             AVFILTER_AUTO_CONVERT_NONE);
112         if (ost->enc_ctx->pix_fmt == AV_PIX_FMT_NONE)
113             return NULL;
114         return av_strdup(av_get_pix_fmt_name(ost->enc_ctx->pix_fmt));
115     }
116     if (ost->enc_ctx->pix_fmt != AV_PIX_FMT_NONE) {
117         return av_strdup(av_get_pix_fmt_name(choose_pixel_fmt(ost->st, ost->enc_ctx, ost->enc, ost->enc_ctx->pix_fmt)));
118     } else if (ost->enc && ost->enc->pix_fmts) {
119         const enum AVPixelFormat *p;
120         AVIOContext *s = NULL;
121         uint8_t *ret;
122         int len;
123
124         if (avio_open_dyn_buf(&s) < 0)
125             exit_program(1);
126
127         p = ost->enc->pix_fmts;
128         if (ost->enc_ctx->strict_std_compliance <= FF_COMPLIANCE_UNOFFICIAL) {
129             if (ost->enc_ctx->codec_id == AV_CODEC_ID_MJPEG) {
130                 p = (const enum AVPixelFormat[]) { AV_PIX_FMT_YUVJ420P, AV_PIX_FMT_YUVJ422P, AV_PIX_FMT_YUV420P, AV_PIX_FMT_YUV422P, AV_PIX_FMT_NONE };
131             } else if (ost->enc_ctx->codec_id == AV_CODEC_ID_LJPEG) {
132                 p = (const enum AVPixelFormat[]) { AV_PIX_FMT_YUVJ420P, AV_PIX_FMT_YUVJ422P, AV_PIX_FMT_YUVJ444P, AV_PIX_FMT_YUV420P,
133                                                     AV_PIX_FMT_YUV422P, AV_PIX_FMT_YUV444P, AV_PIX_FMT_BGRA, AV_PIX_FMT_NONE };
134             }
135         }
136
137         for (; *p != AV_PIX_FMT_NONE; p++) {
138             const char *name = av_get_pix_fmt_name(*p);
139             avio_printf(s, "%s|", name);
140         }
141         len = avio_close_dyn_buf(s, &ret);
142         ret[len - 1] = 0;
143         return ret;
144     } else
145         return NULL;
146 }
147
148 /* Define a function for building a string containing a list of
149  * allowed formats. */
150 #define DEF_CHOOSE_FORMAT(type, var, supported_list, none, get_name)           \
151 static char *choose_ ## var ## s(OutputStream *ost)                            \
152 {                                                                              \
153     if (ost->enc_ctx->var != none) {                                           \
154         get_name(ost->enc_ctx->var);                                           \
155         return av_strdup(name);                                                \
156     } else if (ost->enc && ost->enc->supported_list) {                         \
157         const type *p;                                                         \
158         AVIOContext *s = NULL;                                                 \
159         uint8_t *ret;                                                          \
160         int len;                                                               \
161                                                                                \
162         if (avio_open_dyn_buf(&s) < 0)                                         \
163             exit_program(1);                                                           \
164                                                                                \
165         for (p = ost->enc->supported_list; *p != none; p++) {                  \
166             get_name(*p);                                                      \
167             avio_printf(s, "%s|", name);                                       \
168         }                                                                      \
169         len = avio_close_dyn_buf(s, &ret);                                     \
170         ret[len - 1] = 0;                                                      \
171         return ret;                                                            \
172     } else                                                                     \
173         return NULL;                                                           \
174 }
175
176 // DEF_CHOOSE_FORMAT(enum AVPixelFormat, pix_fmt, pix_fmts, AV_PIX_FMT_NONE,
177 //                   GET_PIX_FMT_NAME)
178
179 DEF_CHOOSE_FORMAT(enum AVSampleFormat, sample_fmt, sample_fmts,
180                   AV_SAMPLE_FMT_NONE, GET_SAMPLE_FMT_NAME)
181
182 DEF_CHOOSE_FORMAT(int, sample_rate, supported_samplerates, 0,
183                   GET_SAMPLE_RATE_NAME)
184
185 DEF_CHOOSE_FORMAT(uint64_t, channel_layout, channel_layouts, 0,
186                   GET_CH_LAYOUT_NAME)
187
188 FilterGraph *init_simple_filtergraph(InputStream *ist, OutputStream *ost)
189 {
190     FilterGraph *fg = av_mallocz(sizeof(*fg));
191
192     if (!fg)
193         exit_program(1);
194     fg->index = nb_filtergraphs;
195
196     GROW_ARRAY(fg->outputs, fg->nb_outputs);
197     if (!(fg->outputs[0] = av_mallocz(sizeof(*fg->outputs[0]))))
198         exit_program(1);
199     fg->outputs[0]->ost   = ost;
200     fg->outputs[0]->graph = fg;
201
202     ost->filter = fg->outputs[0];
203
204     GROW_ARRAY(fg->inputs, fg->nb_inputs);
205     if (!(fg->inputs[0] = av_mallocz(sizeof(*fg->inputs[0]))))
206         exit_program(1);
207     fg->inputs[0]->ist   = ist;
208     fg->inputs[0]->graph = fg;
209
210     GROW_ARRAY(ist->filters, ist->nb_filters);
211     ist->filters[ist->nb_filters - 1] = fg->inputs[0];
212
213     GROW_ARRAY(filtergraphs, nb_filtergraphs);
214     filtergraphs[nb_filtergraphs - 1] = fg;
215
216     return fg;
217 }
218
219 static void init_input_filter(FilterGraph *fg, AVFilterInOut *in)
220 {
221     InputStream *ist = NULL;
222     enum AVMediaType type = avfilter_pad_get_type(in->filter_ctx->input_pads, in->pad_idx);
223     int i;
224
225     // TODO: support other filter types
226     if (type != AVMEDIA_TYPE_VIDEO && type != AVMEDIA_TYPE_AUDIO) {
227         av_log(NULL, AV_LOG_FATAL, "Only video and audio filters supported "
228                "currently.\n");
229         exit_program(1);
230     }
231
232     if (in->name) {
233         AVFormatContext *s;
234         AVStream       *st = NULL;
235         char *p;
236         int file_idx = strtol(in->name, &p, 0);
237
238         if (file_idx < 0 || file_idx >= nb_input_files) {
239             av_log(NULL, AV_LOG_FATAL, "Invalid file index %d in filtergraph description %s.\n",
240                    file_idx, fg->graph_desc);
241             exit_program(1);
242         }
243         s = input_files[file_idx]->ctx;
244
245         for (i = 0; i < s->nb_streams; i++) {
246             enum AVMediaType stream_type = s->streams[i]->codec->codec_type;
247             if (stream_type != type &&
248                 !(stream_type == AVMEDIA_TYPE_SUBTITLE &&
249                   type == AVMEDIA_TYPE_VIDEO /* sub2video hack */))
250                 continue;
251             if (check_stream_specifier(s, s->streams[i], *p == ':' ? p + 1 : p) == 1) {
252                 st = s->streams[i];
253                 break;
254             }
255         }
256         if (!st) {
257             av_log(NULL, AV_LOG_FATAL, "Stream specifier '%s' in filtergraph description %s "
258                    "matches no streams.\n", p, fg->graph_desc);
259             exit_program(1);
260         }
261         ist = input_streams[input_files[file_idx]->ist_index + st->index];
262     } else {
263         /* find the first unused stream of corresponding type */
264         for (i = 0; i < nb_input_streams; i++) {
265             ist = input_streams[i];
266             if (ist->dec_ctx->codec_type == type && ist->discard)
267                 break;
268         }
269         if (i == nb_input_streams) {
270             av_log(NULL, AV_LOG_FATAL, "Cannot find a matching stream for "
271                    "unlabeled input pad %d on filter %s\n", in->pad_idx,
272                    in->filter_ctx->name);
273             exit_program(1);
274         }
275     }
276     av_assert0(ist);
277
278     ist->discard         = 0;
279     ist->decoding_needed |= DECODING_FOR_FILTER;
280     ist->st->discard = AVDISCARD_NONE;
281
282     GROW_ARRAY(fg->inputs, fg->nb_inputs);
283     if (!(fg->inputs[fg->nb_inputs - 1] = av_mallocz(sizeof(*fg->inputs[0]))))
284         exit_program(1);
285     fg->inputs[fg->nb_inputs - 1]->ist   = ist;
286     fg->inputs[fg->nb_inputs - 1]->graph = fg;
287
288     GROW_ARRAY(ist->filters, ist->nb_filters);
289     ist->filters[ist->nb_filters - 1] = fg->inputs[fg->nb_inputs - 1];
290 }
291
292 static int insert_trim(int64_t start_time, int64_t duration,
293                        AVFilterContext **last_filter, int *pad_idx,
294                        const char *filter_name)
295 {
296     AVFilterGraph *graph = (*last_filter)->graph;
297     AVFilterContext *ctx;
298     const AVFilter *trim;
299     enum AVMediaType type = avfilter_pad_get_type((*last_filter)->output_pads, *pad_idx);
300     const char *name = (type == AVMEDIA_TYPE_VIDEO) ? "trim" : "atrim";
301     int ret = 0;
302
303     if (duration == INT64_MAX && start_time == AV_NOPTS_VALUE)
304         return 0;
305
306     trim = avfilter_get_by_name(name);
307     if (!trim) {
308         av_log(NULL, AV_LOG_ERROR, "%s filter not present, cannot limit "
309                "recording time.\n", name);
310         return AVERROR_FILTER_NOT_FOUND;
311     }
312
313     ctx = avfilter_graph_alloc_filter(graph, trim, filter_name);
314     if (!ctx)
315         return AVERROR(ENOMEM);
316
317     if (duration != INT64_MAX) {
318         ret = av_opt_set_int(ctx, "durationi", duration,
319                                 AV_OPT_SEARCH_CHILDREN);
320     }
321     if (ret >= 0 && start_time != AV_NOPTS_VALUE) {
322         ret = av_opt_set_int(ctx, "starti", start_time,
323                                 AV_OPT_SEARCH_CHILDREN);
324     }
325     if (ret < 0) {
326         av_log(ctx, AV_LOG_ERROR, "Error configuring the %s filter", name);
327         return ret;
328     }
329
330     ret = avfilter_init_str(ctx, NULL);
331     if (ret < 0)
332         return ret;
333
334     ret = avfilter_link(*last_filter, *pad_idx, ctx, 0);
335     if (ret < 0)
336         return ret;
337
338     *last_filter = ctx;
339     *pad_idx     = 0;
340     return 0;
341 }
342
343 static int insert_filter(AVFilterContext **last_filter, int *pad_idx,
344                          const char *filter_name, const char *args)
345 {
346     AVFilterGraph *graph = (*last_filter)->graph;
347     AVFilterContext *ctx;
348     int ret;
349
350     ret = avfilter_graph_create_filter(&ctx,
351                                        avfilter_get_by_name(filter_name),
352                                        filter_name, args, NULL, graph);
353     if (ret < 0)
354         return ret;
355
356     ret = avfilter_link(*last_filter, *pad_idx, ctx, 0);
357     if (ret < 0)
358         return ret;
359
360     *last_filter = ctx;
361     *pad_idx     = 0;
362     return 0;
363 }
364
365 static int configure_output_video_filter(FilterGraph *fg, OutputFilter *ofilter, AVFilterInOut *out)
366 {
367     char *pix_fmts;
368     OutputStream *ost = ofilter->ost;
369     OutputFile    *of = output_files[ost->file_index];
370     AVCodecContext *codec = ost->enc_ctx;
371     AVFilterContext *last_filter = out->filter_ctx;
372     int pad_idx = out->pad_idx;
373     int ret;
374     char name[255];
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("buffersink"),
379                                        name, NULL, NULL, fg->graph);
380
381     if (ret < 0)
382         return ret;
383
384     if (codec->width || codec->height) {
385         char args[255];
386         AVFilterContext *filter;
387
388         snprintf(args, sizeof(args), "%d:%d:0x%X",
389                  codec->width,
390                  codec->height,
391                  (unsigned)ost->sws_flags);
392         snprintf(name, sizeof(name), "scaler for output stream %d:%d",
393                  ost->file_index, ost->index);
394         if ((ret = avfilter_graph_create_filter(&filter, avfilter_get_by_name("scale"),
395                                                 name, args, NULL, fg->graph)) < 0)
396             return ret;
397         if ((ret = avfilter_link(last_filter, pad_idx, filter, 0)) < 0)
398             return ret;
399
400         last_filter = filter;
401         pad_idx = 0;
402     }
403
404     if ((pix_fmts = choose_pix_fmts(ost))) {
405         AVFilterContext *filter;
406         snprintf(name, sizeof(name), "pixel format for output stream %d:%d",
407                  ost->file_index, ost->index);
408         ret = avfilter_graph_create_filter(&filter,
409                                            avfilter_get_by_name("format"),
410                                            "format", pix_fmts, NULL, fg->graph);
411         av_freep(&pix_fmts);
412         if (ret < 0)
413             return ret;
414         if ((ret = avfilter_link(last_filter, pad_idx, filter, 0)) < 0)
415             return ret;
416
417         last_filter = filter;
418         pad_idx     = 0;
419     }
420
421     if (ost->frame_rate.num && 0) {
422         AVFilterContext *fps;
423         char args[255];
424
425         snprintf(args, sizeof(args), "fps=%d/%d", ost->frame_rate.num,
426                  ost->frame_rate.den);
427         snprintf(name, sizeof(name), "fps for output stream %d:%d",
428                  ost->file_index, ost->index);
429         ret = avfilter_graph_create_filter(&fps, avfilter_get_by_name("fps"),
430                                            name, args, NULL, fg->graph);
431         if (ret < 0)
432             return ret;
433
434         ret = avfilter_link(last_filter, pad_idx, fps, 0);
435         if (ret < 0)
436             return ret;
437         last_filter = fps;
438         pad_idx = 0;
439     }
440
441     snprintf(name, sizeof(name), "trim for output stream %d:%d",
442              ost->file_index, ost->index);
443     ret = insert_trim(of->start_time, of->recording_time,
444                       &last_filter, &pad_idx, name);
445     if (ret < 0)
446         return ret;
447
448
449     if ((ret = avfilter_link(last_filter, pad_idx, ofilter->filter, 0)) < 0)
450         return ret;
451
452     return 0;
453 }
454
455 static int configure_output_audio_filter(FilterGraph *fg, OutputFilter *ofilter, AVFilterInOut *out)
456 {
457     OutputStream *ost = ofilter->ost;
458     OutputFile    *of = output_files[ost->file_index];
459     AVCodecContext *codec  = ost->enc_ctx;
460     AVFilterContext *last_filter = out->filter_ctx;
461     int pad_idx = out->pad_idx;
462     char *sample_fmts, *sample_rates, *channel_layouts;
463     char name[255];
464     int ret;
465
466     snprintf(name, sizeof(name), "output stream %d:%d", ost->file_index, ost->index);
467     ret = avfilter_graph_create_filter(&ofilter->filter,
468                                        avfilter_get_by_name("abuffersink"),
469                                        name, NULL, NULL, fg->graph);
470     if (ret < 0)
471         return ret;
472     if ((ret = av_opt_set_int(ofilter->filter, "all_channel_counts", 1, AV_OPT_SEARCH_CHILDREN)) < 0)
473         return ret;
474
475 #define AUTO_INSERT_FILTER(opt_name, filter_name, arg) do {                 \
476     AVFilterContext *filt_ctx;                                              \
477                                                                             \
478     av_log(NULL, AV_LOG_INFO, opt_name " is forwarded to lavfi "            \
479            "similarly to -af " filter_name "=%s.\n", arg);                  \
480                                                                             \
481     ret = avfilter_graph_create_filter(&filt_ctx,                           \
482                                        avfilter_get_by_name(filter_name),   \
483                                        filter_name, arg, NULL, fg->graph);  \
484     if (ret < 0)                                                            \
485         return ret;                                                         \
486                                                                             \
487     ret = avfilter_link(last_filter, pad_idx, filt_ctx, 0);                 \
488     if (ret < 0)                                                            \
489         return ret;                                                         \
490                                                                             \
491     last_filter = filt_ctx;                                                 \
492     pad_idx = 0;                                                            \
493 } while (0)
494     if (ost->audio_channels_mapped) {
495         int i;
496         AVBPrint pan_buf;
497         av_bprint_init(&pan_buf, 256, 8192);
498         av_bprintf(&pan_buf, "0x%"PRIx64,
499                    av_get_default_channel_layout(ost->audio_channels_mapped));
500         for (i = 0; i < ost->audio_channels_mapped; i++)
501             if (ost->audio_channels_map[i] != -1)
502                 av_bprintf(&pan_buf, ":c%d=c%d", i, ost->audio_channels_map[i]);
503
504         AUTO_INSERT_FILTER("-map_channel", "pan", pan_buf.str);
505         av_bprint_finalize(&pan_buf, NULL);
506     }
507
508     if (codec->channels && !codec->channel_layout)
509         codec->channel_layout = av_get_default_channel_layout(codec->channels);
510
511     sample_fmts     = choose_sample_fmts(ost);
512     sample_rates    = choose_sample_rates(ost);
513     channel_layouts = choose_channel_layouts(ost);
514     if (sample_fmts || sample_rates || channel_layouts) {
515         AVFilterContext *format;
516         char args[256];
517         args[0] = 0;
518
519         if (sample_fmts)
520             av_strlcatf(args, sizeof(args), "sample_fmts=%s:",
521                             sample_fmts);
522         if (sample_rates)
523             av_strlcatf(args, sizeof(args), "sample_rates=%s:",
524                             sample_rates);
525         if (channel_layouts)
526             av_strlcatf(args, sizeof(args), "channel_layouts=%s:",
527                             channel_layouts);
528
529         av_freep(&sample_fmts);
530         av_freep(&sample_rates);
531         av_freep(&channel_layouts);
532
533         snprintf(name, sizeof(name), "audio format for output stream %d:%d",
534                  ost->file_index, ost->index);
535         ret = avfilter_graph_create_filter(&format,
536                                            avfilter_get_by_name("aformat"),
537                                            name, args, NULL, fg->graph);
538         if (ret < 0)
539             return ret;
540
541         ret = avfilter_link(last_filter, pad_idx, format, 0);
542         if (ret < 0)
543             return ret;
544
545         last_filter = format;
546         pad_idx = 0;
547     }
548
549     if (audio_volume != 256 && 0) {
550         char args[256];
551
552         snprintf(args, sizeof(args), "%f", audio_volume / 256.);
553         AUTO_INSERT_FILTER("-vol", "volume", args);
554     }
555
556     if (ost->apad && of->shortest) {
557         char args[256];
558         int i;
559
560         for (i=0; i<of->ctx->nb_streams; i++)
561             if (of->ctx->streams[i]->codec->codec_type == AVMEDIA_TYPE_VIDEO)
562                 break;
563
564         if (i<of->ctx->nb_streams) {
565             snprintf(args, sizeof(args), "%s", ost->apad);
566             AUTO_INSERT_FILTER("-apad", "apad", args);
567         }
568     }
569
570     snprintf(name, sizeof(name), "trim for output stream %d:%d",
571              ost->file_index, ost->index);
572     ret = insert_trim(of->start_time, of->recording_time,
573                       &last_filter, &pad_idx, name);
574     if (ret < 0)
575         return ret;
576
577     if ((ret = avfilter_link(last_filter, pad_idx, ofilter->filter, 0)) < 0)
578         return ret;
579
580     return 0;
581 }
582
583 #define DESCRIBE_FILTER_LINK(f, inout, in)                         \
584 {                                                                  \
585     AVFilterContext *ctx = inout->filter_ctx;                      \
586     AVFilterPad *pads = in ? ctx->input_pads  : ctx->output_pads;  \
587     int       nb_pads = in ? ctx->nb_inputs   : ctx->nb_outputs;   \
588     AVIOContext *pb;                                               \
589                                                                    \
590     if (avio_open_dyn_buf(&pb) < 0)                                \
591         exit_program(1);                                           \
592                                                                    \
593     avio_printf(pb, "%s", ctx->filter->name);                      \
594     if (nb_pads > 1)                                               \
595         avio_printf(pb, ":%s", avfilter_pad_get_name(pads, inout->pad_idx));\
596     avio_w8(pb, 0);                                                \
597     avio_close_dyn_buf(pb, &f->name);                              \
598 }
599
600 int configure_output_filter(FilterGraph *fg, OutputFilter *ofilter, AVFilterInOut *out)
601 {
602     av_freep(&ofilter->name);
603     DESCRIBE_FILTER_LINK(ofilter, out, 0);
604
605     switch (avfilter_pad_get_type(out->filter_ctx->output_pads, out->pad_idx)) {
606     case AVMEDIA_TYPE_VIDEO: return configure_output_video_filter(fg, ofilter, out);
607     case AVMEDIA_TYPE_AUDIO: return configure_output_audio_filter(fg, ofilter, out);
608     default: av_assert0(0);
609     }
610 }
611
612 static int sub2video_prepare(InputStream *ist)
613 {
614     AVFormatContext *avf = input_files[ist->file_index]->ctx;
615     int i, w, h;
616
617     /* Compute the size of the canvas for the subtitles stream.
618        If the subtitles codec has set a size, use it. Otherwise use the
619        maximum dimensions of the video streams in the same file. */
620     w = ist->dec_ctx->width;
621     h = ist->dec_ctx->height;
622     if (!(w && h)) {
623         for (i = 0; i < avf->nb_streams; i++) {
624             if (avf->streams[i]->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
625                 w = FFMAX(w, avf->streams[i]->codec->width);
626                 h = FFMAX(h, avf->streams[i]->codec->height);
627             }
628         }
629         if (!(w && h)) {
630             w = FFMAX(w, 720);
631             h = FFMAX(h, 576);
632         }
633         av_log(avf, AV_LOG_INFO, "sub2video: using %dx%d canvas\n", w, h);
634     }
635     ist->sub2video.w = ist->dec_ctx->width  = ist->resample_width  = w;
636     ist->sub2video.h = ist->dec_ctx->height = ist->resample_height = h;
637
638     /* rectangles are AV_PIX_FMT_PAL8, but we have no guarantee that the
639        palettes for all rectangles are identical or compatible */
640     ist->resample_pix_fmt = ist->dec_ctx->pix_fmt = AV_PIX_FMT_RGB32;
641
642     ist->sub2video.frame = av_frame_alloc();
643     if (!ist->sub2video.frame)
644         return AVERROR(ENOMEM);
645     ist->sub2video.last_pts = INT64_MIN;
646     return 0;
647 }
648
649 static int configure_input_video_filter(FilterGraph *fg, InputFilter *ifilter,
650                                         AVFilterInOut *in)
651 {
652     AVFilterContext *last_filter;
653     const AVFilter *buffer_filt = avfilter_get_by_name("buffer");
654     InputStream *ist = ifilter->ist;
655     InputFile     *f = input_files[ist->file_index];
656     AVRational tb = ist->framerate.num ? av_inv_q(ist->framerate) :
657                                          ist->st->time_base;
658     AVRational fr = ist->framerate;
659     AVRational sar;
660     AVBPrint args;
661     char name[255];
662     int ret, pad_idx = 0;
663     int64_t tsoffset = 0;
664
665     if (ist->dec_ctx->codec_type == AVMEDIA_TYPE_AUDIO) {
666         av_log(NULL, AV_LOG_ERROR, "Cannot connect video filter to audio input\n");
667         return AVERROR(EINVAL);
668     }
669
670     if (!fr.num)
671         fr = av_guess_frame_rate(input_files[ist->file_index]->ctx, ist->st, NULL);
672
673     if (ist->dec_ctx->codec_type == AVMEDIA_TYPE_SUBTITLE) {
674         ret = sub2video_prepare(ist);
675         if (ret < 0)
676             return ret;
677     }
678
679     sar = ist->st->sample_aspect_ratio.num ?
680           ist->st->sample_aspect_ratio :
681           ist->dec_ctx->sample_aspect_ratio;
682     if(!sar.den)
683         sar = (AVRational){0,1};
684     av_bprint_init(&args, 0, 1);
685     av_bprintf(&args,
686              "video_size=%dx%d:pix_fmt=%d:time_base=%d/%d:"
687              "pixel_aspect=%d/%d:sws_param=flags=%d", ist->resample_width,
688              ist->resample_height,
689              ist->hwaccel_retrieve_data ? ist->hwaccel_retrieved_pix_fmt : ist->resample_pix_fmt,
690              tb.num, tb.den, sar.num, sar.den,
691              SWS_BILINEAR + ((ist->dec_ctx->flags&CODEC_FLAG_BITEXACT) ? SWS_BITEXACT:0));
692     if (fr.num && fr.den)
693         av_bprintf(&args, ":frame_rate=%d/%d", fr.num, fr.den);
694     snprintf(name, sizeof(name), "graph %d input from stream %d:%d", fg->index,
695              ist->file_index, ist->st->index);
696
697     if ((ret = avfilter_graph_create_filter(&ifilter->filter, buffer_filt, name,
698                                             args.str, NULL, fg->graph)) < 0)
699         return ret;
700     last_filter = ifilter->filter;
701
702     if (ist->autorotate) {
703         uint8_t* displaymatrix = av_stream_get_side_data(ist->st,
704                                                          AV_PKT_DATA_DISPLAYMATRIX, NULL);
705         if (displaymatrix) {
706             double rot = av_display_rotation_get((int32_t*) displaymatrix);
707             if (rot < -135 || rot > 135) {
708                 ret = insert_filter(&last_filter, &pad_idx, "vflip", NULL);
709                 if (ret < 0)
710                     return ret;
711                 ret = insert_filter(&last_filter, &pad_idx, "hflip", NULL);
712             } else if (rot < -45) {
713                 ret = insert_filter(&last_filter, &pad_idx, "transpose", "dir=clock");
714             } else if (rot > 45) {
715                 ret = insert_filter(&last_filter, &pad_idx, "transpose", "dir=cclock");
716             }
717             if (ret < 0)
718                 return ret;
719         }
720     }
721
722     if (ist->framerate.num) {
723         AVFilterContext *setpts;
724
725         snprintf(name, sizeof(name), "force CFR for input from stream %d:%d",
726                  ist->file_index, ist->st->index);
727         if ((ret = avfilter_graph_create_filter(&setpts,
728                                                 avfilter_get_by_name("setpts"),
729                                                 name, "N", NULL,
730                                                 fg->graph)) < 0)
731             return ret;
732
733         if ((ret = avfilter_link(last_filter, 0, setpts, 0)) < 0)
734             return ret;
735
736         last_filter = setpts;
737     }
738
739     if (do_deinterlace) {
740         AVFilterContext *yadif;
741
742         snprintf(name, sizeof(name), "deinterlace input from stream %d:%d",
743                  ist->file_index, ist->st->index);
744         if ((ret = avfilter_graph_create_filter(&yadif,
745                                                 avfilter_get_by_name("yadif"),
746                                                 name, "", NULL,
747                                                 fg->graph)) < 0)
748             return ret;
749
750         if ((ret = avfilter_link(last_filter, 0, yadif, 0)) < 0)
751             return ret;
752
753         last_filter = yadif;
754     }
755
756     snprintf(name, sizeof(name), "trim for input stream %d:%d",
757              ist->file_index, ist->st->index);
758     if (copy_ts) {
759         tsoffset = f->start_time == AV_NOPTS_VALUE ? 0 : f->start_time;
760         if (!start_at_zero && f->ctx->start_time != AV_NOPTS_VALUE)
761             tsoffset += f->ctx->start_time;
762     }
763     ret = insert_trim(((f->start_time == AV_NOPTS_VALUE) || !f->accurate_seek) ?
764                       AV_NOPTS_VALUE : tsoffset, f->recording_time,
765                       &last_filter, &pad_idx, name);
766     if (ret < 0)
767         return ret;
768
769     if ((ret = avfilter_link(last_filter, 0, in->filter_ctx, in->pad_idx)) < 0)
770         return ret;
771     return 0;
772 }
773
774 static int configure_input_audio_filter(FilterGraph *fg, InputFilter *ifilter,
775                                         AVFilterInOut *in)
776 {
777     AVFilterContext *last_filter;
778     const AVFilter *abuffer_filt = avfilter_get_by_name("abuffer");
779     InputStream *ist = ifilter->ist;
780     InputFile     *f = input_files[ist->file_index];
781     AVBPrint args;
782     char name[255];
783     int ret, pad_idx = 0;
784     int64_t tsoffset = 0;
785
786     if (ist->dec_ctx->codec_type != AVMEDIA_TYPE_AUDIO) {
787         av_log(NULL, AV_LOG_ERROR, "Cannot connect audio filter to non audio input\n");
788         return AVERROR(EINVAL);
789     }
790
791     av_bprint_init(&args, 0, AV_BPRINT_SIZE_AUTOMATIC);
792     av_bprintf(&args, "time_base=%d/%d:sample_rate=%d:sample_fmt=%s",
793              1, ist->dec_ctx->sample_rate,
794              ist->dec_ctx->sample_rate,
795              av_get_sample_fmt_name(ist->dec_ctx->sample_fmt));
796     if (ist->dec_ctx->channel_layout)
797         av_bprintf(&args, ":channel_layout=0x%"PRIx64,
798                    ist->dec_ctx->channel_layout);
799     else
800         av_bprintf(&args, ":channels=%d", ist->dec_ctx->channels);
801     snprintf(name, sizeof(name), "graph %d input from stream %d:%d", fg->index,
802              ist->file_index, ist->st->index);
803
804     if ((ret = avfilter_graph_create_filter(&ifilter->filter, abuffer_filt,
805                                             name, args.str, NULL,
806                                             fg->graph)) < 0)
807         return ret;
808     last_filter = ifilter->filter;
809
810 #define AUTO_INSERT_FILTER_INPUT(opt_name, filter_name, arg) do {                 \
811     AVFilterContext *filt_ctx;                                              \
812                                                                             \
813     av_log(NULL, AV_LOG_INFO, opt_name " is forwarded to lavfi "            \
814            "similarly to -af " filter_name "=%s.\n", arg);                  \
815                                                                             \
816     snprintf(name, sizeof(name), "graph %d %s for input stream %d:%d",      \
817                 fg->index, filter_name, ist->file_index, ist->st->index);   \
818     ret = avfilter_graph_create_filter(&filt_ctx,                           \
819                                        avfilter_get_by_name(filter_name),   \
820                                        name, arg, NULL, fg->graph);         \
821     if (ret < 0)                                                            \
822         return ret;                                                         \
823                                                                             \
824     ret = avfilter_link(last_filter, 0, filt_ctx, 0);                       \
825     if (ret < 0)                                                            \
826         return ret;                                                         \
827                                                                             \
828     last_filter = filt_ctx;                                                 \
829 } while (0)
830
831     if (audio_sync_method > 0) {
832         char args[256] = {0};
833
834         av_strlcatf(args, sizeof(args), "async=%d", audio_sync_method);
835         if (audio_drift_threshold != 0.1)
836             av_strlcatf(args, sizeof(args), ":min_hard_comp=%f", audio_drift_threshold);
837         if (!fg->reconfiguration)
838             av_strlcatf(args, sizeof(args), ":first_pts=0");
839         AUTO_INSERT_FILTER_INPUT("-async", "aresample", args);
840     }
841
842 //     if (ost->audio_channels_mapped) {
843 //         int i;
844 //         AVBPrint pan_buf;
845 //         av_bprint_init(&pan_buf, 256, 8192);
846 //         av_bprintf(&pan_buf, "0x%"PRIx64,
847 //                    av_get_default_channel_layout(ost->audio_channels_mapped));
848 //         for (i = 0; i < ost->audio_channels_mapped; i++)
849 //             if (ost->audio_channels_map[i] != -1)
850 //                 av_bprintf(&pan_buf, ":c%d=c%d", i, ost->audio_channels_map[i]);
851 //         AUTO_INSERT_FILTER_INPUT("-map_channel", "pan", pan_buf.str);
852 //         av_bprint_finalize(&pan_buf, NULL);
853 //     }
854
855     if (audio_volume != 256) {
856         char args[256];
857
858         av_log(NULL, AV_LOG_WARNING, "-vol has been deprecated. Use the volume "
859                "audio filter instead.\n");
860
861         snprintf(args, sizeof(args), "%f", audio_volume / 256.);
862         AUTO_INSERT_FILTER_INPUT("-vol", "volume", args);
863     }
864
865     snprintf(name, sizeof(name), "trim for input stream %d:%d",
866              ist->file_index, ist->st->index);
867     if (copy_ts) {
868         tsoffset = f->start_time == AV_NOPTS_VALUE ? 0 : f->start_time;
869         if (!start_at_zero && f->ctx->start_time != AV_NOPTS_VALUE)
870             tsoffset += f->ctx->start_time;
871     }
872     ret = insert_trim(((f->start_time == AV_NOPTS_VALUE) || !f->accurate_seek) ?
873                       AV_NOPTS_VALUE : tsoffset, f->recording_time,
874                       &last_filter, &pad_idx, name);
875     if (ret < 0)
876         return ret;
877
878     if ((ret = avfilter_link(last_filter, 0, in->filter_ctx, in->pad_idx)) < 0)
879         return ret;
880
881     return 0;
882 }
883
884 static int configure_input_filter(FilterGraph *fg, InputFilter *ifilter,
885                                   AVFilterInOut *in)
886 {
887     av_freep(&ifilter->name);
888     DESCRIBE_FILTER_LINK(ifilter, in, 1);
889
890     if (!ifilter->ist->dec) {
891         av_log(NULL, AV_LOG_ERROR,
892                "No decoder for stream #%d:%d, filtering impossible\n",
893                ifilter->ist->file_index, ifilter->ist->st->index);
894         return AVERROR_DECODER_NOT_FOUND;
895     }
896     switch (avfilter_pad_get_type(in->filter_ctx->input_pads, in->pad_idx)) {
897     case AVMEDIA_TYPE_VIDEO: return configure_input_video_filter(fg, ifilter, in);
898     case AVMEDIA_TYPE_AUDIO: return configure_input_audio_filter(fg, ifilter, in);
899     default: av_assert0(0);
900     }
901 }
902
903 int configure_filtergraph(FilterGraph *fg)
904 {
905     AVFilterInOut *inputs, *outputs, *cur;
906     int ret, i, init = !fg->graph, simple = !fg->graph_desc;
907     const char *graph_desc = simple ? fg->outputs[0]->ost->avfilter :
908                                       fg->graph_desc;
909
910     avfilter_graph_free(&fg->graph);
911     if (!(fg->graph = avfilter_graph_alloc()))
912         return AVERROR(ENOMEM);
913
914     if (simple) {
915         OutputStream *ost = fg->outputs[0]->ost;
916         char args[512];
917         AVDictionaryEntry *e = NULL;
918
919         snprintf(args, sizeof(args), "flags=0x%X", (unsigned)ost->sws_flags);
920         fg->graph->scale_sws_opts = av_strdup(args);
921
922         args[0] = 0;
923         while ((e = av_dict_get(ost->swr_opts, "", e,
924                                 AV_DICT_IGNORE_SUFFIX))) {
925             av_strlcatf(args, sizeof(args), "%s=%s:", e->key, e->value);
926         }
927         if (strlen(args))
928             args[strlen(args)-1] = 0;
929         av_opt_set(fg->graph, "aresample_swr_opts", args, 0);
930
931         args[0] = '\0';
932         while ((e = av_dict_get(fg->outputs[0]->ost->resample_opts, "", e,
933                                 AV_DICT_IGNORE_SUFFIX))) {
934             av_strlcatf(args, sizeof(args), "%s=%s:", e->key, e->value);
935         }
936         if (strlen(args))
937             args[strlen(args) - 1] = '\0';
938         fg->graph->resample_lavr_opts = av_strdup(args);
939
940         e = av_dict_get(ost->encoder_opts, "threads", NULL, 0);
941         if (e)
942             av_opt_set(fg->graph, "threads", e->value, 0);
943     }
944
945     if ((ret = avfilter_graph_parse2(fg->graph, graph_desc, &inputs, &outputs)) < 0)
946         return ret;
947
948     if (simple && (!inputs || inputs->next || !outputs || outputs->next)) {
949         av_log(NULL, AV_LOG_ERROR, "Simple filtergraph '%s' does not have "
950                "exactly one input and output.\n", graph_desc);
951         return AVERROR(EINVAL);
952     }
953
954     for (cur = inputs; !simple && init && cur; cur = cur->next)
955         init_input_filter(fg, cur);
956
957     for (cur = inputs, i = 0; cur; cur = cur->next, i++)
958         if ((ret = configure_input_filter(fg, fg->inputs[i], cur)) < 0) {
959             avfilter_inout_free(&inputs);
960             avfilter_inout_free(&outputs);
961             return ret;
962         }
963     avfilter_inout_free(&inputs);
964
965     if (!init || simple) {
966         /* we already know the mappings between lavfi outputs and output streams,
967          * so we can finish the setup */
968         for (cur = outputs, i = 0; cur; cur = cur->next, i++)
969             configure_output_filter(fg, fg->outputs[i], cur);
970         avfilter_inout_free(&outputs);
971
972         if ((ret = avfilter_graph_config(fg->graph, NULL)) < 0)
973             return ret;
974     } else {
975         /* wait until output mappings are processed */
976         for (cur = outputs; cur;) {
977             GROW_ARRAY(fg->outputs, fg->nb_outputs);
978             if (!(fg->outputs[fg->nb_outputs - 1] = av_mallocz(sizeof(*fg->outputs[0]))))
979                 exit_program(1);
980             fg->outputs[fg->nb_outputs - 1]->graph   = fg;
981             fg->outputs[fg->nb_outputs - 1]->out_tmp = cur;
982             cur = cur->next;
983             fg->outputs[fg->nb_outputs - 1]->out_tmp->next = NULL;
984         }
985     }
986
987     fg->reconfiguration = 1;
988
989     for (i = 0; i < fg->nb_outputs; i++) {
990         OutputStream *ost = fg->outputs[i]->ost;
991         if (ost &&
992             ost->enc->type == AVMEDIA_TYPE_AUDIO &&
993             !(ost->enc->capabilities & CODEC_CAP_VARIABLE_FRAME_SIZE))
994             av_buffersink_set_frame_size(ost->filter->filter,
995                                          ost->enc_ctx->frame_size);
996     }
997
998     return 0;
999 }
1000
1001 int ist_in_filtergraph(FilterGraph *fg, InputStream *ist)
1002 {
1003     int i;
1004     for (i = 0; i < fg->nb_inputs; i++)
1005         if (fg->inputs[i]->ist == ist)
1006             return 1;
1007     return 0;
1008 }
1009