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