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