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