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