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