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