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