mov: enable parsing for VC-1.
[libav.git] / avconv.c
CommitLineData
6291d7e4
AK
1/*
2 * avconv main
3 * Copyright (c) 2000-2011 The libav developers.
4 *
5 * This file is part of Libav.
6 *
7 * Libav is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU Lesser General Public
9 * License as published by the Free Software Foundation; either
10 * version 2.1 of the License, or (at your option) any later version.
11 *
12 * Libav is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 * Lesser General Public License for more details.
16 *
17 * You should have received a copy of the GNU Lesser General Public
18 * License along with Libav; if not, write to the Free Software
19 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20 */
21
22#include "config.h"
23#include <ctype.h>
24#include <string.h>
25#include <math.h>
26#include <stdlib.h>
27#include <errno.h>
28#include <signal.h>
29#include <limits.h>
30#include <unistd.h>
31#include "libavformat/avformat.h"
32#include "libavdevice/avdevice.h"
33#include "libswscale/swscale.h"
bcb82fe1 34#include "libavresample/avresample.h"
6291d7e4 35#include "libavutil/opt.h"
6291d7e4
AK
36#include "libavutil/audioconvert.h"
37#include "libavutil/parseutils.h"
38#include "libavutil/samplefmt.h"
39#include "libavutil/colorspace.h"
40#include "libavutil/fifo.h"
41#include "libavutil/intreadwrite.h"
42#include "libavutil/dict.h"
43#include "libavutil/mathematics.h"
44#include "libavutil/pixdesc.h"
45#include "libavutil/avstring.h"
46#include "libavutil/libm.h"
64dca32c 47#include "libavutil/imgutils.h"
6291d7e4
AK
48#include "libavformat/os_support.h"
49
6291d7e4
AK
50# include "libavfilter/avfilter.h"
51# include "libavfilter/avfiltergraph.h"
04a14d4d 52# include "libavfilter/buffersrc.h"
ac712309 53# include "libavfilter/buffersink.h"
6291d7e4 54# include "libavfilter/vsrc_buffer.h"
6291d7e4
AK
55
56#if HAVE_SYS_RESOURCE_H
57#include <sys/types.h>
58#include <sys/time.h>
59#include <sys/resource.h>
60#elif HAVE_GETPROCESSTIMES
61#include <windows.h>
62#endif
63#if HAVE_GETPROCESSMEMORYINFO
64#include <windows.h>
65#include <psapi.h>
66#endif
67
68#if HAVE_SYS_SELECT_H
69#include <sys/select.h>
70#endif
71
72#include <time.h>
73
74#include "cmdutils.h"
75
76#include "libavutil/avassert.h"
77
e8c04f62
AK
78#define VSYNC_AUTO -1
79#define VSYNC_PASSTHROUGH 0
80#define VSYNC_CFR 1
81#define VSYNC_VFR 2
82
6291d7e4
AK
83const char program_name[] = "avconv";
84const int program_birth_year = 2000;
85
86/* select an input stream for an output stream */
87typedef struct StreamMap {
8d2e4a7e 88 int disabled; /** 1 is this mapping is disabled by a negative map */
6291d7e4
AK
89 int file_index;
90 int stream_index;
91 int sync_file_index;
92 int sync_stream_index;
3b266da3 93 char *linklabel; /** name of an output link, for mapping lavfi outputs */
6291d7e4
AK
94} StreamMap;
95
96/**
97 * select an input file for an output file
98 */
99typedef struct MetadataMap {
02494787
DB
100 int file; ///< file index
101 char type; ///< type of metadata to copy -- (g)lobal, (s)tream, (c)hapter or (p)rogram
102 int index; ///< stream/chapter/program number
6291d7e4
AK
103} MetadataMap;
104
6291d7e4
AK
105static const OptionDef options[];
106
6291d7e4 107static int video_discard = 0;
f4ad238c 108static int same_quant = 0;
6291d7e4 109static int do_deinterlace = 0;
6291d7e4 110static int intra_dc_precision = 8;
6291d7e4 111static int qp_hist = 0;
6291d7e4 112
6291d7e4 113static int file_overwrite = 0;
6291d7e4
AK
114static int do_benchmark = 0;
115static int do_hex_dump = 0;
116static int do_pkt_dump = 0;
6291d7e4
AK
117static int do_pass = 0;
118static char *pass_logfilename_prefix = NULL;
e8c04f62 119static int video_sync_method = VSYNC_AUTO;
7636c8c6
AD
120static int audio_sync_method = 0;
121static float audio_drift_threshold = 0.1;
122static int copy_ts = 0;
7bb3e625 123static int copy_tb = 1;
6291d7e4
AK
124static int opt_shortest = 0;
125static char *vstats_filename;
126static FILE *vstats_file;
6291d7e4 127
6291d7e4
AK
128static int audio_volume = 256;
129
130static int exit_on_error = 0;
131static int using_stdin = 0;
6291d7e4
AK
132static int64_t video_size = 0;
133static int64_t audio_size = 0;
134static int64_t extra_size = 0;
135static int nb_frames_dup = 0;
136static int nb_frames_drop = 0;
137static int input_sync;
6291d7e4
AK
138
139static float dts_delta_threshold = 10;
140
3460dd8a
AK
141static int print_stats = 1;
142
6291d7e4
AK
143#define DEFAULT_PASS_LOGFILENAME_PREFIX "av2pass"
144
560f7774
AK
145typedef struct InputFilter {
146 AVFilterContext *filter;
147 struct InputStream *ist;
148 struct FilterGraph *graph;
149} InputFilter;
150
151typedef struct OutputFilter {
152 AVFilterContext *filter;
153 struct OutputStream *ost;
154 struct FilterGraph *graph;
3b266da3
AK
155
156 /* temporary storage until stream maps are processed */
157 AVFilterInOut *out_tmp;
560f7774
AK
158} OutputFilter;
159
160typedef struct FilterGraph {
3b266da3
AK
161 int index;
162 const char *graph_desc;
163
560f7774
AK
164 AVFilterGraph *graph;
165
166 InputFilter **inputs;
167 int nb_inputs;
168 OutputFilter **outputs;
169 int nb_outputs;
170} FilterGraph;
171
64dca32c
AK
172typedef struct FrameBuffer {
173 uint8_t *base[4];
174 uint8_t *data[4];
175 int linesize[4];
176
177 int h, w;
178 enum PixelFormat pix_fmt;
179
180 int refcount;
181 struct InputStream *ist;
182 struct FrameBuffer *next;
183} FrameBuffer;
184
6494c001
AK
185typedef struct InputStream {
186 int file_index;
187 AVStream *st;
188 int discard; /* true if stream data should be discarded */
189 int decoding_needed; /* true if the packets must be decoded in 'raw_fifo' */
190 AVCodec *dec;
9179f27c 191 AVFrame *decoded_frame;
6494c001
AK
192
193 int64_t start; /* time when read started */
3101bb66
AK
194 /* predicted dts of the next packet read for this stream or (when there are
195 * several frames in a packet) of the next frame in current packet */
196 int64_t next_dts;
23576b3f
AK
197 /* dts of the last packet read for this stream */
198 int64_t last_dts;
6494c001
AK
199 PtsCorrectionContext pts_ctx;
200 double ts_scale;
201 int is_start; /* is 1 at the start and after a discontinuity */
202 int showed_multi_packet_warning;
203 AVDictionary *opts;
64dca32c 204
e77c8662
AK
205 int resample_height;
206 int resample_width;
207 int resample_pix_fmt;
208
369cb092
AK
209 int resample_sample_fmt;
210 int resample_sample_rate;
211 int resample_channels;
212 uint64_t resample_channel_layout;
213
64dca32c
AK
214 /* a pool of free buffers for decoded data */
215 FrameBuffer *buffer_pool;
560f7774
AK
216
217 /* decoded data from this stream goes into all those filters
0ad26cdf 218 * currently video and audio only */
560f7774
AK
219 InputFilter **filters;
220 int nb_filters;
6494c001
AK
221} InputStream;
222
223typedef struct InputFile {
224 AVFormatContext *ctx;
225 int eof_reached; /* true if eof reached */
226 int ist_index; /* index of first stream in ist_table */
227 int buffer_size; /* current total buffer size */
228 int64_t ts_offset;
ed5b1326
AK
229 int nb_streams; /* number of stream that avconv is aware of; may be different
230 from ctx.nb_streams if new streams appear during av_read_frame() */
f4805328 231 int rate_emu;
6494c001 232} InputFile;
6291d7e4
AK
233
234typedef struct OutputStream {
235 int file_index; /* file index */
236 int index; /* stream index in the output file */
237 int source_index; /* InputStream index */
238 AVStream *st; /* stream in the output file */
239 int encoding_needed; /* true if encoding needed for this stream */
240 int frame_number;
241 /* input pts and corresponding output pts
242 for A/V sync */
7636c8c6 243 // double sync_ipts; /* dts from the AVPacket of the demuxer in second units */
6291d7e4 244 struct InputStream *sync_ist; /* input stream to sync against */
7636c8c6 245 int64_t sync_opts; /* output frame counter, could be changed to some true timestamp */ // FIXME look at frame_number
1270e12e
AK
246 /* pts of the first frame encoded for this stream, used for limiting
247 * recording time */
248 int64_t first_pts;
6291d7e4
AK
249 AVBitStreamFilterContext *bitstream_filters;
250 AVCodec *enc;
96139b5e 251 int64_t max_frames;
836ce905 252 AVFrame *filtered_frame;
6291d7e4
AK
253
254 /* video only */
6291d7e4 255 AVRational frame_rate;
bef737a7 256 int force_fps;
828e0bcb 257 int top_field_first;
6291d7e4
AK
258
259 float frame_aspect_ratio;
560f7774 260 float last_quality;
6291d7e4
AK
261
262 /* forced key frames */
263 int64_t *forced_kf_pts;
264 int forced_kf_count;
265 int forced_kf_index;
266
6291d7e4
AK
267 FILE *logfile;
268
560f7774 269 OutputFilter *filter;
6291d7e4 270 char *avfilter;
6291d7e4 271
f8c314c8
AK
272 int64_t sws_flags;
273 AVDictionary *opts;
274 int is_past_recording_time;
275 int stream_copy;
276 const char *attachment_filename;
277 int copy_initial_nonkeyframes;
b7327887
AK
278
279 enum PixelFormat pix_fmts[2];
6291d7e4
AK
280} OutputStream;
281
6291d7e4 282
af70aa45
AK
283typedef struct OutputFile {
284 AVFormatContext *ctx;
285 AVDictionary *opts;
4288e031 286 int ost_index; /* index of the first stream in output_streams */
ef44a607 287 int64_t recording_time; /* desired length of the resulting file in microseconds */
ea065176 288 int64_t start_time; /* start time in microseconds */
f21f294e 289 uint64_t limit_filesize;
af70aa45
AK
290} OutputFile;
291
2e215267
AK
292static InputStream **input_streams = NULL;
293static int nb_input_streams = 0;
294static InputFile **input_files = NULL;
295static int nb_input_files = 0;
6291d7e4 296
2e215267
AK
297static OutputStream **output_streams = NULL;
298static int nb_output_streams = 0;
299static OutputFile **output_files = NULL;
300static int nb_output_files = 0;
af70aa45 301
560f7774
AK
302static FilterGraph **filtergraphs;
303int nb_filtergraphs;
304
575ec4e1 305typedef struct OptionsContext {
6b779ccc
AK
306 /* input/output options */
307 int64_t start_time;
7041bb3b 308 const char *format;
6b779ccc 309
35e6f8c1
AK
310 SpecifierOpt *codec_names;
311 int nb_codec_names;
6a11686d
AK
312 SpecifierOpt *audio_channels;
313 int nb_audio_channels;
e2469ccf
AK
314 SpecifierOpt *audio_sample_rate;
315 int nb_audio_sample_rate;
91ea4811
AK
316 SpecifierOpt *frame_rates;
317 int nb_frame_rates;
d4397b03
AK
318 SpecifierOpt *frame_sizes;
319 int nb_frame_sizes;
b2254d83
AK
320 SpecifierOpt *frame_pix_fmts;
321 int nb_frame_pix_fmts;
35e6f8c1 322
6b779ccc
AK
323 /* input options */
324 int64_t input_ts_offset;
f4805328 325 int rate_emu;
6b779ccc 326
33f75d72
AK
327 SpecifierOpt *ts_scale;
328 int nb_ts_scale;
a2c0b830
AK
329 SpecifierOpt *dump_attachment;
330 int nb_dump_attachment;
33f75d72 331
575ec4e1
AK
332 /* output options */
333 StreamMap *stream_maps;
334 int nb_stream_maps;
847529f8
AK
335 /* first item specifies output metadata, second is input */
336 MetadataMap (*meta_data_maps)[2];
337 int nb_meta_data_maps;
338 int metadata_global_manual;
339 int metadata_streams_manual;
340 int metadata_chapters_manual;
4dbc6cee
AK
341 const char **attachments;
342 int nb_attachments;
6b779ccc 343
c5bb372e
AK
344 int chapters_input_file;
345
6b779ccc 346 int64_t recording_time;
13ccba50 347 uint64_t limit_filesize;
dc26318c
AK
348 float mux_preload;
349 float mux_max_delay;
039267f1 350
2130981a
AK
351 int video_disable;
352 int audio_disable;
353 int subtitle_disable;
354 int data_disable;
355
495ecfd1
AK
356 /* indexed by output file stream index */
357 int *streamid_map;
358 int nb_streamid_map;
359
039267f1
AK
360 SpecifierOpt *metadata;
361 int nb_metadata;
96139b5e
AK
362 SpecifierOpt *max_frames;
363 int nb_max_frames;
d821cbe2
AK
364 SpecifierOpt *bitstream_filters;
365 int nb_bitstream_filters;
013887eb
AK
366 SpecifierOpt *codec_tags;
367 int nb_codec_tags;
05bffc12
AK
368 SpecifierOpt *sample_fmts;
369 int nb_sample_fmts;
77d9c454
AK
370 SpecifierOpt *qscale;
371 int nb_qscale;
7c029672
AK
372 SpecifierOpt *forced_key_frames;
373 int nb_forced_key_frames;
bef737a7
AK
374 SpecifierOpt *force_fps;
375 int nb_force_fps;
ca46fde7
AK
376 SpecifierOpt *frame_aspect_ratios;
377 int nb_frame_aspect_ratios;
0e68c783
AK
378 SpecifierOpt *rc_overrides;
379 int nb_rc_overrides;
2c2cff16
AK
380 SpecifierOpt *intra_matrices;
381 int nb_intra_matrices;
382 SpecifierOpt *inter_matrices;
383 int nb_inter_matrices;
828e0bcb
AK
384 SpecifierOpt *top_field_first;
385 int nb_top_field_first;
a7b5e841
AK
386 SpecifierOpt *metadata_map;
387 int nb_metadata_map;
3ec34462
AK
388 SpecifierOpt *presets;
389 int nb_presets;
a2aeeb22
AK
390 SpecifierOpt *copy_initial_nonkeyframes;
391 int nb_copy_initial_nonkeyframes;
8e5ce590
AK
392 SpecifierOpt *filters;
393 int nb_filters;
575ec4e1
AK
394} OptionsContext;
395
35e6f8c1
AK
396#define MATCH_PER_STREAM_OPT(name, type, outvar, fmtctx, st)\
397{\
398 int i, ret;\
399 for (i = 0; i < o->nb_ ## name; i++) {\
400 char *spec = o->name[i].specifier;\
401 if ((ret = check_stream_specifier(fmtctx, st, spec)) > 0)\
402 outvar = o->name[i].u.type;\
403 else if (ret < 0)\
404 exit_program(1);\
405 }\
406}
407
575ec4e1
AK
408static void reset_options(OptionsContext *o)
409{
410 const OptionDef *po = options;
3b266da3 411 int i;
575ec4e1
AK
412
413 /* all OPT_SPEC and OPT_STRING can be freed in generic way */
414 while (po->name) {
415 void *dst = (uint8_t*)o + po->u.off;
416
417 if (po->flags & OPT_SPEC) {
418 SpecifierOpt **so = dst;
419 int i, *count = (int*)(so + 1);
420 for (i = 0; i < *count; i++) {
421 av_freep(&(*so)[i].specifier);
422 if (po->flags & OPT_STRING)
423 av_freep(&(*so)[i].u.str);
424 }
425 av_freep(so);
426 *count = 0;
427 } else if (po->flags & OPT_OFFSET && po->flags & OPT_STRING)
428 av_freep(dst);
429 po++;
430 }
431
3b266da3
AK
432 for (i = 0; i < o->nb_stream_maps; i++)
433 av_freep(&o->stream_maps[i].linklabel);
575ec4e1 434 av_freep(&o->stream_maps);
847529f8 435 av_freep(&o->meta_data_maps);
495ecfd1 436 av_freep(&o->streamid_map);
575ec4e1
AK
437
438 memset(o, 0, sizeof(*o));
6b779ccc 439
dc26318c 440 o->mux_max_delay = 0.7;
6b779ccc 441 o->recording_time = INT64_MAX;
13ccba50 442 o->limit_filesize = UINT64_MAX;
c5bb372e 443 o->chapters_input_file = INT_MAX;
6b779ccc 444
575ec4e1
AK
445 uninit_opts();
446 init_opts();
447}
448
bc1ef855 449static int alloc_buffer(InputStream *ist, AVCodecContext *s, FrameBuffer **pbuf)
64dca32c 450{
64dca32c 451 FrameBuffer *buf = av_mallocz(sizeof(*buf));
3715d841 452 int i, ret;
64dca32c
AK
453 const int pixel_size = av_pix_fmt_descriptors[s->pix_fmt].comp[0].step_minus1+1;
454 int h_chroma_shift, v_chroma_shift;
455 int edge = 32; // XXX should be avcodec_get_edge_width(), but that fails on svq1
456 int w = s->width, h = s->height;
457
458 if (!buf)
459 return AVERROR(ENOMEM);
460
461 if (!(s->flags & CODEC_FLAG_EMU_EDGE)) {
462 w += 2*edge;
463 h += 2*edge;
464 }
465
466 avcodec_align_dimensions(s, &w, &h);
467 if ((ret = av_image_alloc(buf->base, buf->linesize, w, h,
468 s->pix_fmt, 32)) < 0) {
469 av_freep(&buf);
470 return ret;
471 }
472 /* XXX this shouldn't be needed, but some tests break without this line
473 * those decoders are buggy and need to be fixed.
474 * the following tests fail:
f320fb89 475 * cdgraphics, ansi, aasc, fraps-v1, qtrle-1bit
64dca32c
AK
476 */
477 memset(buf->base[0], 128, ret);
478
479 avcodec_get_chroma_sub_sample(s->pix_fmt, &h_chroma_shift, &v_chroma_shift);
3715d841 480 for (i = 0; i < FF_ARRAY_ELEMS(buf->data); i++) {
64dca32c
AK
481 const int h_shift = i==0 ? 0 : h_chroma_shift;
482 const int v_shift = i==0 ? 0 : v_chroma_shift;
483 if (s->flags & CODEC_FLAG_EMU_EDGE)
484 buf->data[i] = buf->base[i];
485 else
486 buf->data[i] = buf->base[i] +
487 FFALIGN((buf->linesize[i]*edge >> v_shift) +
488 (pixel_size*edge >> h_shift), 32);
489 }
490 buf->w = s->width;
491 buf->h = s->height;
492 buf->pix_fmt = s->pix_fmt;
493 buf->ist = ist;
494
495 *pbuf = buf;
496 return 0;
497}
498
499static void free_buffer_pool(InputStream *ist)
500{
501 FrameBuffer *buf = ist->buffer_pool;
502 while (buf) {
503 ist->buffer_pool = buf->next;
504 av_freep(&buf->base[0]);
505 av_free(buf);
506 buf = ist->buffer_pool;
507 }
508}
509
510static void unref_buffer(InputStream *ist, FrameBuffer *buf)
511{
512 av_assert0(buf->refcount);
513 buf->refcount--;
514 if (!buf->refcount) {
515 buf->next = ist->buffer_pool;
516 ist->buffer_pool = buf;
517 }
518}
519
520static int codec_get_buffer(AVCodecContext *s, AVFrame *frame)
521{
522 InputStream *ist = s->opaque;
523 FrameBuffer *buf;
524 int ret, i;
525
bc1ef855 526 if (!ist->buffer_pool && (ret = alloc_buffer(ist, s, &ist->buffer_pool)) < 0)
64dca32c
AK
527 return ret;
528
529 buf = ist->buffer_pool;
530 ist->buffer_pool = buf->next;
531 buf->next = NULL;
532 if (buf->w != s->width || buf->h != s->height || buf->pix_fmt != s->pix_fmt) {
533 av_freep(&buf->base[0]);
534 av_free(buf);
bc1ef855 535 if ((ret = alloc_buffer(ist, s, &buf)) < 0)
64dca32c
AK
536 return ret;
537 }
538 buf->refcount++;
539
540 frame->opaque = buf;
541 frame->type = FF_BUFFER_TYPE_USER;
542 frame->extended_data = frame->data;
543 frame->pkt_pts = s->pkt ? s->pkt->pts : AV_NOPTS_VALUE;
bc1ef855
RB
544 frame->width = buf->w;
545 frame->height = buf->h;
546 frame->format = buf->pix_fmt;
547 frame->sample_aspect_ratio = s->sample_aspect_ratio;
64dca32c
AK
548
549 for (i = 0; i < FF_ARRAY_ELEMS(buf->data); i++) {
550 frame->base[i] = buf->base[i]; // XXX h264.c uses base though it shouldn't
551 frame->data[i] = buf->data[i];
552 frame->linesize[i] = buf->linesize[i];
553 }
554
555 return 0;
556}
557
558static void codec_release_buffer(AVCodecContext *s, AVFrame *frame)
559{
560 InputStream *ist = s->opaque;
561 FrameBuffer *buf = frame->opaque;
562 int i;
563
564 for (i = 0; i < FF_ARRAY_ELEMS(frame->data); i++)
565 frame->data[i] = NULL;
566
567 unref_buffer(ist, buf);
568}
569
04a14d4d
AK
570static void filter_release_buffer(AVFilterBuffer *fb)
571{
572 FrameBuffer *buf = fb->priv;
573 av_free(fb);
574 unref_buffer(buf->ist, buf);
575}
576
369cb092
AK
577/**
578 * Define a function for building a string containing a list of
579 * allowed formats,
580 */
581#define DEF_CHOOSE_FORMAT(type, var, supported_list, none, get_name, separator) \
582static char *choose_ ## var ## s(OutputStream *ost) \
583{ \
584 if (ost->st->codec->var != none) { \
585 get_name(ost->st->codec->var); \
586 return av_strdup(name); \
587 } else if (ost->enc->supported_list) { \
588 const type *p; \
589 AVIOContext *s = NULL; \
590 uint8_t *ret; \
591 int len; \
592 \
593 if (avio_open_dyn_buf(&s) < 0) \
594 exit_program(1); \
595 \
596 for (p = ost->enc->supported_list; *p != none; p++) { \
597 get_name(*p); \
598 avio_printf(s, "%s" separator, name); \
599 } \
600 len = avio_close_dyn_buf(s, &ret); \
601 ret[len - 1] = 0; \
602 return ret; \
603 } else \
604 return NULL; \
605}
606
607#define GET_PIX_FMT_NAME(pix_fmt)\
608 const char *name = av_get_pix_fmt_name(pix_fmt);
609
610DEF_CHOOSE_FORMAT(enum PixelFormat, pix_fmt, pix_fmts, PIX_FMT_NONE,
611 GET_PIX_FMT_NAME, ":")
612
613#define GET_SAMPLE_FMT_NAME(sample_fmt)\
614 const char *name = av_get_sample_fmt_name(sample_fmt)
615
616DEF_CHOOSE_FORMAT(enum AVSampleFormat, sample_fmt, sample_fmts,
617 AV_SAMPLE_FMT_NONE, GET_SAMPLE_FMT_NAME, ",")
618
619#define GET_SAMPLE_RATE_NAME(rate)\
620 char name[16];\
621 snprintf(name, sizeof(name), "%d", rate);
622
623DEF_CHOOSE_FORMAT(int, sample_rate, supported_samplerates, 0,
624 GET_SAMPLE_RATE_NAME, ",")
625
626#define GET_CH_LAYOUT_NAME(ch_layout)\
627 char name[16];\
628 snprintf(name, sizeof(name), "0x%"PRIx64, ch_layout);
629
630DEF_CHOOSE_FORMAT(uint64_t, channel_layout, channel_layouts, 0,
631 GET_CH_LAYOUT_NAME, ",")
632
633static int configure_audio_filters(FilterGraph *fg, AVFilterContext **in_filter,
634 AVFilterContext **out_filter)
b7327887 635{
369cb092
AK
636 InputStream *ist = fg->inputs[0]->ist;
637 OutputStream *ost = fg->outputs[0]->ost;
638 AVCodecContext *codec = ost->st->codec;
639 AVCodecContext *icodec = ist->st->codec;
640 char *sample_fmts, *sample_rates, *channel_layouts;
641 char args[256];
642 int ret;
643
644 avfilter_graph_free(&fg->graph);
645 if (!(fg->graph = avfilter_graph_alloc()))
646 return AVERROR(ENOMEM);
647
648 snprintf(args, sizeof(args), "time_base=%d/%d:sample_rate=%d:sample_fmt=%s:"
649 "channel_layout=0x%"PRIx64, ist->st->time_base.num,
650 ist->st->time_base.den, icodec->sample_rate,
651 av_get_sample_fmt_name(icodec->sample_fmt), icodec->channel_layout);
652 ret = avfilter_graph_create_filter(&fg->inputs[0]->filter,
653 avfilter_get_by_name("abuffer"),
654 "src", args, NULL, fg->graph);
655 if (ret < 0)
656 return ret;
ac712309 657
369cb092
AK
658 ret = avfilter_graph_create_filter(&fg->outputs[0]->filter,
659 avfilter_get_by_name("abuffersink"),
660 "out", NULL, NULL, fg->graph);
661 if (ret < 0)
ac712309 662 return ret;
369cb092
AK
663
664 *in_filter = fg->inputs[0]->filter;
665 *out_filter = fg->outputs[0]->filter;
666
667 if (codec->channels && !codec->channel_layout)
668 codec->channel_layout = av_get_default_channel_layout(codec->channels);
669
670 sample_fmts = choose_sample_fmts(ost);
671 sample_rates = choose_sample_rates(ost);
672 channel_layouts = choose_channel_layouts(ost);
673 if (sample_fmts || sample_rates || channel_layouts) {
674 AVFilterContext *format;
675 char args[256];
676 int len = 0;
677
678 if (sample_fmts)
679 len += snprintf(args + len, sizeof(args) - len, "sample_fmts=%s:",
680 sample_fmts);
681 if (sample_rates)
682 len += snprintf(args + len, sizeof(args) - len, "sample_rates=%s:",
683 sample_rates);
684 if (channel_layouts)
685 len += snprintf(args + len, sizeof(args) - len, "channel_layouts=%s:",
686 channel_layouts);
687 args[len - 1] = 0;
688
689 av_freep(&sample_fmts);
690 av_freep(&sample_rates);
691 av_freep(&channel_layouts);
692
693 ret = avfilter_graph_create_filter(&format,
694 avfilter_get_by_name("aformat"),
695 "aformat", args, NULL, fg->graph);
696 if (ret < 0)
697 return ret;
698
699 ret = avfilter_link(format, 0, fg->outputs[0]->filter, 0);
700 if (ret < 0)
701 return ret;
702
703 *out_filter = format;
704 }
705
6eeb9a04
AK
706 if (audio_sync_method > 0) {
707 AVFilterContext *async;
708 char args[256];
709 int len = 0;
710
711 av_log(NULL, AV_LOG_WARNING, "-async has been deprecated. Used the "
712 "asyncts audio filter instead.\n");
713
714 if (audio_sync_method > 1)
715 len += snprintf(args + len, sizeof(args) - len, "compensate=1:"
716 "max_comp=%d:", audio_sync_method);
717 snprintf(args + len, sizeof(args) - len, "min_delta=%f",
718 audio_drift_threshold);
719
720 ret = avfilter_graph_create_filter(&async,
721 avfilter_get_by_name("asyncts"),
722 "async", args, NULL, fg->graph);
723 if (ret < 0)
724 return ret;
725
726 ret = avfilter_link(*in_filter, 0, async, 0);
727 if (ret < 0)
728 return ret;
729
730 *in_filter = async;
731 }
732
369cb092 733 return 0;
b7327887
AK
734}
735
369cb092
AK
736static int configure_video_filters(FilterGraph *fg, AVFilterContext **in_filter,
737 AVFilterContext **out_filter)
6291d7e4 738{
560f7774
AK
739 InputStream *ist = fg->inputs[0]->ist;
740 OutputStream *ost = fg->outputs[0]->ost;
369cb092 741 AVFilterContext *filter;
6291d7e4 742 AVCodecContext *codec = ost->st->codec;
ac712309 743 char *pix_fmts;
6291d7e4
AK
744 AVRational sample_aspect_ratio;
745 char args[255];
746 int ret;
747
7636c8c6 748 if (ist->st->sample_aspect_ratio.num) {
6291d7e4 749 sample_aspect_ratio = ist->st->sample_aspect_ratio;
7636c8c6 750 } else
6291d7e4
AK
751 sample_aspect_ratio = ist->st->codec->sample_aspect_ratio;
752
753 snprintf(args, 255, "%d:%d:%d:%d:%d:%d:%d", ist->st->codec->width,
754 ist->st->codec->height, ist->st->codec->pix_fmt, 1, AV_TIME_BASE,
755 sample_aspect_ratio.num, sample_aspect_ratio.den);
756
560f7774
AK
757 ret = avfilter_graph_create_filter(&fg->inputs[0]->filter,
758 avfilter_get_by_name("buffer"),
759 "src", args, NULL, fg->graph);
6291d7e4
AK
760 if (ret < 0)
761 return ret;
ac712309
AK
762 ret = avfilter_graph_create_filter(&fg->outputs[0]->filter,
763 avfilter_get_by_name("buffersink"),
764 "out", NULL, NULL, fg->graph);
6291d7e4
AK
765 if (ret < 0)
766 return ret;
369cb092
AK
767 *in_filter = fg->inputs[0]->filter;
768 *out_filter = fg->outputs[0]->filter;
6291d7e4 769
6c9eac19 770 if (codec->width || codec->height) {
6291d7e4
AK
771 snprintf(args, 255, "%d:%d:flags=0x%X",
772 codec->width,
773 codec->height,
3b3ea346 774 (unsigned)ost->sws_flags);
6291d7e4 775 if ((ret = avfilter_graph_create_filter(&filter, avfilter_get_by_name("scale"),
560f7774 776 NULL, args, NULL, fg->graph)) < 0)
6291d7e4 777 return ret;
369cb092 778 if ((ret = avfilter_link(*in_filter, 0, filter, 0)) < 0)
6291d7e4 779 return ret;
369cb092 780 *in_filter = filter;
ac712309
AK
781 }
782
369cb092 783 if ((pix_fmts = choose_pix_fmts(ost))) {
ac712309
AK
784 if ((ret = avfilter_graph_create_filter(&filter,
785 avfilter_get_by_name("format"),
786 "format", pix_fmts, NULL,
787 fg->graph)) < 0)
788 return ret;
369cb092 789 if ((ret = avfilter_link(filter, 0, *out_filter, 0)) < 0)
ac712309
AK
790 return ret;
791
369cb092 792 *out_filter = filter;
ac712309 793 av_freep(&pix_fmts);
6291d7e4
AK
794 }
795
3b3ea346 796 snprintf(args, sizeof(args), "flags=0x%X", (unsigned)ost->sws_flags);
560f7774 797 fg->graph->scale_sws_opts = av_strdup(args);
6291d7e4 798
369cb092
AK
799 return 0;
800}
801
802static int configure_simple_filtergraph(FilterGraph *fg)
803{
804 OutputStream *ost = fg->outputs[0]->ost;
805 AVFilterContext *in_filter, *out_filter;
806 int ret;
807
808 avfilter_graph_free(&fg->graph);
809 fg->graph = avfilter_graph_alloc();
810
811 switch (ost->st->codec->codec_type) {
812 case AVMEDIA_TYPE_VIDEO:
813 ret = configure_video_filters(fg, &in_filter, &out_filter);
814 break;
815 case AVMEDIA_TYPE_AUDIO:
816 ret = configure_audio_filters(fg, &in_filter, &out_filter);
817 break;
818 default: av_assert0(0);
819 }
820 if (ret < 0)
821 return ret;
822
6291d7e4 823 if (ost->avfilter) {
91d3cbe0
SS
824 AVFilterInOut *outputs = avfilter_inout_alloc();
825 AVFilterInOut *inputs = avfilter_inout_alloc();
6291d7e4
AK
826
827 outputs->name = av_strdup("in");
ac712309 828 outputs->filter_ctx = in_filter;
6291d7e4
AK
829 outputs->pad_idx = 0;
830 outputs->next = NULL;
831
832 inputs->name = av_strdup("out");
ac712309 833 inputs->filter_ctx = out_filter;
6291d7e4
AK
834 inputs->pad_idx = 0;
835 inputs->next = NULL;
836
560f7774 837 if ((ret = avfilter_graph_parse(fg->graph, ost->avfilter, inputs, outputs, NULL)) < 0)
6291d7e4 838 return ret;
6291d7e4 839 } else {
ac712309 840 if ((ret = avfilter_link(in_filter, 0, out_filter, 0)) < 0)
6291d7e4
AK
841 return ret;
842 }
843
560f7774 844 if ((ret = avfilter_graph_config(fg->graph, NULL)) < 0)
6291d7e4
AK
845 return ret;
846
560f7774 847 ost->filter = fg->outputs[0];
6291d7e4
AK
848
849 return 0;
850}
6291d7e4 851
560f7774
AK
852static FilterGraph *init_simple_filtergraph(InputStream *ist, OutputStream *ost)
853{
854 FilterGraph *fg = av_mallocz(sizeof(*fg));
855
856 if (!fg)
857 exit_program(1);
3b266da3 858 fg->index = nb_filtergraphs;
560f7774
AK
859
860 fg->outputs = grow_array(fg->outputs, sizeof(*fg->outputs), &fg->nb_outputs,
861 fg->nb_outputs + 1);
862 if (!(fg->outputs[0] = av_mallocz(sizeof(*fg->outputs[0]))))
863 exit_program(1);
864 fg->outputs[0]->ost = ost;
865 fg->outputs[0]->graph = fg;
866
867 fg->inputs = grow_array(fg->inputs, sizeof(*fg->inputs), &fg->nb_inputs,
868 fg->nb_inputs + 1);
869 if (!(fg->inputs[0] = av_mallocz(sizeof(*fg->inputs[0]))))
870 exit_program(1);
871 fg->inputs[0]->ist = ist;
872 fg->inputs[0]->graph = fg;
873
874 ist->filters = grow_array(ist->filters, sizeof(*ist->filters),
875 &ist->nb_filters, ist->nb_filters + 1);
876 ist->filters[ist->nb_filters - 1] = fg->inputs[0];
877
878 filtergraphs = grow_array(filtergraphs, sizeof(*filtergraphs),
879 &nb_filtergraphs, nb_filtergraphs + 1);
880 filtergraphs[nb_filtergraphs - 1] = fg;
881
882 return fg;
883}
884
3b266da3
AK
885static void init_input_filter(FilterGraph *fg, AVFilterInOut *in)
886{
887 InputStream *ist;
888 enum AVMediaType type = in->filter_ctx->input_pads[in->pad_idx].type;
889 int i;
890
891 // TODO: support other filter types
0ad26cdf
AK
892 if (type != AVMEDIA_TYPE_VIDEO && type != AVMEDIA_TYPE_AUDIO) {
893 av_log(NULL, AV_LOG_FATAL, "Only video and audio filters supported "
894 "currently.\n");
3b266da3
AK
895 exit_program(1);
896 }
897
898 if (in->name) {
899 AVFormatContext *s;
900 AVStream *st = NULL;
901 char *p;
902 int file_idx = strtol(in->name, &p, 0);
903
1381081c 904 if (file_idx < 0 || file_idx >= nb_input_files) {
3b266da3
AK
905 av_log(NULL, AV_LOG_FATAL, "Invalid file index %d in filtegraph description %s.\n",
906 file_idx, fg->graph_desc);
907 exit_program(1);
908 }
909 s = input_files[file_idx]->ctx;
910
911 for (i = 0; i < s->nb_streams; i++) {
912 if (s->streams[i]->codec->codec_type != type)
913 continue;
914 if (check_stream_specifier(s, s->streams[i], *p == ':' ? p + 1 : p) == 1) {
915 st = s->streams[i];
916 break;
917 }
918 }
919 if (!st) {
920 av_log(NULL, AV_LOG_FATAL, "Stream specifier '%s' in filtergraph description %s "
921 "matches no streams.\n", p, fg->graph_desc);
922 exit_program(1);
923 }
924 ist = input_streams[input_files[file_idx]->ist_index + st->index];
925 } else {
926 /* find the first unused stream of corresponding type */
927 for (i = 0; i < nb_input_streams; i++) {
928 ist = input_streams[i];
929 if (ist->st->codec->codec_type == type && ist->discard)
930 break;
931 }
932 if (i == nb_input_streams) {
933 av_log(NULL, AV_LOG_FATAL, "Cannot find a matching stream for "
934 "unlabeled input pad %d on filter %s", in->pad_idx,
935 in->filter_ctx->name);
936 exit_program(1);
937 }
938 }
939 ist->discard = 0;
940 ist->decoding_needed = 1;
941 ist->st->discard = AVDISCARD_NONE;
942
943 fg->inputs = grow_array(fg->inputs, sizeof(*fg->inputs),
944 &fg->nb_inputs, fg->nb_inputs + 1);
945 if (!(fg->inputs[fg->nb_inputs - 1] = av_mallocz(sizeof(*fg->inputs[0]))))
946 exit_program(1);
947 fg->inputs[fg->nb_inputs - 1]->ist = ist;
948 fg->inputs[fg->nb_inputs - 1]->graph = fg;
949
950 ist->filters = grow_array(ist->filters, sizeof(*ist->filters),
951 &ist->nb_filters, ist->nb_filters + 1);
952 ist->filters[ist->nb_filters - 1] = fg->inputs[fg->nb_inputs - 1];
953}
954
0ad26cdf 955static int configure_output_video_filter(FilterGraph *fg, OutputFilter *ofilter, AVFilterInOut *out)
3b266da3 956{
ac712309 957 char *pix_fmts;
3b266da3
AK
958 AVCodecContext *codec = ofilter->ost->st->codec;
959 AVFilterContext *last_filter = out->filter_ctx;
960 int pad_idx = out->pad_idx;
961 int ret;
962
3b266da3 963
ac712309
AK
964 ret = avfilter_graph_create_filter(&ofilter->filter,
965 avfilter_get_by_name("buffersink"),
966 "out", NULL, pix_fmts, fg->graph);
3b266da3
AK
967 if (ret < 0)
968 return ret;
969
970 if (codec->width || codec->height) {
971 char args[255];
ac712309
AK
972 AVFilterContext *filter;
973
3b266da3
AK
974 snprintf(args, sizeof(args), "%d:%d:flags=0x%X",
975 codec->width,
976 codec->height,
977 (unsigned)ofilter->ost->sws_flags);
ac712309 978 if ((ret = avfilter_graph_create_filter(&filter, avfilter_get_by_name("scale"),
3b266da3
AK
979 NULL, args, NULL, fg->graph)) < 0)
980 return ret;
ac712309 981 if ((ret = avfilter_link(last_filter, pad_idx, filter, 0)) < 0)
3b266da3 982 return ret;
ac712309
AK
983
984 last_filter = filter;
3b266da3
AK
985 pad_idx = 0;
986 }
987
369cb092 988 if ((pix_fmts = choose_pix_fmts(ofilter->ost))) {
ac712309
AK
989 AVFilterContext *filter;
990 if ((ret = avfilter_graph_create_filter(&filter,
991 avfilter_get_by_name("format"),
992 "format", pix_fmts, NULL,
993 fg->graph)) < 0)
994 return ret;
995 if ((ret = avfilter_link(last_filter, pad_idx, filter, 0)) < 0)
996 return ret;
997
998 last_filter = filter;
999 pad_idx = 0;
1000 av_freep(&pix_fmts);
1001 }
1002
3b266da3
AK
1003 if ((ret = avfilter_link(last_filter, pad_idx, ofilter->filter, 0)) < 0)
1004 return ret;
1005
1006 return 0;
1007}
1008
0ad26cdf
AK
1009static int configure_output_audio_filter(FilterGraph *fg, OutputFilter *ofilter, AVFilterInOut *out)
1010{
1011 OutputStream *ost = ofilter->ost;
1012 AVCodecContext *codec = ost->st->codec;
1013 AVFilterContext *last_filter = out->filter_ctx;
1014 int pad_idx = out->pad_idx;
1015 char *sample_fmts, *sample_rates, *channel_layouts;
1016 int ret;
1017
1018 ret = avfilter_graph_create_filter(&ofilter->filter,
1019 avfilter_get_by_name("abuffersink"),
1020 "out", NULL, NULL, fg->graph);
1021 if (ret < 0)
1022 return ret;
1023
1024 if (codec->channels && !codec->channel_layout)
1025 codec->channel_layout = av_get_default_channel_layout(codec->channels);
1026
1027 sample_fmts = choose_sample_fmts(ost);
1028 sample_rates = choose_sample_rates(ost);
1029 channel_layouts = choose_channel_layouts(ost);
1030 if (sample_fmts || sample_rates || channel_layouts) {
1031 AVFilterContext *format;
1032 char args[256];
1033 int len = 0;
1034
1035 if (sample_fmts)
1036 len += snprintf(args + len, sizeof(args) - len, "sample_fmts=%s:",
1037 sample_fmts);
1038 if (sample_rates)
1039 len += snprintf(args + len, sizeof(args) - len, "sample_rates=%s:",
1040 sample_rates);
1041 if (channel_layouts)
1042 len += snprintf(args + len, sizeof(args) - len, "channel_layouts=%s:",
1043 channel_layouts);
1044 args[len - 1] = 0;
1045
1046 av_freep(&sample_fmts);
1047 av_freep(&sample_rates);
1048 av_freep(&channel_layouts);
1049
1050 ret = avfilter_graph_create_filter(&format,
1051 avfilter_get_by_name("aformat"),
1052 "aformat", args, NULL, fg->graph);
1053 if (ret < 0)
1054 return ret;
1055
1056 ret = avfilter_link(last_filter, pad_idx, format, 0);
1057 if (ret < 0)
1058 return ret;
1059
1060 last_filter = format;
1061 pad_idx = 0;
1062 }
1063
1064 if (audio_sync_method > 0) {
1065 AVFilterContext *async;
1066 char args[256];
1067 int len = 0;
1068
1069 av_log(NULL, AV_LOG_WARNING, "-async has been deprecated. Used the "
1070 "asyncts audio filter instead.\n");
1071
1072 if (audio_sync_method > 1)
1073 len += snprintf(args + len, sizeof(args) - len, "compensate=1:"
1074 "max_comp=%d:", audio_sync_method);
1075 snprintf(args + len, sizeof(args) - len, "min_delta=%f",
1076 audio_drift_threshold);
1077
1078 ret = avfilter_graph_create_filter(&async,
1079 avfilter_get_by_name("asyncts"),
1080 "async", args, NULL, fg->graph);
1081 if (ret < 0)
1082 return ret;
1083
1084 ret = avfilter_link(last_filter, pad_idx, async, 0);
1085 if (ret < 0)
1086 return ret;
1087
1088 last_filter = async;
1089 pad_idx = 0;
1090 }
1091
1092 if ((ret = avfilter_link(last_filter, pad_idx, ofilter->filter, 0)) < 0)
1093 return ret;
1094
1095 return 0;
1096}
1097
1098static int configure_output_filter(FilterGraph *fg, OutputFilter *ofilter, AVFilterInOut *out)
1099{
1100 switch (out->filter_ctx->output_pads[out->pad_idx].type) {
1101 case AVMEDIA_TYPE_VIDEO: return configure_output_video_filter(fg, ofilter, out);
1102 case AVMEDIA_TYPE_AUDIO: return configure_output_audio_filter(fg, ofilter, out);
1103 default: av_assert0(0);
1104 }
1105}
1106
3b266da3
AK
1107static int configure_complex_filter(FilterGraph *fg)
1108{
1109 AVFilterInOut *inputs, *outputs, *cur;
1110 int ret, i, init = !fg->graph;
1111
1112 avfilter_graph_free(&fg->graph);
1113 if (!(fg->graph = avfilter_graph_alloc()))
1114 return AVERROR(ENOMEM);
1115
1116 if ((ret = avfilter_graph_parse2(fg->graph, fg->graph_desc, &inputs, &outputs)) < 0)
1117 return ret;
1118
1119 for (cur = inputs; init && cur; cur = cur->next)
1120 init_input_filter(fg, cur);
1121
1122 for (cur = inputs, i = 0; cur; cur = cur->next, i++) {
1123 InputFilter *ifilter = fg->inputs[i];
1124 InputStream *ist = ifilter->ist;
1125 AVRational sar;
0ad26cdf 1126 AVFilter *filter;
3b266da3
AK
1127 char args[255];
1128
0ad26cdf
AK
1129 switch (cur->filter_ctx->input_pads[cur->pad_idx].type) {
1130 case AVMEDIA_TYPE_VIDEO:
1131 sar = ist->st->sample_aspect_ratio.num ?
1132 ist->st->sample_aspect_ratio :
1133 ist->st->codec->sample_aspect_ratio;
1134 snprintf(args, sizeof(args), "%d:%d:%d:%d:%d:%d:%d", ist->st->codec->width,
1135 ist->st->codec->height, ist->st->codec->pix_fmt, 1, AV_TIME_BASE,
1136 sar.num, sar.den);
1137 filter = avfilter_get_by_name("buffer");
1138 break;
1139 case AVMEDIA_TYPE_AUDIO:
1140 snprintf(args, sizeof(args), "time_base=%d/%d:sample_rate=%d:"
1141 "sample_fmt=%s:channel_layout=0x%"PRIx64,
1142 ist->st->time_base.num, ist->st->time_base.den,
1143 ist->st->codec->sample_rate,
1144 av_get_sample_fmt_name(ist->st->codec->sample_fmt),
1145 ist->st->codec->channel_layout);
1146 filter = avfilter_get_by_name("abuffer");
1147 break;
1148 default:
1149 av_assert0(0);
1150 }
3b266da3
AK
1151
1152 if ((ret = avfilter_graph_create_filter(&ifilter->filter,
0ad26cdf 1153 filter, cur->name,
3b266da3
AK
1154 args, NULL, fg->graph)) < 0)
1155 return ret;
1156 if ((ret = avfilter_link(ifilter->filter, 0,
1157 cur->filter_ctx, cur->pad_idx)) < 0)
1158 return ret;
1159 }
1160 avfilter_inout_free(&inputs);
1161
1162 if (!init) {
1163 /* we already know the mappings between lavfi outputs and output streams,
1164 * so we can finish the setup */
1165 for (cur = outputs, i = 0; cur; cur = cur->next, i++)
1166 configure_output_filter(fg, fg->outputs[i], cur);
1167 avfilter_inout_free(&outputs);
1168
1169 if ((ret = avfilter_graph_config(fg->graph, NULL)) < 0)
1170 return ret;
1171 } else {
1172 /* wait until output mappings are processed */
1173 for (cur = outputs; cur;) {
1174 fg->outputs = grow_array(fg->outputs, sizeof(*fg->outputs),
1175 &fg->nb_outputs, fg->nb_outputs + 1);
1176 if (!(fg->outputs[fg->nb_outputs - 1] = av_mallocz(sizeof(*fg->outputs[0]))))
1177 exit_program(1);
1178 fg->outputs[fg->nb_outputs - 1]->graph = fg;
1179 fg->outputs[fg->nb_outputs - 1]->out_tmp = cur;
1180 cur = cur->next;
1181 fg->outputs[fg->nb_outputs - 1]->out_tmp->next = NULL;
1182 }
1183 }
1184
1185 return 0;
1186}
1187
1188static int configure_complex_filters(void)
1189{
1190 int i, ret = 0;
1191
1192 for (i = 0; i < nb_filtergraphs; i++)
1193 if (!filtergraphs[i]->graph &&
1194 (ret = configure_complex_filter(filtergraphs[i])) < 0)
1195 return ret;
1196 return 0;
1197}
1198
1199static int configure_filtergraph(FilterGraph *fg)
1200{
369cb092
AK
1201 return fg->graph_desc ? configure_complex_filter(fg) :
1202 configure_simple_filtergraph(fg);
3b266da3
AK
1203}
1204
1205static int ist_in_filtergraph(FilterGraph *fg, InputStream *ist)
1206{
1207 int i;
1208 for (i = 0; i < fg->nb_inputs; i++)
1209 if (fg->inputs[i]->ist == ist)
1210 return 1;
1211 return 0;
1212}
1213
6291d7e4
AK
1214static void term_exit(void)
1215{
1216 av_log(NULL, AV_LOG_QUIET, "");
1217}
1218
1219static volatile int received_sigterm = 0;
1220static volatile int received_nb_signals = 0;
1221
1222static void
1223sigterm_handler(int sig)
1224{
1225 received_sigterm = sig;
1226 received_nb_signals++;
1227 term_exit();
1228}
1229
1230static void term_init(void)
1231{
7636c8c6 1232 signal(SIGINT , sigterm_handler); /* Interrupt (ANSI). */
6291d7e4
AK
1233 signal(SIGTERM, sigterm_handler); /* Termination (ANSI). */
1234#ifdef SIGXCPU
1235 signal(SIGXCPU, sigterm_handler);
1236#endif
1237}
1238
2abe947a 1239static int decode_interrupt_cb(void *ctx)
6291d7e4
AK
1240{
1241 return received_nb_signals > 1;
1242}
1243
2abe947a
MS
1244static const AVIOInterruptCB int_cb = { decode_interrupt_cb, NULL };
1245
dad09ff9 1246void exit_program(int ret)
6291d7e4 1247{
560f7774
AK
1248 int i, j;
1249
1250 for (i = 0; i < nb_filtergraphs; i++) {
1251 avfilter_graph_free(&filtergraphs[i]->graph);
1252 for (j = 0; j < filtergraphs[i]->nb_inputs; j++)
1253 av_freep(&filtergraphs[i]->inputs[j]);
1254 av_freep(&filtergraphs[i]->inputs);
1255 for (j = 0; j < filtergraphs[i]->nb_outputs; j++)
1256 av_freep(&filtergraphs[i]->outputs[j]);
1257 av_freep(&filtergraphs[i]->outputs);
1258 av_freep(&filtergraphs[i]);
1259 }
1260 av_freep(&filtergraphs);
6291d7e4
AK
1261
1262 /* close files */
7636c8c6 1263 for (i = 0; i < nb_output_files; i++) {
2e215267 1264 AVFormatContext *s = output_files[i]->ctx;
6291d7e4
AK
1265 if (!(s->oformat->flags & AVFMT_NOFILE) && s->pb)
1266 avio_close(s->pb);
1267 avformat_free_context(s);
2e215267
AK
1268 av_dict_free(&output_files[i]->opts);
1269 av_freep(&output_files[i]);
6291d7e4 1270 }
1135a071 1271 for (i = 0; i < nb_output_streams; i++) {
2e215267 1272 AVBitStreamFilterContext *bsfc = output_streams[i]->bitstream_filters;
1135a071
JG
1273 while (bsfc) {
1274 AVBitStreamFilterContext *next = bsfc->next;
1275 av_bitstream_filter_close(bsfc);
1276 bsfc = next;
1277 }
2e215267 1278 output_streams[i]->bitstream_filters = NULL;
ac646076 1279
2e215267 1280 av_freep(&output_streams[i]->avfilter);
836ce905 1281 av_freep(&output_streams[i]->filtered_frame);
2e215267 1282 av_freep(&output_streams[i]);
1135a071 1283 }
7636c8c6 1284 for (i = 0; i < nb_input_files; i++) {
2e215267
AK
1285 avformat_close_input(&input_files[i]->ctx);
1286 av_freep(&input_files[i]);
6291d7e4 1287 }
9179f27c 1288 for (i = 0; i < nb_input_streams; i++) {
2e215267 1289 av_freep(&input_streams[i]->decoded_frame);
2e215267
AK
1290 av_dict_free(&input_streams[i]->opts);
1291 free_buffer_pool(input_streams[i]);
560f7774 1292 av_freep(&input_streams[i]->filters);
2e215267 1293 av_freep(&input_streams[i]);
9179f27c 1294 }
6291d7e4 1295
6291d7e4
AK
1296 if (vstats_file)
1297 fclose(vstats_file);
1298 av_free(vstats_filename);
1299
6291d7e4
AK
1300 av_freep(&input_streams);
1301 av_freep(&input_files);
4288e031 1302 av_freep(&output_streams);
af70aa45 1303 av_freep(&output_files);
6291d7e4 1304
6291d7e4 1305 uninit_opts();
6291d7e4 1306
6291d7e4 1307 avfilter_uninit();
776f2bb9 1308 avformat_network_deinit();
6291d7e4
AK
1309
1310 if (received_sigterm) {
e3245b26
AK
1311 av_log(NULL, AV_LOG_INFO, "Received signal %d: terminating.\n",
1312 (int) received_sigterm);
6291d7e4
AK
1313 exit (255);
1314 }
1315
f75e3d25 1316 exit(ret);
6291d7e4
AK
1317}
1318
1319static void assert_avoptions(AVDictionary *m)
1320{
1321 AVDictionaryEntry *t;
1322 if ((t = av_dict_get(m, "", NULL, AV_DICT_IGNORE_SUFFIX))) {
f24facd3 1323 av_log(NULL, AV_LOG_FATAL, "Option %s not found.\n", t->key);
6291d7e4
AK
1324 exit_program(1);
1325 }
1326}
1327
1328static void assert_codec_experimental(AVCodecContext *c, int encoder)
1329{
1330 const char *codec_string = encoder ? "encoder" : "decoder";
1331 AVCodec *codec;
1332 if (c->codec->capabilities & CODEC_CAP_EXPERIMENTAL &&
1333 c->strict_std_compliance > FF_COMPLIANCE_EXPERIMENTAL) {
f24facd3 1334 av_log(NULL, AV_LOG_FATAL, "%s '%s' is experimental and might produce bad "
6291d7e4
AK
1335 "results.\nAdd '-strict experimental' if you want to use it.\n",
1336 codec_string, c->codec->name);
1337 codec = encoder ? avcodec_find_encoder(c->codec->id) : avcodec_find_decoder(c->codec->id);
1338 if (!(codec->capabilities & CODEC_CAP_EXPERIMENTAL))
f24facd3 1339 av_log(NULL, AV_LOG_FATAL, "Or use the non experimental %s '%s'.\n",
6291d7e4
AK
1340 codec_string, codec->name);
1341 exit_program(1);
1342 }
1343}
1344
6291d7e4
AK
1345/**
1346 * Update the requested input sample format based on the output sample format.
1347 * This is currently only used to request float output from decoders which
1348 * support multiple sample formats, one of which is AV_SAMPLE_FMT_FLT.
1349 * Ideally this will be removed in the future when decoders do not do format
1350 * conversion and only output in their native format.
1351 */
1352static void update_sample_fmt(AVCodecContext *dec, AVCodec *dec_codec,
1353 AVCodecContext *enc)
1354{
1355 /* if sample formats match or a decoder sample format has already been
1356 requested, just return */
1357 if (enc->sample_fmt == dec->sample_fmt ||
1358 dec->request_sample_fmt > AV_SAMPLE_FMT_NONE)
1359 return;
1360
1361 /* if decoder supports more than one output format */
1362 if (dec_codec && dec_codec->sample_fmts &&
1363 dec_codec->sample_fmts[0] != AV_SAMPLE_FMT_NONE &&
1364 dec_codec->sample_fmts[1] != AV_SAMPLE_FMT_NONE) {
1365 const enum AVSampleFormat *p;
1366 int min_dec = -1, min_inc = -1;
1367
1368 /* find a matching sample format in the encoder */
1369 for (p = dec_codec->sample_fmts; *p != AV_SAMPLE_FMT_NONE; p++) {
1370 if (*p == enc->sample_fmt) {
1371 dec->request_sample_fmt = *p;
1372 return;
1373 } else if (*p > enc->sample_fmt) {
1374 min_inc = FFMIN(min_inc, *p - enc->sample_fmt);
1375 } else
1376 min_dec = FFMIN(min_dec, enc->sample_fmt - *p);
1377 }
1378
1379 /* if none match, provide the one that matches quality closest */
1380 dec->request_sample_fmt = min_inc > 0 ? enc->sample_fmt + min_inc :
1381 enc->sample_fmt - min_dec;
1382 }
1383}
1384
6291d7e4 1385static double
6e983902 1386get_sync_ipts(const OutputStream *ost, int64_t pts)
6291d7e4 1387{
2e215267 1388 OutputFile *of = output_files[ost->file_index];
6e983902 1389 return (double)(pts - of->start_time) / AV_TIME_BASE;
6291d7e4
AK
1390}
1391
f15f02c2 1392static void write_frame(AVFormatContext *s, AVPacket *pkt, OutputStream *ost)
7636c8c6 1393{
f15f02c2
AK
1394 AVBitStreamFilterContext *bsfc = ost->bitstream_filters;
1395 AVCodecContext *avctx = ost->st->codec;
6291d7e4
AK
1396 int ret;
1397
99932847
AK
1398 /*
1399 * Audio encoders may split the packets -- #frames in != #packets out.
1400 * But there is no reordering, so we can limit the number of output packets
1401 * by simply dropping them here.
1402 * Counting encoded video frames needs to be done separately because of
1403 * reordering, see do_video_out()
1404 */
1405 if (!(avctx->codec_type == AVMEDIA_TYPE_VIDEO && avctx->codec)) {
c9594fe0
JR
1406 if (ost->frame_number >= ost->max_frames) {
1407 av_free_packet(pkt);
99932847 1408 return;
c9594fe0 1409 }
99932847
AK
1410 ost->frame_number++;
1411 }
1412
7636c8c6
AD
1413 while (bsfc) {
1414 AVPacket new_pkt = *pkt;
1415 int a = av_bitstream_filter_filter(bsfc, avctx, NULL,
1416 &new_pkt.data, &new_pkt.size,
1417 pkt->data, pkt->size,
1418 pkt->flags & AV_PKT_FLAG_KEY);
1419 if (a > 0) {
6291d7e4 1420 av_free_packet(pkt);
7636c8c6
AD
1421 new_pkt.destruct = av_destruct_packet;
1422 } else if (a < 0) {
e3245b26
AK
1423 av_log(NULL, AV_LOG_ERROR, "%s failed for stream %d, codec %s",
1424 bsfc->filter->name, pkt->stream_index,
1425 avctx->codec ? avctx->codec->name : "copy");
6291d7e4
AK
1426 print_error("", a);
1427 if (exit_on_error)
1428 exit_program(1);
1429 }
7636c8c6 1430 *pkt = new_pkt;
6291d7e4 1431
7636c8c6 1432 bsfc = bsfc->next;
6291d7e4
AK
1433 }
1434
61a09968 1435 pkt->stream_index = ost->index;
7636c8c6
AD
1436 ret = av_interleaved_write_frame(s, pkt);
1437 if (ret < 0) {
6291d7e4
AK
1438 print_error("av_interleaved_write_frame()", ret);
1439 exit_program(1);
1440 }
1441}
1442
1270e12e
AK
1443static int check_recording_time(OutputStream *ost)
1444{
2e215267 1445 OutputFile *of = output_files[ost->file_index];
1270e12e
AK
1446
1447 if (of->recording_time != INT64_MAX &&
1448 av_compare_ts(ost->sync_opts - ost->first_pts, ost->st->codec->time_base, of->recording_time,
1449 AV_TIME_BASE_Q) >= 0) {
1450 ost->is_past_recording_time = 1;
1451 return 0;
1452 }
1453 return 1;
1454}
1455
369cb092
AK
1456static void do_audio_out(AVFormatContext *s, OutputStream *ost,
1457 AVFrame *frame)
ee458cb1
JR
1458{
1459 AVCodecContext *enc = ost->st->codec;
ee458cb1 1460 AVPacket pkt;
369cb092 1461 int got_packet = 0;
ee458cb1
JR
1462
1463 av_init_packet(&pkt);
1464 pkt.data = NULL;
1465 pkt.size = 0;
1466
369cb092
AK
1467 if (!check_recording_time(ost))
1468 return;
1270e12e 1469
369cb092 1470 if (frame->pts == AV_NOPTS_VALUE || audio_sync_method < 0)
9b9fc9ba 1471 frame->pts = ost->sync_opts;
369cb092 1472 ost->sync_opts = frame->pts + frame->nb_samples;
ee458cb1 1473
ee458cb1
JR
1474 if (avcodec_encode_audio2(enc, &pkt, frame, &got_packet) < 0) {
1475 av_log(NULL, AV_LOG_FATAL, "Audio encoding failed\n");
1476 exit_program(1);
1477 }
1478
1479 if (got_packet) {
ee458cb1
JR
1480 if (pkt.pts != AV_NOPTS_VALUE)
1481 pkt.pts = av_rescale_q(pkt.pts, enc->time_base, ost->st->time_base);
a75bc764
JR
1482 if (pkt.dts != AV_NOPTS_VALUE)
1483 pkt.dts = av_rescale_q(pkt.dts, enc->time_base, ost->st->time_base);
ee458cb1
JR
1484 if (pkt.duration > 0)
1485 pkt.duration = av_rescale_q(pkt.duration, enc->time_base, ost->st->time_base);
1486
1487 write_frame(s, &pkt, ost);
1488
1489 audio_size += pkt.size;
1490 }
6291d7e4
AK
1491}
1492
1493static void pre_process_video_frame(InputStream *ist, AVPicture *picture, void **bufp)
1494{
1495 AVCodecContext *dec;
1496 AVPicture *picture2;
1497 AVPicture picture_tmp;
1498 uint8_t *buf = 0;
1499
1500 dec = ist->st->codec;
1501
1502 /* deinterlace : must be done before any resize */
1503 if (do_deinterlace) {
1504 int size;
1505
1506 /* create temporary picture */
1507 size = avpicture_get_size(dec->pix_fmt, dec->width, dec->height);
7636c8c6 1508 buf = av_malloc(size);
6291d7e4
AK
1509 if (!buf)
1510 return;
1511
1512 picture2 = &picture_tmp;
1513 avpicture_fill(picture2, buf, dec->pix_fmt, dec->width, dec->height);
1514
7636c8c6 1515 if (avpicture_deinterlace(picture2, picture,
6291d7e4
AK
1516 dec->pix_fmt, dec->width, dec->height) < 0) {
1517 /* if error, do not deinterlace */
e3245b26 1518 av_log(NULL, AV_LOG_WARNING, "Deinterlacing failed\n");
6291d7e4
AK
1519 av_free(buf);
1520 buf = NULL;
1521 picture2 = picture;
1522 }
1523 } else {
1524 picture2 = picture;
1525 }
1526
1527 if (picture != picture2)
1528 *picture = *picture2;
1529 *bufp = buf;
1530}
1531
6291d7e4
AK
1532static void do_subtitle_out(AVFormatContext *s,
1533 OutputStream *ost,
1534 InputStream *ist,
1535 AVSubtitle *sub,
1536 int64_t pts)
1537{
1538 static uint8_t *subtitle_out = NULL;
1539 int subtitle_out_max_size = 1024 * 1024;
1540 int subtitle_out_size, nb, i;
1541 AVCodecContext *enc;
1542 AVPacket pkt;
1543
1544 if (pts == AV_NOPTS_VALUE) {
e3245b26 1545 av_log(NULL, AV_LOG_ERROR, "Subtitle packets must have a pts\n");
6291d7e4
AK
1546 if (exit_on_error)
1547 exit_program(1);
1548 return;
1549 }
1550
1551 enc = ost->st->codec;
1552
1553 if (!subtitle_out) {
1554 subtitle_out = av_malloc(subtitle_out_max_size);
1555 }
1556
1557 /* Note: DVB subtitle need one packet to draw them and one other
1558 packet to clear them */
1559 /* XXX: signal it in the codec context ? */
1560 if (enc->codec_id == CODEC_ID_DVB_SUBTITLE)
1561 nb = 2;
1562 else
1563 nb = 1;
1564
7636c8c6 1565 for (i = 0; i < nb; i++) {
1270e12e
AK
1566 ost->sync_opts = av_rescale_q(pts, ist->st->time_base, enc->time_base);
1567 if (!check_recording_time(ost))
1568 return;
1569
6291d7e4
AK
1570 sub->pts = av_rescale_q(pts, ist->st->time_base, AV_TIME_BASE_Q);
1571 // start_display_time is required to be 0
7636c8c6
AD
1572 sub->pts += av_rescale_q(sub->start_display_time, (AVRational){ 1, 1000 }, AV_TIME_BASE_Q);
1573 sub->end_display_time -= sub->start_display_time;
6291d7e4
AK
1574 sub->start_display_time = 0;
1575 subtitle_out_size = avcodec_encode_subtitle(enc, subtitle_out,
1576 subtitle_out_max_size, sub);
1577 if (subtitle_out_size < 0) {
e3245b26 1578 av_log(NULL, AV_LOG_FATAL, "Subtitle encoding failed\n");
6291d7e4
AK
1579 exit_program(1);
1580 }
1581
1582 av_init_packet(&pkt);
6291d7e4
AK
1583 pkt.data = subtitle_out;
1584 pkt.size = subtitle_out_size;
7636c8c6 1585 pkt.pts = av_rescale_q(sub->pts, AV_TIME_BASE_Q, ost->st->time_base);
6291d7e4
AK
1586 if (enc->codec_id == CODEC_ID_DVB_SUBTITLE) {
1587 /* XXX: the pts correction is handled here. Maybe handling
1588 it in the codec would be better */
1589 if (i == 0)
1590 pkt.pts += 90 * sub->start_display_time;
1591 else
1592 pkt.pts += 90 * sub->end_display_time;
1593 }
f15f02c2 1594 write_frame(s, &pkt, ost);
6291d7e4
AK
1595 }
1596}
1597
87ef060c
AC
1598static void do_video_out(AVFormatContext *s,
1599 OutputStream *ost,
87ef060c
AC
1600 AVFrame *in_picture,
1601 int *frame_size, float quality)
1602{
553735f5 1603 int nb_frames, i, ret, format_video_sync;
f593628e 1604 AVCodecContext *enc;
d43040e2 1605 double sync_ipts, delta;
87ef060c
AC
1606
1607 enc = ost->st->codec;
87ef060c 1608
6e983902 1609 sync_ipts = get_sync_ipts(ost, in_picture->pts) / av_q2d(enc->time_base);
d43040e2 1610 delta = sync_ipts - ost->sync_opts;
87ef060c
AC
1611
1612 /* by default, we output a single frame */
1613 nb_frames = 1;
1614
1615 *frame_size = 0;
1616
553735f5 1617 format_video_sync = video_sync_method;
e8c04f62
AK
1618 if (format_video_sync == VSYNC_AUTO)
1619 format_video_sync = (s->oformat->flags & AVFMT_NOTIMESTAMPS) ? VSYNC_PASSTHROUGH :
1620 (s->oformat->flags & AVFMT_VARIABLE_FPS) ? VSYNC_VFR : VSYNC_CFR;
553735f5 1621
d43040e2
AK
1622 switch (format_video_sync) {
1623 case VSYNC_CFR:
7636c8c6 1624 // FIXME set to 0.5 after we fix some dts/pts bugs like in avidec.c
d43040e2 1625 if (delta < -1.1)
87ef060c 1626 nb_frames = 0;
d43040e2
AK
1627 else if (delta > 1.1)
1628 nb_frames = lrintf(delta);
1629 break;
1630 case VSYNC_VFR:
1631 if (delta <= -0.6)
1632 nb_frames = 0;
1633 else if (delta > 0.6)
4f150068 1634 ost->sync_opts = lrint(sync_ipts);
d43040e2
AK
1635 break;
1636 case VSYNC_PASSTHROUGH:
4f150068 1637 ost->sync_opts = lrint(sync_ipts);
d43040e2
AK
1638 break;
1639 default:
1640 av_assert0(0);
1641 }
87ef060c 1642
96139b5e 1643 nb_frames = FFMIN(nb_frames, ost->max_frames - ost->frame_number);
d43040e2
AK
1644 if (nb_frames == 0) {
1645 nb_frames_drop++;
1646 av_log(NULL, AV_LOG_VERBOSE, "*** drop!\n");
87ef060c 1647 return;
d43040e2
AK
1648 } else if (nb_frames > 1) {
1649 nb_frames_dup += nb_frames - 1;
1650 av_log(NULL, AV_LOG_VERBOSE, "*** %d dup!\n", nb_frames - 1);
1651 }
87ef060c 1652
1270e12e
AK
1653 if (!ost->frame_number)
1654 ost->first_pts = ost->sync_opts;
1655
6291d7e4 1656 /* duplicates frame if needed */
7636c8c6 1657 for (i = 0; i < nb_frames; i++) {
6291d7e4
AK
1658 AVPacket pkt;
1659 av_init_packet(&pkt);
8e37038a
AK
1660 pkt.data = NULL;
1661 pkt.size = 0;
6291d7e4 1662
1270e12e
AK
1663 if (!check_recording_time(ost))
1664 return;
1665
150ddbc1
MR
1666 if (s->oformat->flags & AVFMT_RAWPICTURE &&
1667 enc->codec->id == CODEC_ID_RAWVIDEO) {
6291d7e4 1668 /* raw pictures are written as AVPicture structure to
bb337b4f 1669 avoid any copies. We support temporarily the older
6291d7e4 1670 method. */
f593628e
AC
1671 enc->coded_frame->interlaced_frame = in_picture->interlaced_frame;
1672 enc->coded_frame->top_field_first = in_picture->top_field_first;
4648fe63 1673 pkt.data = (uint8_t *)in_picture;
7636c8c6
AD
1674 pkt.size = sizeof(AVPicture);
1675 pkt.pts = av_rescale_q(ost->sync_opts, enc->time_base, ost->st->time_base);
6291d7e4
AK
1676 pkt.flags |= AV_PKT_FLAG_KEY;
1677
f15f02c2 1678 write_frame(s, &pkt, ost);
6291d7e4 1679 } else {
8e37038a 1680 int got_packet;
6291d7e4
AK
1681 AVFrame big_picture;
1682
4648fe63 1683 big_picture = *in_picture;
6291d7e4
AK
1684 /* better than nothing: use input picture interlaced
1685 settings */
1686 big_picture.interlaced_frame = in_picture->interlaced_frame;
1687 if (ost->st->codec->flags & (CODEC_FLAG_INTERLACED_DCT|CODEC_FLAG_INTERLACED_ME)) {
828e0bcb 1688 if (ost->top_field_first == -1)
6291d7e4
AK
1689 big_picture.top_field_first = in_picture->top_field_first;
1690 else
828e0bcb 1691 big_picture.top_field_first = !!ost->top_field_first;
6291d7e4
AK
1692 }
1693
f4ad238c 1694 /* handles same_quant here. This is not correct because it may
6291d7e4
AK
1695 not be a global option */
1696 big_picture.quality = quality;
d242d80e 1697 if (!enc->me_threshold)
6291d7e4 1698 big_picture.pict_type = 0;
7636c8c6 1699 big_picture.pts = ost->sync_opts;
6291d7e4
AK
1700 if (ost->forced_kf_index < ost->forced_kf_count &&
1701 big_picture.pts >= ost->forced_kf_pts[ost->forced_kf_index]) {
1702 big_picture.pict_type = AV_PICTURE_TYPE_I;
1703 ost->forced_kf_index++;
1704 }
8e37038a 1705 ret = avcodec_encode_video2(enc, &pkt, &big_picture, &got_packet);
6291d7e4 1706 if (ret < 0) {
e3245b26 1707 av_log(NULL, AV_LOG_FATAL, "Video encoding failed\n");
6291d7e4
AK
1708 exit_program(1);
1709 }
1710
8e37038a
AK
1711 if (got_packet) {
1712 if (pkt.pts != AV_NOPTS_VALUE)
1713 pkt.pts = av_rescale_q(pkt.pts, enc->time_base, ost->st->time_base);
1714 if (pkt.dts != AV_NOPTS_VALUE)
1715 pkt.dts = av_rescale_q(pkt.dts, enc->time_base, ost->st->time_base);
6291d7e4 1716
f15f02c2 1717 write_frame(s, &pkt, ost);
39da3b22
AK
1718 *frame_size = pkt.size;
1719 video_size += pkt.size;
324fbadf 1720
6291d7e4
AK
1721 /* if two pass, output log */
1722 if (ost->logfile && enc->stats_out) {
1723 fprintf(ost->logfile, "%s", enc->stats_out);
1724 }
1725 }
1726 }
1727 ost->sync_opts++;
99932847
AK
1728 /*
1729 * For video, number of frames in == number of packets out.
1730 * But there may be reordering, so we can't throw away frames on encoder
1731 * flush, we need to limit them here, before they go into encoder.
1732 */
1733 ost->frame_number++;
6291d7e4
AK
1734 }
1735}
1736
7636c8c6
AD
1737static double psnr(double d)
1738{
1739 return -10.0 * log(d) / log(10.0);
6291d7e4
AK
1740}
1741
1742static void do_video_stats(AVFormatContext *os, OutputStream *ost,
1743 int frame_size)
1744{
1745 AVCodecContext *enc;
1746 int frame_number;
1747 double ti1, bitrate, avg_bitrate;
1748
1749 /* this is executed just the first time do_video_stats is called */
1750 if (!vstats_file) {
1751 vstats_file = fopen(vstats_filename, "w");
1752 if (!vstats_file) {
1753 perror("fopen");
1754 exit_program(1);
1755 }
1756 }
1757
1758 enc = ost->st->codec;
1759 if (enc->codec_type == AVMEDIA_TYPE_VIDEO) {
1760 frame_number = ost->frame_number;
7636c8c6 1761 fprintf(vstats_file, "frame= %5d q= %2.1f ", frame_number, enc->coded_frame->quality / (float)FF_QP2LAMBDA);
6291d7e4 1762 if (enc->flags&CODEC_FLAG_PSNR)
7636c8c6 1763 fprintf(vstats_file, "PSNR= %6.2f ", psnr(enc->coded_frame->error[0] / (enc->width * enc->height * 255.0 * 255.0)));
6291d7e4
AK
1764
1765 fprintf(vstats_file,"f_size= %6d ", frame_size);
1766 /* compute pts value */
1767 ti1 = ost->sync_opts * av_q2d(enc->time_base);
1768 if (ti1 < 0.01)
1769 ti1 = 0.01;
1770
7636c8c6 1771 bitrate = (frame_size * 8) / av_q2d(enc->time_base) / 1000.0;
6291d7e4
AK
1772 avg_bitrate = (double)(video_size * 8) / ti1 / 1000.0;
1773 fprintf(vstats_file, "s_size= %8.0fkB time= %0.3f br= %7.1fkbits/s avg_br= %7.1fkbits/s ",
7636c8c6 1774 (double)video_size / 1024, ti1, bitrate, avg_bitrate);
6291d7e4
AK
1775 fprintf(vstats_file, "type= %c\n", av_get_picture_type_char(enc->coded_frame->pict_type));
1776 }
1777}
1778
560f7774
AK
1779/* check for new output on any of the filtergraphs */
1780static int poll_filters(void)
1781{
1782 AVFilterBufferRef *picref;
1783 AVFrame *filtered_frame = NULL;
ac712309 1784 int i, frame_size;
560f7774
AK
1785
1786 for (i = 0; i < nb_output_streams; i++) {
1787 OutputStream *ost = output_streams[i];
1788 OutputFile *of = output_files[ost->file_index];
369cb092 1789 int ret = 0;
560f7774
AK
1790
1791 if (!ost->filter || ost->is_past_recording_time)
1792 continue;
1793
1794 if (!ost->filtered_frame && !(ost->filtered_frame = avcodec_alloc_frame())) {
1795 return AVERROR(ENOMEM);
1796 } else
1797 avcodec_get_frame_defaults(ost->filtered_frame);
1798 filtered_frame = ost->filtered_frame;
1799
369cb092
AK
1800 while (ret >= 0) {
1801 if (ost->enc->type == AVMEDIA_TYPE_AUDIO &&
1802 !(ost->enc->capabilities & CODEC_CAP_VARIABLE_FRAME_SIZE))
1803 ret = av_buffersink_read_samples(ost->filter->filter, &picref,
1804 ost->st->codec->frame_size);
1805 else
1806 ret = av_buffersink_read(ost->filter->filter, &picref);
1807
1808 if (ret < 0)
1809 break;
1810
ac712309 1811 avfilter_copy_buf_props(filtered_frame, picref);
369cb092
AK
1812 if (ost->enc->type == AVMEDIA_TYPE_VIDEO)
1813 filtered_frame->pts = av_rescale_q(picref->pts,
1814 ost->filter->filter->inputs[0]->time_base,
1815 AV_TIME_BASE_Q);
1816 else if (picref->pts != AV_NOPTS_VALUE)
1817 filtered_frame->pts = av_rescale_q(picref->pts,
1818 ost->filter->filter->inputs[0]->time_base,
1819 ost->st->codec->time_base) -
1820 av_rescale_q(of->start_time,
1821 AV_TIME_BASE_Q,
1822 ost->st->codec->time_base);
560f7774 1823
01e98b1b
AK
1824 if (of->start_time && filtered_frame->pts < of->start_time) {
1825 avfilter_unref_buffer(picref);
1826 continue;
1827 }
560f7774
AK
1828
1829 switch (ost->filter->filter->inputs[0]->type) {
1830 case AVMEDIA_TYPE_VIDEO:
1831 if (!ost->frame_aspect_ratio)
1832 ost->st->codec->sample_aspect_ratio = picref->video->pixel_aspect;
1833
1834 do_video_out(of->ctx, ost, filtered_frame, &frame_size,
1835 same_quant ? ost->last_quality :
1836 ost->st->codec->global_quality);
1837 if (vstats_filename && frame_size)
1838 do_video_stats(of->ctx, ost, frame_size);
1839 break;
369cb092
AK
1840 case AVMEDIA_TYPE_AUDIO:
1841 do_audio_out(of->ctx, ost, filtered_frame);
1842 break;
560f7774 1843 default:
369cb092 1844 // TODO support subtitle filters
560f7774
AK
1845 av_assert0(0);
1846 }
1847
1848 avfilter_unref_buffer(picref);
1849 }
1850 }
1851 return 0;
1852}
1853
ea9367e9 1854static void print_report(int is_last_report, int64_t timer_start)
6291d7e4
AK
1855{
1856 char buf[1024];
1857 OutputStream *ost;
1858 AVFormatContext *oc;
1859 int64_t total_size;
1860 AVCodecContext *enc;
1861 int frame_number, vid, i;
1862 double bitrate, ti1, pts;
1863 static int64_t last_time = -1;
1864 static int qp_histogram[52];
1865
3460dd8a
AK
1866 if (!print_stats && !is_last_report)
1867 return;
1868
6291d7e4
AK
1869 if (!is_last_report) {
1870 int64_t cur_time;
1871 /* display the report every 0.5 seconds */
1872 cur_time = av_gettime();
1873 if (last_time == -1) {
1874 last_time = cur_time;
1875 return;
1876 }
1877 if ((cur_time - last_time) < 500000)
1878 return;
1879 last_time = cur_time;
1880 }
1881
1882
2e215267 1883 oc = output_files[0]->ctx;
6291d7e4
AK
1884
1885 total_size = avio_size(oc->pb);
7636c8c6
AD
1886 if (total_size < 0) // FIXME improve avio_size() so it works with non seekable output too
1887 total_size = avio_tell(oc->pb);
6291d7e4
AK
1888
1889 buf[0] = '\0';
1890 ti1 = 1e10;
1891 vid = 0;
ea9367e9 1892 for (i = 0; i < nb_output_streams; i++) {
6291d7e4 1893 float q = -1;
2e215267 1894 ost = output_streams[i];
6291d7e4 1895 enc = ost->st->codec;
3d813e4c 1896 if (!ost->stream_copy && enc->coded_frame)
7636c8c6 1897 q = enc->coded_frame->quality / (float)FF_QP2LAMBDA;
6291d7e4
AK
1898 if (vid && enc->codec_type == AVMEDIA_TYPE_VIDEO) {
1899 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "q=%2.1f ", q);
1900 }
1901 if (!vid && enc->codec_type == AVMEDIA_TYPE_VIDEO) {
7636c8c6 1902 float t = (av_gettime() - timer_start) / 1000000.0;
6291d7e4
AK
1903
1904 frame_number = ost->frame_number;
1905 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "frame=%5d fps=%3d q=%3.1f ",
7636c8c6
AD
1906 frame_number, (t > 1) ? (int)(frame_number / t + 0.5) : 0, q);
1907 if (is_last_report)
6291d7e4 1908 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "L");
7636c8c6 1909 if (qp_hist) {
6291d7e4
AK
1910 int j;
1911 int qp = lrintf(q);
7636c8c6 1912 if (qp >= 0 && qp < FF_ARRAY_ELEMS(qp_histogram))
6291d7e4 1913 qp_histogram[qp]++;
7636c8c6
AD
1914 for (j = 0; j < 32; j++)
1915 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "%X", (int)lrintf(log(qp_histogram[j] + 1) / log(2)));
6291d7e4 1916 }
7636c8c6 1917 if (enc->flags&CODEC_FLAG_PSNR) {
6291d7e4 1918 int j;
7636c8c6
AD
1919 double error, error_sum = 0;
1920 double scale, scale_sum = 0;
1921 char type[3] = { 'Y','U','V' };
6291d7e4 1922 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "PSNR=");
7636c8c6
AD
1923 for (j = 0; j < 3; j++) {
1924 if (is_last_report) {
1925 error = enc->error[j];
1926 scale = enc->width * enc->height * 255.0 * 255.0 * frame_number;
1927 } else {
1928 error = enc->coded_frame->error[j];
1929 scale = enc->width * enc->height * 255.0 * 255.0;
6291d7e4 1930 }
7636c8c6
AD
1931 if (j)
1932 scale /= 4;
6291d7e4
AK
1933 error_sum += error;
1934 scale_sum += scale;
7636c8c6 1935 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "%c:%2.2f ", type[j], psnr(error / scale));
6291d7e4 1936 }
7636c8c6 1937 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "*:%2.2f ", psnr(error_sum / scale_sum));
6291d7e4
AK
1938 }
1939 vid = 1;
1940 }
1941 /* compute min output value */
1942 pts = (double)ost->st->pts.val * av_q2d(ost->st->time_base);
1943 if ((pts < ti1) && (pts > 0))
1944 ti1 = pts;
1945 }
1946 if (ti1 < 0.01)
1947 ti1 = 0.01;
1948
e3245b26 1949 bitrate = (double)(total_size * 8) / ti1 / 1000.0;
6291d7e4 1950
e3245b26 1951 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
6291d7e4
AK
1952 "size=%8.0fkB time=%0.2f bitrate=%6.1fkbits/s",
1953 (double)total_size / 1024, ti1, bitrate);
1954
e3245b26
AK
1955 if (nb_frames_dup || nb_frames_drop)
1956 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), " dup=%d drop=%d",
1957 nb_frames_dup, nb_frames_drop);
6291d7e4 1958
f5646a32 1959 av_log(NULL, AV_LOG_INFO, "%s \r", buf);
6291d7e4 1960
e3245b26 1961 fflush(stderr);
6291d7e4 1962
e3245b26 1963 if (is_last_report) {
6291d7e4 1964 int64_t raw= audio_size + video_size + extra_size;
e3245b26
AK
1965 av_log(NULL, AV_LOG_INFO, "\n");
1966 av_log(NULL, AV_LOG_INFO, "video:%1.0fkB audio:%1.0fkB global headers:%1.0fkB muxing overhead %f%%\n",
7636c8c6
AD
1967 video_size / 1024.0,
1968 audio_size / 1024.0,
1969 extra_size / 1024.0,
1970 100.0 * (total_size - raw) / raw
6291d7e4
AK
1971 );
1972 }
1973}
1974
ea9367e9 1975static void flush_encoders(void)
4a4ce2e7
AK
1976{
1977 int i, ret;
1978
ea9367e9 1979 for (i = 0; i < nb_output_streams; i++) {
2e215267 1980 OutputStream *ost = output_streams[i];
6f1c66d5 1981 AVCodecContext *enc = ost->st->codec;
2e215267 1982 AVFormatContext *os = output_files[ost->file_index]->ctx;
ee458cb1 1983 int stop_encoding = 0;
6f1c66d5 1984
b62b5cb6 1985 if (!ost->encoding_needed)
6f1c66d5
AK
1986 continue;
1987
7636c8c6 1988 if (ost->st->codec->codec_type == AVMEDIA_TYPE_AUDIO && enc->frame_size <= 1)
6f1c66d5 1989 continue;
150ddbc1 1990 if (ost->st->codec->codec_type == AVMEDIA_TYPE_VIDEO && (os->oformat->flags & AVFMT_RAWPICTURE) && enc->codec->id == CODEC_ID_RAWVIDEO)
6f1c66d5
AK
1991 continue;
1992
7636c8c6 1993 for (;;) {
369cb092
AK
1994 int (*encode)(AVCodecContext*, AVPacket*, const AVFrame*, int*) = NULL;
1995 const char *desc;
1996 int64_t *size;
6f1c66d5
AK
1997
1998 switch (ost->st->codec->codec_type) {
1999 case AVMEDIA_TYPE_AUDIO:
369cb092
AK
2000 encode = avcodec_encode_audio2;
2001 desc = "Audio";
2002 size = &audio_size;
6f1c66d5
AK
2003 break;
2004 case AVMEDIA_TYPE_VIDEO:
369cb092
AK
2005 encode = avcodec_encode_video2;
2006 desc = "Video";
2007 size = &video_size;
2008 break;
2009 default:
2010 stop_encoding = 1;
2011 }
2012
2013 if (encode) {
2014 AVPacket pkt;
2015 int got_packet;
2016 av_init_packet(&pkt);
2017 pkt.data = NULL;
2018 pkt.size = 0;
2019
2020 ret = encode(enc, &pkt, NULL, &got_packet);
6f1c66d5 2021 if (ret < 0) {
369cb092 2022 av_log(NULL, AV_LOG_FATAL, "%s encoding failed\n", desc);
6f1c66d5
AK
2023 exit_program(1);
2024 }
369cb092 2025 *size += ret;
6f1c66d5
AK
2026 if (ost->logfile && enc->stats_out) {
2027 fprintf(ost->logfile, "%s", enc->stats_out);
2028 }
8e37038a 2029 if (!got_packet) {
ee458cb1
JR
2030 stop_encoding = 1;
2031 break;
2032 }
8e37038a
AK
2033 if (pkt.pts != AV_NOPTS_VALUE)
2034 pkt.pts = av_rescale_q(pkt.pts, enc->time_base, ost->st->time_base);
2035 if (pkt.dts != AV_NOPTS_VALUE)
2036 pkt.dts = av_rescale_q(pkt.dts, enc->time_base, ost->st->time_base);
ee458cb1 2037 write_frame(os, &pkt, ost);
4a4ce2e7 2038 }
369cb092 2039
ee458cb1 2040 if (stop_encoding)
6f1c66d5 2041 break;
4a4ce2e7
AK
2042 }
2043 }
2044}
2045
7204ec1a
AK
2046/*
2047 * Check whether a packet from ist should be written into ost at this time
2048 */
2049static int check_output_constraints(InputStream *ist, OutputStream *ost)
2050{
2e215267
AK
2051 OutputFile *of = output_files[ost->file_index];
2052 int ist_index = input_files[ist->file_index]->ist_index + ist->st->index;
7204ec1a
AK
2053
2054 if (ost->source_index != ist_index)
2055 return 0;
2056
23576b3f 2057 if (of->start_time && ist->last_dts < of->start_time)
7204ec1a
AK
2058 return 0;
2059
7204ec1a
AK
2060 return 1;
2061}
2062
2063static void do_streamcopy(InputStream *ist, OutputStream *ost, const AVPacket *pkt)
2064{
2e215267 2065 OutputFile *of = output_files[ost->file_index];
7204ec1a
AK
2066 int64_t ost_tb_start_time = av_rescale_q(of->start_time, AV_TIME_BASE_Q, ost->st->time_base);
2067 AVPacket opkt;
2068
2069 av_init_packet(&opkt);
2070
2071 if ((!ost->frame_number && !(pkt->flags & AV_PKT_FLAG_KEY)) &&
2072 !ost->copy_initial_nonkeyframes)
2073 return;
2074
1270e12e 2075 if (of->recording_time != INT64_MAX &&
23576b3f 2076 ist->last_dts >= of->recording_time + of->start_time) {
1270e12e
AK
2077 ost->is_past_recording_time = 1;
2078 return;
2079 }
2080
7204ec1a
AK
2081 /* force the input stream PTS */
2082 if (ost->st->codec->codec_type == AVMEDIA_TYPE_AUDIO)
2083 audio_size += pkt->size;
2084 else if (ost->st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
2085 video_size += pkt->size;
2086 ost->sync_opts++;
2087 }
2088
7204ec1a
AK
2089 if (pkt->pts != AV_NOPTS_VALUE)
2090 opkt.pts = av_rescale_q(pkt->pts, ist->st->time_base, ost->st->time_base) - ost_tb_start_time;
2091 else
2092 opkt.pts = AV_NOPTS_VALUE;
2093
2094 if (pkt->dts == AV_NOPTS_VALUE)
23576b3f 2095 opkt.dts = av_rescale_q(ist->last_dts, AV_TIME_BASE_Q, ost->st->time_base);
7204ec1a
AK
2096 else
2097 opkt.dts = av_rescale_q(pkt->dts, ist->st->time_base, ost->st->time_base);
2098 opkt.dts -= ost_tb_start_time;
2099
2100 opkt.duration = av_rescale_q(pkt->duration, ist->st->time_base, ost->st->time_base);
2101 opkt.flags = pkt->flags;
2102
7636c8c6
AD
2103 // FIXME remove the following 2 lines they shall be replaced by the bitstream filters
2104 if ( ost->st->codec->codec_id != CODEC_ID_H264
7204ec1a
AK
2105 && ost->st->codec->codec_id != CODEC_ID_MPEG1VIDEO
2106 && ost->st->codec->codec_id != CODEC_ID_MPEG2VIDEO
ae5a9355 2107 && ost->st->codec->codec_id != CODEC_ID_VC1
7204ec1a
AK
2108 ) {
2109 if (av_parser_change(ist->st->parser, ost->st->codec, &opkt.data, &opkt.size, pkt->data, pkt->size, pkt->flags & AV_PKT_FLAG_KEY))
2110 opkt.destruct = av_destruct_packet;
2111 } else {
2112 opkt.data = pkt->data;
2113 opkt.size = pkt->size;
2114 }
2115
f15f02c2 2116 write_frame(of->ctx, &opkt, ost);
7204ec1a 2117 ost->st->codec->frame_number++;
7204ec1a
AK
2118 av_free_packet(&opkt);
2119}
2120
2a651b71
AK
2121static void rate_emu_sleep(InputStream *ist)
2122{
2e215267 2123 if (input_files[ist->file_index]->rate_emu) {
23576b3f 2124 int64_t pts = av_rescale(ist->last_dts, 1000000, AV_TIME_BASE);
2a651b71
AK
2125 int64_t now = av_gettime() - ist->start;
2126 if (pts > now)
2127 usleep(pts - now);
2128 }
2129}
2130
369cb092
AK
2131static int guess_input_channel_layout(InputStream *ist)
2132{
2133 AVCodecContext *dec = ist->st->codec;
2134
2135 if (!dec->channel_layout) {
2136 char layout_name[256];
2137
2138 dec->channel_layout = av_get_default_channel_layout(dec->channels);
2139 if (!dec->channel_layout)
2140 return 0;
2141 av_get_channel_layout_string(layout_name, sizeof(layout_name),
2142 dec->channels, dec->channel_layout);
2143 av_log(NULL, AV_LOG_WARNING, "Guessed Channel Layout for Input Stream "
2144 "#%d.%d : %s\n", ist->file_index, ist->st->index, layout_name);
2145 }
2146 return 1;
2147}
2148
ded28ba3
AK
2149static int transcode_audio(InputStream *ist, AVPacket *pkt, int *got_output)
2150{
d1241ff3
JR
2151 AVFrame *decoded_frame;
2152 AVCodecContext *avctx = ist->st->codec;
ded28ba3 2153 int bps = av_get_bytes_per_sample(ist->st->codec->sample_fmt);
369cb092 2154 int i, ret, resample_changed;
ded28ba3 2155
9179f27c 2156 if (!ist->decoded_frame && !(ist->decoded_frame = avcodec_alloc_frame()))
d1241ff3 2157 return AVERROR(ENOMEM);
9179f27c
JR
2158 else
2159 avcodec_get_frame_defaults(ist->decoded_frame);
2160 decoded_frame = ist->decoded_frame;
ded28ba3 2161
d1241ff3
JR
2162 ret = avcodec_decode_audio4(avctx, decoded_frame, got_output, pkt);
2163 if (ret < 0) {
ded28ba3 2164 return ret;
d1241ff3 2165 }
ded28ba3 2166
ded28ba3
AK
2167 if (!*got_output) {
2168 /* no audio frame */
369cb092
AK
2169 if (!pkt->size)
2170 for (i = 0; i < ist->nb_filters; i++)
2171 av_buffersrc_buffer(ist->filters[i]->filter, NULL);
af8ad892 2172 return ret;
ded28ba3
AK
2173 }
2174
d1241ff3
JR
2175 /* if the decoder provides a pts, use it instead of the last packet pts.
2176 the decoder could be delaying output by a packet or more. */
2177 if (decoded_frame->pts != AV_NOPTS_VALUE)
3101bb66 2178 ist->next_dts = decoded_frame->pts;
369cb092
AK
2179 else if (pkt->pts != AV_NOPTS_VALUE) {
2180 decoded_frame->pts = pkt->pts;
2181 pkt->pts = AV_NOPTS_VALUE;
2182 }
ded28ba3
AK
2183
2184 // preprocess audio (volume)
2185 if (audio_volume != 256) {
d1241ff3
JR
2186 int decoded_data_size = decoded_frame->nb_samples * avctx->channels * bps;
2187 void *samples = decoded_frame->data[0];
2188 switch (avctx->sample_fmt) {
ded28ba3
AK
2189 case AV_SAMPLE_FMT_U8:
2190 {
2191 uint8_t *volp = samples;
2192 for (i = 0; i < (decoded_data_size / sizeof(*volp)); i++) {
2193 int v = (((*volp - 128) * audio_volume + 128) >> 8) + 128;
2194 *volp++ = av_clip_uint8(v);
2195 }
2196 break;
2197 }
2198 case AV_SAMPLE_FMT_S16:
2199 {
2200 int16_t *volp = samples;
2201 for (i = 0; i < (decoded_data_size / sizeof(*volp)); i++) {
2202 int v = ((*volp) * audio_volume + 128) >> 8;
2203 *volp++ = av_clip_int16(v);
2204 }
2205 break;
2206 }
2207 case AV_SAMPLE_FMT_S32:
2208 {
2209 int32_t *volp = samples;
2210 for (i = 0; i < (decoded_data_size / sizeof(*volp)); i++) {
2211 int64_t v = (((int64_t)*volp * audio_volume + 128) >> 8);
2212 *volp++ = av_clipl_int32(v);
2213 }
2214 break;
2215 }
2216 case AV_SAMPLE_FMT_FLT:
2217 {
2218 float *volp = samples;
2219 float scale = audio_volume / 256.f;
2220 for (i = 0; i < (decoded_data_size / sizeof(*volp)); i++) {
2221 *volp++ *= scale;
2222 }
2223 break;
2224 }
2225 case AV_SAMPLE_FMT_DBL:
2226 {
2227 double *volp = samples;
2228 double scale = audio_volume / 256.;
2229 for (i = 0; i < (decoded_data_size / sizeof(*volp)); i++) {
2230 *volp++ *= scale;
2231 }
2232 break;
2233 }
2234 default:
2235 av_log(NULL, AV_LOG_FATAL,
2236 "Audio volume adjustment on sample format %s is not supported.\n",
2237 av_get_sample_fmt_name(ist->st->codec->sample_fmt));
2238 exit_program(1);
2239 }
2240 }
2241
2242 rate_emu_sleep(ist);
2243
369cb092
AK
2244 resample_changed = ist->resample_sample_fmt != decoded_frame->format ||
2245 ist->resample_channels != avctx->channels ||
2246 ist->resample_channel_layout != decoded_frame->channel_layout ||
2247 ist->resample_sample_rate != decoded_frame->sample_rate;
2248 if (resample_changed) {
2249 char layout1[64], layout2[64];
ded28ba3 2250
369cb092
AK
2251 if (!guess_input_channel_layout(ist)) {
2252 av_log(NULL, AV_LOG_FATAL, "Unable to find default channel "
2253 "layout for Input Stream #%d.%d\n", ist->file_index,
2254 ist->st->index);
2255 exit_program(1);
2256 }
2257 decoded_frame->channel_layout = avctx->channel_layout;
2258
2259 av_get_channel_layout_string(layout1, sizeof(layout1), ist->resample_channels,
2260 ist->resample_channel_layout);
2261 av_get_channel_layout_string(layout2, sizeof(layout2), avctx->channels,
2262 decoded_frame->channel_layout);
2263
2264 av_log(NULL, AV_LOG_INFO,
2265 "Input stream #%d:%d frame changed from rate:%d fmt:%s ch:%d chl:%s to rate:%d fmt:%s ch:%d chl:%s\n",
2266 ist->file_index, ist->st->index,
2267 ist->resample_sample_rate, av_get_sample_fmt_name(ist->resample_sample_fmt),
2268 ist->resample_channels, layout1,
2269 decoded_frame->sample_rate, av_get_sample_fmt_name(decoded_frame->format),
2270 avctx->channels, layout2);
2271
2272 ist->resample_sample_fmt = decoded_frame->format;
2273 ist->resample_sample_rate = decoded_frame->sample_rate;
2274 ist->resample_channel_layout = decoded_frame->channel_layout;
2275 ist->resample_channels = avctx->channels;
2276
2277 for (i = 0; i < nb_filtergraphs; i++)
2278 if (ist_in_filtergraph(filtergraphs[i], ist) &&
2279 configure_filtergraph(filtergraphs[i]) < 0) {
2280 av_log(NULL, AV_LOG_FATAL, "Error reinitializing filters!\n");
2281 exit_program(1);
2282 }
ded28ba3 2283 }
110d2af2 2284
369cb092
AK
2285 for (i = 0; i < ist->nb_filters; i++)
2286 av_buffersrc_write_frame(ist->filters[i]->filter, decoded_frame);
2287
af8ad892 2288 return ret;
ded28ba3
AK
2289}
2290
45d4b66f
AK
2291static int transcode_video(InputStream *ist, AVPacket *pkt, int *got_output, int64_t *pkt_pts)
2292{
560f7774 2293 AVFrame *decoded_frame;
45d4b66f 2294 void *buffer_to_free = NULL;
e77c8662 2295 int i, ret = 0, resample_changed;
45d4b66f 2296 float quality;
45d4b66f 2297
9179f27c 2298 if (!ist->decoded_frame && !(ist->decoded_frame = avcodec_alloc_frame()))
45d4b66f 2299 return AVERROR(ENOMEM);
9179f27c
JR
2300 else
2301 avcodec_get_frame_defaults(ist->decoded_frame);
2302 decoded_frame = ist->decoded_frame;
45d4b66f 2303 pkt->pts = *pkt_pts;
23576b3f 2304 pkt->dts = ist->last_dts;
45d4b66f
AK
2305 *pkt_pts = AV_NOPTS_VALUE;
2306
2307 ret = avcodec_decode_video2(ist->st->codec,
2308 decoded_frame, got_output, pkt);
2309 if (ret < 0)
9179f27c 2310 return ret;
45d4b66f
AK
2311
2312 quality = same_quant ? decoded_frame->quality : 0;
2313 if (!*got_output) {
2314 /* no picture yet */
89605e4a
AK
2315 if (!pkt->size)
2316 for (i = 0; i < ist->nb_filters; i++)
2317 av_buffersrc_buffer(ist->filters[i]->filter, NULL);
af8ad892 2318 return ret;
45d4b66f 2319 }
b34856a1
AK
2320 decoded_frame->pts = guess_correct_pts(&ist->pts_ctx, decoded_frame->pkt_pts,
2321 decoded_frame->pkt_dts);
45d4b66f
AK
2322 pkt->size = 0;
2323 pre_process_video_frame(ist, (AVPicture *)decoded_frame, &buffer_to_free);
2324
2325 rate_emu_sleep(ist);
2326
695ec04e
AK
2327 if (ist->st->sample_aspect_ratio.num)
2328 decoded_frame->sample_aspect_ratio = ist->st->sample_aspect_ratio;
2329
e77c8662
AK
2330 resample_changed = ist->resample_width != decoded_frame->width ||
2331 ist->resample_height != decoded_frame->height ||
2332 ist->resample_pix_fmt != decoded_frame->format;
2333 if (resample_changed) {
2334 av_log(NULL, AV_LOG_INFO,
2335 "Input stream #%d:%d frame changed from size:%dx%d fmt:%s to size:%dx%d fmt:%s\n",
2336 ist->file_index, ist->st->index,
2337 ist->resample_width, ist->resample_height, av_get_pix_fmt_name(ist->resample_pix_fmt),
2338 decoded_frame->width, decoded_frame->height, av_get_pix_fmt_name(decoded_frame->format));
2339
2340 ist->resample_width = decoded_frame->width;
2341 ist->resample_height = decoded_frame->height;
2342 ist->resample_pix_fmt = decoded_frame->format;
e77c8662 2343
3b266da3
AK
2344 for (i = 0; i < nb_filtergraphs; i++)
2345 if (ist_in_filtergraph(filtergraphs[i], ist) &&
2346 configure_filtergraph(filtergraphs[i]) < 0) {
ac646076
AK
2347 av_log(NULL, AV_LOG_FATAL, "Error reinitializing filters!\n");
2348 exit_program(1);
3b266da3
AK
2349 }
2350 }
ac646076 2351
3b266da3 2352 for (i = 0; i < ist->nb_filters; i++) {
560f7774
AK
2353 // XXX what an ugly hack
2354 if (ist->filters[i]->graph->nb_outputs == 1)
2355 ist->filters[i]->graph->outputs[0]->ost->last_quality = quality;
2356
04a14d4d
AK
2357 if (ist->st->codec->codec->capabilities & CODEC_CAP_DR1) {
2358 FrameBuffer *buf = decoded_frame->opaque;
2359 AVFilterBufferRef *fb = avfilter_get_video_buffer_ref_from_arrays(
2360 decoded_frame->data, decoded_frame->linesize,
2361 AV_PERM_READ | AV_PERM_PRESERVE,
2362 ist->st->codec->width, ist->st->codec->height,
2363 ist->st->codec->pix_fmt);
2364
2365 avfilter_copy_frame_props(fb, decoded_frame);
04a14d4d
AK
2366 fb->buf->priv = buf;
2367 fb->buf->free = filter_release_buffer;
2368
2369 buf->refcount++;
560f7774 2370 av_buffersrc_buffer(ist->filters[i]->filter, fb);
04a14d4d 2371 } else
720c6b78 2372 av_buffersrc_write_frame(ist->filters[i]->filter, decoded_frame);
45d4b66f
AK
2373 }
2374
45d4b66f 2375 av_free(buffer_to_free);
45d4b66f
AK
2376 return ret;
2377}
2378
9595234c
AK
2379static int transcode_subtitles(InputStream *ist, AVPacket *pkt, int *got_output)
2380{
2381 AVSubtitle subtitle;
2382 int i, ret = avcodec_decode_subtitle2(ist->st->codec,
2383 &subtitle, got_output, pkt);
2384 if (ret < 0)
2385 return ret;
2386 if (!*got_output)
af8ad892 2387 return ret;
9595234c
AK
2388
2389 rate_emu_sleep(ist);
2390
2391 for (i = 0; i < nb_output_streams; i++) {
2e215267 2392 OutputStream *ost = output_streams[i];
9595234c
AK
2393
2394 if (!check_output_constraints(ist, ost) || !ost->encoding_needed)
2395 continue;
2396
2e215267 2397 do_subtitle_out(output_files[ost->file_index]->ctx, ost, ist, &subtitle, pkt->pts);
9595234c
AK
2398 }
2399
2400 avsubtitle_free(&subtitle);
af8ad892 2401 return ret;
9595234c
AK
2402}
2403
6291d7e4 2404/* pkt = NULL means EOF (needed to flush decoder buffers) */
ea9367e9 2405static int output_packet(InputStream *ist, const AVPacket *pkt)
6291d7e4 2406{
ffa0674e 2407 int i;
6291d7e4 2408 int got_output;
6291d7e4 2409 int64_t pkt_pts = AV_NOPTS_VALUE;
6291d7e4 2410 AVPacket avpkt;
6291d7e4 2411
3101bb66 2412 if (ist->next_dts == AV_NOPTS_VALUE)
23576b3f 2413 ist->next_dts = ist->last_dts;
6291d7e4
AK
2414
2415 if (pkt == NULL) {
2416 /* EOF handling */
2417 av_init_packet(&avpkt);
2418 avpkt.data = NULL;
2419 avpkt.size = 0;
2420 goto handle_eof;
2421 } else {
2422 avpkt = *pkt;
2423 }
2424
7636c8c6 2425 if (pkt->dts != AV_NOPTS_VALUE)
23576b3f 2426 ist->next_dts = ist->last_dts = av_rescale_q(pkt->dts, ist->st->time_base, AV_TIME_BASE_Q);
7636c8c6 2427 if (pkt->pts != AV_NOPTS_VALUE)
6291d7e4
AK
2428 pkt_pts = av_rescale_q(pkt->pts, ist->st->time_base, AV_TIME_BASE_Q);
2429
7636c8c6 2430 // while we have more to decode or while the decoder did output something on EOF
2a651b71 2431 while (ist->decoding_needed && (avpkt.size > 0 || (!pkt && got_output))) {
ffa0674e 2432 int ret = 0;
6291d7e4 2433 handle_eof:
6291d7e4 2434
23576b3f 2435 ist->last_dts = ist->next_dts;
8b0268a8
AK
2436
2437 if (avpkt.size && avpkt.size != pkt->size) {
e3245b26
AK
2438 av_log(NULL, ist->showed_multi_packet_warning ? AV_LOG_VERBOSE : AV_LOG_WARNING,
2439 "Multiple frames in a packet from stream %d\n", pkt->stream_index);
8b0268a8
AK
2440 ist->showed_multi_packet_warning = 1;
2441 }
6291d7e4 2442
7636c8c6 2443 switch (ist->st->codec->codec_type) {
82963f8f
AK
2444 case AVMEDIA_TYPE_AUDIO:
2445 ret = transcode_audio (ist, &avpkt, &got_output);
2446 break;
2447 case AVMEDIA_TYPE_VIDEO:
2448 ret = transcode_video (ist, &avpkt, &got_output, &pkt_pts);
b34856a1
AK
2449 if (avpkt.duration)
2450 ist->next_dts += av_rescale_q(avpkt.duration, ist->st->time_base, AV_TIME_BASE_Q);
722410ad
AK
2451 else if (ist->st->r_frame_rate.num)
2452 ist->next_dts += av_rescale_q(1, (AVRational){ist->st->r_frame_rate.den,
2453 ist->st->r_frame_rate.num},
2454 AV_TIME_BASE_Q);
b34856a1
AK
2455 else if (ist->st->codec->time_base.num != 0) {
2456 int ticks = ist->st->parser ? ist->st->parser->repeat_pict + 1 :
2457 ist->st->codec->ticks_per_frame;
2458 ist->next_dts += av_rescale_q(ticks, ist->st->codec->time_base, AV_TIME_BASE_Q);
2459 }
82963f8f
AK
2460 break;
2461 case AVMEDIA_TYPE_SUBTITLE:
2462 ret = transcode_subtitles(ist, &avpkt, &got_output);
2463 break;
78162b4e
AK
2464 default:
2465 return -1;
2466 }
6291d7e4 2467
d3c1d37a
AK
2468 if (ret < 0)
2469 return ret;
aa38cff2
JG
2470 // touch data and size only if not EOF
2471 if (pkt) {
2472 avpkt.data += ret;
2473 avpkt.size -= ret;
2474 }
82963f8f 2475 if (!got_output) {
af8ad892 2476 continue;
82963f8f 2477 }
6291d7e4 2478 }
6291d7e4 2479
7204ec1a 2480 /* handle stream copy */
2a651b71
AK
2481 if (!ist->decoding_needed) {
2482 rate_emu_sleep(ist);
23576b3f 2483 ist->last_dts = ist->next_dts;
2a651b71
AK
2484 switch (ist->st->codec->codec_type) {
2485 case AVMEDIA_TYPE_AUDIO:
3101bb66 2486 ist->next_dts += ((int64_t)AV_TIME_BASE * ist->st->codec->frame_size) /
2a651b71
AK
2487 ist->st->codec->sample_rate;
2488 break;
2489 case AVMEDIA_TYPE_VIDEO:
2490 if (ist->st->codec->time_base.num != 0) {
7636c8c6 2491 int ticks = ist->st->parser ? ist->st->parser->repeat_pict + 1 : ist->st->codec->ticks_per_frame;
3101bb66 2492 ist->next_dts += ((int64_t)AV_TIME_BASE *
2a651b71
AK
2493 ist->st->codec->time_base.num * ticks) /
2494 ist->st->codec->time_base.den;
2495 }
2496 break;
2497 }
2498 }
ea9367e9 2499 for (i = 0; pkt && i < nb_output_streams; i++) {
2e215267 2500 OutputStream *ost = output_streams[i];
7204ec1a
AK
2501
2502 if (!check_output_constraints(ist, ost) || ost->encoding_needed)
2503 continue;
2504
2505 do_streamcopy(ist, ost, pkt);
2506 }
2507
6291d7e4
AK
2508 return 0;
2509}
2510
ea9367e9 2511static void print_sdp(void)
6291d7e4
AK
2512{
2513 char sdp[2048];
af70aa45 2514 int i;
ea9367e9 2515 AVFormatContext **avc = av_malloc(sizeof(*avc) * nb_output_files);
af70aa45
AK
2516
2517 if (!avc)
2518 exit_program(1);
ea9367e9 2519 for (i = 0; i < nb_output_files; i++)
2e215267 2520 avc[i] = output_files[i]->ctx;
6291d7e4 2521
ea9367e9 2522 av_sdp_create(avc, nb_output_files, sdp, sizeof(sdp));
6291d7e4
AK
2523 printf("SDP:\n%s\n", sdp);
2524 fflush(stdout);
af70aa45 2525 av_freep(&avc);
6291d7e4
AK
2526}
2527
ea9367e9 2528static int init_input_stream(int ist_index, char *error, int error_len)
630902a1
AK
2529{
2530 int i;
2e215267 2531 InputStream *ist = input_streams[ist_index];
630902a1
AK
2532 if (ist->decoding_needed) {
2533 AVCodec *codec = ist->dec;
630902a1 2534 if (!codec) {
9a414d89 2535 snprintf(error, error_len, "Decoder (codec id %d) not found for input stream #%d:%d",
630902a1
AK
2536 ist->st->codec->codec_id, ist->file_index, ist->st->index);
2537 return AVERROR(EINVAL);
2538 }
2539
2540 /* update requested sample format for the decoder based on the
2541 corresponding encoder sample format */
2542 for (i = 0; i < nb_output_streams; i++) {
2e215267 2543 OutputStream *ost = output_streams[i];
630902a1
AK
2544 if (ost->source_index == ist_index) {
2545 update_sample_fmt(ist->st->codec, codec, ost->st->codec);
2546 break;
2547 }
2548 }
2549
64dca32c
AK
2550 if (codec->type == AVMEDIA_TYPE_VIDEO && codec->capabilities & CODEC_CAP_DR1) {
2551 ist->st->codec->get_buffer = codec_get_buffer;
2552 ist->st->codec->release_buffer = codec_release_buffer;
2553 ist->st->codec->opaque = ist;
2554 }
2555
2473a45c
JG
2556 if (!av_dict_get(ist->opts, "threads", NULL, 0))
2557 av_dict_set(&ist->opts, "threads", "auto", 0);
630902a1 2558 if (avcodec_open2(ist->st->codec, codec, &ist->opts) < 0) {
9a414d89 2559 snprintf(error, error_len, "Error while opening decoder for input stream #%d:%d",
630902a1
AK
2560 ist->file_index, ist->st->index);
2561 return AVERROR(EINVAL);
2562 }
2563 assert_codec_experimental(ist->st->codec, 0);
2564 assert_avoptions(ist->opts);
2565 }
2566
23576b3f 2567 ist->last_dts = ist->st->avg_frame_rate.num ? - ist->st->codec->has_b_frames * AV_TIME_BASE / av_q2d(ist->st->avg_frame_rate) : 0;
3101bb66 2568 ist->next_dts = AV_NOPTS_VALUE;
630902a1
AK
2569 init_pts_correction(&ist->pts_ctx);
2570 ist->is_start = 1;
2571
2572 return 0;
2573}
2574
3b266da3
AK
2575static InputStream *get_input_stream(OutputStream *ost)
2576{
2577 if (ost->source_index >= 0)
2578 return input_streams[ost->source_index];
2579
2580 if (ost->filter) {
2581 FilterGraph *fg = ost->filter->graph;
2582 int i;
2583
2584 for (i = 0; i < fg->nb_inputs; i++)
2585 if (fg->inputs[i]->ist->st->codec->codec_type == ost->st->codec->codec_type)
2586 return fg->inputs[i]->ist;
2587 }
2588
2589 return NULL;
2590}
2591
ea9367e9 2592static int transcode_init(void)
6291d7e4 2593{
2c474ddb 2594 int ret = 0, i, j, k;
1bb77e51 2595 AVFormatContext *oc;
6291d7e4 2596 AVCodecContext *codec, *icodec;
4288e031 2597 OutputStream *ost;
6291d7e4
AK
2598 InputStream *ist;
2599 char error[1024];
2600 int want_sdp = 1;
b0c9e8e0 2601
f4805328
AK
2602 /* init framerate emulation */
2603 for (i = 0; i < nb_input_files; i++) {
2e215267 2604 InputFile *ifile = input_files[i];
f4805328
AK
2605 if (ifile->rate_emu)
2606 for (j = 0; j < ifile->nb_streams; j++)
2e215267 2607 input_streams[j + ifile->ist_index]->start = av_gettime();
f4805328 2608 }
6291d7e4
AK
2609
2610 /* output stream init */
03f30c83 2611 for (i = 0; i < nb_output_files; i++) {
2e215267 2612 oc = output_files[i]->ctx;
1bb77e51
AK
2613 if (!oc->nb_streams && !(oc->oformat->flags & AVFMT_NOSTREAMS)) {
2614 av_dump_format(oc, i, oc->filename, 1);
e3245b26 2615 av_log(NULL, AV_LOG_ERROR, "Output file #%d does not contain any stream\n", i);
eaf2d37a 2616 return AVERROR(EINVAL);
6291d7e4 2617 }
6291d7e4
AK
2618 }
2619
3b266da3
AK
2620 /* init complex filtergraphs */
2621 for (i = 0; i < nb_filtergraphs; i++)
2622 if ((ret = avfilter_graph_config(filtergraphs[i]->graph, NULL)) < 0)
2623 return ret;
2624
6291d7e4 2625 /* for each output stream, we compute the right encoding parameters */
4288e031 2626 for (i = 0; i < nb_output_streams; i++) {
2e215267
AK
2627 ost = output_streams[i];
2628 oc = output_files[ost->file_index]->ctx;
3b266da3 2629 ist = get_input_stream(ost);
6291d7e4 2630
4dbc6cee
AK
2631 if (ost->attachment_filename)
2632 continue;
2633
03f30c83 2634 codec = ost->st->codec;
6291d7e4 2635
3b266da3
AK
2636 if (ist) {
2637 icodec = ist->st->codec;
2638
2639 ost->st->disposition = ist->st->disposition;
2640 codec->bits_per_raw_sample = icodec->bits_per_raw_sample;
2641 codec->chroma_sample_location = icodec->chroma_sample_location;
2642 }
6291d7e4 2643
3d813e4c 2644 if (ost->stream_copy) {
8c4022ac
AK
2645 uint64_t extra_size;
2646
2647 av_assert0(ist && !ost->filter);
2648
2649 extra_size = (uint64_t)icodec->extradata_size + FF_INPUT_BUFFER_PADDING_SIZE;
6291d7e4 2650
e6d2b737 2651 if (extra_size > INT_MAX) {
eaf2d37a 2652 return AVERROR(EINVAL);
e6d2b737 2653 }
6291d7e4
AK
2654
2655 /* if stream_copy is selected, no need to decode or encode */
03f30c83 2656 codec->codec_id = icodec->codec_id;
6291d7e4
AK
2657 codec->codec_type = icodec->codec_type;
2658
03f30c83
AK
2659 if (!codec->codec_tag) {
2660 if (!oc->oformat->codec_tag ||
2661 av_codec_get_id (oc->oformat->codec_tag, icodec->codec_tag) == codec->codec_id ||
2662 av_codec_get_tag(oc->oformat->codec_tag, icodec->codec_id) <= 0)
6291d7e4
AK
2663 codec->codec_tag = icodec->codec_tag;
2664 }
2665
03f30c83 2666 codec->bit_rate = icodec->bit_rate;
6291d7e4
AK
2667 codec->rc_max_rate = icodec->rc_max_rate;
2668 codec->rc_buffer_size = icodec->rc_buffer_size;
4bf3c8f2 2669 codec->field_order = icodec->field_order;
03f30c83 2670 codec->extradata = av_mallocz(extra_size);
e6d2b737 2671 if (!codec->extradata) {
eaf2d37a 2672 return AVERROR(ENOMEM);
e6d2b737 2673 }
6291d7e4 2674 memcpy(codec->extradata, icodec->extradata, icodec->extradata_size);
03f30c83 2675 codec->extradata_size = icodec->extradata_size;
7bb3e625 2676 if (!copy_tb) {
03f30c83 2677 codec->time_base = icodec->time_base;
6291d7e4
AK
2678 codec->time_base.num *= icodec->ticks_per_frame;
2679 av_reduce(&codec->time_base.num, &codec->time_base.den,
2680 codec->time_base.num, codec->time_base.den, INT_MAX);
03f30c83 2681 } else
6291d7e4 2682 codec->time_base = ist->st->time_base;
03f30c83 2683
7636c8c6 2684 switch (codec->codec_type) {
6291d7e4 2685 case AVMEDIA_TYPE_AUDIO:
7636c8c6 2686 if (audio_volume != 256) {
e3245b26 2687 av_log(NULL, AV_LOG_FATAL, "-acodec copy and -vol are incompatible (frames are not decoded)\n");
6291d7e4
AK
2688 exit_program(1);
2689 }
03f30c83
AK
2690 codec->channel_layout = icodec->channel_layout;
2691 codec->sample_rate = icodec->sample_rate;
2692 codec->channels = icodec->channels;
2693 codec->frame_size = icodec->frame_size;
6291d7e4 2694 codec->audio_service_type = icodec->audio_service_type;
03f30c83 2695 codec->block_align = icodec->block_align;
6291d7e4
AK
2696 break;
2697 case AVMEDIA_TYPE_VIDEO:
03f30c83
AK
2698 codec->pix_fmt = icodec->pix_fmt;
2699 codec->width = icodec->width;
2700 codec->height = icodec->height;
2701 codec->has_b_frames = icodec->has_b_frames;
6291d7e4 2702 if (!codec->sample_aspect_ratio.num) {
03f30c83 2703 codec->sample_aspect_ratio =
6291d7e4
AK
2704 ost->st->sample_aspect_ratio =
2705 ist->st->sample_aspect_ratio.num ? ist->st->sample_aspect_ratio :
2706 ist->st->codec->sample_aspect_ratio.num ?
2707 ist->st->codec->sample_aspect_ratio : (AVRational){0, 1};
2708 }
2709 break;
2710 case AVMEDIA_TYPE_SUBTITLE:
03f30c83 2711 codec->width = icodec->width;
6291d7e4
AK
2712 codec->height = icodec->height;
2713 break;
2714 case AVMEDIA_TYPE_DATA:
3ccd1580 2715 case AVMEDIA_TYPE_ATTACHMENT:
6291d7e4
AK
2716 break;
2717 default:
2718 abort();
2719 }
2720 } else {
2994913d
AK
2721 if (!ost->enc) {
2722 /* should only happen when a default codec is not present. */
2723 snprintf(error, sizeof(error), "Automatic encoder selection "
2724 "failed for output stream #%d:%d. Default encoder for "
2725 "format %s is probably disabled. Please choose an "
2726 "encoder manually.\n", ost->file_index, ost->index,
2727 oc->oformat->name);
2728 ret = AVERROR(EINVAL);
2729 goto dump_format;
2730 }
03f30c83 2731
3b266da3
AK
2732 if (ist)
2733 ist->decoding_needed = 1;
11fdb7e1 2734 ost->encoding_needed = 1;
03f30c83 2735
369cb092
AK
2736 if (!ost->filter &&
2737 (codec->codec_type == AVMEDIA_TYPE_VIDEO ||
2738 codec->codec_type == AVMEDIA_TYPE_AUDIO)) {
3b266da3
AK
2739 FilterGraph *fg;
2740 fg = init_simple_filtergraph(ist, ost);
369cb092 2741 if (configure_simple_filtergraph(fg)) {
3b266da3
AK
2742 av_log(NULL, AV_LOG_FATAL, "Error opening filters!\n");
2743 exit(1);
2744 }
369cb092 2745 }
3b266da3 2746
369cb092
AK
2747 switch (codec->codec_type) {
2748 case AVMEDIA_TYPE_AUDIO:
2749 codec->sample_fmt = ost->filter->filter->inputs[0]->format;
2750 codec->sample_rate = ost->filter->filter->inputs[0]->sample_rate;
2751 codec->channel_layout = ost->filter->filter->inputs[0]->channel_layout;
2752 codec->channels = av_get_channel_layout_nb_channels(codec->channel_layout);
2753 codec->time_base = (AVRational){ 1, codec->sample_rate };
2754 break;
2755 case AVMEDIA_TYPE_VIDEO:
832ba44d
AK
2756 /*
2757 * We want CFR output if and only if one of those is true:
2758 * 1) user specified output framerate with -r
2759 * 2) user specified -vsync cfr
2760 * 3) output format is CFR and the user didn't force vsync to
2761 * something else than CFR
2762 *
2763 * in such a case, set ost->frame_rate
2764 */
3b266da3 2765 if (!ost->frame_rate.num && ist &&
832ba44d
AK
2766 (video_sync_method == VSYNC_CFR ||
2767 (video_sync_method == VSYNC_AUTO &&
2768 !(oc->oformat->flags & (AVFMT_NOTIMESTAMPS | AVFMT_VARIABLE_FPS))))) {
2769 ost->frame_rate = ist->st->r_frame_rate.num ? ist->st->r_frame_rate : (AVRational){25, 1};
2770 if (ost->enc && ost->enc->supported_framerates && !ost->force_fps) {
2771 int idx = av_find_nearest_q_idx(ost->frame_rate, ost->enc->supported_framerates);
2772 ost->frame_rate = ost->enc->supported_framerates[idx];
2773 }
6291d7e4 2774 }
832ba44d
AK
2775 if (ost->frame_rate.num) {
2776 codec->time_base = (AVRational){ost->frame_rate.den, ost->frame_rate.num};
2777 video_sync_method = VSYNC_CFR;
3b266da3 2778 } else if (ist)
832ba44d 2779 codec->time_base = ist->st->time_base;
3b266da3
AK
2780 else
2781 codec->time_base = ost->filter->filter->inputs[0]->time_base;
6291d7e4 2782
3b266da3
AK
2783 codec->width = ost->filter->filter->inputs[0]->w;
2784 codec->height = ost->filter->filter->inputs[0]->h;
2785 codec->sample_aspect_ratio = ost->st->sample_aspect_ratio =
2786 ost->frame_aspect_ratio ? // overridden by the -aspect cli option
2787 av_d2q(ost->frame_aspect_ratio * codec->height/codec->width, 255) :
2788 ost->filter->filter->inputs[0]->sample_aspect_ratio;
2789 codec->pix_fmt = ost->filter->filter->inputs[0]->format;
b7327887 2790
9dced854
AK
2791 if (codec->width != icodec->width ||
2792 codec->height != icodec->height ||
2793 codec->pix_fmt != icodec->pix_fmt) {
b7327887
AK
2794 codec->bits_per_raw_sample = 0;
2795 }
2796
6291d7e4
AK
2797 break;
2798 case AVMEDIA_TYPE_SUBTITLE:
c9af8326 2799 codec->time_base = (AVRational){1, 1000};
6291d7e4
AK
2800 break;
2801 default:
2802 abort();
2803 break;
2804 }
2805 /* two pass mode */
515901fa 2806 if ((codec->flags & (CODEC_FLAG_PASS1 | CODEC_FLAG_PASS2))) {
6291d7e4
AK
2807 char logfilename[1024];
2808 FILE *f;
2809
2810 snprintf(logfilename, sizeof(logfilename), "%s-%d.log",
2811 pass_logfilename_prefix ? pass_logfilename_prefix : DEFAULT_PASS_LOGFILENAME_PREFIX,
2812 i);
6e8be949
AK
2813 if (!strcmp(ost->enc->name, "libx264")) {
2814 av_dict_set(&ost->opts, "stats", logfilename, AV_DICT_DONT_OVERWRITE);
2815 } else {
64334ddb
AK
2816 if (codec->flags & CODEC_FLAG_PASS1) {
2817 f = fopen(logfilename, "wb");
2818 if (!f) {
2819 av_log(NULL, AV_LOG_FATAL, "Cannot write log file '%s' for pass-1 encoding: %s\n",
2820 logfilename, strerror(errno));
2821 exit_program(1);
2822 }
2823 ost->logfile = f;
2824 } else {
2825 char *logbuffer;
2826 size_t logbuffer_size;
2827 if (cmdutils_read_file(logfilename, &logbuffer, &logbuffer_size) < 0) {
2828 av_log(NULL, AV_LOG_FATAL, "Error reading log file '%s' for pass-2 encoding\n",
2829 logfilename);
2830 exit_program(1);
2831 }
2832 codec->stats_in = logbuffer;
6291d7e4 2833 }
6e8be949 2834 }
6291d7e4
AK
2835 }
2836 }
6291d7e4
AK
2837 }
2838
2839 /* open each encoder */
4288e031 2840 for (i = 0; i < nb_output_streams; i++) {
2e215267 2841 ost = output_streams[i];
6291d7e4 2842 if (ost->encoding_needed) {
03f30c83 2843 AVCodec *codec = ost->enc;
3b266da3 2844 AVCodecContext *dec = NULL;
3b266da3
AK
2845
2846 if ((ist = get_input_stream(ost)))
2847 dec = ist->st->codec;
2848 if (dec && dec->subtitle_header) {
6291d7e4
AK
2849 ost->st->codec->subtitle_header = av_malloc(dec->subtitle_header_size);
2850 if (!ost->st->codec->subtitle_header) {
2851 ret = AVERROR(ENOMEM);
2852 goto dump_format;
2853 }
2854 memcpy(ost->st->codec->subtitle_header, dec->subtitle_header, dec->subtitle_header_size);
2855 ost->st->codec->subtitle_header_size = dec->subtitle_header_size;
2856 }
2473a45c
JG
2857 if (!av_dict_get(ost->opts, "threads", NULL, 0))
2858 av_dict_set(&ost->opts, "threads", "auto", 0);
6291d7e4 2859 if (avcodec_open2(ost->st->codec, codec, &ost->opts) < 0) {
9a414d89 2860 snprintf(error, sizeof(error), "Error while opening encoder for output stream #%d:%d - maybe incorrect parameters such as bit_rate, rate, width or height",
6291d7e4
AK
2861 ost->file_index, ost->index);
2862 ret = AVERROR(EINVAL);
2863 goto dump_format;
2864 }
2865 assert_codec_experimental(ost->st->codec, 1);
2866 assert_avoptions(ost->opts);
2867 if (ost->st->codec->bit_rate && ost->st->codec->bit_rate < 1000)
2868 av_log(NULL, AV_LOG_WARNING, "The bitrate parameter is set too low."
2869 "It takes bits/s as argument, not kbits/s\n");
2870 extra_size += ost->st->codec->extradata_size;
d242d80e
AK
2871
2872 if (ost->st->codec->me_threshold)
2e215267 2873 input_streams[ost->source_index]->st->codec->debug |= FF_DEBUG_MV;
6291d7e4
AK
2874 }
2875 }
2876
630902a1
AK
2877 /* init input streams */
2878 for (i = 0; i < nb_input_streams; i++)
ea9367e9 2879 if ((ret = init_input_stream(i, error, sizeof(error))) < 0)
630902a1 2880 goto dump_format;
6291d7e4 2881
2c474ddb
AK
2882 /* discard unused programs */
2883 for (i = 0; i < nb_input_files; i++) {
2e215267 2884 InputFile *ifile = input_files[i];
2c474ddb
AK
2885 for (j = 0; j < ifile->ctx->nb_programs; j++) {
2886 AVProgram *p = ifile->ctx->programs[j];
2887 int discard = AVDISCARD_ALL;
2888
2889 for (k = 0; k < p->nb_stream_indexes; k++)
2e215267 2890 if (!input_streams[ifile->ist_index + p->stream_index[k]]->discard) {
2c474ddb
AK
2891 discard = AVDISCARD_DEFAULT;
2892 break;
2893 }
2894 p->discard = discard;
2895 }
2896 }
2897
6291d7e4 2898 /* open files and write file headers */
af70aa45 2899 for (i = 0; i < nb_output_files; i++) {
2e215267 2900 oc = output_files[i]->ctx;
1bb77e51 2901 oc->interrupt_callback = int_cb;
2e215267 2902 if (avformat_write_header(oc, &output_files[i]->opts) < 0) {
6291d7e4
AK
2903 snprintf(error, sizeof(error), "Could not write header for output file #%d (incorrect codec parameters ?)", i);
2904 ret = AVERROR(EINVAL);
2905 goto dump_format;
2906 }
2e215267 2907 assert_avoptions(output_files[i]->opts);
1bb77e51 2908 if (strcmp(oc->oformat->name, "rtp")) {
6291d7e4
AK
2909 want_sdp = 0;
2910 }
2911 }
2912
2913 dump_format:
2914 /* dump the file output parameters - cannot be done before in case
2915 of stream copy */
03f30c83 2916 for (i = 0; i < nb_output_files; i++) {
2e215267 2917 av_dump_format(output_files[i]->ctx, i, output_files[i]->ctx->filename, 1);
6291d7e4
AK
2918 }
2919
2920 /* dump the stream mapping */
e3245b26 2921 av_log(NULL, AV_LOG_INFO, "Stream mapping:\n");
3b266da3
AK
2922 for (i = 0; i < nb_input_streams; i++) {
2923 ist = input_streams[i];
2924
2925 for (j = 0; j < ist->nb_filters; j++) {
2926 AVFilterLink *link = ist->filters[j]->filter->outputs[0];
2927 if (ist->filters[j]->graph->graph_desc) {
2928 av_log(NULL, AV_LOG_INFO, " Stream #%d:%d (%s) -> %s",
2929 ist->file_index, ist->st->index, ist->dec ? ist->dec->name : "?",
2930 link->dst->filter->name);
2931 if (link->dst->input_count > 1)
2932 av_log(NULL, AV_LOG_INFO, ":%s", link->dstpad->name);
2933 if (nb_filtergraphs > 1)
2934 av_log(NULL, AV_LOG_INFO, " (graph %d)", ist->filters[j]->graph->index);
2935 av_log(NULL, AV_LOG_INFO, "\n");
2936 }
2937 }
2938 }
2939
e3245b26 2940 for (i = 0; i < nb_output_streams; i++) {
2e215267 2941 ost = output_streams[i];
4dbc6cee
AK
2942
2943 if (ost->attachment_filename) {
2944 /* an attached file */
2945 av_log(NULL, AV_LOG_INFO, " File %s -> Stream #%d:%d\n",
2946 ost->attachment_filename, ost->file_index, ost->index);
2947 continue;
2948 }
3b266da3
AK
2949
2950 if (ost->filter && ost->filter->graph->graph_desc) {
2951 /* output from a complex graph */
2952 AVFilterLink *link = ost->filter->filter->inputs[0];
2953 av_log(NULL, AV_LOG_INFO, " %s", link->src->filter->name);
2954 if (link->src->output_count > 1)
2955 av_log(NULL, AV_LOG_INFO, ":%s", link->srcpad->name);
2956 if (nb_filtergraphs > 1)
2957 av_log(NULL, AV_LOG_INFO, " (graph %d)", ost->filter->graph->index);
2958
2959 av_log(NULL, AV_LOG_INFO, " -> Stream #%d:%d (%s)\n", ost->file_index,
2960 ost->index, ost->enc ? ost->enc->name : "?");
2961 continue;
2962 }
2963
9a414d89 2964 av_log(NULL, AV_LOG_INFO, " Stream #%d:%d -> #%d:%d",
2e215267
AK
2965 input_streams[ost->source_index]->file_index,
2966 input_streams[ost->source_index]->st->index,
e3245b26
AK
2967 ost->file_index,
2968 ost->index);
2e215267 2969 if (ost->sync_ist != input_streams[ost->source_index])
9a414d89 2970 av_log(NULL, AV_LOG_INFO, " [sync #%d:%d]",
e3245b26
AK
2971 ost->sync_ist->file_index,
2972 ost->sync_ist->st->index);
3d813e4c 2973 if (ost->stream_copy)
e3245b26
AK
2974 av_log(NULL, AV_LOG_INFO, " (copy)");
2975 else
2e215267
AK
2976 av_log(NULL, AV_LOG_INFO, " (%s -> %s)", input_streams[ost->source_index]->dec ?
2977 input_streams[ost->source_index]->dec->name : "?",
e3245b26
AK
2978 ost->enc ? ost->enc->name : "?");
2979 av_log(NULL, AV_LOG_INFO, "\n");
6291d7e4
AK
2980 }
2981
2982 if (ret) {
e3245b26 2983 av_log(NULL, AV_LOG_ERROR, "%s\n", error);
eaf2d37a 2984 return ret;
6291d7e4
AK
2985 }
2986
2987 if (want_sdp) {
ea9367e9 2988 print_sdp();
6291d7e4
AK
2989 }
2990
eaf2d37a
AC
2991 return 0;
2992}
2993
2994/*
2995 * The following code is the main loop of the file converter
2996 */
ea9367e9 2997static int transcode(void)
eaf2d37a
AC
2998{
2999 int ret, i;
3000 AVFormatContext *is, *os;
3001 OutputStream *ost;
3002 InputStream *ist;
3003 uint8_t *no_packet;
7636c8c6 3004 int no_packet_count = 0;
eaf2d37a
AC
3005 int64_t timer_start;
3006
3007 if (!(no_packet = av_mallocz(nb_input_files)))
3008 exit_program(1);
3009
ea9367e9 3010 ret = transcode_init();
eaf2d37a
AC
3011 if (ret < 0)
3012 goto fail;
3013
e3245b26 3014 av_log(NULL, AV_LOG_INFO, "Press ctrl-c to stop encoding\n");
6291d7e4
AK
3015 term_init();
3016
3017 timer_start = av_gettime();
3018
7636c8c6 3019 for (; received_sigterm == 0;) {
3b266da3 3020 int file_index, ist_index, past_recording_time = 1;
6291d7e4 3021 AVPacket pkt;
9be3c124 3022 int64_t ipts_min;
6291d7e4 3023
9be3c124 3024 ipts_min = INT64_MAX;
6291d7e4 3025
3b266da3 3026 /* check if there's any stream where output is still needed */
4288e031 3027 for (i = 0; i < nb_output_streams; i++) {
f21f294e 3028 OutputFile *of;
2e215267 3029 ost = output_streams[i];
3b266da3
AK
3030 of = output_files[ost->file_index];
3031 os = output_files[ost->file_index]->ctx;
3032 if (ost->is_past_recording_time ||
f21f294e 3033 (os->pb && avio_tell(os->pb) >= of->limit_filesize))
6291d7e4 3034 continue;
3b266da3
AK
3035 if (ost->frame_number > ost->max_frames) {
3036 int j;
3037 for (j = 0; j < of->ctx->nb_streams; j++)
3038 output_streams[of->ost_index + j]->is_past_recording_time = 1;
3039 continue;
3040 }
3041 past_recording_time = 0;
3042 }
3043 if (past_recording_time)
3044 break;
3045
3046 /* select the stream that we must read now by looking at the
3047 smallest output pts */
3048 file_index = -1;
3049 for (i = 0; i < nb_input_streams; i++) {
3050 int64_t ipts;
3051 ist = input_streams[i];
23576b3f 3052 ipts = ist->last_dts;
3b266da3
AK
3053 if (ist->discard || no_packet[ist->file_index])
3054 continue;
2e215267 3055 if (!input_files[ist->file_index]->eof_reached) {
7636c8c6 3056 if (ipts < ipts_min) {
6291d7e4 3057 ipts_min = ipts;
3b266da3 3058 file_index = ist->file_index;
6291d7e4
AK
3059 }
3060 }
6291d7e4
AK
3061 }
3062 /* if none, if is finished */
3063 if (file_index < 0) {
7636c8c6
AD
3064 if (no_packet_count) {
3065 no_packet_count = 0;
b0c9e8e0 3066 memset(no_packet, 0, nb_input_files);
6291d7e4
AK
3067 usleep(10000);
3068 continue;
3069 }
3070 break;
3071 }
3072
6291d7e4 3073 /* read a frame from it and output it in the fifo */
2e215267 3074 is = input_files[file_index]->ctx;
7636c8c6
AD
3075 ret = av_read_frame(is, &pkt);
3076 if (ret == AVERROR(EAGAIN)) {
3077 no_packet[file_index] = 1;
6291d7e4
AK
3078 no_packet_count++;
3079 continue;
3080 }
3081 if (ret < 0) {
2e215267 3082 input_files[file_index]->eof_reached = 1;
9e8aae44
AK
3083
3084 for (i = 0; i < input_files[file_index]->nb_streams; i++) {
3085 ist = input_streams[input_files[file_index]->ist_index + i];
3086 if (ist->decoding_needed)
3087 output_packet(ist, NULL);
3088 }
3089
6291d7e4
AK
3090 if (opt_shortest)
3091 break;
3092 else
3093 continue;
3094 }
3095
7636c8c6 3096 no_packet_count = 0;
b0c9e8e0 3097 memset(no_packet, 0, nb_input_files);
6291d7e4
AK
3098
3099 if (do_pkt_dump) {
3100 av_pkt_dump_log2(NULL, AV_LOG_DEBUG, &pkt, do_hex_dump,
3101 is->streams[pkt.stream_index]);
3102 }
3103 /* the following test is needed in case new streams appear
3104 dynamically in stream : we ignore them */
2e215267 3105 if (pkt.stream_index >= input_files[file_index]->nb_streams)
6291d7e4 3106 goto discard_packet;
2e215267
AK
3107 ist_index = input_files[file_index]->ist_index + pkt.stream_index;
3108 ist = input_streams[ist_index];
6291d7e4
AK
3109 if (ist->discard)
3110 goto discard_packet;
3111
3112 if (pkt.dts != AV_NOPTS_VALUE)
2e215267 3113 pkt.dts += av_rescale_q(input_files[ist->file_index]->ts_offset, AV_TIME_BASE_Q, ist->st->time_base);
6291d7e4 3114 if (pkt.pts != AV_NOPTS_VALUE)
2e215267 3115 pkt.pts += av_rescale_q(input_files[ist->file_index]->ts_offset, AV_TIME_BASE_Q, ist->st->time_base);
6291d7e4 3116
7636c8c6 3117 if (pkt.pts != AV_NOPTS_VALUE)
33f75d72 3118 pkt.pts *= ist->ts_scale;
7636c8c6 3119 if (pkt.dts != AV_NOPTS_VALUE)
33f75d72 3120 pkt.dts *= ist->ts_scale;
6291d7e4 3121
7636c8c6 3122 //fprintf(stderr, "next:%"PRId64" dts:%"PRId64" off:%"PRId64" %d\n",
3101bb66 3123 // ist->next_dts,
7636c8c6
AD
3124 // pkt.dts, input_files[ist->file_index].ts_offset,
3125 // ist->st->codec->codec_type);
3101bb66 3126 if (pkt.dts != AV_NOPTS_VALUE && ist->next_dts != AV_NOPTS_VALUE
6291d7e4 3127 && (is->iformat->flags & AVFMT_TS_DISCONT)) {
7636c8c6 3128 int64_t pkt_dts = av_rescale_q(pkt.dts, ist->st->time_base, AV_TIME_BASE_Q);
3101bb66 3129 int64_t delta = pkt_dts - ist->next_dts;
23576b3f 3130 if ((FFABS(delta) > 1LL * dts_delta_threshold * AV_TIME_BASE || pkt_dts + 1 < ist->last_dts) && !copy_ts) {
2e215267 3131 input_files[ist->file_index]->ts_offset -= delta;
7636c8c6
AD
3132 av_log(NULL, AV_LOG_DEBUG,
3133 "timestamp discontinuity %"PRId64", new offset= %"PRId64"\n",
2e215267 3134 delta, input_files[ist->file_index]->ts_offset);
6291d7e4 3135 pkt.dts-= av_rescale_q(delta, AV_TIME_BASE_Q, ist->st->time_base);
7636c8c6 3136 if (pkt.pts != AV_NOPTS_VALUE)
6291d7e4
AK
3137 pkt.pts-= av_rescale_q(delta, AV_TIME_BASE_Q, ist->st->time_base);
3138 }
3139 }
3140
7636c8c6 3141 // fprintf(stderr,"read #%d.%d size=%d\n", ist->file_index, ist->st->index, pkt.size);
560f7774 3142 if (output_packet(ist, &pkt) < 0 || poll_filters() < 0) {
9a414d89 3143 av_log(NULL, AV_LOG_ERROR, "Error while decoding stream #%d:%d\n",
e3245b26 3144 ist->file_index, ist->st->index);
6291d7e4
AK
3145 if (exit_on_error)
3146 exit_program(1);
3147 av_free_packet(&pkt);
b9630bcf 3148 continue;
6291d7e4
AK
3149 }
3150
3151 discard_packet:
3152 av_free_packet(&pkt);
3153
3154 /* dump report by using the output first video and audio streams */
ea9367e9 3155 print_report(0, timer_start);
6291d7e4
AK
3156 }
3157
3158 /* at the end of stream, we must flush the decoder buffers */
3159 for (i = 0; i < nb_input_streams; i++) {
2e215267 3160 ist = input_streams[i];
9e8aae44 3161 if (!input_files[ist->file_index]->eof_reached && ist->decoding_needed) {
ea9367e9 3162 output_packet(ist, NULL);
6291d7e4
AK
3163 }
3164 }
560f7774 3165 poll_filters();
ea9367e9 3166 flush_encoders();
6291d7e4
AK
3167
3168 term_exit();
3169
3170 /* write the trailer if needed and close file */
7636c8c6 3171 for (i = 0; i < nb_output_files; i++) {
2e215267 3172 os = output_files[i]->ctx;
6291d7e4
AK
3173 av_write_trailer(os);
3174 }
3175
3176 /* dump report by using the first video and audio streams */
ea9367e9 3177 print_report(1, timer_start);
6291d7e4
AK
3178
3179 /* close each encoder */
4288e031 3180 for (i = 0; i < nb_output_streams; i++) {
2e215267 3181 ost = output_streams[i];
6291d7e4
AK
3182 if (ost->encoding_needed) {
3183 av_freep(&ost->st->codec->stats_in);
3184 avcodec_close(ost->st->codec);
3185 }
6291d7e4
AK
3186 }
3187
3188 /* close each decoder */
3189 for (i = 0; i < nb_input_streams; i++) {
2e215267 3190 ist = input_streams[i];
6291d7e4
AK
3191 if (ist->decoding_needed) {
3192 avcodec_close(ist->st->codec);
3193 }
3194 }
3195
3196 /* finished ! */
3197 ret = 0;
3198
3199 fail:
b0c9e8e0 3200 av_freep(&no_packet);
6291d7e4 3201
4288e031
AK
3202 if (output_streams) {
3203 for (i = 0; i < nb_output_streams; i++) {
2e215267 3204 ost = output_streams[i];
6291d7e4 3205 if (ost) {
3d813e4c 3206 if (ost->stream_copy)
6291d7e4
AK
3207 av_freep(&ost->st->codec->extradata);
3208 if (ost->logfile) {
3209 fclose(ost->logfile);
3210 ost->logfile = NULL;
3211 }
6291d7e4 3212 av_freep(&ost->st->codec->subtitle_header);
6291d7e4 3213 av_free(ost->forced_kf_pts);
6291d7e4 3214 av_dict_free(&ost->opts);
6291d7e4
AK
3215 }
3216 }
6291d7e4
AK
3217 }
3218 return ret;
3219}
3220
ca46fde7 3221static double parse_frame_aspect_ratio(const char *arg)
6291d7e4
AK
3222{
3223 int x = 0, y = 0;
3224 double ar = 0;
3225 const char *p;
3226 char *end;
3227
3228 p = strchr(arg, ':');
3229 if (p) {
3230 x = strtol(arg, &end, 10);
3231 if (end == p)
7636c8c6 3232 y = strtol(end + 1, &end, 10);
6291d7e4
AK
3233 if (x > 0 && y > 0)
3234 ar = (double)x / (double)y;
3235 } else
3236 ar = strtod(arg, NULL);
3237
3238 if (!ar) {
e3245b26 3239 av_log(NULL, AV_LOG_FATAL, "Incorrect aspect ratio specification.\n");
ca46fde7 3240 exit_program(1);
6291d7e4 3241 }
ca46fde7 3242 return ar;
6291d7e4
AK
3243}
3244
35e6f8c1 3245static int opt_audio_codec(OptionsContext *o, const char *opt, const char *arg)
6291d7e4 3246{
35e6f8c1 3247 return parse_option(o, "codec:a", arg, options);
6291d7e4
AK
3248}
3249
35e6f8c1 3250static int opt_video_codec(OptionsContext *o, const char *opt, const char *arg)
6291d7e4 3251{
35e6f8c1 3252 return parse_option(o, "codec:v", arg, options);
6291d7e4
AK
3253}
3254
35e6f8c1 3255static int opt_subtitle_codec(OptionsContext *o, const char *opt, const char *arg)
6291d7e4 3256{
35e6f8c1 3257 return parse_option(o, "codec:s", arg, options);
6291d7e4
AK
3258}
3259
35e6f8c1 3260static int opt_data_codec(OptionsContext *o, const char *opt, const char *arg)
6291d7e4 3261{
35e6f8c1 3262 return parse_option(o, "codec:d", arg, options);
6291d7e4
AK
3263}
3264
575ec4e1 3265static int opt_map(OptionsContext *o, const char *opt, const char *arg)
6291d7e4 3266{
8d2e4a7e
AK
3267 StreamMap *m = NULL;
3268 int i, negative = 0, file_idx;
3269 int sync_file_idx = -1, sync_stream_idx;
3270 char *p, *sync;
3271 char *map;
6291d7e4 3272
8d2e4a7e
AK
3273 if (*arg == '-') {
3274 negative = 1;
3275 arg++;
3276 }
3277 map = av_strdup(arg);
6291d7e4 3278
8d2e4a7e
AK
3279 /* parse sync stream first, just pick first matching stream */
3280 if (sync = strchr(map, ',')) {
3281 *sync = 0;
3282 sync_file_idx = strtol(sync + 1, &sync, 0);
3283 if (sync_file_idx >= nb_input_files || sync_file_idx < 0) {
f24facd3 3284 av_log(NULL, AV_LOG_FATAL, "Invalid sync file index: %d.\n", sync_file_idx);
8d2e4a7e
AK
3285 exit_program(1);
3286 }
3287 if (*sync)
3288 sync++;
2e215267
AK
3289 for (i = 0; i < input_files[sync_file_idx]->nb_streams; i++)
3290 if (check_stream_specifier(input_files[sync_file_idx]->ctx,
3291 input_files[sync_file_idx]->ctx->streams[i], sync) == 1) {
8d2e4a7e
AK
3292 sync_stream_idx = i;
3293 break;
3294 }
2e215267 3295 if (i == input_files[sync_file_idx]->nb_streams) {
f24facd3 3296 av_log(NULL, AV_LOG_FATAL, "Sync stream specification in map %s does not "
8d2e4a7e
AK
3297 "match any streams.\n", arg);
3298 exit_program(1);
3299 }
3300 }
6291d7e4 3301
8d2e4a7e 3302
3b266da3
AK
3303 if (map[0] == '[') {
3304 /* this mapping refers to lavfi output */
3305 const char *c = map + 1;
3306 o->stream_maps = grow_array(o->stream_maps, sizeof(*o->stream_maps),
3307 &o->nb_stream_maps, o->nb_stream_maps + 1);
3308 m = &o->stream_maps[o->nb_stream_maps - 1];
3309 m->linklabel = av_get_token(&c, "]");
3310 if (!m->linklabel) {
3311 av_log(NULL, AV_LOG_ERROR, "Invalid output link label: %s.\n", map);
3312 exit_program(1);
3313 }
3314 } else {
3e901cbc
AK
3315 file_idx = strtol(map, &p, 0);
3316 if (file_idx >= nb_input_files || file_idx < 0) {
3317 av_log(NULL, AV_LOG_FATAL, "Invalid input file index: %d.\n", file_idx);
3318 exit_program(1);
8d2e4a7e 3319 }
3e901cbc
AK
3320 if (negative)
3321 /* disable some already defined maps */
3322 for (i = 0; i < o->nb_stream_maps; i++) {
3323 m = &o->stream_maps[i];
3324 if (file_idx == m->file_index &&
3325 check_stream_specifier(input_files[m->file_index]->ctx,
3326 input_files[m->file_index]->ctx->streams[m->stream_index],
3327 *p == ':' ? p + 1 : p) > 0)
3328 m->disabled = 1;
3329 }
3330 else
3331 for (i = 0; i < input_files[file_idx]->nb_streams; i++) {
3332 if (check_stream_specifier(input_files[file_idx]->ctx, input_files[file_idx]->ctx->streams[i],
3333 *p == ':' ? p + 1 : p) <= 0)
3334 continue;
3335 o->stream_maps = grow_array(o->stream_maps, sizeof(*o->stream_maps),
3336 &o->nb_stream_maps, o->nb_stream_maps + 1);
3337 m = &o->stream_maps[o->nb_stream_maps - 1];
3338
3339 m->file_index = file_idx;
3340 m->stream_index = i;
3341
3342 if (sync_file_idx >= 0) {
3343 m->sync_file_index = sync_file_idx;
3344 m->sync_stream_index = sync_stream_idx;
3345 } else {
3346 m->sync_file_index = file_idx;
3347 m->sync_stream_index = i;
3348 }
8d2e4a7e 3349 }
3b266da3 3350 }
8d2e4a7e
AK
3351
3352 if (!m) {
f24facd3 3353 av_log(NULL, AV_LOG_FATAL, "Stream map '%s' matches no streams.\n", arg);
8d2e4a7e
AK
3354 exit_program(1);
3355 }
3356
3357 av_freep(&map);
6291d7e4
AK
3358 return 0;
3359}
3360
4dbc6cee
AK
3361static int opt_attach(OptionsContext *o, const char *opt, const char *arg)
3362{
3363 o->attachments = grow_array(o->attachments, sizeof(*o->attachments),
3364 &o->nb_attachments, o->nb_attachments + 1);
3365 o->attachments[o->nb_attachments - 1] = arg;
3366 return 0;
3367}
3368
a7b5e841
AK
3369/**
3370 * Parse a metadata specifier in arg.
3371 * @param type metadata type is written here -- g(lobal)/s(tream)/c(hapter)/p(rogram)
3372 * @param index for type c/p, chapter/program index is written here
3373 * @param stream_spec for type s, the stream specifier is written here
3374 */
3375static void parse_meta_type(char *arg, char *type, int *index, const char **stream_spec)
6291d7e4 3376{
039267f1 3377 if (*arg) {
a2a38d96 3378 *type = *arg;
6291d7e4
AK
3379 switch (*arg) {
3380 case 'g':
3381 break;
3382 case 's':
a7b5e841
AK
3383 if (*(++arg) && *arg != ':') {
3384 av_log(NULL, AV_LOG_FATAL, "Invalid metadata specifier %s.\n", arg);
3385 exit_program(1);
3386 }
3387 *stream_spec = *arg == ':' ? arg + 1 : "";
3388 break;
6291d7e4
AK
3389 case 'c':
3390 case 'p':
e6e6060c
AK
3391 if (*(++arg) == ':')
3392 *index = strtol(++arg, NULL, 0);
6291d7e4
AK
3393 break;
3394 default:
e3245b26 3395 av_log(NULL, AV_LOG_FATAL, "Invalid metadata type %c.\n", *arg);
6291d7e4
AK
3396 exit_program(1);
3397 }
3398 } else
3399 *type = 'g';
3400}
3401
a7b5e841 3402static int copy_metadata(char *outspec, char *inspec, AVFormatContext *oc, AVFormatContext *ic, OptionsContext *o)
6291d7e4 3403{
a7b5e841
AK
3404 AVDictionary **meta_in = NULL;
3405 AVDictionary **meta_out;
3406 int i, ret = 0;
3407 char type_in, type_out;
3408 const char *istream_spec = NULL, *ostream_spec = NULL;
3409 int idx_in = 0, idx_out = 0;
6291d7e4 3410
a7b5e841
AK
3411 parse_meta_type(inspec, &type_in, &idx_in, &istream_spec);
3412 parse_meta_type(outspec, &type_out, &idx_out, &ostream_spec);
6291d7e4 3413
a7b5e841 3414 if (type_in == 'g' || type_out == 'g')
847529f8 3415 o->metadata_global_manual = 1;
a7b5e841 3416 if (type_in == 's' || type_out == 's')
847529f8 3417 o->metadata_streams_manual = 1;
a7b5e841 3418 if (type_in == 'c' || type_out == 'c')
847529f8 3419 o->metadata_chapters_manual = 1;
6291d7e4 3420
a7b5e841
AK
3421#define METADATA_CHECK_INDEX(index, nb_elems, desc)\
3422 if ((index) < 0 || (index) >= (nb_elems)) {\
3423 av_log(NULL, AV_LOG_FATAL, "Invalid %s index %d while processing metadata maps.\n",\
3424 (desc), (index));\
3425 exit_program(1);\
3426 }
3427
3428#define SET_DICT(type, meta, context, index)\
3429 switch (type) {\
3430 case 'g':\
3431 meta = &context->metadata;\
3432 break;\
3433 case 'c':\
3434 METADATA_CHECK_INDEX(index, context->nb_chapters, "chapter")\
3435 meta = &context->chapters[index]->metadata;\
3436 break;\
3437 case 'p':\
3438 METADATA_CHECK_INDEX(index, context->nb_programs, "program")\
3439 meta = &context->programs[index]->metadata;\
3440 break;\
3441 }\
3442
3443 SET_DICT(type_in, meta_in, ic, idx_in);
3444 SET_DICT(type_out, meta_out, oc, idx_out);
3445
3446 /* for input streams choose first matching stream */
3447 if (type_in == 's') {
3448 for (i = 0; i < ic->nb_streams; i++) {
3449 if ((ret = check_stream_specifier(ic, ic->streams[i], istream_spec)) > 0) {
3450 meta_in = &ic->streams[i]->metadata;
3451 break;
3452 } else if (ret < 0)
3453 exit_program(1);
3454 }
3455 if (!meta_in) {
3456 av_log(NULL, AV_LOG_FATAL, "Stream specifier %s does not match any streams.\n", istream_spec);
3457 exit_program(1);
3458 }
3459 }
3460
3461 if (type_out == 's') {
3462 for (i = 0; i < oc->nb_streams; i++) {
3463 if ((ret = check_stream_specifier(oc, oc->streams[i], ostream_spec)) > 0) {
3464 meta_out = &oc->streams[i]->metadata;
3465 av_dict_copy(meta_out, *meta_in, AV_DICT_DONT_OVERWRITE);
3466 } else if (ret < 0)
3467 exit_program(1);
3468 }
3469 } else
3470 av_dict_copy(meta_out, *meta_in, AV_DICT_DONT_OVERWRITE);
3471
6291d7e4
AK
3472 return 0;
3473}
3474
1b648c7c 3475static AVCodec *find_codec_or_die(const char *name, enum AVMediaType type, int encoder)
169f0647
AK
3476{
3477 const char *codec_string = encoder ? "encoder" : "decoder";
3478 AVCodec *codec;
3479
169f0647
AK
3480 codec = encoder ?
3481 avcodec_find_encoder_by_name(name) :
3482 avcodec_find_decoder_by_name(name);
7636c8c6 3483 if (!codec) {
f24facd3 3484 av_log(NULL, AV_LOG_FATAL, "Unknown %s '%s'\n", codec_string, name);
169f0647
AK
3485 exit_program(1);
3486 }
7636c8c6 3487 if (codec->type != type) {
f24facd3 3488 av_log(NULL, AV_LOG_FATAL, "Invalid %s type '%s'\n", codec_string, name);
169f0647
AK
3489 exit_program(1);
3490 }
1b648c7c 3491 return codec;
169f0647
AK
3492}
3493
1b648c7c 3494static AVCodec *choose_decoder(OptionsContext *o, AVFormatContext *s, AVStream *st)
169f0647 3495{
169f0647 3496 char *codec_name = NULL;
169f0647 3497
35e6f8c1 3498 MATCH_PER_STREAM_OPT(codec_names, str, codec_name, s, st);
1b648c7c
AK
3499 if (codec_name) {
3500 AVCodec *codec = find_codec_or_die(codec_name, st->codec->codec_type, 0);
3501 st->codec->codec_id = codec->id;
3502 return codec;
3503 } else
3504 return avcodec_find_decoder(st->codec->codec_id);
169f0647 3505}
6291d7e4 3506
88867844
AK
3507/**
3508 * Add all the streams from the given input file to the global
3509 * list of input streams.
3510 */
35e6f8c1 3511static void add_input_streams(OptionsContext *o, AVFormatContext *ic)
88867844 3512{
c88d5319 3513 int i;
88867844
AK
3514
3515 for (i = 0; i < ic->nb_streams; i++) {
3516 AVStream *st = ic->streams[i];
3517 AVCodecContext *dec = st->codec;
2e215267
AK
3518 InputStream *ist = av_mallocz(sizeof(*ist));
3519
3520 if (!ist)
3521 exit_program(1);
88867844 3522
88867844 3523 input_streams = grow_array(input_streams, sizeof(*input_streams), &nb_input_streams, nb_input_streams + 1);
2e215267
AK
3524 input_streams[nb_input_streams - 1] = ist;
3525
88867844
AK
3526 ist->st = st;
3527 ist->file_index = nb_input_files;
3528 ist->discard = 1;
13f6917c 3529 st->discard = AVDISCARD_ALL;
88867844
AK
3530 ist->opts = filter_codec_opts(codec_opts, ist->st->codec->codec_id, ic, st);
3531
059fb8c8
AK
3532 ist->ts_scale = 1.0;
3533 MATCH_PER_STREAM_OPT(ts_scale, dbl, ist->ts_scale, ic, st);
88867844 3534
1b648c7c 3535 ist->dec = choose_decoder(o, ic, st);
88867844
AK
3536
3537 switch (dec->codec_type) {
88867844 3538 case AVMEDIA_TYPE_VIDEO:
e77c8662
AK
3539 ist->resample_height = dec->height;