Move the allocation of the AVOutputStream structure earlier in the
[libav.git] / ffmpeg.c
CommitLineData
85f07f22 1/*
115329f1 2 * FFmpeg main
01310af2 3 * Copyright (c) 2000-2003 Fabrice Bellard
85f07f22 4 *
b78e7197
DB
5 * This file is part of FFmpeg.
6 *
7 * FFmpeg is free software; you can redistribute it and/or
bf5af568
FB
8 * modify it under the terms of the GNU Lesser General Public
9 * License as published by the Free Software Foundation; either
b78e7197 10 * version 2.1 of the License, or (at your option) any later version.
85f07f22 11 *
b78e7197 12 * FFmpeg is distributed in the hope that it will be useful,
85f07f22 13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
bf5af568
FB
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 * Lesser General Public License for more details.
85f07f22 16 *
bf5af568 17 * You should have received a copy of the GNU Lesser General Public
b78e7197 18 * License along with FFmpeg; if not, write to the Free Software
5509bffa 19 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
85f07f22 20 */
364a9607 21
7246177d 22/* needed for usleep() */
d0feff2a 23#define _XOPEN_SOURCE 600
7246177d 24
0f4e8165
RB
25#include "config.h"
26#include <ctype.h>
27#include <string.h>
28#include <math.h>
29#include <stdlib.h>
30#include <errno.h>
d86b83f8 31#include <signal.h>
22f7a060 32#include <limits.h>
7246177d 33#include <unistd.h>
245976da
DB
34#include "libavformat/avformat.h"
35#include "libavdevice/avdevice.h"
36#include "libswscale/swscale.h"
245976da 37#include "libavcodec/opt.h"
ce1ee094 38#include "libavcodec/audioconvert.h"
126b638e 39#include "libavcore/parseutils.h"
2b4abbd6 40#include "libavutil/colorspace.h"
245976da 41#include "libavutil/fifo.h"
718c7b18 42#include "libavutil/pixdesc.h"
245976da 43#include "libavutil/avstring.h"
335ee1aa 44#include "libavutil/libm.h"
245976da 45#include "libavformat/os_support.h"
daf8e955 46
46847a33
MN
47#if CONFIG_AVFILTER
48# include "libavfilter/avfilter.h"
49# include "libavfilter/avfiltergraph.h"
50# include "libavfilter/graphparser.h"
51# include "libavfilter/vsrc_buffer.h"
52#endif
53
b250f9c6 54#if HAVE_SYS_RESOURCE_H
0a1b29de 55#include <sys/types.h>
fc5607f8 56#include <sys/time.h>
b091aa44 57#include <sys/resource.h>
b250f9c6 58#elif HAVE_GETPROCESSTIMES
7495c306
RP
59#include <windows.h>
60#endif
fc5607f8
RD
61#if HAVE_GETPROCESSMEMORYINFO
62#include <windows.h>
63#include <psapi.h>
64#endif
7495c306 65
b250f9c6 66#if HAVE_SYS_SELECT_H
fb1d2d7b
BC
67#include <sys/select.h>
68#endif
69
b250f9c6 70#if HAVE_TERMIOS_H
85f07f22
FB
71#include <fcntl.h>
72#include <sys/ioctl.h>
85f07f22 73#include <sys/time.h>
85f07f22 74#include <termios.h>
b250f9c6 75#elif HAVE_CONIO_H
4b54c6d0 76#include <conio.h>
bdc4796f 77#endif
bf5af568 78#include <time.h>
85f07f22 79
01310af2
FB
80#include "cmdutils.h"
81
b64b4134 82#include "libavutil/avassert.h"
2b18dcd0 83
64555bd9 84const char program_name[] = "FFmpeg";
ea9c581f 85const int program_birth_year = 2000;
86074ed1 86
85f07f22
FB
87/* select an input stream for an output stream */
88typedef struct AVStreamMap {
89 int file_index;
90 int stream_index;
b4a3389e
WG
91 int sync_file_index;
92 int sync_stream_index;
85f07f22
FB
93} AVStreamMap;
94
3f07e8db
MN
95/**
96 * select an input file for an output file
97 */
0a38bafd
PB
98typedef struct AVMetaDataMap {
99 int out_file;
100 int in_file;
101} AVMetaDataMap;
102
580a6c57 103static const OptionDef options[];
85f07f22 104
60402344 105#define MAX_FILES 100
84fd51e5
AJ
106#if !FF_API_MAX_STREAMS
107#define MAX_STREAMS 1024 /* arbitrary sanity check value */
108#endif
85f07f22 109
ef6fc647 110static const char *last_asked_format = NULL;
85f07f22 111static AVFormatContext *input_files[MAX_FILES];
a6a92a9a 112static int64_t input_files_ts_offset[MAX_FILES];
2c6958aa 113static double *input_files_ts_scale[MAX_FILES] = {NULL};
311e223f 114static AVCodec **input_codecs = NULL;
85f07f22 115static int nb_input_files = 0;
311e223f 116static int nb_input_codecs = 0;
2c6958aa 117static int nb_input_files_ts_scale[MAX_FILES] = {0};
85f07f22
FB
118
119static AVFormatContext *output_files[MAX_FILES];
0a6d97b3 120static AVCodec **output_codecs = NULL;
85f07f22 121static int nb_output_files = 0;
0a6d97b3 122static int nb_output_codecs = 0;
85f07f22 123
3a8e8824 124static AVStreamMap *stream_maps = NULL;
85f07f22
FB
125static int nb_stream_maps;
126
0a38bafd
PB
127static AVMetaDataMap meta_data_maps[MAX_FILES];
128static int nb_meta_data_maps;
129
006e8108 130/* indexed by output file stream index */
e640f261
AJ
131static int *streamid_map = NULL;
132static int nb_streamid_map = 0;
006e8108 133
55cf1959
MN
134static int frame_width = 0;
135static int frame_height = 0;
880e8ba7 136static float frame_aspect_ratio = 0;
644a9262 137static enum PixelFormat frame_pix_fmt = PIX_FMT_NONE;
ce1ee094 138static enum SampleFormat audio_sample_fmt = SAMPLE_FMT_NONE;
ab6d194a
MN
139static int frame_topBand = 0;
140static int frame_bottomBand = 0;
141static int frame_leftBand = 0;
142static int frame_rightBand = 0;
cf7fc795 143static int max_frames[4] = {INT_MAX, INT_MAX, INT_MAX, INT_MAX};
89129c6b 144static AVRational frame_rate;
158c7f05 145static float video_qscale = 0;
84f608f4
VM
146static uint16_t *intra_matrix = NULL;
147static uint16_t *inter_matrix = NULL;
464a631c 148static const char *video_rc_override_string=NULL;
85f07f22 149static int video_disable = 0;
f3356e9c 150static int video_discard = 0;
4a897224 151static char *video_codec_name = NULL;
83a36b2e 152static unsigned int video_codec_tag = 0;
0fc2c0f6 153static char *video_language = NULL;
85f07f22 154static int same_quality = 0;
cfcf0ffd 155static int do_deinterlace = 0;
bb198e19 156static int top_field_first = -1;
f4f3223f 157static int me_threshold = 0;
1a11cbcc 158static int intra_dc_precision = 8;
5894e1bb 159static int loop_input = 0;
8108551a 160static int loop_output = AVFMT_NOOUTPUTLOOP;
0888fd22 161static int qp_hist = 0;
46847a33
MN
162#if CONFIG_AVFILTER
163static char *vfilters = NULL;
aa1249b8 164AVFilterGraph *graph = NULL;
46847a33 165#endif
85f07f22 166
85f07f22
FB
167static int intra_only = 0;
168static int audio_sample_rate = 44100;
13367a46 169static int64_t channel_layout = 0;
c57c770d
JR
170#define QSCALE_NONE -99999
171static float audio_qscale = QSCALE_NONE;
85f07f22
FB
172static int audio_disable = 0;
173static int audio_channels = 1;
4a897224 174static char *audio_codec_name = NULL;
83a36b2e 175static unsigned int audio_codec_tag = 0;
cf7fc795
FB
176static char *audio_language = NULL;
177
11bf3847 178static int subtitle_disable = 0;
4a897224 179static char *subtitle_codec_name = NULL;
cf7fc795 180static char *subtitle_language = NULL;
83a36b2e 181static unsigned int subtitle_codec_tag = 0;
85f07f22 182
17c88cb0
MN
183static float mux_preload= 0.5;
184static float mux_max_delay= 0.7;
2db3c638 185
fc7ad2af 186static int64_t recording_time = INT64_MAX;
8831db5c 187static int64_t start_time = 0;
25d34458 188static int64_t recording_timestamp = 0;
a6a92a9a 189static int64_t input_ts_offset = 0;
85f07f22 190static int file_overwrite = 0;
a5926d85
AJ
191static int metadata_count;
192static AVMetadataTag *metadata;
5727b222 193static int do_benchmark = 0;
a0663ba4 194static int do_hex_dump = 0;
254abc2e 195static int do_pkt_dump = 0;
43f1708f 196static int do_psnr = 0;
5abdb4b1 197static int do_pass = 0;
ad16627f 198static char *pass_logfilename_prefix = NULL;
1629626f
FB
199static int audio_stream_copy = 0;
200static int video_stream_copy = 0;
cf7fc795 201static int subtitle_stream_copy = 0;
8858816d 202static int video_sync_method= -1;
986ebcdb 203static int audio_sync_method= 0;
d4d226a8 204static float audio_drift_threshold= 0.1;
72bd8100 205static int copy_ts= 0;
76bdac6d 206static int opt_shortest = 0;
90ad92b3 207static int video_global_header = 0;
b60d1379 208static char *vstats_filename;
032aa7df 209static FILE *vstats_file;
50e143c4 210static int opt_programid = 0;
50e3477f 211static int copy_initial_nonkeyframes = 0;
5abdb4b1 212
bdfcbbed
MK
213static int rate_emu = 0;
214
a5df11ab 215static int video_channel = 0;
df0cecdd 216static char *video_standard;
79a7c268 217
a9aa3467 218static int audio_volume = 256;
8aa3ee32 219
f2abc559 220static int exit_on_error = 0;
d9a916e2 221static int using_stdin = 0;
f068206e 222static int verbose = 1;
9c3d33d6 223static int thread_count= 1;
b51469a0 224static int q_pressed = 0;
1008ceb3
MN
225static int64_t video_size = 0;
226static int64_t audio_size = 0;
227static int64_t extra_size = 0;
a6a92a9a
WG
228static int nb_frames_dup = 0;
229static int nb_frames_drop = 0;
6e454c38 230static int input_sync;
76bdac6d 231static uint64_t limit_filesize = 0;
d2845b75 232static int force_fps = 0;
d9a916e2 233
5b6d5596 234static int pgmyuv_compatibility_hack=0;
a8482aab 235static float dts_delta_threshold = 10;
5b6d5596 236
e60da588 237static unsigned int sws_flags = SWS_BICUBIC;
18a54b04 238
29cc1c23 239static int64_t timer_start;
8bbf6db9 240
3321cb3f
BC
241static uint8_t *audio_buf;
242static uint8_t *audio_out;
b8919a30 243unsigned int allocated_audio_out_size, allocated_audio_buf_size;
3321cb3f
BC
244
245static short *samples;
246
748c2fca
MN
247static AVBitStreamFilterContext *video_bitstream_filters=NULL;
248static AVBitStreamFilterContext *audio_bitstream_filters=NULL;
e1cc8339 249static AVBitStreamFilterContext *subtitle_bitstream_filters=NULL;
620a67d5
AJ
250static AVBitStreamFilterContext **bitstream_filters[MAX_FILES] = {NULL};
251static int nb_bitstream_filters[MAX_FILES] = {0};
5b6d5596 252
ad16627f 253#define DEFAULT_PASS_LOGFILENAME_PREFIX "ffmpeg2pass"
85f07f22 254
b4a3389e
WG
255struct AVInputStream;
256
85f07f22
FB
257typedef struct AVOutputStream {
258 int file_index; /* file index */
259 int index; /* stream index in the output file */
260 int source_index; /* AVInputStream index */
261 AVStream *st; /* stream in the output file */
ec5517d5
FB
262 int encoding_needed; /* true if encoding needed for this stream */
263 int frame_number;
264 /* input pts and corresponding output pts
265 for A/V sync */
b4a3389e
WG
266 //double sync_ipts; /* dts from the AVPacket of the demuxer in second units */
267 struct AVInputStream *sync_ist; /* input stream to sync against */
e928649b 268 int64_t sync_opts; /* output frame counter, could be changed to some true timestamp */ //FIXME look at frame_number
85f07f22 269 /* video only */
07d0cdfc 270 int video_resample;
a4d36c11 271 AVFrame pict_tmp; /* temporary image for resampling */
18a54b04
LA
272 struct SwsContext *img_resample_ctx; /* for image resampling */
273 int resample_height;
352666c1 274 int resample_width;
01a3c821 275 int resample_pix_fmt;
34b10a57 276
352666c1
EB
277 /* full frame size of first frame */
278 int original_height;
279 int original_width;
280
281 /* cropping area sizes */
07d0cdfc 282 int video_crop;
352666c1
EB
283 int topBand;
284 int bottomBand;
34b10a57 285 int leftBand;
352666c1
EB
286 int rightBand;
287
288 /* cropping area of first frame */
289 int original_topBand;
290 int original_bottomBand;
291 int original_leftBand;
292 int original_rightBand;
115329f1 293
85f07f22
FB
294 /* audio only */
295 int audio_resample;
296 ReSampleContext *resample; /* for audio resampling */
a79db0f7
PR
297 int reformat_pair;
298 AVAudioConvert *reformat_ctx;
41dd680d 299 AVFifoBuffer *fifo; /* for compression: one audio fifo per codec */
5abdb4b1 300 FILE *logfile;
85f07f22
FB
301} AVOutputStream;
302
9fdf4b58
NG
303static AVOutputStream **output_streams_for_file[MAX_FILES] = { NULL };
304static int nb_output_streams_for_file[MAX_FILES] = { 0 };
305
85f07f22
FB
306typedef struct AVInputStream {
307 int file_index;
308 int index;
309 AVStream *st;
310 int discard; /* true if stream data should be discarded */
311 int decoding_needed; /* true if the packets must be decoded in 'raw_fifo' */
0c1a9eda 312 int64_t sample_index; /* current sample */
bdfcbbed
MK
313
314 int64_t start; /* time when read started */
254abc2e
FB
315 int64_t next_pts; /* synthetic pts for cases where pkt.pts
316 is not defined */
e7d0374f 317 int64_t pts; /* current pts */
0ff4f0c0 318 PtsCorrectionContext pts_ctx;
ff4905a5 319 int is_start; /* is 1 at the start and after a discontinuity */
3ff0daf0 320 int showed_multi_packet_warning;
55a7e946 321 int is_past_recording_time;
46847a33 322#if CONFIG_AVFILTER
dfd57757 323 AVFilterContext *output_video_filter;
46847a33
MN
324 AVFilterContext *input_video_filter;
325 AVFrame *filter_frame;
326 int has_filter_frame;
ecc8dada 327 AVFilterBufferRef *picref;
46847a33 328#endif
85f07f22
FB
329} AVInputStream;
330
331typedef struct AVInputFile {
332 int eof_reached; /* true if eof reached */
333 int ist_index; /* index of first stream in ist_table */
334 int buffer_size; /* current total buffer size */
79fdaa4c 335 int nb_streams; /* nb streams we are aware of */
85f07f22
FB
336} AVInputFile;
337
b250f9c6 338#if HAVE_TERMIOS_H
bdc4796f 339
85f07f22
FB
340/* init terminal so that we can grab keys */
341static struct termios oldtty;
64f6e357 342#endif
85f07f22 343
46847a33 344#if CONFIG_AVFILTER
46847a33
MN
345
346static int get_filtered_video_pic(AVFilterContext *ctx,
ecc8dada 347 AVFilterBufferRef **picref, AVFrame *pic2,
46847a33
MN
348 uint64_t *pts)
349{
ecc8dada 350 AVFilterBufferRef *pic;
46847a33
MN
351
352 if(avfilter_request_frame(ctx->inputs[0]))
353 return -1;
5d4890d7 354 if(!(pic = ctx->inputs[0]->cur_buf))
46847a33
MN
355 return -1;
356 *picref = pic;
5d4890d7 357 ctx->inputs[0]->cur_buf = NULL;
46847a33
MN
358
359 *pts = pic->pts;
360
361 memcpy(pic2->data, pic->data, sizeof(pic->data));
362 memcpy(pic2->linesize, pic->linesize, sizeof(pic->linesize));
cc80caff
HM
363 pic2->interlaced_frame = pic->video->interlaced;
364 pic2->top_field_first = pic->video->top_field_first;
46847a33
MN
365
366 return 1;
367}
368
46847a33
MN
369static int configure_filters(AVInputStream *ist, AVOutputStream *ost)
370{
a9f3cb93 371 AVFilterContext *last_filter, *filter;
46847a33
MN
372 /** filter graph containing all filters including input & output */
373 AVCodecContext *codec = ost->st->codec;
374 AVCodecContext *icodec = ist->st->codec;
f7ead94c 375 FFSinkContext ffsink_ctx = { .pix_fmt = codec->pix_fmt };
46847a33 376 char args[255];
4ddf0d29 377 int ret;
46847a33 378
aa1249b8 379 graph = av_mallocz(sizeof(AVFilterGraph));
46847a33 380
4ddf0d29
SS
381 if ((ret = avfilter_open(&ist->input_video_filter, avfilter_get_by_name("buffer"), "src")) < 0)
382 return ret;
f7ead94c 383 if ((ret = avfilter_open(&ist->output_video_filter, &ffsink, "out")) < 0)
4ddf0d29 384 return ret;
46847a33 385
94498ec9
SS
386 snprintf(args, 255, "%d:%d:%d:%d:%d", ist->st->codec->width,
387 ist->st->codec->height, ist->st->codec->pix_fmt,
388 ist->st->time_base.num, ist->st->time_base.den);
4ddf0d29
SS
389 if ((ret = avfilter_init_filter(ist->input_video_filter, args, NULL)) < 0)
390 return ret;
f7ead94c 391 if ((ret = avfilter_init_filter(ist->output_video_filter, NULL, &ffsink_ctx)) < 0)
4ddf0d29 392 return ret;
46847a33
MN
393
394 /* add input and output filters to the overall graph */
aa1249b8 395 avfilter_graph_add_filter(graph, ist->input_video_filter);
dfd57757 396 avfilter_graph_add_filter(graph, ist->output_video_filter);
46847a33 397
a9f3cb93 398 last_filter = ist->input_video_filter;
46847a33 399
79b90b25 400 if (ost->video_crop) {
2bc05d35
SS
401 snprintf(args, 255, "%d:%d:%d:%d",
402 codec->width, codec->height,
403 ost->leftBand, ost->topBand);
4ddf0d29
SS
404 if ((ret = avfilter_open(&filter, avfilter_get_by_name("crop"), NULL)) < 0)
405 return ret;
406 if ((ret = avfilter_init_filter(filter, args, NULL)) < 0)
407 return ret;
408 if ((ret = avfilter_link(last_filter, 0, filter, 0)) < 0)
409 return ret;
a9f3cb93
BC
410 last_filter = filter;
411 avfilter_graph_add_filter(graph, last_filter);
46847a33
MN
412 }
413
414 if((codec->width !=
0c22311b
MN
415 icodec->width - (frame_leftBand + frame_rightBand)) ||
416 (codec->height != icodec->height - (frame_topBand + frame_bottomBand))) {
6e82e7fa 417 snprintf(args, 255, "%d:%d:flags=0x%X",
0c22311b
MN
418 codec->width,
419 codec->height,
46847a33 420 (int)av_get_int(sws_opts, "sws_flags", NULL));
4ddf0d29
SS
421 if ((ret = avfilter_open(&filter, avfilter_get_by_name("scale"), NULL)) < 0)
422 return ret;
423 if ((ret = avfilter_init_filter(filter, args, NULL)) < 0)
424 return ret;
425 if ((ret = avfilter_link(last_filter, 0, filter, 0)) < 0)
426 return ret;
a9f3cb93
BC
427 last_filter = filter;
428 avfilter_graph_add_filter(graph, last_filter);
46847a33
MN
429 }
430
f96363df
BC
431 snprintf(args, sizeof(args), "flags=0x%X", (int)av_get_int(sws_opts, "sws_flags", NULL));
432 graph->scale_sws_opts = av_strdup(args);
433
79b90b25 434 if (vfilters) {
46847a33
MN
435 AVFilterInOut *outputs = av_malloc(sizeof(AVFilterInOut));
436 AVFilterInOut *inputs = av_malloc(sizeof(AVFilterInOut));
437
438 outputs->name = av_strdup("in");
a9f3cb93 439 outputs->filter = last_filter;
46847a33
MN
440 outputs->pad_idx = 0;
441 outputs->next = NULL;
442
443 inputs->name = av_strdup("out");
dfd57757 444 inputs->filter = ist->output_video_filter;
46847a33
MN
445 inputs->pad_idx = 0;
446 inputs->next = NULL;
447
4ddf0d29
SS
448 if ((ret = avfilter_graph_parse(graph, vfilters, inputs, outputs, NULL)) < 0)
449 return ret;
46847a33
MN
450 av_freep(&vfilters);
451 } else {
dfd57757 452 if ((ret = avfilter_link(last_filter, 0, ist->output_video_filter, 0)) < 0)
4ddf0d29 453 return ret;
46847a33
MN
454 }
455
46847a33 456 /* configure all the filter links */
4ddf0d29
SS
457 if ((ret = avfilter_graph_check_validity(graph, NULL)) < 0)
458 return ret;
459 if ((ret = avfilter_graph_config_formats(graph, NULL)) < 0)
460 return ret;
461 if ((ret = avfilter_graph_config_links(graph, NULL)) < 0)
462 return ret;
46847a33 463
dfd57757
SS
464 codec->width = ist->output_video_filter->inputs[0]->w;
465 codec->height = ist->output_video_filter->inputs[0]->h;
46847a33
MN
466
467 return 0;
468}
469#endif /* CONFIG_AVFILTER */
470
85f07f22
FB
471static void term_exit(void)
472{
6b6bca64 473 av_log(NULL, AV_LOG_QUIET, "");
64f6e357 474#if HAVE_TERMIOS_H
85f07f22 475 tcsetattr (0, TCSANOW, &oldtty);
9a9509e6 476#endif
64f6e357 477}
85f07f22 478
e9a832e5 479static volatile int received_sigterm = 0;
9680a722
RP
480
481static void
482sigterm_handler(int sig)
483{
484 received_sigterm = sig;
485 term_exit();
486}
487
85f07f22
FB
488static void term_init(void)
489{
b250f9c6 490#if HAVE_TERMIOS_H
85f07f22
FB
491 struct termios tty;
492
493 tcgetattr (0, &tty);
494 oldtty = tty;
9a9509e6 495 atexit(term_exit);
85f07f22
FB
496
497 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
498 |INLCR|IGNCR|ICRNL|IXON);
499 tty.c_oflag |= OPOST;
500 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
501 tty.c_cflag &= ~(CSIZE|PARENB);
502 tty.c_cflag |= CS8;
503 tty.c_cc[VMIN] = 1;
504 tty.c_cc[VTIME] = 0;
115329f1 505
85f07f22 506 tcsetattr (0, TCSANOW, &tty);
d86b83f8
RP
507 signal(SIGQUIT, sigterm_handler); /* Quit (POSIX). */
508#endif
85f07f22 509
9680a722 510 signal(SIGINT , sigterm_handler); /* Interrupt (ANSI). */
9680a722 511 signal(SIGTERM, sigterm_handler); /* Termination (ANSI). */
ffcc6e24
MR
512#ifdef SIGXCPU
513 signal(SIGXCPU, sigterm_handler);
514#endif
85f07f22
FB
515}
516
517/* read a key without blocking */
518static int read_key(void)
519{
b250f9c6 520#if HAVE_TERMIOS_H
9ddd71fc 521 int n = 1;
85f07f22 522 unsigned char ch;
9ddd71fc 523 struct timeval tv;
85f07f22
FB
524 fd_set rfds;
525
526 FD_ZERO(&rfds);
527 FD_SET(0, &rfds);
528 tv.tv_sec = 0;
529 tv.tv_usec = 0;
530 n = select(1, &rfds, NULL, NULL, &tv);
531 if (n > 0) {
cb09b2ed
PG
532 n = read(0, &ch, 1);
533 if (n == 1)
85f07f22 534 return ch;
cb09b2ed
PG
535
536 return n;
85f07f22 537 }
b250f9c6 538#elif HAVE_CONIO_H
4b54c6d0
RP
539 if(kbhit())
540 return(getch());
d86b83f8 541#endif
85f07f22
FB
542 return -1;
543}
544
b51469a0
LS
545static int decode_interrupt_cb(void)
546{
547 return q_pressed || (q_pressed = read_key() == 'q');
548}
549
639e4ec8 550static int ffmpeg_exit(int ret)
e5295c0d
RP
551{
552 int i;
553
554 /* close files */
555 for(i=0;i<nb_output_files;i++) {
556 /* maybe av_close_output_file ??? */
557 AVFormatContext *s = output_files[i];
558 int j;
8767060c 559 if (!(s->oformat->flags & AVFMT_NOFILE) && s->pb)
e5295c0d
RP
560 url_fclose(s->pb);
561 for(j=0;j<s->nb_streams;j++) {
094d9df7 562 av_metadata_free(&s->streams[j]->metadata);
e5295c0d 563 av_free(s->streams[j]->codec);
fd0368e7 564 av_free(s->streams[j]->info);
e5295c0d
RP
565 av_free(s->streams[j]);
566 }
094d9df7
AJ
567 for(j=0;j<s->nb_programs;j++) {
568 av_metadata_free(&s->programs[j]->metadata);
569 }
570 for(j=0;j<s->nb_chapters;j++) {
571 av_metadata_free(&s->chapters[j]->metadata);
572 }
573 av_metadata_free(&s->metadata);
e5295c0d 574 av_free(s);
620a67d5 575 av_free(bitstream_filters[i]);
9fdf4b58 576 av_free(output_streams_for_file[i]);
e5295c0d 577 }
2c6958aa 578 for(i=0;i<nb_input_files;i++) {
e5295c0d 579 av_close_input_file(input_files[i]);
2c6958aa
AJ
580 av_free(input_files_ts_scale[i]);
581 }
e5295c0d 582
e5295c0d
RP
583 av_free(intra_matrix);
584 av_free(inter_matrix);
585
586 if (vstats_file)
587 fclose(vstats_file);
588 av_free(vstats_filename);
589
590 av_free(opt_names);
e640f261 591 av_free(streamid_map);
311e223f 592 av_free(input_codecs);
0a6d97b3 593 av_free(output_codecs);
3a8e8824 594 av_free(stream_maps);
e5295c0d
RP
595
596 av_free(video_codec_name);
597 av_free(audio_codec_name);
598 av_free(subtitle_codec_name);
599
600 av_free(video_standard);
601
a5c33faa 602 uninit_opts();
3321cb3f
BC
603 av_free(audio_buf);
604 av_free(audio_out);
b8919a30 605 allocated_audio_buf_size= allocated_audio_out_size= 0;
3321cb3f 606 av_free(samples);
5973490a 607
46847a33
MN
608#if CONFIG_AVFILTER
609 avfilter_uninit();
610#endif
611
e5295c0d
RP
612 if (received_sigterm) {
613 fprintf(stderr,
614 "Received signal %d: terminating.\n",
615 (int) received_sigterm);
616 exit (255);
617 }
618
296df4e7
RP
619 exit(ret); /* not all OS-es handle main() return value */
620 return ret;
dba249ab
AJ
621}
622
623/* similar to ff_dynarray_add() and av_fast_realloc() */
624static void *grow_array(void *array, int elem_size, int *size, int new_size)
625{
626 if (new_size >= INT_MAX / elem_size) {
627 fprintf(stderr, "Array too big.\n");
628 ffmpeg_exit(1);
629 }
630 if (*size < new_size) {
631 uint8_t *tmp = av_realloc(array, new_size*elem_size);
632 if (!tmp) {
633 fprintf(stderr, "Could not alloc buffer.\n");
634 ffmpeg_exit(1);
635 }
636 memset(tmp + *size*elem_size, 0, (new_size-*size) * elem_size);
637 *size = new_size;
638 return tmp;
639 }
640 return array;
e5295c0d
RP
641}
642
aa1de0d9
RB
643static void choose_sample_fmt(AVStream *st, AVCodec *codec)
644{
645 if(codec && codec->sample_fmts){
646 const enum SampleFormat *p= codec->sample_fmts;
647 for(; *p!=-1; p++){
648 if(*p == st->codec->sample_fmt)
649 break;
650 }
651 if(*p == -1)
652 st->codec->sample_fmt = codec->sample_fmts[0];
653 }
654}
655
10d0f5e0
MN
656static void choose_sample_rate(AVStream *st, AVCodec *codec)
657{
658 if(codec && codec->supported_samplerates){
659 const int *p= codec->supported_samplerates;
3c5e1b36 660 int best=0;
10d0f5e0
MN
661 int best_dist=INT_MAX;
662 for(; *p; p++){
663 int dist= abs(st->codec->sample_rate - *p);
664 if(dist < best_dist){
665 best_dist= dist;
666 best= *p;
667 }
668 }
ff866063
MN
669 if(best_dist){
670 av_log(st->codec, AV_LOG_WARNING, "Requested sampling rate unsupported using closest supported (%d)\n", best);
671 }
10d0f5e0
MN
672 st->codec->sample_rate= best;
673 }
674}
675
aa1de0d9
RB
676static void choose_pixel_fmt(AVStream *st, AVCodec *codec)
677{
678 if(codec && codec->pix_fmts){
679 const enum PixelFormat *p= codec->pix_fmts;
680 for(; *p!=-1; p++){
681 if(*p == st->codec->pix_fmt)
682 break;
683 }
684 if(*p == -1
685 && !( st->codec->codec_id==CODEC_ID_MJPEG
2d525ef4 686 && st->codec->strict_std_compliance <= FF_COMPLIANCE_UNOFFICIAL
aa1de0d9
RB
687 && ( st->codec->pix_fmt == PIX_FMT_YUV420P
688 || st->codec->pix_fmt == PIX_FMT_YUV422P)))
689 st->codec->pix_fmt = codec->pix_fmts[0];
690 }
691}
692
b29f97d1 693static int read_ffserver_streams(AVFormatContext *s, const char *filename)
85f07f22 694{
79fdaa4c 695 int i, err;
85f07f22 696 AVFormatContext *ic;
3438d82d 697 int nopts = 0;
85f07f22 698
79fdaa4c
FB
699 err = av_open_input_file(&ic, filename, NULL, FFM_PACKET_SIZE, NULL);
700 if (err < 0)
701 return err;
85f07f22
FB
702 /* copy stream format */
703 s->nb_streams = ic->nb_streams;
704 for(i=0;i<ic->nb_streams;i++) {
705 AVStream *st;
d9521cb1 706 AVCodec *codec;
1e491e29 707
f37f8d4c 708 // FIXME: a more elegant solution is needed
e1031171 709 st = av_mallocz(sizeof(AVStream));
85f07f22 710 memcpy(st, ic->streams[i], sizeof(AVStream));
f37f8d4c 711 st->codec = avcodec_alloc_context();
7ef61879
RP
712 if (!st->codec) {
713 print_error(filename, AVERROR(ENOMEM));
639e4ec8 714 ffmpeg_exit(1);
7ef61879 715 }
d9521cb1 716 avcodec_copy_context(st->codec, ic->streams[i]->codec);
85f07f22 717 s->streams[i] = st;
837d248d 718
d9521cb1
RB
719 codec = avcodec_find_encoder(st->codec->codec_id);
720 if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO) {
721 if (audio_stream_copy) {
722 st->stream_copy = 1;
723 } else
724 choose_sample_fmt(st, codec);
725 } else if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
726 if (video_stream_copy) {
727 st->stream_copy = 1;
728 } else
729 choose_pixel_fmt(st, codec);
730 }
837d248d 731
dbedf2aa
BC
732 if(!st->codec->thread_count)
733 st->codec->thread_count = 1;
734 if(st->codec->thread_count>1)
735 avcodec_thread_init(st->codec, st->codec->thread_count);
736
3438d82d
BC
737 if(st->codec->flags & CODEC_FLAG_BITEXACT)
738 nopts = 1;
85f07f22
FB
739 }
740
3438d82d
BC
741 if (!nopts)
742 s->timestamp = av_gettime();
743
85f07f22
FB
744 av_close_input_file(ic);
745 return 0;
746}
747
b4a3389e
WG
748static double
749get_sync_ipts(const AVOutputStream *ost)
750{
751 const AVInputStream *ist = ost->sync_ist;
fec401f7 752 return (double)(ist->pts - start_time)/AV_TIME_BASE;
b4a3389e
WG
753}
754
748c2fca 755static void write_frame(AVFormatContext *s, AVPacket *pkt, AVCodecContext *avctx, AVBitStreamFilterContext *bsfc){
0ac07031
MN
756 int ret;
757
748c2fca
MN
758 while(bsfc){
759 AVPacket new_pkt= *pkt;
760 int a= av_bitstream_filter_filter(bsfc, avctx, NULL,
761 &new_pkt.data, &new_pkt.size,
762 pkt->data, pkt->size,
cc947f04 763 pkt->flags & AV_PKT_FLAG_KEY);
7055cdac 764 if(a>0){
748c2fca
MN
765 av_free_packet(pkt);
766 new_pkt.destruct= av_destruct_packet;
7055cdac 767 } else if(a<0){
1f8e32cd
DB
768 fprintf(stderr, "%s failed for stream %d, codec %s",
769 bsfc->filter->name, pkt->stream_index,
770 avctx->codec ? avctx->codec->name : "copy");
7055cdac 771 print_error("", a);
f2abc559 772 if (exit_on_error)
639e4ec8 773 ffmpeg_exit(1);
748c2fca
MN
774 }
775 *pkt= new_pkt;
776
777 bsfc= bsfc->next;
778 }
779
0ac07031
MN
780 ret= av_interleaved_write_frame(s, pkt);
781 if(ret < 0){
782 print_error("av_interleaved_write_frame()", ret);
639e4ec8 783 ffmpeg_exit(1);
0ac07031 784 }
748c2fca
MN
785}
786
817b23ff 787#define MAX_AUDIO_PACKET_SIZE (128 * 1024)
85f07f22 788
115329f1
DB
789static void do_audio_out(AVFormatContext *s,
790 AVOutputStream *ost,
85f07f22
FB
791 AVInputStream *ist,
792 unsigned char *buf, int size)
793{
0c1a9eda 794 uint8_t *buftmp;
15bfe412 795 int64_t audio_out_size, audio_buf_size;
7a086a85 796 int64_t allocated_for_size= size;
d66c7abc 797
85f07f22 798 int size_out, frame_bytes, ret;
01f4895c 799 AVCodecContext *enc= ost->st->codec;
2886f311 800 AVCodecContext *dec= ist->st->codec;
287ba997
PR
801 int osize= av_get_bits_per_sample_format(enc->sample_fmt)/8;
802 int isize= av_get_bits_per_sample_format(dec->sample_fmt)/8;
15bfe412
MN
803 const int coded_bps = av_get_bits_per_sample(enc->codec->id);
804
7a086a85
MN
805need_realloc:
806 audio_buf_size= (allocated_for_size + isize*dec->channels - 1) / (isize*dec->channels);
15bfe412 807 audio_buf_size= (audio_buf_size*enc->sample_rate + dec->sample_rate) / dec->sample_rate;
8b484d0f 808 audio_buf_size= audio_buf_size*2 + 10000; //safety factors for the deprecated resampling API
79c85beb 809 audio_buf_size= FFMAX(audio_buf_size, enc->frame_size);
15bfe412
MN
810 audio_buf_size*= osize*enc->channels;
811
812 audio_out_size= FFMAX(audio_buf_size, enc->frame_size * osize * enc->channels);
813 if(coded_bps > 8*osize)
814 audio_out_size= audio_out_size * coded_bps / (8*osize);
815 audio_out_size += FF_MIN_BUFFER_SIZE;
816
817 if(audio_out_size > INT_MAX || audio_buf_size > INT_MAX){
818 fprintf(stderr, "Buffer sizes too large\n");
639e4ec8 819 ffmpeg_exit(1);
15bfe412 820 }
85f07f22 821
b8919a30
MN
822 av_fast_malloc(&audio_buf, &allocated_audio_buf_size, audio_buf_size);
823 av_fast_malloc(&audio_out, &allocated_audio_out_size, audio_out_size);
e185a2f6
MN
824 if (!audio_buf || !audio_out){
825 fprintf(stderr, "Out of memory in do_audio_out\n");
639e4ec8 826 ffmpeg_exit(1);
e185a2f6 827 }
d66c7abc 828
2886f311
829 if (enc->channels != dec->channels)
830 ost->audio_resample = 1;
831
832 if (ost->audio_resample && !ost->resample) {
d1e3c6fd
BC
833 if (dec->sample_fmt != SAMPLE_FMT_S16)
834 fprintf(stderr, "Warning, using s16 intermediate sample format for resampling\n");
835 ost->resample = av_audio_resample_init(enc->channels, dec->channels,
836 enc->sample_rate, dec->sample_rate,
837 enc->sample_fmt, dec->sample_fmt,
838 16, 10, 0, 0.8);
2886f311
839 if (!ost->resample) {
840 fprintf(stderr, "Can not resample %d channels @ %d Hz to %d channels @ %d Hz\n",
841 dec->channels, dec->sample_rate,
842 enc->channels, enc->sample_rate);
639e4ec8 843 ffmpeg_exit(1);
2886f311
844 }
845 }
846
a79db0f7 847#define MAKE_SFMT_PAIR(a,b) ((a)+SAMPLE_FMT_NB*(b))
d1e3c6fd 848 if (!ost->audio_resample && dec->sample_fmt!=enc->sample_fmt &&
a79db0f7 849 MAKE_SFMT_PAIR(enc->sample_fmt,dec->sample_fmt)!=ost->reformat_pair) {
a79db0f7
PR
850 if (ost->reformat_ctx)
851 av_audio_convert_free(ost->reformat_ctx);
852 ost->reformat_ctx = av_audio_convert_alloc(enc->sample_fmt, 1,
853 dec->sample_fmt, 1, NULL, 0);
854 if (!ost->reformat_ctx) {
855 fprintf(stderr, "Cannot convert %s sample format to %s sample format\n",
856 avcodec_get_sample_fmt_name(dec->sample_fmt),
857 avcodec_get_sample_fmt_name(enc->sample_fmt));
639e4ec8 858 ffmpeg_exit(1);
a79db0f7
PR
859 }
860 ost->reformat_pair=MAKE_SFMT_PAIR(enc->sample_fmt,dec->sample_fmt);
861 }
862
986ebcdb 863 if(audio_sync_method){
115329f1 864 double delta = get_sync_ipts(ost) * enc->sample_rate - ost->sync_opts
37f5a713
JR
865 - av_fifo_size(ost->fifo)/(enc->channels * 2);
866 double idelta= delta*dec->sample_rate / enc->sample_rate;
ff19d16b 867 int byte_delta= ((int)idelta)*2*dec->channels;
ff4905a5 868
986ebcdb
MN
869 //FIXME resample delay
870 if(fabs(delta) > 50){
d4d226a8 871 if(ist->is_start || fabs(delta) > audio_drift_threshold*enc->sample_rate){
ff4905a5 872 if(byte_delta < 0){
f41dd5aa 873 byte_delta= FFMAX(byte_delta, -size);
ff4905a5
MN
874 size += byte_delta;
875 buf -= byte_delta;
876 if(verbose > 2)
877 fprintf(stderr, "discarding %d audio samples\n", (int)-delta);
878 if(!size)
879 return;
880 ist->is_start=0;
881 }else{
882 static uint8_t *input_tmp= NULL;
883 input_tmp= av_realloc(input_tmp, byte_delta + size);
884
7a086a85
MN
885 if(byte_delta > allocated_for_size - size){
886 allocated_for_size= byte_delta + (int64_t)size;
887 goto need_realloc;
888 }
889 ist->is_start=0;
ff4905a5
MN
890
891 memset(input_tmp, 0, byte_delta);
892 memcpy(input_tmp + byte_delta, buf, size);
893 buf= input_tmp;
894 size += byte_delta;
895 if(verbose > 2)
896 fprintf(stderr, "adding %d audio samples of silence\n", (int)delta);
897 }
898 }else if(audio_sync_method>1){
f66e4f5f 899 int comp= av_clip(delta, -audio_sync_method, audio_sync_method);
b926b628 900 av_assert0(ost->audio_resample);
ff4905a5
MN
901 if(verbose > 2)
902 fprintf(stderr, "compensating audio timestamp drift:%f compensation:%d in:%d\n", delta, comp, enc->sample_rate);
41dd680d 903// 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));
ff4905a5
MN
904 av_resample_compensate(*(struct AVResampleContext**)ost->resample, comp, enc->sample_rate);
905 }
115329f1 906 }
986ebcdb 907 }else
b4a3389e 908 ost->sync_opts= lrintf(get_sync_ipts(ost) * enc->sample_rate)
37f5a713 909 - av_fifo_size(ost->fifo)/(enc->channels * 2); //FIXME wrong
85f07f22
FB
910
911 if (ost->audio_resample) {
912 buftmp = audio_buf;
115329f1 913 size_out = audio_resample(ost->resample,
85f07f22 914 (short *)buftmp, (short *)buf,
37f5a713 915 size / (dec->channels * isize));
287ba997 916 size_out = size_out * enc->channels * osize;
85f07f22
FB
917 } else {
918 buftmp = buf;
919 size_out = size;
920 }
921
d1e3c6fd 922 if (!ost->audio_resample && dec->sample_fmt!=enc->sample_fmt) {
a79db0f7 923 const void *ibuf[6]= {buftmp};
80f47250 924 void *obuf[6]= {audio_buf};
287ba997
PR
925 int istride[6]= {isize};
926 int ostride[6]= {osize};
a79db0f7
PR
927 int len= size_out/istride[0];
928 if (av_audio_convert(ost->reformat_ctx, obuf, ostride, ibuf, istride, len)<0) {
929 printf("av_audio_convert() failed\n");
f2abc559 930 if (exit_on_error)
639e4ec8 931 ffmpeg_exit(1);
a79db0f7
PR
932 return;
933 }
80f47250 934 buftmp = audio_buf;
287ba997 935 size_out = len*osize;
a79db0f7
PR
936 }
937
85f07f22 938 /* now encode as many frames as possible */
a0663ba4 939 if (enc->frame_size > 1) {
85f07f22 940 /* output resampled raw samples */
41dd680d 941 if (av_fifo_realloc2(ost->fifo, av_fifo_size(ost->fifo) + size_out) < 0) {
745b39d5 942 fprintf(stderr, "av_fifo_realloc2() failed\n");
639e4ec8 943 ffmpeg_exit(1);
745b39d5 944 }
41dd680d 945 av_fifo_generic_write(ost->fifo, buftmp, size_out, NULL);
85f07f22 946
287ba997 947 frame_bytes = enc->frame_size * osize * enc->channels;
115329f1 948
41dd680d 949 while (av_fifo_size(ost->fifo) >= frame_bytes) {
e928649b
MN
950 AVPacket pkt;
951 av_init_packet(&pkt);
952
3898eed8 953 av_fifo_generic_read(ost->fifo, audio_buf, frame_bytes, NULL);
0871ae1a 954
5bc440e7
MN
955 //FIXME pass ost->sync_opts as AVFrame.pts in avcodec_encode_audio()
956
115329f1 957 ret = avcodec_encode_audio(enc, audio_out, audio_out_size,
a0663ba4 958 (short *)audio_buf);
528271ff
MN
959 if (ret < 0) {
960 fprintf(stderr, "Audio encoding failed\n");
639e4ec8 961 ffmpeg_exit(1);
528271ff 962 }
1008ceb3 963 audio_size += ret;
e928649b
MN
964 pkt.stream_index= ost->index;
965 pkt.data= audio_out;
966 pkt.size= ret;
e7902f20 967 if(enc->coded_frame && enc->coded_frame->pts != AV_NOPTS_VALUE)
c0df9d75 968 pkt.pts= av_rescale_q(enc->coded_frame->pts, enc->time_base, ost->st->time_base);
cc947f04 969 pkt.flags |= AV_PKT_FLAG_KEY;
37f5a713 970 write_frame(s, &pkt, enc, bitstream_filters[ost->file_index][pkt.stream_index]);
115329f1 971
986ebcdb 972 ost->sync_opts += enc->frame_size;
85f07f22
FB
973 }
974 } else {
e928649b
MN
975 AVPacket pkt;
976 av_init_packet(&pkt);
986ebcdb 977
287ba997 978 ost->sync_opts += size_out / (osize * enc->channels);
986ebcdb 979
a0663ba4 980 /* output a pcm frame */
287ba997
PR
981 /* determine the size of the coded buffer */
982 size_out /= osize;
983 if (coded_bps)
060b8592 984 size_out = size_out*coded_bps/8;
287ba997 985
5ee05a62
MN
986 if(size_out > audio_out_size){
987 fprintf(stderr, "Internal error, buffer size too small\n");
639e4ec8 988 ffmpeg_exit(1);
5ee05a62
MN
989 }
990
5bc440e7 991 //FIXME pass ost->sync_opts as AVFrame.pts in avcodec_encode_audio()
115329f1 992 ret = avcodec_encode_audio(enc, audio_out, size_out,
bb270c08 993 (short *)buftmp);
528271ff
MN
994 if (ret < 0) {
995 fprintf(stderr, "Audio encoding failed\n");
639e4ec8 996 ffmpeg_exit(1);
528271ff 997 }
1008ceb3 998 audio_size += ret;
e928649b
MN
999 pkt.stream_index= ost->index;
1000 pkt.data= audio_out;
1001 pkt.size= ret;
e7902f20 1002 if(enc->coded_frame && enc->coded_frame->pts != AV_NOPTS_VALUE)
c0df9d75 1003 pkt.pts= av_rescale_q(enc->coded_frame->pts, enc->time_base, ost->st->time_base);
cc947f04 1004 pkt.flags |= AV_PKT_FLAG_KEY;
37f5a713 1005 write_frame(s, &pkt, enc, bitstream_filters[ost->file_index][pkt.stream_index]);
85f07f22
FB
1006 }
1007}
1008
10d104e4
PG
1009static void pre_process_video_frame(AVInputStream *ist, AVPicture *picture, void **bufp)
1010{
1011 AVCodecContext *dec;
1012 AVPicture *picture2;
1013 AVPicture picture_tmp;
0c1a9eda 1014 uint8_t *buf = 0;
10d104e4 1015
01f4895c 1016 dec = ist->st->codec;
10d104e4
PG
1017
1018 /* deinterlace : must be done before any resize */
fdf11906 1019 if (do_deinterlace) {
10d104e4
PG
1020 int size;
1021
1022 /* create temporary picture */
1023 size = avpicture_get_size(dec->pix_fmt, dec->width, dec->height);
1024 buf = av_malloc(size);
1025 if (!buf)
1026 return;
115329f1 1027
10d104e4
PG
1028 picture2 = &picture_tmp;
1029 avpicture_fill(picture2, buf, dec->pix_fmt, dec->width, dec->height);
1030
9e1cc598
RP
1031 if(avpicture_deinterlace(picture2, picture,
1032 dec->pix_fmt, dec->width, dec->height) < 0) {
1033 /* if error, do not deinterlace */
1034 fprintf(stderr, "Deinterlacing failed\n");
1035 av_free(buf);
1036 buf = NULL;
1037 picture2 = picture;
1038 }
10d104e4
PG
1039 } else {
1040 picture2 = picture;
1041 }
1042
10d104e4
PG
1043 if (picture != picture2)
1044 *picture = *picture2;
1045 *bufp = buf;
1046}
1047
ec5517d5
FB
1048/* we begin to correct av delay at this threshold */
1049#define AV_DELAY_MAX 0.100
85f07f22 1050
115329f1
DB
1051static void do_subtitle_out(AVFormatContext *s,
1052 AVOutputStream *ost,
cf7fc795
FB
1053 AVInputStream *ist,
1054 AVSubtitle *sub,
1055 int64_t pts)
1056{
1057 static uint8_t *subtitle_out = NULL;
7f4fca03 1058 int subtitle_out_max_size = 1024 * 1024;
cf7fc795
FB
1059 int subtitle_out_size, nb, i;
1060 AVCodecContext *enc;
1061 AVPacket pkt;
1062
1063 if (pts == AV_NOPTS_VALUE) {
1064 fprintf(stderr, "Subtitle packets must have a pts\n");
f2abc559 1065 if (exit_on_error)
639e4ec8 1066 ffmpeg_exit(1);
cf7fc795
FB
1067 return;
1068 }
1069
01f4895c 1070 enc = ost->st->codec;
cf7fc795
FB
1071
1072 if (!subtitle_out) {
1073 subtitle_out = av_malloc(subtitle_out_max_size);
1074 }
1075
1076 /* Note: DVB subtitle need one packet to draw them and one other
1077 packet to clear them */
1078 /* XXX: signal it in the codec context ? */
1079 if (enc->codec_id == CODEC_ID_DVB_SUBTITLE)
1080 nb = 2;
1081 else
1082 nb = 1;
1083
1084 for(i = 0; i < nb; i++) {
4bbe788a 1085 sub->pts = av_rescale_q(pts, ist->st->time_base, AV_TIME_BASE_Q);
8b03c014
RD
1086 // start_display_time is required to be 0
1087 sub->pts += av_rescale_q(sub->start_display_time, (AVRational){1, 1000}, AV_TIME_BASE_Q);
1088 sub->end_display_time -= sub->start_display_time;
1089 sub->start_display_time = 0;
115329f1 1090 subtitle_out_size = avcodec_encode_subtitle(enc, subtitle_out,
cf7fc795 1091 subtitle_out_max_size, sub);
266649a5
RD
1092 if (subtitle_out_size < 0) {
1093 fprintf(stderr, "Subtitle encoding failed\n");
639e4ec8 1094 ffmpeg_exit(1);
266649a5 1095 }
115329f1 1096
cf7fc795
FB
1097 av_init_packet(&pkt);
1098 pkt.stream_index = ost->index;
1099 pkt.data = subtitle_out;
1100 pkt.size = subtitle_out_size;
8b03c014 1101 pkt.pts = av_rescale_q(sub->pts, AV_TIME_BASE_Q, ost->st->time_base);
cf7fc795
FB
1102 if (enc->codec_id == CODEC_ID_DVB_SUBTITLE) {
1103 /* XXX: the pts correction is handled here. Maybe handling
1104 it in the codec would be better */
1105 if (i == 0)
1106 pkt.pts += 90 * sub->start_display_time;
1107 else
1108 pkt.pts += 90 * sub->end_display_time;
1109 }
748c2fca 1110 write_frame(s, &pkt, ost->st->codec, bitstream_filters[ost->file_index][pkt.stream_index]);
cf7fc795
FB
1111 }
1112}
1113
8a6cb114 1114static int bit_buffer_size= 1024*256;
27537106 1115static uint8_t *bit_buffer= NULL;
1ff93ffc 1116
115329f1
DB
1117static void do_video_out(AVFormatContext *s,
1118 AVOutputStream *ost,
85f07f22 1119 AVInputStream *ist,
7a0f9d7e 1120 AVFrame *in_picture,
986ebcdb 1121 int *frame_size)
85f07f22 1122{
ec5517d5 1123 int nb_frames, i, ret;
46847a33 1124#if !CONFIG_AVFILTER
352666c1 1125 int64_t topBand, bottomBand, leftBand, rightBand;
46847a33 1126#endif
07d0cdfc 1127 AVFrame *final_picture, *formatted_picture, *resampling_dst, *padding_src;
18a54b04 1128 AVFrame picture_crop_temp, picture_pad_temp;
cfcf0ffd 1129 AVCodecContext *enc, *dec;
47b229db 1130 double sync_ipts;
115329f1 1131
a4d36c11 1132 avcodec_get_frame_defaults(&picture_crop_temp);
07d0cdfc 1133 avcodec_get_frame_defaults(&picture_pad_temp);
a4d36c11 1134
01f4895c
MN
1135 enc = ost->st->codec;
1136 dec = ist->st->codec;
85f07f22 1137
47b229db
AS
1138 sync_ipts = get_sync_ipts(ost) / av_q2d(enc->time_base);
1139
ec5517d5
FB
1140 /* by default, we output a single frame */
1141 nb_frames = 1;
1142
204c0f48
PG
1143 *frame_size = 0;
1144
9ff261a2 1145 if(video_sync_method){
d55065a2 1146 double vdelta = sync_ipts - ost->sync_opts;
e928649b
MN
1147 //FIXME set to 0.5 after we fix some dts/pts bugs like in avidec.c
1148 if (vdelta < -1.1)
1149 nb_frames = 0;
e6fdc2b1
MN
1150 else if (video_sync_method == 2 || (video_sync_method<0 && (s->oformat->flags & AVFMT_VARIABLE_FPS))){
1151 if(vdelta<=-0.6){
1152 nb_frames=0;
1153 }else if(vdelta>0.6)
47b229db 1154 ost->sync_opts= lrintf(sync_ipts);
e6fdc2b1 1155 }else if (vdelta > 1.1)
70122f29 1156 nb_frames = lrintf(vdelta);
fc6765d7 1157//fprintf(stderr, "vdelta:%f, ost->sync_opts:%"PRId64", ost->sync_ipts:%f nb_frames:%d\n", vdelta, ost->sync_opts, get_sync_ipts(ost), nb_frames);
50c3dd32
MN
1158 if (nb_frames == 0){
1159 ++nb_frames_drop;
1160 if (verbose>2)
1161 fprintf(stderr, "*** drop!\n");
8300609b 1162 }else if (nb_frames > 1) {
ed30e518 1163 nb_frames_dup += nb_frames - 1;
50c3dd32 1164 if (verbose>2)
8300609b 1165 fprintf(stderr, "*** %d dup!\n", nb_frames-1);
50c3dd32
MN
1166 }
1167 }else
47b229db 1168 ost->sync_opts= lrintf(sync_ipts);
445f1b83 1169
72415b2a 1170 nb_frames= FFMIN(nb_frames, max_frames[AVMEDIA_TYPE_VIDEO] - ost->frame_number);
115329f1 1171 if (nb_frames <= 0)
85f07f22 1172 return;
ce7c56c2 1173
46847a33
MN
1174#if CONFIG_AVFILTER
1175 formatted_picture = in_picture;
1176#else
07d0cdfc 1177 if (ost->video_crop) {
636d6a4a 1178 if (av_picture_crop((AVPicture *)&picture_crop_temp, (AVPicture *)in_picture, dec->pix_fmt, ost->topBand, ost->leftBand) < 0) {
49a06a4d 1179 fprintf(stderr, "error cropping picture\n");
f2abc559 1180 if (exit_on_error)
639e4ec8 1181 ffmpeg_exit(1);
4e780252 1182 return;
07d0cdfc
LA
1183 }
1184 formatted_picture = &picture_crop_temp;
18a54b04
LA
1185 } else {
1186 formatted_picture = in_picture;
07d0cdfc 1187 }
46847a33 1188#endif
07d0cdfc
LA
1189
1190 final_picture = formatted_picture;
1191 padding_src = formatted_picture;
1192 resampling_dst = &ost->pict_tmp;
07d0cdfc 1193
b83ccbff
MN
1194 if( (ost->resample_height != (ist->st->codec->height - (ost->topBand + ost->bottomBand)))
1195 || (ost->resample_width != (ist->st->codec->width - (ost->leftBand + ost->rightBand)))
1196 || (ost->resample_pix_fmt!= ist->st->codec->pix_fmt) ) {
1197
1198 fprintf(stderr,"Input Stream #%d.%d frame size changed to %dx%d, %s\n", ist->file_index, ist->index, ist->st->codec->width, ist->st->codec->height,avcodec_get_pix_fmt_name(ist->st->codec->pix_fmt));
1199 if(!ost->video_resample)
639e4ec8 1200 ffmpeg_exit(1);
b83ccbff
MN
1201 }
1202
46847a33 1203#if !CONFIG_AVFILTER
85f07f22 1204 if (ost->video_resample) {
07d0cdfc 1205 padding_src = NULL;
34b10a57 1206 final_picture = &ost->pict_tmp;
352666c1 1207 if( (ost->resample_height != (ist->st->codec->height - (ost->topBand + ost->bottomBand)))
01a3c821
JGG
1208 || (ost->resample_width != (ist->st->codec->width - (ost->leftBand + ost->rightBand)))
1209 || (ost->resample_pix_fmt!= ist->st->codec->pix_fmt) ) {
352666c1 1210
352666c1
EB
1211 /* keep bands proportional to the frame size */
1212 topBand = ((int64_t)ist->st->codec->height * ost->original_topBand / ost->original_height) & ~1;
1213 bottomBand = ((int64_t)ist->st->codec->height * ost->original_bottomBand / ost->original_height) & ~1;
1214 leftBand = ((int64_t)ist->st->codec->width * ost->original_leftBand / ost->original_width) & ~1;
1215 rightBand = ((int64_t)ist->st->codec->width * ost->original_rightBand / ost->original_width) & ~1;
1216
1217 /* sanity check to ensure no bad band sizes sneak in */
b926b628
MN
1218 av_assert0(topBand <= INT_MAX && topBand >= 0);
1219 av_assert0(bottomBand <= INT_MAX && bottomBand >= 0);
1220 av_assert0(leftBand <= INT_MAX && leftBand >= 0);
1221 av_assert0(rightBand <= INT_MAX && rightBand >= 0);
352666c1
EB
1222
1223 ost->topBand = topBand;
1224 ost->bottomBand = bottomBand;
1225 ost->leftBand = leftBand;
1226 ost->rightBand = rightBand;
1227
1228 ost->resample_height = ist->st->codec->height - (ost->topBand + ost->bottomBand);
1229 ost->resample_width = ist->st->codec->width - (ost->leftBand + ost->rightBand);
01a3c821 1230 ost->resample_pix_fmt= ist->st->codec->pix_fmt;
352666c1
EB
1231
1232 /* initialize a new scaler context */
1233 sws_freeContext(ost->img_resample_ctx);
1234 sws_flags = av_get_int(sws_opts, "sws_flags", NULL);
1235 ost->img_resample_ctx = sws_getContext(
1236 ist->st->codec->width - (ost->leftBand + ost->rightBand),
1237 ist->st->codec->height - (ost->topBand + ost->bottomBand),
1238 ist->st->codec->pix_fmt,
0c22311b
MN
1239 ost->st->codec->width,
1240 ost->st->codec->height,
352666c1
EB
1241 ost->st->codec->pix_fmt,
1242 sws_flags, NULL, NULL, NULL);
1243 if (ost->img_resample_ctx == NULL) {
1244 fprintf(stderr, "Cannot get resampling context\n");
639e4ec8 1245 ffmpeg_exit(1);
352666c1
EB
1246 }
1247 }
18a54b04
LA
1248 sws_scale(ost->img_resample_ctx, formatted_picture->data, formatted_picture->linesize,
1249 0, ost->resample_height, resampling_dst->data, resampling_dst->linesize);
f122deb4 1250 }
46847a33 1251#endif
07d0cdfc 1252
85f07f22 1253 /* duplicates frame if needed */
ec5517d5 1254 for(i=0;i<nb_frames;i++) {
e928649b
MN
1255 AVPacket pkt;
1256 av_init_packet(&pkt);
1257 pkt.stream_index= ost->index;
1258
e8750b00
FR
1259 if (s->oformat->flags & AVFMT_RAWPICTURE) {
1260 /* raw pictures are written as AVPicture structure to
1261 avoid any copies. We support temorarily the older
1262 method. */
2744ca9a 1263 AVFrame* old_frame = enc->coded_frame;
bb270c08 1264 enc->coded_frame = dec->coded_frame; //FIXME/XXX remove this hack
e928649b
MN
1265 pkt.data= (uint8_t *)final_picture;
1266 pkt.size= sizeof(AVPicture);
b4dba580 1267 pkt.pts= av_rescale_q(ost->sync_opts, enc->time_base, ost->st->time_base);
cc947f04 1268 pkt.flags |= AV_PKT_FLAG_KEY;
e928649b 1269
748c2fca 1270 write_frame(s, &pkt, ost->st->codec, bitstream_filters[ost->file_index][pkt.stream_index]);
bb270c08 1271 enc->coded_frame = old_frame;
e8750b00 1272 } else {
492cd3a9 1273 AVFrame big_picture;
a4d36c11
MN
1274
1275 big_picture= *final_picture;
7a0f9d7e
FB
1276 /* better than nothing: use input picture interlaced
1277 settings */
1278 big_picture.interlaced_frame = in_picture->interlaced_frame;
72415b2a 1279 if(avcodec_opts[AVMEDIA_TYPE_VIDEO]->flags & (CODEC_FLAG_INTERLACED_DCT|CODEC_FLAG_INTERLACED_ME)){
bb198e19
MN
1280 if(top_field_first == -1)
1281 big_picture.top_field_first = in_picture->top_field_first;
1282 else
2a8edc5d 1283 big_picture.top_field_first = top_field_first;
bb198e19 1284 }
7a0f9d7e 1285
85f07f22
FB
1286 /* handles sameq here. This is not correct because it may
1287 not be a global option */
f62c025a 1288 big_picture.quality = same_quality ? ist->st->quality : ost->st->quality;
f4f3223f
MN
1289 if(!me_threshold)
1290 big_picture.pict_type = 0;
50c3dd32 1291// big_picture.pts = AV_NOPTS_VALUE;
c0df9d75
MN
1292 big_picture.pts= ost->sync_opts;
1293// big_picture.pts= av_rescale(ost->sync_opts, AV_TIME_BASE*(int64_t)enc->time_base.num, enc->time_base.den);
949b1a13 1294//av_log(NULL, AV_LOG_DEBUG, "%"PRId64" -> encoder\n", ost->sync_opts);
115329f1 1295 ret = avcodec_encode_video(enc,
8a6cb114 1296 bit_buffer, bit_buffer_size,
1e491e29 1297 &big_picture);
95af5e1c 1298 if (ret < 0) {
4156a436 1299 fprintf(stderr, "Video encoding failed\n");
639e4ec8 1300 ffmpeg_exit(1);
4156a436 1301 }
54e28a85 1302
4bbc6260 1303 if(ret>0){
27537106 1304 pkt.data= bit_buffer;
e928649b 1305 pkt.size= ret;
e6b4e4ff 1306 if(enc->coded_frame->pts != AV_NOPTS_VALUE)
c0df9d75 1307 pkt.pts= av_rescale_q(enc->coded_frame->pts, enc->time_base, ost->st->time_base);
949b1a13 1308/*av_log(NULL, AV_LOG_DEBUG, "encoder -> %"PRId64"/%"PRId64"\n",
c0df9d75
MN
1309 pkt.pts != AV_NOPTS_VALUE ? av_rescale(pkt.pts, enc->time_base.den, AV_TIME_BASE*(int64_t)enc->time_base.num) : -1,
1310 pkt.dts != AV_NOPTS_VALUE ? av_rescale(pkt.dts, enc->time_base.den, AV_TIME_BASE*(int64_t)enc->time_base.num) : -1);*/
50c3dd32 1311
e6b4e4ff 1312 if(enc->coded_frame->key_frame)
cc947f04 1313 pkt.flags |= AV_PKT_FLAG_KEY;
748c2fca 1314 write_frame(s, &pkt, ost->st->codec, bitstream_filters[ost->file_index][pkt.stream_index]);
e928649b 1315 *frame_size = ret;
44eb047a 1316 video_size += ret;
54e28a85
BC
1317 //fprintf(stderr,"\nFrame: %3d size: %5d type: %d",
1318 // enc->frame_number-1, ret, enc->pict_type);
e928649b
MN
1319 /* if two pass, output log */
1320 if (ost->logfile && enc->stats_out) {
1321 fprintf(ost->logfile, "%s", enc->stats_out);
1322 }
5abdb4b1 1323 }
85f07f22 1324 }
50c3dd32 1325 ost->sync_opts++;
ec5517d5 1326 ost->frame_number++;
85f07f22
FB
1327 }
1328}
1329
140cb663 1330static double psnr(double d){
b29f97d1 1331 return -10.0*log(d)/log(10.0);
140cb663
MN
1332}
1333
115329f1 1334static void do_video_stats(AVFormatContext *os, AVOutputStream *ost,
ec5517d5 1335 int frame_size)
ce7c56c2 1336{
ce7c56c2
J
1337 AVCodecContext *enc;
1338 int frame_number;
ce7c56c2 1339 double ti1, bitrate, avg_bitrate;
115329f1 1340
b60d1379 1341 /* this is executed just the first time do_video_stats is called */
032aa7df
SS
1342 if (!vstats_file) {
1343 vstats_file = fopen(vstats_filename, "w");
1344 if (!vstats_file) {
4bd0c2b1 1345 perror("fopen");
639e4ec8 1346 ffmpeg_exit(1);
4bd0c2b1
BF
1347 }
1348 }
1349
01f4895c 1350 enc = ost->st->codec;
72415b2a 1351 if (enc->codec_type == AVMEDIA_TYPE_VIDEO) {
ec5517d5 1352 frame_number = ost->frame_number;
032aa7df 1353 fprintf(vstats_file, "frame= %5d q= %2.1f ", frame_number, enc->coded_frame->quality/(float)FF_QP2LAMBDA);
140cb663 1354 if (enc->flags&CODEC_FLAG_PSNR)
032aa7df 1355 fprintf(vstats_file, "PSNR= %6.2f ", psnr(enc->coded_frame->error[0]/(enc->width*enc->height*255.0*255.0)));
115329f1 1356
032aa7df 1357 fprintf(vstats_file,"f_size= %6d ", frame_size);
ec5517d5 1358 /* compute pts value */
c0df9d75 1359 ti1 = ost->sync_opts * av_q2d(enc->time_base);
ce7c56c2
J
1360 if (ti1 < 0.01)
1361 ti1 = 0.01;
115329f1 1362
c0df9d75 1363 bitrate = (frame_size * 8) / av_q2d(enc->time_base) / 1000.0;
1008ceb3 1364 avg_bitrate = (double)(video_size * 8) / ti1 / 1000.0;
032aa7df 1365 fprintf(vstats_file, "s_size= %8.0fkB time= %0.3f br= %7.1fkbits/s avg_br= %7.1fkbits/s ",
1008ceb3 1366 (double)video_size / 1024, ti1, bitrate, avg_bitrate);
032aa7df 1367 fprintf(vstats_file,"type= %c\n", av_get_pict_type_char(enc->coded_frame->pict_type));
ce7c56c2 1368 }
ec5517d5
FB
1369}
1370
b29f97d1 1371static void print_report(AVFormatContext **output_files,
bb270c08
DB
1372 AVOutputStream **ost_table, int nb_ostreams,
1373 int is_last_report)
ec5517d5
FB
1374{
1375 char buf[1024];
1376 AVOutputStream *ost;
b5ee9c23 1377 AVFormatContext *oc;
0c1a9eda 1378 int64_t total_size;
ec5517d5
FB
1379 AVCodecContext *enc;
1380 int frame_number, vid, i;
1381 double bitrate, ti1, pts;
0c1a9eda 1382 static int64_t last_time = -1;
0888fd22 1383 static int qp_histogram[52];
115329f1 1384
ec5517d5 1385 if (!is_last_report) {
0c1a9eda 1386 int64_t cur_time;
ec5517d5
FB
1387 /* display the report every 0.5 seconds */
1388 cur_time = av_gettime();
1389 if (last_time == -1) {
1390 last_time = cur_time;
1391 return;
115329f1 1392 }
ec5517d5
FB
1393 if ((cur_time - last_time) < 500000)
1394 return;
1395 last_time = cur_time;
1396 }
1397
ce7c56c2 1398
ec5517d5
FB
1399 oc = output_files[0];
1400
899681cd 1401 total_size = url_fsize(oc->pb);
859d95ba 1402 if(total_size<0) // FIXME improve url_fsize() so it works with non seekable output too
899681cd 1403 total_size= url_ftell(oc->pb);
115329f1 1404
ec5517d5
FB
1405 buf[0] = '\0';
1406 ti1 = 1e10;
1407 vid = 0;
1408 for(i=0;i<nb_ostreams;i++) {
1409 ost = ost_table[i];
01f4895c 1410 enc = ost->st->codec;
72415b2a 1411 if (vid && enc->codec_type == AVMEDIA_TYPE_VIDEO) {
0ecca7a4 1412 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "q=%2.1f ",
e6b4e4ff 1413 !ost->st->stream_copy ?
99fb79b5 1414 enc->coded_frame->quality/(float)FF_QP2LAMBDA : -1);
10d104e4 1415 }
72415b2a 1416 if (!vid && enc->codec_type == AVMEDIA_TYPE_VIDEO) {
7fc98937
LW
1417 float t = (av_gettime()-timer_start) / 1000000.0;
1418
ec5517d5 1419 frame_number = ost->frame_number;
7fc98937
LW
1420 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "frame=%5d fps=%3d q=%3.1f ",
1421 frame_number, (t>1)?(int)(frame_number/t+0.5) : 0,
e6b4e4ff 1422 !ost->st->stream_copy ?
99fb79b5 1423 enc->coded_frame->quality/(float)FF_QP2LAMBDA : -1);
890972be 1424 if(is_last_report)
0ecca7a4 1425 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "L");
e6b4e4ff 1426 if(qp_hist){
0888fd22
MN
1427 int j;
1428 int qp= lrintf(enc->coded_frame->quality/(float)FF_QP2LAMBDA);
37d3e066 1429 if(qp>=0 && qp<FF_ARRAY_ELEMS(qp_histogram))
0888fd22
MN
1430 qp_histogram[qp]++;
1431 for(j=0; j<32; j++)
1432 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "%X", (int)lrintf(log(qp_histogram[j]+1)/log(2)));
1433 }
890972be
MN
1434 if (enc->flags&CODEC_FLAG_PSNR){
1435 int j;
1436 double error, error_sum=0;
1437 double scale, scale_sum=0;
1438 char type[3]= {'Y','U','V'};
0ecca7a4 1439 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "PSNR=");
890972be
MN
1440 for(j=0; j<3; j++){
1441 if(is_last_report){
1442 error= enc->error[j];
1443 scale= enc->width*enc->height*255.0*255.0*frame_number;
1444 }else{
1445 error= enc->coded_frame->error[j];
1446 scale= enc->width*enc->height*255.0*255.0;
1447 }
1448 if(j) scale/=4;
1449 error_sum += error;
1450 scale_sum += scale;
0ecca7a4 1451 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "%c:%2.2f ", type[j], psnr(error/scale));
890972be 1452 }
0ecca7a4 1453 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "*:%2.2f ", psnr(error_sum/scale_sum));
890972be 1454 }
ec5517d5
FB
1455 vid = 1;
1456 }
1457 /* compute min output value */
43924f01 1458 pts = (double)ost->st->pts.val * av_q2d(ost->st->time_base);
5d9827bc 1459 if ((pts < ti1) && (pts > 0))
ec5517d5
FB
1460 ti1 = pts;
1461 }
1462 if (ti1 < 0.01)
1463 ti1 = 0.01;
115329f1 1464
f068206e
BE
1465 if (verbose || is_last_report) {
1466 bitrate = (double)(total_size * 8) / ti1 / 1000.0;
115329f1
DB
1467
1468 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
475f4d8d 1469 "size=%8.0fkB time=%0.2f bitrate=%6.1fkbits/s",
ec5517d5 1470 (double)total_size / 1024, ti1, bitrate);
a6a92a9a 1471
0f649d66 1472 if (nb_frames_dup || nb_frames_drop)
bb270c08
DB
1473 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), " dup=%d drop=%d",
1474 nb_frames_dup, nb_frames_drop);
115329f1 1475
d8019eb5
AD
1476 if (verbose >= 0)
1477 fprintf(stderr, "%s \r", buf);
1478
ec5517d5
FB
1479 fflush(stderr);
1480 }
115329f1 1481
1008ceb3
MN
1482 if (is_last_report && verbose >= 0){
1483 int64_t raw= audio_size + video_size + extra_size;
f068206e 1484 fprintf(stderr, "\n");
1008ceb3
MN
1485 fprintf(stderr, "video:%1.0fkB audio:%1.0fkB global headers:%1.0fkB muxing overhead %f%%\n",
1486 video_size/1024.0,
1487 audio_size/1024.0,
1488 extra_size/1024.0,
1489 100.0*(total_size - raw)/raw
1490 );
1491 }
ce7c56c2
J
1492}
1493
a700a6ae
FB
1494/* pkt = NULL means EOF (needed to flush decoder buffers) */
1495static int output_packet(AVInputStream *ist, int ist_index,
1496 AVOutputStream **ost_table, int nb_ostreams,
4b85a28f 1497 const AVPacket *pkt)
a700a6ae
FB
1498{
1499 AVFormatContext *os;
1500 AVOutputStream *ost;
ede0e475 1501 int ret, i;
8157483d 1502 int got_picture;
a700a6ae 1503 AVFrame picture;
a700a6ae 1504 void *buffer_to_free;
f038fe8b 1505 static unsigned int samples_size= 0;
cf7fc795 1506 AVSubtitle subtitle, *subtitle_to_free;
0ff4f0c0 1507 int64_t pkt_pts = AV_NOPTS_VALUE;
46847a33 1508#if CONFIG_AVFILTER
d21f58b5 1509 int frame_available;
46847a33
MN
1510#endif
1511
ede0e475 1512 AVPacket avpkt;
9d66ef18 1513 int bps = av_get_bits_per_sample_format(ist->st->codec->sample_fmt)>>3;
ede0e475 1514
ed923859
MN
1515 if(ist->next_pts == AV_NOPTS_VALUE)
1516 ist->next_pts= ist->pts;
1517
a700a6ae
FB
1518 if (pkt == NULL) {
1519 /* EOF handling */
031e14ea 1520 av_init_packet(&avpkt);
ede0e475
TB
1521 avpkt.data = NULL;
1522 avpkt.size = 0;
a700a6ae 1523 goto handle_eof;
031e14ea
TB
1524 } else {
1525 avpkt = *pkt;
a700a6ae
FB
1526 }
1527
b1b818fc
MN
1528 if(pkt->dts != AV_NOPTS_VALUE)
1529 ist->next_pts = ist->pts = av_rescale_q(pkt->dts, ist->st->time_base, AV_TIME_BASE_Q);
0ff4f0c0
AS
1530 if(pkt->pts != AV_NOPTS_VALUE)
1531 pkt_pts = av_rescale_q(pkt->pts, ist->st->time_base, AV_TIME_BASE_Q);
b1b818fc 1532
bd6754aa 1533 //while we have more to decode or while the decoder did output something on EOF
ede0e475 1534 while (avpkt.size > 0 || (!pkt && ist->next_pts != ist->pts)) {
036c1382
MN
1535 uint8_t *data_buf, *decoded_data_buf;
1536 int data_size, decoded_data_size;
a700a6ae 1537 handle_eof:
b1b818fc 1538 ist->pts= ist->next_pts;
19d5da50 1539
d859bb1d 1540 if(avpkt.size && avpkt.size != pkt->size &&
6e2fdc3e 1541 ((!ist->showed_multi_packet_warning && verbose>0) || verbose>1)){
40cb57a2 1542 fprintf(stderr, "Multiple frames in a packet from stream %d\n", pkt->stream_index);
3ff0daf0
MN
1543 ist->showed_multi_packet_warning=1;
1544 }
40cb57a2 1545
a700a6ae 1546 /* decode the packet if needed */
036c1382
MN
1547 decoded_data_buf = NULL; /* fail safe */
1548 decoded_data_size= 0;
1549 data_buf = avpkt.data;
1550 data_size = avpkt.size;
cf7fc795 1551 subtitle_to_free = NULL;
a700a6ae 1552 if (ist->decoding_needed) {
01f4895c 1553 switch(ist->st->codec->codec_type) {
72415b2a 1554 case AVMEDIA_TYPE_AUDIO:{
81b060fa
LM
1555 if(pkt && samples_size < FFMAX(pkt->size*sizeof(*samples), AVCODEC_MAX_AUDIO_FRAME_SIZE)) {
1556 samples_size = FFMAX(pkt->size*sizeof(*samples), AVCODEC_MAX_AUDIO_FRAME_SIZE);
1557 av_free(samples);
1558 samples= av_malloc(samples_size);
1559 }
036c1382 1560 decoded_data_size= samples_size;
a700a6ae
FB
1561 /* XXX: could avoid copy if PCM 16 bits with same
1562 endianness as CPU */
036c1382 1563 ret = avcodec_decode_audio3(ist->st->codec, samples, &decoded_data_size,
ede0e475 1564 &avpkt);
a700a6ae
FB
1565 if (ret < 0)
1566 goto fail_decode;
ede0e475
TB
1567 avpkt.data += ret;
1568 avpkt.size -= ret;
036c1382 1569 data_size = ret;
a700a6ae 1570 /* Some bug in mpeg audio decoder gives */
036c1382
MN
1571 /* decoded_data_size < 0, it seems they are overflows */
1572 if (decoded_data_size <= 0) {
a700a6ae
FB
1573 /* no audio frame */
1574 continue;
1575 }
036c1382
MN
1576 decoded_data_buf = (uint8_t *)samples;
1577 ist->next_pts += ((int64_t)AV_TIME_BASE/bps * decoded_data_size) /
01f4895c 1578 (ist->st->codec->sample_rate * ist->st->codec->channels);
df84ac2e 1579 break;}
72415b2a 1580 case AVMEDIA_TYPE_VIDEO:
036c1382 1581 decoded_data_size = (ist->st->codec->width * ist->st->codec->height * 3) / 2;
a700a6ae 1582 /* XXX: allocate picture correctly */
9740beff 1583 avcodec_get_frame_defaults(&picture);
0ff4f0c0
AS
1584 ist->st->codec->reordered_opaque = pkt_pts;
1585 pkt_pts = AV_NOPTS_VALUE;
9740beff 1586
ede0e475
TB
1587 ret = avcodec_decode_video2(ist->st->codec,
1588 &picture, &got_picture, &avpkt);
a700a6ae 1589 ist->st->quality= picture.quality;
115329f1 1590 if (ret < 0)
a700a6ae
FB
1591 goto fail_decode;
1592 if (!got_picture) {
1593 /* no picture yet */
1594 goto discard_packet;
1595 }
0ff4f0c0 1596 ist->next_pts = ist->pts = guess_correct_pts(&ist->pts_ctx, picture.reordered_opaque, ist->pts);
01f4895c 1597 if (ist->st->codec->time_base.num != 0) {
3797c74b 1598 int ticks= ist->st->parser ? ist->st->parser->repeat_pict+1 : ist->st->codec->ticks_per_frame;
115329f1 1599 ist->next_pts += ((int64_t)AV_TIME_BASE *
34583e1b 1600 ist->st->codec->time_base.num * ticks) /
01f4895c 1601 ist->st->codec->time_base.den;
a700a6ae 1602 }
ede0e475 1603 avpkt.size = 0;
a700a6ae 1604 break;
72415b2a 1605 case AVMEDIA_TYPE_SUBTITLE:
ede0e475 1606 ret = avcodec_decode_subtitle2(ist->st->codec,
28db3215 1607 &subtitle, &got_picture, &avpkt);
cf7fc795 1608 if (ret < 0)
a700a6ae 1609 goto fail_decode;
28db3215 1610 if (!got_picture) {
cf7fc795 1611 goto discard_packet;
a700a6ae 1612 }
cf7fc795 1613 subtitle_to_free = &subtitle;
ede0e475 1614 avpkt.size = 0;
cf7fc795
FB
1615 break;
1616 default:
1617 goto fail_decode;
1618 }
1619 } else {
bde0705c 1620 switch(ist->st->codec->codec_type) {
72415b2a 1621 case AVMEDIA_TYPE_AUDIO:
bde0705c 1622 ist->next_pts += ((int64_t)AV_TIME_BASE * ist->st->codec->frame_size) /
1c715415 1623 ist->st->codec->sample_rate;
bde0705c 1624 break;
72415b2a 1625 case AVMEDIA_TYPE_VIDEO:
bde0705c 1626 if (ist->st->codec->time_base.num != 0) {
3797c74b 1627 int ticks= ist->st->parser ? ist->st->parser->repeat_pict+1 : ist->st->codec->ticks_per_frame;
bde0705c 1628 ist->next_pts += ((int64_t)AV_TIME_BASE *
34583e1b 1629 ist->st->codec->time_base.num * ticks) /
bde0705c 1630 ist->st->codec->time_base.den;
2fef0bdf 1631 }
bde0705c 1632 break;
a700a6ae 1633 }
ede0e475
TB
1634 ret = avpkt.size;
1635 avpkt.size = 0;
bde0705c 1636 }
a700a6ae 1637
bde0705c 1638 buffer_to_free = NULL;
72415b2a 1639 if (ist->st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
bde0705c
LW
1640 pre_process_video_frame(ist, (AVPicture *)&picture,
1641 &buffer_to_free);
1642 }
a700a6ae 1643
46847a33
MN
1644#if CONFIG_AVFILTER
1645 if (ist->st->codec->codec_type == AVMEDIA_TYPE_VIDEO && ist->input_video_filter) {
1646 // add it to be filtered
1647 av_vsrc_buffer_add_frame(ist->input_video_filter, &picture,
1648 ist->pts,
1649 ist->st->codec->sample_aspect_ratio);
1650 }
1651#endif
1652
bde0705c 1653 // preprocess audio (volume)
72415b2a 1654 if (ist->st->codec->codec_type == AVMEDIA_TYPE_AUDIO) {
bde0705c
LW
1655 if (audio_volume != 256) {
1656 short *volp;
1657 volp = samples;
036c1382 1658 for(i=0;i<(decoded_data_size / sizeof(short));i++) {
bde0705c
LW
1659 int v = ((*volp) * audio_volume + 128) >> 8;
1660 if (v < -32768) v = -32768;
1661 if (v > 32767) v = 32767;
1662 *volp++ = v;
7e987c33
C
1663 }
1664 }
bde0705c 1665 }
7e987c33 1666
bde0705c 1667 /* frame rate emulation */
3a25ca18 1668 if (rate_emu) {
cb103a19 1669 int64_t pts = av_rescale(ist->pts, 1000000, AV_TIME_BASE);
bde0705c
LW
1670 int64_t now = av_gettime() - ist->start;
1671 if (pts > now)
1672 usleep(pts - now);
bde0705c 1673 }
46847a33 1674#if CONFIG_AVFILTER
d21f58b5 1675 frame_available = ist->st->codec->codec_type != AVMEDIA_TYPE_VIDEO ||
dfd57757 1676 !ist->output_video_filter || avfilter_poll_frame(ist->output_video_filter->inputs[0]);
46847a33 1677#endif
bde0705c
LW
1678 /* if output time reached then transcode raw format,
1679 encode packets and output them */
1680 if (start_time == 0 || ist->pts >= start_time)
46847a33 1681#if CONFIG_AVFILTER
d21f58b5 1682 while (frame_available) {
dfd57757
SS
1683 if (ist->st->codec->codec_type == AVMEDIA_TYPE_VIDEO && ist->output_video_filter)
1684 get_filtered_video_pic(ist->output_video_filter, &ist->picref, &picture, &ist->pts);
46847a33 1685#endif
bde0705c
LW
1686 for(i=0;i<nb_ostreams;i++) {
1687 int frame_size;
a700a6ae 1688
bde0705c
LW
1689 ost = ost_table[i];
1690 if (ost->source_index == ist_index) {
1691 os = output_files[ost->file_index];
a700a6ae 1692
bde0705c
LW
1693 /* set the input output pts pairs */
1694 //ost->sync_ipts = (double)(ist->pts + input_files_ts_offset[ist->file_index] - start_time)/ AV_TIME_BASE;
1695
1696 if (ost->encoding_needed) {
b926b628 1697 av_assert0(ist->decoding_needed);
bde0705c 1698 switch(ost->st->codec->codec_type) {
72415b2a 1699 case AVMEDIA_TYPE_AUDIO:
036c1382 1700 do_audio_out(os, ost, ist, decoded_data_buf, decoded_data_size);
bde0705c 1701 break;
72415b2a 1702 case AVMEDIA_TYPE_VIDEO:
46847a33 1703#if CONFIG_AVFILTER
cc80caff
HM
1704 if (ist->picref->video)
1705 ost->st->codec->sample_aspect_ratio = ist->picref->video->pixel_aspect;
46847a33 1706#endif
bde0705c 1707 do_video_out(os, ost, ist, &picture, &frame_size);
b60d1379 1708 if (vstats_filename && frame_size)
bde0705c
LW
1709 do_video_stats(os, ost, frame_size);
1710 break;
72415b2a 1711 case AVMEDIA_TYPE_SUBTITLE:
bde0705c
LW
1712 do_subtitle_out(os, ost, ist, &subtitle,
1713 pkt->pts);
1714 break;
1715 default:
0f4e8165 1716 abort();
bde0705c
LW
1717 }
1718 } else {
1719 AVFrame avframe; //FIXME/XXX remove this
1720 AVPacket opkt;
cdf38a17
MN
1721 int64_t ost_tb_start_time= av_rescale_q(start_time, AV_TIME_BASE_Q, ost->st->time_base);
1722
bde0705c
LW
1723 av_init_packet(&opkt);
1724
cc947f04 1725 if ((!ost->frame_number && !(pkt->flags & AV_PKT_FLAG_KEY)) && !copy_initial_nonkeyframes)
7cacf1e8
MN
1726 continue;
1727
bde0705c
LW
1728 /* no reencoding needed : output the packet directly */
1729 /* force the input stream PTS */
1730
1731 avcodec_get_frame_defaults(&avframe);
1732 ost->st->codec->coded_frame= &avframe;
cc947f04 1733 avframe.key_frame = pkt->flags & AV_PKT_FLAG_KEY;
bde0705c 1734
72415b2a 1735 if(ost->st->codec->codec_type == AVMEDIA_TYPE_AUDIO)
bde0705c 1736 audio_size += data_size;
72415b2a 1737 else if (ost->st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
bde0705c
LW
1738 video_size += data_size;
1739 ost->sync_opts++;
1740 }
1741
1742 opkt.stream_index= ost->index;
1743 if(pkt->pts != AV_NOPTS_VALUE)
cdf38a17 1744 opkt.pts= av_rescale_q(pkt->pts, ist->st->time_base, ost->st->time_base) - ost_tb_start_time;
bde0705c
LW
1745 else
1746 opkt.pts= AV_NOPTS_VALUE;
1747
d2ce2f5e 1748 if (pkt->dts == AV_NOPTS_VALUE)
181782ae 1749 opkt.dts = av_rescale_q(ist->pts, AV_TIME_BASE_Q, ost->st->time_base);
d2ce2f5e
BC
1750 else
1751 opkt.dts = av_rescale_q(pkt->dts, ist->st->time_base, ost->st->time_base);
cdf38a17 1752 opkt.dts -= ost_tb_start_time;
c0dd7b7c 1753
a03d59b7 1754 opkt.duration = av_rescale_q(pkt->duration, ist->st->time_base, ost->st->time_base);
bde0705c
LW
1755 opkt.flags= pkt->flags;
1756
1757 //FIXME remove the following 2 lines they shall be replaced by the bitstream filters
5bfe91e6
MN
1758 if( ost->st->codec->codec_id != CODEC_ID_H264
1759 && ost->st->codec->codec_id != CODEC_ID_MPEG1VIDEO
1760 && ost->st->codec->codec_id != CODEC_ID_MPEG2VIDEO
1761 ) {
cc947f04 1762 if(av_parser_change(ist->st->parser, ost->st->codec, &opkt.data, &opkt.size, data_buf, data_size, pkt->flags & AV_PKT_FLAG_KEY))
9f907d85 1763 opkt.destruct= av_destruct_packet;
d310d56a
BC
1764 } else {
1765 opkt.data = data_buf;
1766 opkt.size = data_size;
1767 }
bde0705c 1768
8b389f15 1769 write_frame(os, &opkt, ost->st->codec, bitstream_filters[ost->file_index][opkt.stream_index]);
bde0705c
LW
1770 ost->st->codec->frame_number++;
1771 ost->frame_number++;
1772 av_free_packet(&opkt);
a700a6ae
FB
1773 }
1774 }
bde0705c 1775 }
46847a33
MN
1776
1777#if CONFIG_AVFILTER
748db0fc 1778 frame_available = (ist->st->codec->codec_type == AVMEDIA_TYPE_VIDEO) &&
dfd57757 1779 ist->output_video_filter && avfilter_poll_frame(ist->output_video_filter->inputs[0]);
46847a33 1780 if(ist->picref)
7fce481a 1781 avfilter_unref_buffer(ist->picref);
46847a33
MN
1782 }
1783#endif
bde0705c
LW
1784 av_free(buffer_to_free);
1785 /* XXX: allocate the subtitles in the codec ? */
1786 if (subtitle_to_free) {
1787 if (subtitle_to_free->rects != NULL) {
1788 for (i = 0; i < subtitle_to_free->num_rects; i++) {
25b4c651
MN
1789 av_freep(&subtitle_to_free->rects[i]->pict.data[0]);
1790 av_freep(&subtitle_to_free->rects[i]->pict.data[1]);
db4fac64 1791 av_freep(&subtitle_to_free->rects[i]);
c6ec28b1 1792 }
bde0705c 1793 av_freep(&subtitle_to_free->rects);
cf7fc795 1794 }
bde0705c
LW
1795 subtitle_to_free->num_rects = 0;
1796 subtitle_to_free = NULL;
a700a6ae 1797 }
bde0705c 1798 }
a700a6ae 1799 discard_packet:
6f824977
MN
1800 if (pkt == NULL) {
1801 /* EOF handling */
115329f1 1802
6f824977
MN
1803 for(i=0;i<nb_ostreams;i++) {
1804 ost = ost_table[i];
1805 if (ost->source_index == ist_index) {
01f4895c 1806 AVCodecContext *enc= ost->st->codec;
6f824977 1807 os = output_files[ost->file_index];
115329f1 1808
72415b2a 1809 if(ost->st->codec->codec_type == AVMEDIA_TYPE_AUDIO && enc->frame_size <=1)
6f824977 1810 continue;
72415b2a 1811 if(ost->st->codec->codec_type == AVMEDIA_TYPE_VIDEO && (os->oformat->flags & AVFMT_RAWPICTURE))
6f824977
MN
1812 continue;
1813
1814 if (ost->encoding_needed) {
1815 for(;;) {
1816 AVPacket pkt;
cef7cc72 1817 int fifo_bytes;
6f824977
MN
1818 av_init_packet(&pkt);
1819 pkt.stream_index= ost->index;
115329f1 1820
01f4895c 1821 switch(ost->st->codec->codec_type) {
72415b2a 1822 case AVMEDIA_TYPE_AUDIO:
41dd680d 1823 fifo_bytes = av_fifo_size(ost->fifo);
cef7cc72
JR
1824 ret = 0;
1825 /* encode any samples remaining in fifo */
b10d7e4e 1826 if (fifo_bytes > 0) {
22c4c3e0 1827 int osize = av_get_bits_per_sample_format(enc->sample_fmt) >> 3;
cef7cc72 1828 int fs_tmp = enc->frame_size;
b10d7e4e 1829
79c85beb 1830 av_fifo_generic_read(ost->fifo, audio_buf, fifo_bytes, NULL);
b10d7e4e
BC
1831 if (enc->codec->capabilities & CODEC_CAP_SMALL_LAST_FRAME) {
1832 enc->frame_size = fifo_bytes / (osize * enc->channels);
1833 } else { /* pad */
1834 int frame_bytes = enc->frame_size*osize*enc->channels;
79c85beb 1835 if (allocated_audio_buf_size < frame_bytes)
639e4ec8 1836 ffmpeg_exit(1);
e91376d1 1837 memset(audio_buf+fifo_bytes, 0, frame_bytes - fifo_bytes);
b10d7e4e
BC
1838 }
1839
79c85beb 1840 ret = avcodec_encode_audio(enc, bit_buffer, bit_buffer_size, (short *)audio_buf);
7c8689ef
BC
1841 pkt.duration = av_rescale((int64_t)enc->frame_size*ost->st->time_base.den,
1842 ost->st->time_base.num, enc->sample_rate);
cef7cc72 1843 enc->frame_size = fs_tmp;
9e0db7d5
MN
1844 }
1845 if(ret <= 0) {
cef7cc72
JR
1846 ret = avcodec_encode_audio(enc, bit_buffer, bit_buffer_size, NULL);
1847 }
528271ff
MN
1848 if (ret < 0) {
1849 fprintf(stderr, "Audio encoding failed\n");
639e4ec8 1850 ffmpeg_exit(1);
528271ff 1851 }
6f824977 1852 audio_size += ret;
cc947f04 1853 pkt.flags |= AV_PKT_FLAG_KEY;
6f824977 1854 break;
72415b2a 1855 case AVMEDIA_TYPE_VIDEO:
8a6cb114 1856 ret = avcodec_encode_video(enc, bit_buffer, bit_buffer_size, NULL);
528271ff
MN
1857 if (ret < 0) {
1858 fprintf(stderr, "Video encoding failed\n");
639e4ec8 1859 ffmpeg_exit(1);
528271ff 1860 }
6f824977
MN
1861 video_size += ret;
1862 if(enc->coded_frame && enc->coded_frame->key_frame)
cc947f04 1863 pkt.flags |= AV_PKT_FLAG_KEY;
6f824977
MN
1864 if (ost->logfile && enc->stats_out) {
1865 fprintf(ost->logfile, "%s", enc->stats_out);
1866 }
1867 break;
1868 default:
1869 ret=-1;
1870 }
115329f1 1871
6f824977
MN
1872 if(ret<=0)
1873 break;
27537106 1874 pkt.data= bit_buffer;
6f824977 1875 pkt.size= ret;
e7902f20 1876 if(enc->coded_frame && enc->coded_frame->pts != AV_NOPTS_VALUE)
c0df9d75 1877 pkt.pts= av_rescale_q(enc->coded_frame->pts, enc->time_base, ost->st->time_base);
748c2fca 1878 write_frame(os, &pkt, ost->st->codec, bitstream_filters[ost->file_index][pkt.stream_index]);
6f824977
MN
1879 }
1880 }
1881 }
1882 }
1883 }
115329f1 1884
a700a6ae
FB
1885 return 0;
1886 fail_decode:
1887 return -1;
1888}
1889
6d1ba1ac
LA
1890static void print_sdp(AVFormatContext **avc, int n)
1891{
1892 char sdp[2048];
1893
1894 avf_sdp_create(avc, n, sdp, sizeof(sdp));
1895 printf("SDP:\n%s\n", sdp);
536cd1db 1896 fflush(stdout);
6d1ba1ac 1897}
a700a6ae 1898
7a39f142
AK
1899static int copy_chapters(int infile, int outfile)
1900{
1901 AVFormatContext *is = input_files[infile];
1902 AVFormatContext *os = output_files[outfile];
1903 int i;
1904
1905 for (i = 0; i < is->nb_chapters; i++) {
1906 AVChapter *in_ch = is->chapters[i], *out_ch;
1907 AVMetadataTag *t = NULL;
1908 int64_t ts_off = av_rescale_q(start_time - input_files_ts_offset[infile],
1909 AV_TIME_BASE_Q, in_ch->time_base);
1910 int64_t rt = (recording_time == INT64_MAX) ? INT64_MAX :
1911 av_rescale_q(recording_time, AV_TIME_BASE_Q, in_ch->time_base);
1912
1913
1914 if (in_ch->end < ts_off)
1915 continue;
1916 if (rt != INT64_MAX && in_ch->start > rt + ts_off)
1917 break;
1918
1919 out_ch = av_mallocz(sizeof(AVChapter));
1920 if (!out_ch)
1921 return AVERROR(ENOMEM);
1922
1923 out_ch->id = in_ch->id;
1924 out_ch->time_base = in_ch->time_base;
1925 out_ch->start = FFMAX(0, in_ch->start - ts_off);
1926 out_ch->end = FFMIN(rt, in_ch->end - ts_off);
1927
1928 while ((t = av_metadata_get(in_ch->metadata, "", t, AV_METADATA_IGNORE_SUFFIX)))
1929 av_metadata_set2(&out_ch->metadata, t->key, t->value, 0);
1930
1931 os->nb_chapters++;
1932 os->chapters = av_realloc(os->chapters, sizeof(AVChapter)*os->nb_chapters);
1933 if (!os->chapters)
1934 return AVERROR(ENOMEM);
1935 os->chapters[os->nb_chapters - 1] = out_ch;
1936 }
1937 return 0;
1938}
1939
85f07f22
FB
1940/*
1941 * The following code is the main loop of the file converter
1942 */
3aace1bc 1943static int transcode(AVFormatContext **output_files,
065a20cb
SS
1944 int nb_output_files,
1945 AVFormatContext **input_files,
1946 int nb_input_files,
1947 AVStreamMap *stream_maps, int nb_stream_maps)
85f07f22 1948{
002c95d7 1949 int ret = 0, i, j, k, n, nb_istreams = 0, nb_ostreams = 0;
85f07f22
FB
1950 AVFormatContext *is, *os;
1951 AVCodecContext *codec, *icodec;
1952 AVOutputStream *ost, **ost_table = NULL;
1953 AVInputStream *ist, **ist_table = NULL;
bdc4796f 1954 AVInputFile *file_table;
002c95d7 1955 char error[1024];
cb09b2ed 1956 int key;
6d1ba1ac 1957 int want_sdp = 1;
545465ec
MN
1958 uint8_t no_packet[MAX_FILES]={0};
1959 int no_packet_count=0;
bdc4796f 1960
90901860 1961 file_table= av_mallocz(nb_input_files * sizeof(AVInputFile));
bdc4796f
FB
1962 if (!file_table)
1963 goto fail;
115329f1 1964
85f07f22
FB
1965 /* input stream init */
1966 j = 0;
1967 for(i=0;i<nb_input_files;i++) {
1968 is = input_files[i];
1969 file_table[i].ist_index = j;
79fdaa4c 1970 file_table[i].nb_streams = is->nb_streams;
85f07f22
FB
1971 j += is->nb_streams;
1972 }
1973 nb_istreams = j;
1974
1975 ist_table = av_mallocz(nb_istreams * sizeof(AVInputStream *));
1976 if (!ist_table)
bdc4796f 1977 goto fail;
115329f1 1978
85f07f22
FB
1979 for(i=0;i<nb_istreams;i++) {
1980 ist = av_mallocz(sizeof(AVInputStream));
1981 if (!ist)
1982 goto fail;
1983 ist_table[i] = ist;
1984 }
1985 j = 0;
1986 for(i=0;i<nb_input_files;i++) {
1987 is = input_files[i];
1988 for(k=0;k<is->nb_streams;k++) {
1989 ist = ist_table[j++];
1990 ist->st = is->streams[k];
1991 ist->file_index = i;
1992 ist->index = k;
1993 ist->discard = 1; /* the stream is discarded by default
1994 (changed later) */
bdfcbbed 1995
3a25ca18 1996 if (rate_emu) {
bdfcbbed 1997 ist->start = av_gettime();
bdfcbbed 1998 }
85f07f22
FB
1999 }
2000 }
2001
2002 /* output stream init */
2003 nb_ostreams = 0;
2004 for(i=0;i<nb_output_files;i++) {
2005 os = output_files[i];
8a7bde1c 2006 if (!os->nb_streams) {
fc5d0db5
SS
2007 dump_format(output_files[i], i, output_files[i]->filename, 1);
2008 fprintf(stderr, "Output file #%d does not contain any stream\n", i);
d62ccec8
JM
2009 ret = AVERROR(EINVAL);
2010 goto fail;
8a7bde1c 2011 }
85f07f22
FB
2012 nb_ostreams += os->nb_streams;
2013 }
2014 if (nb_stream_maps > 0 && nb_stream_maps != nb_ostreams) {
2015 fprintf(stderr, "Number of stream maps must match number of output streams\n");
d62ccec8
JM
2016 ret = AVERROR(EINVAL);
2017 goto fail;
85f07f22
FB
2018 }
2019
bd073980
BF
2020 /* Sanity check the mapping args -- do the input files & streams exist? */
2021 for(i=0;i<nb_stream_maps;i++) {
2022 int fi = stream_maps[i].file_index;
2023 int si = stream_maps[i].stream_index;
115329f1 2024
bd073980
BF
2025 if (fi < 0 || fi > nb_input_files - 1 ||
2026 si < 0 || si > file_table[fi].nb_streams - 1) {
2027 fprintf(stderr,"Could not find input stream #%d.%d\n", fi, si);
d62ccec8
JM
2028 ret = AVERROR(EINVAL);
2029 goto fail;
bd073980 2030 }
b4a3389e
WG
2031 fi = stream_maps[i].sync_file_index;
2032 si = stream_maps[i].sync_stream_index;
2033 if (fi < 0 || fi > nb_input_files - 1 ||
2034 si < 0 || si > file_table[fi].nb_streams - 1) {
2035 fprintf(stderr,"Could not find sync stream #%d.%d\n", fi, si);
d62ccec8
JM
2036 ret = AVERROR(EINVAL);
2037 goto fail;
b4a3389e 2038 }
bd073980 2039 }
115329f1 2040
85f07f22
FB
2041 ost_table = av_mallocz(sizeof(AVOutputStream *) * nb_ostreams);
2042 if (!ost_table)
2043 goto fail;
85f07f22
FB
2044 n = 0;
2045 for(k=0;k<nb_output_files;k++) {
2046 os = output_files[k];
de427ff4 2047 for(i=0;i<os->nb_streams;i++,n++) {
85f07f22 2048 int found;
9fdf4b58 2049 ost = ost_table[n] = output_streams_for_file[k][i];
85f07f22
FB
2050 ost->st = os->streams[i];
2051 if (nb_stream_maps > 0) {
de427ff4
SS
2052 ost->source_index = file_table[stream_maps[n].file_index].ist_index +
2053 stream_maps[n].stream_index;
115329f1 2054
bd073980 2055 /* Sanity check that the stream types match */
01f4895c 2056 if (ist_table[ost->source_index]->st->codec->codec_type != ost->st->codec->codec_type) {
150d5a25
SS
2057 int i= ost->file_index;
2058 dump_format(output_files[i], i, output_files[i]->filename, 1);
bd073980 2059 fprintf(stderr, "Codec type mismatch for mapping #%d.%d -> #%d.%d\n",
de427ff4 2060 stream_maps[n].file_index, stream_maps[n].stream_index,
bd073980 2061 ost->file_index, ost->index);
639e4ec8 2062 ffmpeg_exit(1);
bd073980 2063 }
115329f1 2064
85f07f22 2065 } else {
247e3954 2066 int best_nb_frames=-1;
3f1710e7
RP
2067 /* get corresponding input stream index : we select the first one with the right type */
2068 found = 0;
2069 for(j=0;j<nb_istreams;j++) {
2070 int skip=0;
2071 ist = ist_table[j];
2072 if(opt_programid){
2073 int pi,si;
2074 AVFormatContext *f= input_files[ ist->file_index ];
2075 skip=1;
2076 for(pi=0; pi<f->nb_programs; pi++){
2077 AVProgram *p= f->programs[pi];
2078 if(p->id == opt_programid)
2079 for(si=0; si<p->nb_stream_indexes; si++){
2080 if(f->streams[ p->stream_index[si] ] == ist->st)
2081 skip=0;
2082 }
6d3d3b83 2083 }
3f1710e7
RP
2084 }
2085 if (ist->discard && ist->st->discard != AVDISCARD_ALL && !skip &&
2086 ist->st->codec->codec_type == ost->st->codec->codec_type) {
2087 if(best_nb_frames < ist->st->codec_info_nb_frames){
2088 best_nb_frames= ist->st->codec_info_nb_frames;
2089 ost->source_index = j;
2090 found = 1;
85f07f22
FB
2091 }
2092 }
3f1710e7 2093 }
a15bc651
NS
2094
2095 if (!found) {
2096 if(! opt_programid) {
2097 /* try again and reuse existing stream */
2098 for(j=0;j<nb_istreams;j++) {
2099 ist = ist_table[j];
6d3d3b83
MN
2100 if ( ist->st->codec->codec_type == ost->st->codec->codec_type
2101 && ist->st->discard != AVDISCARD_ALL) {
a15bc651
NS
2102 ost->source_index = j;
2103 found = 1;
2104 }
2105 }
50e143c4 2106 }
85f07f22 2107 if (!found) {
462cca10
SS
2108 int i= ost->file_index;
2109 dump_format(output_files[i], i, output_files[i]->filename, 1);
85f07f22
FB
2110 fprintf(stderr, "Could not find input stream matching output stream #%d.%d\n",
2111 ost->file_index, ost->index);
639e4ec8 2112 ffmpeg_exit(1);
85f07f22
FB
2113 }
2114 }
2115 }
2116 ist = ist_table[ost->source_index];
2117 ist->discard = 0;
b4a3389e 2118 ost->sync_ist = (nb_stream_maps > 0) ?
de427ff4
SS
2119 ist_table[file_table[stream_maps[n].sync_file_index].ist_index +
2120 stream_maps[n].sync_stream_index] : ist;
85f07f22
FB
2121 }
2122 }
2123
85f07f22
FB
2124 /* for each output stream, we compute the right encoding parameters */
2125 for(i=0;i<nb_ostreams;i++) {
46e6fb4c 2126 AVMetadataTag *t = NULL;
85f07f22 2127 ost = ost_table[i];
365515ac 2128 os = output_files[ost->file_index];
85f07f22
FB
2129 ist = ist_table[ost->source_index];
2130
01f4895c
MN
2131 codec = ost->st->codec;
2132 icodec = ist->st->codec;
85f07f22 2133
c71591a5 2134 while ((t = av_metadata_get(ist->st->metadata, "", t, AV_METADATA_IGNORE_SUFFIX))) {
46e6fb4c 2135 av_metadata_set2(&ost->st->metadata, t->key, t->value, AV_METADATA_DONT_OVERWRITE);
c71591a5 2136 }
8e0d882b 2137
90c2295b 2138 ost->st->disposition = ist->st->disposition;
a39b76ea 2139 codec->bits_per_raw_sample= icodec->bits_per_raw_sample;
de961801 2140 codec->chroma_sample_location = icodec->chroma_sample_location;
90c2295b 2141
1629626f 2142 if (ost->st->stream_copy) {
b659c8b4
LA
2143 uint64_t extra_size = (uint64_t)icodec->extradata_size + FF_INPUT_BUFFER_PADDING_SIZE;
2144
2145 if (extra_size > INT_MAX)
2146 goto fail;
2147
1629626f
FB
2148 /* if stream_copy is selected, no need to decode or encode */
2149 codec->codec_id = icodec->codec_id;
2150 codec->codec_type = icodec->codec_type;
365515ac
MN
2151
2152 if(!codec->codec_tag){
2153 if( !os->oformat->codec_tag
37ce3d6b 2154 || av_codec_get_id (os->oformat->codec_tag, icodec->codec_tag) == codec->codec_id
365515ac
MN
2155 || av_codec_get_tag(os->oformat->codec_tag, icodec->codec_id) <= 0)
2156 codec->codec_tag = icodec->codec_tag;
2157 }
2158
1629626f 2159 codec->bit_rate = icodec->bit_rate;
2dec2bb8
MN
2160 codec->rc_max_rate = icodec->rc_max_rate;
2161 codec->rc_buffer_size = icodec->rc_buffer_size;
b659c8b4
LA
2162 codec->extradata= av_mallocz(extra_size);
2163 if (!codec->extradata)
2164 goto fail;
2165 memcpy(codec->extradata, icodec->extradata, icodec->extradata_size);
dffbfd06 2166 codec->extradata_size= icodec->extradata_size;
3797c74b 2167 if(av_q2d(icodec->time_base)*icodec->ticks_per_frame > av_q2d(ist->st->time_base) && av_q2d(ist->st->time_base) < 1.0/1000){
d29de719 2168 codec->time_base = icodec->time_base;
3797c74b 2169 codec->time_base.num *= icodec->ticks_per_frame;
8abcbf2d
BC
2170 av_reduce(&codec->time_base.num, &codec->time_base.den,
2171 codec->time_base.num, codec->time_base.den, INT_MAX);
3797c74b 2172 }else
d29de719 2173 codec->time_base = ist->st->time_base;
1629626f 2174 switch(codec->codec_type) {
72415b2a 2175 case AVMEDIA_TYPE_AUDIO:
d08e3e91
RP
2176 if(audio_volume != 256) {
2177 fprintf(stderr,"-acodec copy and -vol are incompatible (frames are not decoded)\n");
639e4ec8 2178 ffmpeg_exit(1);
d08e3e91 2179 }
13367a46 2180 codec->channel_layout = icodec->channel_layout;
1629626f
FB
2181 codec->sample_rate = icodec->sample_rate;
2182 codec->channels = icodec->channels;
0a3b0447 2183 codec->frame_size = icodec->frame_size;
c1344911 2184 codec->block_align= icodec->block_align;
4efd6f58
MN
2185 if(codec->block_align == 1 && codec->codec_id == CODEC_ID_MP3)
2186 codec->block_align= 0;
bcbd328e
MN
2187 if(codec->codec_id == CODEC_ID_AC3)
2188 codec->block_align= 0;
1629626f 2189 break;
72415b2a 2190 case AVMEDIA_TYPE_VIDEO:
9df3437f 2191 codec->pix_fmt = icodec->pix_fmt;
1629626f
FB
2192 codec->width = icodec->width;
2193 codec->height = icodec->height;
ff8cc24b 2194 codec->has_b_frames = icodec->has_b_frames;
1629626f 2195 break;
72415b2a 2196 case AVMEDIA_TYPE_SUBTITLE:
d43b26ea
DC
2197 codec->width = icodec->width;
2198 codec->height = icodec->height;
cf7fc795 2199 break;
1629626f 2200 default:
0f4e8165 2201 abort();
1629626f
FB
2202 }
2203 } else {
2204 switch(codec->codec_type) {
72415b2a 2205 case AVMEDIA_TYPE_AUDIO:
41dd680d
MN
2206 ost->fifo= av_fifo_alloc(1024);
2207 if(!ost->fifo)
85f07f22 2208 goto fail;
a79db0f7 2209 ost->reformat_pair = MAKE_SFMT_PAIR(SAMPLE_FMT_NONE,SAMPLE_FMT_NONE);
2886f311
2210 ost->audio_resample = codec->sample_rate != icodec->sample_rate || audio_sync_method > 1;
2211 icodec->request_channels = codec->channels;
85f07f22
FB
2212 ist->decoding_needed = 1;
2213 ost->encoding_needed = 1;
1629626f 2214 break;
72415b2a 2215 case AVMEDIA_TYPE_VIDEO:
761c8c92 2216 if (ost->st->codec->pix_fmt == PIX_FMT_NONE) {
562f22a6 2217 fprintf(stderr, "Video pixel format is unknown, stream cannot be encoded\n");
639e4ec8 2218 ffmpeg_exit(1);
761c8c92 2219 }
c3f11d19 2220 ost->video_crop = ((frame_leftBand + frame_rightBand + frame_topBand + frame_bottomBand) != 0);
c3f11d19 2221 ost->video_resample = ((codec->width != icodec->width -
0c22311b 2222 (frame_leftBand + frame_rightBand)) ||
c3f11d19 2223 (codec->height != icodec->height -
0c22311b 2224 (frame_topBand + frame_bottomBand)) ||
18a54b04 2225 (codec->pix_fmt != icodec->pix_fmt));
c3f11d19 2226 if (ost->video_crop) {
352666c1
EB
2227 ost->topBand = ost->original_topBand = frame_topBand;
2228 ost->bottomBand = ost->original_bottomBand = frame_bottomBand;
2229 ost->leftBand = ost->original_leftBand = frame_leftBand;
2230 ost->rightBand = ost->original_rightBand = frame_rightBand;
c3f11d19 2231 }
c3f11d19 2232 if (ost->video_resample) {
2de28abb 2233 avcodec_get_frame_defaults(&ost->pict_tmp);
9d58e0a9
BC
2234 if(avpicture_alloc((AVPicture*)&ost->pict_tmp, codec->pix_fmt,
2235 codec->width, codec->height)) {
eddc482d 2236 fprintf(stderr, "Cannot allocate temp picture, check pix fmt\n");
639e4ec8 2237 ffmpeg_exit(1);
eddc482d 2238 }
9de8e6ac 2239 sws_flags = av_get_int(sws_opts, "sws_flags", NULL);
18a54b04
LA
2240 ost->img_resample_ctx = sws_getContext(
2241 icodec->width - (frame_leftBand + frame_rightBand),
2242 icodec->height - (frame_topBand + frame_bottomBand),
2243 icodec->pix_fmt,
0c22311b
MN
2244 codec->width,
2245 codec->height,
18a54b04
LA
2246 codec->pix_fmt,
2247 sws_flags, NULL, NULL, NULL);
0b50ac8a
LA
2248 if (ost->img_resample_ctx == NULL) {
2249 fprintf(stderr, "Cannot get resampling context\n");
639e4ec8 2250 ffmpeg_exit(1);
0b50ac8a 2251 }
352666c1 2252
46847a33 2253#if !CONFIG_AVFILTER
352666c1
EB
2254 ost->original_height = icodec->height;
2255 ost->original_width = icodec->width;
46847a33 2256#endif
a39b76ea 2257 codec->bits_per_raw_sample= 0;
85f07f22 2258 }
b83ccbff
MN
2259 ost->resample_height = icodec->height - (frame_topBand + frame_bottomBand);
2260 ost->resample_width = icodec->width - (frame_leftBand + frame_rightBand);
2261 ost->resample_pix_fmt= icodec->pix_fmt;
85f07f22
FB
2262 ost->encoding_needed = 1;
2263 ist->decoding_needed = 1;
46847a33
MN
2264
2265#if CONFIG_AVFILTER
2266 if (configure_filters(ist, ost)) {
2267 fprintf(stderr, "Error opening filters!\n");
2268 exit(1);
2269 }
2270#endif
1629626f 2271 break;
72415b2a 2272 case AVMEDIA_TYPE_SUBTITLE:
cf7fc795
FB
2273 ost->encoding_needed = 1;
2274 ist->decoding_needed = 1;
2275 break;
1629626f 2276 default:
0f4e8165 2277 abort();
cf7fc795 2278 break;
85f07f22 2279 }
1629626f 2280 /* two pass mode */
115329f1 2281 if (ost->encoding_needed &&
1629626f
FB
2282 (codec->flags & (CODEC_FLAG_PASS1 | CODEC_FLAG_PASS2))) {
2283 char logfilename[1024];
2284 FILE *f;
115329f1
DB
2285
2286 snprintf(logfilename, sizeof(logfilename), "%s-%d.log",
22730e87
SS
2287 pass_logfilename_prefix ? pass_logfilename_prefix : DEFAULT_PASS_LOGFILENAME_PREFIX,
2288 i);
1629626f 2289 if (codec->flags & CODEC_FLAG_PASS1) {
c56e9e05 2290 f = fopen(logfilename, "wb");
1629626f 2291 if (!f) {
42d1d06e 2292 fprintf(stderr, "Cannot write log file '%s' for pass-1 encoding: %s\n", logfilename, strerror(errno));
639e4ec8 2293 ffmpeg_exit(1);
1629626f
FB
2294 }
2295 ost->logfile = f;
2296 } else {
458b062d
SS
2297 char *logbuffer;
2298 size_t logbuffer_size;
2299 if (read_file(logfilename, &logbuffer, &logbuffer_size) < 0) {
2300 fprintf(stderr, "Error reading log file '%s' for pass-2 encoding\n", logfilename);
639e4ec8 2301 ffmpeg_exit(1);
1629626f 2302 }
1629626f 2303 codec->stats_in = logbuffer;
5abdb4b1 2304 }
5abdb4b1
FB
2305 }
2306 }
72415b2a 2307 if(codec->codec_type == AVMEDIA_TYPE_VIDEO){
8a6cb114 2308 int size= codec->width * codec->height;
c027e91a 2309 bit_buffer_size= FFMAX(bit_buffer_size, 6*size + 200);
8a6cb114 2310 }
85f07f22
FB
2311 }
2312
8a6cb114
MN
2313 if (!bit_buffer)
2314 bit_buffer = av_malloc(bit_buffer_size);
002c95d7 2315 if (!bit_buffer) {
50f3fabc
MR
2316 fprintf(stderr, "Cannot allocate %d bytes output buffer\n",
2317 bit_buffer_size);
002c95d7 2318 ret = AVERROR(ENOMEM);
8a6cb114 2319 goto fail;
1629626f
FB
2320 }
2321
85f07f22
FB
2322 /* open each encoder */
2323 for(i=0;i<nb_ostreams;i++) {
2324 ost = ost_table[i];
2325 if (ost->encoding_needed) {
0a6d97b3 2326 AVCodec *codec = i < nb_output_codecs ? output_codecs[i] : NULL;
6488cf9b 2327 if (!codec)
fd2b356a 2328 codec = avcodec_find_encoder(ost->st->codec->codec_id);
85f07f22 2329 if (!codec) {
f356fc57
BC
2330 snprintf(error, sizeof(error), "Encoder (codec id %d) not found for output stream #%d.%d",
2331 ost->st->codec->codec_id, ost->file_index, ost->index);
002c95d7
BC
2332 ret = AVERROR(EINVAL);
2333 goto dump_format;
85f07f22 2334 }
01f4895c 2335 if (avcodec_open(ost->st->codec, codec) < 0) {
f356fc57 2336 snprintf(error, sizeof(error), "Error while opening encoder for output stream #%d.%d - maybe incorrect parameters such as bit_rate, rate, width or height",
85f07f22 2337 ost->file_index, ost->index);
002c95d7
BC
2338 ret = AVERROR(EINVAL);
2339 goto dump_format;
85f07f22 2340 }
01f4895c 2341 extra_size += ost->st->codec->extradata_size;
85f07f22
FB
2342 }
2343 }
2344
2345 /* open each decoder */
2346 for(i=0;i<nb_istreams;i++) {
2347 ist = ist_table[i];
2348 if (ist->decoding_needed) {
311e223f 2349 AVCodec *codec = i < nb_input_codecs ? input_codecs[i] : NULL;
6488cf9b 2350 if (!codec)
fd2b356a 2351 codec = avcodec_find_decoder(ist->st->codec->codec_id);
85f07f22 2352 if (!codec) {
f356fc57 2353 snprintf(error, sizeof(error), "Decoder (codec id %d) not found for input stream #%d.%d",
01f4895c 2354 ist->st->codec->codec_id, ist->file_index, ist->index);
002c95d7
BC
2355 ret = AVERROR(EINVAL);
2356 goto dump_format;
85f07f22 2357 }
01f4895c 2358 if (avcodec_open(ist->st->codec, codec) < 0) {
f356fc57 2359 snprintf(error, sizeof(error), "Error while opening decoder for input stream #%d.%d",
85f07f22 2360 ist->file_index, ist->index);
002c95d7
BC
2361 ret = AVERROR(EINVAL);
2362 goto dump_format;
85f07f22 2363 }
72415b2a 2364 //if (ist->st->codec->codec_type == AVMEDIA_TYPE_VIDEO)
01f4895c 2365 // ist->st->codec->flags |= CODEC_FLAG_REPEAT_FIELD;
85f07f22
FB
2366 }
2367 }
2368
2369 /* init pts */
2370 for(i=0;i<nb_istreams;i++) {
b8c93c48 2371 AVStream *st;
85f07f22 2372 ist = ist_table[i];
b8c93c48
MN
2373 st= ist->st;
2374 ist->pts = st->avg_frame_rate.num ? - st->codec->has_b_frames*AV_TIME_BASE / av_q2d(st->avg_frame_rate) : 0;
48291040 2375 ist->next_pts = AV_NOPTS_VALUE;
0ff4f0c0 2376 init_pts_correction(&ist->pts_ctx);
ff4905a5 2377 ist->is_start = 1;
85f07f22 2378 }
c5e1e982 2379
0a38bafd
PB
2380 /* set meta data information from input file if required */
2381 for (i=0;i<nb_meta_data_maps;i++) {
2382 AVFormatContext *out_file;
2383 AVFormatContext *in_file;
a5926d85 2384 AVMetadataTag *mtag;
0a38bafd
PB
2385
2386 int out_file_index = meta_data_maps[i].out_file;
2387 int in_file_index = meta_data_maps[i].in_file;
9d58e0a9 2388 if (out_file_index < 0 || out_file_index >= nb_output_files) {
002c95d7
BC
2389 snprintf(error, sizeof(error), "Invalid output file index %d map_meta_data(%d,%d)",
2390 out_file_index, out_file_index, in_file_index);
8fa36ae0 2391 ret = AVERROR(EINVAL);
002c95d7 2392 goto dump_format;
0a38bafd 2393 }
9d58e0a9 2394 if (in_file_index < 0 || in_file_index >= nb_input_files) {
002c95d7
BC
2395 snprintf(error, sizeof(error), "Invalid input file index %d map_meta_data(%d,%d)",
2396 in_file_index, out_file_index, in_file_index);
8fa36ae0 2397 ret = AVERROR(EINVAL);
002c95d7 2398 goto dump_format;
115329f1
DB
2399 }
2400
0a38bafd
PB
2401 out_file = output_files[out_file_index];
2402 in_file = input_files[in_file_index];
2403
a5926d85
AJ
2404
2405 mtag=NULL;
2406 while((mtag=av_metadata_get(in_file->metadata, "", mtag, AV_METADATA_IGNORE_SUFFIX)))
1a6498d7 2407 av_metadata_set2(&out_file->metadata, mtag->key, mtag->value, AV_METADATA_DONT_OVERWRITE);
a5926d85
AJ
2408 av_metadata_conv(out_file, out_file->oformat->metadata_conv,
2409 in_file->iformat->metadata_conv);
0a38bafd 2410 }
115329f1 2411
7a39f142
AK
2412 /* copy chapters from the first input file that has them*/
2413 for (i = 0; i < nb_input_files; i++) {
2414 if (!input_files[i]->nb_chapters)
2415 continue;
2416
2417 for (j = 0; j < nb_output_files; j++)
2418 if ((ret = copy_chapters(i, j)) < 0)
2419 goto dump_format;
2420 }
2421
85f07f22
FB
2422 /* open files and write file headers */
2423 for(i=0;i<nb_output_files;i++) {
2424 os = output_files[i];
79fdaa4c 2425 if (av_write_header(os) < 0) {
002c95d7 2426 snprintf(error, sizeof(error), "Could not write header for output file #%d (incorrect codec parameters ?)", i);
8fa36ae0 2427 ret = AVERROR(EINVAL);
002c95d7 2428 goto dump_format;
a38469e1 2429 }
6d1ba1ac
LA
2430 if (strcmp(output_files[i]->oformat->name, "rtp")) {
2431 want_sdp = 0;
2432 }
2433 }
002c95d7
BC
2434
2435 dump_format:
2436 /* dump the file output parameters - cannot be done before in case
2437 of stream copy */
2438 for(i=0;i<nb_output_files;i++) {
2439 dump_format(output_files[i], i, output_files[i]->filename, 1);
2440 }
2441
2442 /* dump the stream mapping */
2443 if (verbose >= 0) {
2444 fprintf(stderr, "Stream mapping:\n");
2445 for(i=0;i<nb_ostreams;i++) {
2446 ost = ost_table[i];
2447 fprintf(stderr, " Stream #%d.%d -> #%d.%d",
2448 ist_table[ost->source_index]->file_index,
2449 ist_table[ost->source_index]->index,
2450 ost->file_index,
2451 ost->index);
2452 if (ost->sync_ist != ist_table[ost->source_index])
2453 fprintf(stderr, " [sync #%d.%d]",
2454 ost->sync_ist->file_index,
2455 ost->sync_ist->index);
2456 fprintf(stderr, "\n");
2457 }
2458 }
2459
2460 if (ret) {
2461 fprintf(stderr, "%s\n", error);
2462 goto fail;
2463 }
2464
6d1ba1ac
LA
2465 if (want_sdp) {
2466 print_sdp(output_files, nb_output_files);
85f07f22
FB
2467 }
2468
9d58e0a9 2469 if (!using_stdin && verbose >= 0) {
d9a916e2 2470 fprintf(stderr, "Press [q] to stop encoding\n");
b51469a0
LS
2471 url_set_interrupt_cb(decode_interrupt_cb);
2472 }
a38469e1
FB
2473 term_init();
2474
7fc98937 2475 timer_start = av_gettime();
51bd4565 2476
d9a916e2 2477 for(; received_sigterm == 0;) {
85f07f22
FB
2478 int file_index, ist_index;
2479 AVPacket pkt;
a9aeda81
PB
2480 double ipts_min;
2481 double opts_min;
23ffe323 2482
85f07f22 2483 redo:
a9aeda81
PB
2484 ipts_min= 1e100;
2485 opts_min= 1e100;
a38469e1 2486 /* if 'q' pressed, exits */
d9a916e2 2487 if (!using_stdin) {
b51469a0
LS
2488 if (q_pressed)
2489 break;
cb09b2ed
PG
2490 /* read_key() returns 0 on EOF */
2491 key = read_key();
2492 if (key == 'q')
2493 break;
2494 }
a38469e1 2495
ec5517d5
FB
2496 /* select the stream that we must read now by looking at the
2497 smallest output pts */
85f07f22 2498 file_index = -1;
ec5517d5 2499 for(i=0;i<nb_ostreams;i++) {
23ffe323 2500 double ipts, opts;
ec5517d5
FB
2501 ost = ost_table[i];
2502 os = output_files[ost->file_index];
2503 ist = ist_table[ost->source_index];
55a7e946 2504 if(ist->is_past_recording_time || no_packet[ist->file_index])
545465ec 2505 continue;
c0df9d75 2506 opts = ost->st->pts.val * av_q2d(ost->st->time_base);
23ffe323
MN
2507 ipts = (double)ist->pts;
2508 if (!file_table[ist->file_index].eof_reached){
2509 if(ipts < ipts_min) {
2510 ipts_min = ipts;
2511 if(input_sync ) file_index = ist->file_index;
2512 }
2513 if(opts < opts_min) {
2514 opts_min = opts;
2515 if(!input_sync) file_index = ist->file_index;
2516 }
85f07f22 2517 }
01f4895c 2518 if(ost->frame_number >= max_frames[ost->st->codec->codec_type]){
7ca60994
MN
2519 file_index= -1;
2520 break;
2521 }
85f07f22
FB
2522 }
2523 /* if none, if is finished */
51bd4565 2524 if (file_index < 0) {
545465ec
MN
2525 if(no_packet_count){
2526 no_packet_count=0;
2527 memset(no_packet, 0, sizeof(no_packet));
d61f30a7 2528 usleep(10000);
545465ec
MN
2529 continue;
2530 }
85f07f22 2531 break;
ec5517d5
FB
2532 }
2533
b6e16b86 2534 /* finish if limit size exhausted */
c4ab519e 2535 if (limit_filesize != 0 && limit_filesize <= url_ftell(output_files[0]->pb))
b6e16b86
C
2536 break;
2537
254abc2e 2538 /* read a frame from it and output it in the fifo */
85f07f22 2539 is = input_files[file_index];
ad51c68c 2540 ret= av_read_frame(is, &pkt);
b9edbe99 2541 if(ret == AVERROR(EAGAIN)){
545465ec
MN
2542 no_packet[file_index]=1;
2543 no_packet_count++;
ad51c68c 2544 continue;
545465ec 2545 }
ad51c68c 2546 if (ret < 0) {
85f07f22 2547 file_table[file_index].eof_reached = 1;
d24ce947
AB
2548 if (opt_shortest)
2549 break;
2550 else
2551 continue;
85f07f22 2552 }
303e50e6 2553
545465ec
MN
2554 no_packet_count=0;
2555 memset(no_packet, 0, sizeof(no_packet));
2556
254abc2e 2557 if (do_pkt_dump) {
750f0e1f 2558 av_pkt_dump_log(NULL, AV_LOG_DEBUG, &pkt, do_hex_dump);
817b23ff 2559 }
79fdaa4c
FB
2560 /* the following test is needed in case new streams appear
2561 dynamically in stream : we ignore them */
2562 if (pkt.stream_index >= file_table[file_index].nb_streams)
bf5af568 2563 goto discard_packet;
85f07f22
FB
2564 ist_index = file_table[file_index].ist_index + pkt.stream_index;
2565 ist = ist_table[ist_index];
bf5af568
FB
2566 if (ist->discard)
2567 goto discard_packet;
85f07f22 2568
fec401f7
MN
2569 if (pkt.dts != AV_NOPTS_VALUE)
2570 pkt.dts += av_rescale_q(input_files_ts_offset[ist->file_index], AV_TIME_BASE_Q, ist->st->time_base);
2571 if (pkt.pts != AV_NOPTS_VALUE)
2572 pkt.pts += av_rescale_q(input_files_ts_offset[ist->file_index], AV_TIME_BASE_Q, ist->st->time_base);
2573
2c6958aa
AJ
2574 if (pkt.stream_index < nb_input_files_ts_scale[file_index]
2575 && input_files_ts_scale[file_index][pkt.stream_index]){
8833f375
MN
2576 if(pkt.pts != AV_NOPTS_VALUE)
2577 pkt.pts *= input_files_ts_scale[file_index][pkt.stream_index];
2578 if(pkt.dts != AV_NOPTS_VALUE)
2579 pkt.dts *= input_files_ts_scale[file_index][pkt.stream_index];
2580 }
2581
949b1a13 2582// fprintf(stderr, "next:%"PRId64" dts:%"PRId64" off:%"PRId64" %d\n", ist->next_pts, pkt.dts, input_files_ts_offset[ist->file_index], ist->st->codec->codec_type);
965530e1
MN
2583 if (pkt.dts != AV_NOPTS_VALUE && ist->next_pts != AV_NOPTS_VALUE
2584 && (is->iformat->flags & AVFMT_TS_DISCONT)) {
81d6d520
MN
2585 int64_t pkt_dts= av_rescale_q(pkt.dts, ist->st->time_base, AV_TIME_BASE_Q);
2586 int64_t delta= pkt_dts - ist->next_pts;
2587 if((FFABS(delta) > 1LL*dts_delta_threshold*AV_TIME_BASE || pkt_dts+1<ist->pts)&& !copy_ts){
72bd8100
MN
2588 input_files_ts_offset[ist->file_index]-= delta;
2589 if (verbose > 2)
4733abcb 2590 fprintf(stderr, "timestamp discontinuity %"PRId64", new offset= %"PRId64"\n", delta, input_files_ts_offset[ist->file_index]);
fec401f7
MN
2591 pkt.dts-= av_rescale_q(delta, AV_TIME_BASE_Q, ist->st->time_base);
2592 if(pkt.pts != AV_NOPTS_VALUE)
2593 pkt.pts-= av_rescale_q(delta, AV_TIME_BASE_Q, ist->st->time_base);
72bd8100
MN
2594 }
2595 }
2596
f8ccf720 2597 /* finish if recording time exhausted */
6abda15f
FC
2598 if (recording_time != INT64_MAX &&
2599 av_compare_ts(pkt.pts, ist->st->time_base, recording_time + start_time, (AVRational){1, 1000000}) >= 0) {
55a7e946 2600 ist->is_past_recording_time = 1;
f8ccf720 2601 goto discard_packet;
55a7e946 2602 }
f8ccf720 2603
8831db5c 2604 //fprintf(stderr,"read #%d.%d size=%d\n", ist->file_index, ist->index, pkt.size);
a700a6ae 2605 if (output_packet(ist, ist_index, ost_table, nb_ostreams, &pkt) < 0) {
d8019eb5
AD
2606
2607 if (verbose >= 0)
2608 fprintf(stderr, "Error while decoding stream #%d.%d\n",
2609 ist->file_index, ist->index);
f2abc559 2610 if (exit_on_error)
639e4ec8 2611 ffmpeg_exit(1);
a700a6ae
FB
2612 av_free_packet(&pkt);
2613 goto redo;
fe08925f 2614 }
cf7fc795 2615
bf5af568 2616 discard_packet:
85f07f22 2617 av_free_packet(&pkt);
115329f1 2618
ec5517d5
FB
2619 /* dump report by using the output first video and audio streams */
2620 print_report(output_files, ost_table, nb_ostreams, 0);
85f07f22 2621 }
a700a6ae
FB
2622
2623 /* at the end of stream, we must flush the decoder buffers */
2624 for(i=0;i<nb_istreams;i++) {
2625 ist = ist_table[i];
2626 if (ist->decoding_needed) {
2627 output_packet(ist, i, ost_table, nb_ostreams, NULL);
2628 }
2629 }
2630
a38469e1 2631 term_exit();
85f07f22 2632
c4e37247
MN
2633 /* write the trailer if needed and close file */
2634 for(i=0;i<nb_output_files;i++) {
2635 os = output_files[i];
2636 av_write_trailer(os);
2637 }
2638
37f5cd5a
MN
2639 /* dump report by using the first video and audio streams */
2640 print_report(output_files, ost_table, nb_ostreams, 1);
2641
85f07f22
FB
2642 /* close each encoder */
2643 for(i=0;i<nb_ostreams;i++) {
2644 ost = ost_table[i];
2645 if (ost->encoding_needed) {
01f4895c
MN
2646 av_freep(&ost->st->codec->stats_in);
2647 avcodec_close(ost->st->codec);
85f07f22
FB
2648 }
2649 }
115329f1 2650
85f07f22
FB
2651 /* close each decoder */
2652 for(i=0;i<nb_istreams;i++) {
2653 ist = ist_table[i];
2654 if (ist->decoding_needed) {
01f4895c 2655 avcodec_close(ist->st->codec);
85f07f22
FB
2656 }
2657 }
46847a33 2658#if CONFIG_AVFILTER
aa1249b8
BC
2659 if (graph) {
2660 avfilter_graph_destroy(graph);
2661 av_freep(&graph);
46847a33
MN
2662 }
2663#endif
85f07f22 2664
85f07f22 2665 /* finished ! */
00b7fbdc 2666 ret = 0;
115329f1 2667
002c95d7 2668 fail:
83b07470 2669 av_freep(&bit_buffer);
0f1578af 2670 av_free(file_table);
bdc4796f 2671
85f07f22
FB
2672 if (ist_table) {
2673 for(i=0;i<nb_istreams;i++) {
2674 ist = ist_table[i];
0f1578af 2675 av_free(ist);
85f07f22 2676 }
0f1578af 2677 av_free(ist_table);
85f07f22
FB
2678 }
2679 if (ost_table) {
2680 for(i=0;i<nb_ostreams;i++) {
2681 ost = ost_table[i];
2682 if (ost) {
b659c8b4
LA
2683 if (ost->st->stream_copy)
2684 av_freep(&ost->st->codec->extradata);
5abdb4b1
FB
2685 if (ost->logfile) {
2686 fclose(ost->logfile);
2687 ost->logfile = NULL;
2688 }
41dd680d 2689 av_fifo_free(ost->fifo); /* works even if fifo is not
f5a478f6 2690 initialized but set to zero */
0f1578af 2691 av_free(ost->pict_tmp.data[0]);
85f07f22 2692 if (ost->video_resample)
18a54b04 2693 sws_freeContext(ost->img_resample_ctx);
8e4270c5 2694 if (ost->resample)
85f07f22 2695 audio_resample_close(ost->resample);
a79db0f7
PR
2696 if (ost->reformat_ctx)
2697 av_audio_convert_free(ost->reformat_ctx);
0f1578af 2698 av_free(ost);
85f07f22
FB
2699 }
2700 }
0f1578af 2701 av_free(ost_table);
85f07f22
FB
2702 }
2703 return ret;
85f07f22
FB
2704}
2705
b29f97d1 2706static void opt_format(const char *arg)
85f07f22 2707{
817b23ff
FB
2708 /* compatibility stuff for pgmyuv */
2709 if (!strcmp(arg, "pgmyuv")) {
5b6d5596 2710 pgmyuv_compatibility_hack=1;
9286699a 2711// opt_image_format(arg);
5b6d5596 2712 arg = "image2";
17ceb4f9 2713 fprintf(stderr, "pgmyuv format is deprecated, use image2\n");
817b23ff
FB
2714 }
2715
a5abfd8f 2716 last_asked_format = arg;
85f07f22
FB
2717}
2718
464a631c 2719static void opt_video_rc_override_string(const char *arg)
ac2830ec
MN
2720{
2721 video_rc_override_string = arg;
2722}
2723
c48da33c 2724static int opt_me_threshold(const char *opt, const char *arg)
f4f3223f 2725{
c48da33c
SS
2726 me_threshold = parse_number_or_die(opt, arg, OPT_INT64, INT_MIN, INT_MAX);
2727 return 0;
f4f3223f
MN
2728}
2729
c48da33c 2730static int opt_verbose(const char *opt, const char *arg)
f068206e 2731{
46eab093 2732 verbose = parse_number_or_die(opt, arg, OPT_INT64, -10, 10);
c48da33c 2733 return 0;
f068206e
BE
2734}
2735
2fc3866d 2736static int opt_frame_rate(const char *opt, const char *arg)
85f07f22 2737{
126b638e 2738 if (av_parse_video_rate(&frame_rate, arg) < 0) {
2fc3866d 2739 fprintf(stderr, "Incorrect value for %s: %s\n", opt, arg);
639e4ec8 2740 ffmpeg_exit(1);
445f1b83 2741 }
2fc3866d 2742 return 0;
85f07f22
FB
2743}
2744
ebde2a2c 2745static int opt_bitrate(const char *opt, const char *arg)
1b1656c6 2746{
72415b2a 2747 int codec_type = opt[0]=='a' ? AVMEDIA_TYPE_AUDIO : AVMEDIA_TYPE_VIDEO;
1b1656c6
RP
2748
2749 opt_default(opt, arg);
2750
636f1c4c 2751 if (av_get_int(avcodec_opts[codec_type], "b", NULL) < 1000)
1b1656c6 2752 fprintf(stderr, "WARNING: The bitrate parameter is set too low. It takes bits/s as argument, not kbits/s\n");
ebde2a2c
MH
2753
2754 return 0;
1b1656c6
RP
2755}
2756
b29f97d1 2757static void opt_frame_crop_top(const char *arg)
ab6d194a 2758{
115329f1 2759 frame_topBand = atoi(arg);
ab6d194a
MN
2760 if (frame_topBand < 0) {
2761 fprintf(stderr, "Incorrect top crop size\n");
639e4ec8 2762 ffmpeg_exit(1);
ab6d194a 2763 }
ab6d194a 2764 if ((frame_topBand) >= frame_height){
bb270c08 2765 fprintf(stderr, "Vertical crop dimensions are outside the range of the original image.\nRemember to crop first and scale second.\n");
639e4ec8 2766 ffmpeg_exit(1);
ab6d194a 2767 }
54a13282 2768 fprintf(stderr, "-crop* is deprecated in favor of the crop avfilter\n");
ab6d194a
MN
2769 frame_height -= frame_topBand;
2770}
2771
b29f97d1 2772static void opt_frame_crop_bottom(const char *arg)
ab6d194a
MN
2773{
2774 frame_bottomBand = atoi(arg);
2775 if (frame_bottomBand < 0) {
2776 fprintf(stderr, "Incorrect bottom crop size\n");
639e4ec8 2777 ffmpeg_exit(1);
ab6d194a 2778 }
ab6d194a 2779 if ((frame_bottomBand) >= frame_height){
bb270c08 2780 fprintf(stderr, "Vertical crop dimensions are outside the range of the original image.\nRemember to crop first and scale second.\n");
639e4ec8 2781 ffmpeg_exit(1);
ab6d194a 2782 }
54a13282 2783 fprintf(stderr, "-crop* is deprecated in favor of the crop avfilter\n");
ab6d194a
MN
2784 frame_height -= frame_bottomBand;
2785}
2786
b29f97d1 2787static void opt_frame_crop_left(const char *arg)
ab6d194a
MN
2788{
2789 frame_leftBand = atoi(arg);
2790 if (frame_leftBand < 0) {
2791 fprintf(stderr, "Incorrect left crop size\n");
639e4ec8 2792 ffmpeg_exit(1);
ab6d194a 2793 }
ab6d194a 2794 if ((frame_leftBand) >= frame_width){
bb270c08 2795 fprintf(stderr, "Horizontal crop dimensions are outside the range of the original image.\nRemember to crop first and scale second.\n");
639e4ec8 2796 ffmpeg_exit(1);
ab6d194a 2797 }
54a13282 2798 fprintf(stderr, "-crop* is deprecated in favor of the crop avfilter\n");
ab6d194a
MN
2799 frame_width -= frame_leftBand;
2800}
2801
b29f97d1 2802static void opt_frame_crop_right(const char *arg)
ab6d194a
MN
2803{
2804 frame_rightBand = atoi(arg);
2805 if (frame_rightBand < 0) {
2806 fprintf(stderr, "Incorrect right crop size\n");
639e4ec8 2807 ffmpeg_exit(1);
ab6d194a 2808 }
ab6d194a 2809 if ((frame_rightBand) >= frame_width){
bb270c08 2810 fprintf(stderr, "Horizontal crop dimensions are outside the range of the original image.\nRemember to crop first and scale second.\n");
639e4ec8 2811 ffmpeg_exit(1);
ab6d194a 2812 }
54a13282 2813 fprintf(stderr, "-crop* is deprecated in favor of the crop avfilter\n");
ab6d194a
MN
2814 frame_width -= frame_rightBand;
2815}
2816
b29f97d1 2817static void opt_frame_size(const char *arg)
85f07f22 2818{
126b638e 2819 if (av_parse_video_size(&frame_width, &frame_height, arg) < 0) {
85f07f22 2820 fprintf(stderr, "Incorrect frame size\n");
639e4ec8 2821 ffmpeg_exit(1);
85f07f22 2822 }
85f07f22
FB
2823}
2824
9f434b65
SS
2825static int opt_pad(const char *opt, const char *arg) {
2826 fprintf(stderr, "Option '%s' has been removed, use the pad filter instead\n", opt);
2827 return -1;
1ff93ffc
TK
2828}
2829
63167088
RS
2830static void opt_frame_pix_fmt(const char *arg)
2831{
90da2b50 2832 if (strcmp(arg, "list")) {
718c7b18 2833 frame_pix_fmt = av_get_pix_fmt(arg);
90da2b50
SS
2834 if (frame_pix_fmt == PIX_FMT_NONE) {
2835 fprintf(stderr, "Unknown pixel format requested: %s\n", arg);
639e4ec8 2836 ffmpeg_exit(1);
90da2b50
SS
2837 }
2838 } else {
cedac882 2839 show_pix_fmts();
639e4ec8 2840 ffmpeg_exit(0);
c3b95b1d 2841 }
63167088
RS
2842}
2843
5fe03e38
RS
2844static void opt_frame_aspect_ratio(const char *arg)
2845{
2846 int x = 0, y = 0;
2847 double ar = 0;
2848 const char *p;
815f98cc 2849 char *end;
115329f1 2850
5fe03e38
RS
2851 p = strchr(arg, ':');
2852 if (p) {
815f98cc
AJ
2853 x = strtol(arg, &end, 10);
2854 if (end == p)
2855 y = strtol(end+1, &end, 10);
bb270c08
DB
2856 if (x > 0 && y > 0)
2857 ar = (double)x / (double)y;
5fe03e38 2858 } else
815f98cc 2859 ar = strtod(arg, NULL);
5fe03e38
RS
2860
2861 if (!ar) {
2862 fprintf(stderr, "Incorrect aspect ratio specification.\n");
639e4ec8 2863 ffmpeg_exit(1);
5fe03e38
RS
2864 }
2865 frame_aspect_ratio = ar;
2866}
2867
a5926d85
AJ
2868static int opt_metadata(const char *opt, const char *arg)
2869{
2870 char *mid= strchr(arg, '=');
2871
2872 if(!mid){
2873 fprintf(stderr, "Missing =\n");
639e4ec8 2874 ffmpeg_exit(1);
a5926d85
AJ
2875 }
2876 *mid++= 0;
2877
2878 metadata_count++;
2879 metadata= av_realloc(metadata, sizeof(*metadata)*metadata_count);
2880 metadata[metadata_count-1].key = av_strdup(arg);
2881 metadata[metadata_count-1].value= av_strdup(mid);
2882
2883 return 0;
2884}
2885
b29f97d1 2886static void opt_qscale(const char *arg)
85f07f22 2887{
158c7f05 2888 video_qscale = atof(arg);
4e64bead 2889 if (video_qscale <= 0 ||
158c7f05 2890 video_qscale > 255) {
4e64bead 2891 fprintf(stderr, "qscale must be > 0.0 and <= 255\n");
639e4ec8 2892 ffmpeg_exit(1);
85f07f22
FB
2893 }
2894}
2895
bb198e19
MN
2896static void opt_top_field_first(const char *arg)
2897{
2898 top_field_first= atoi(arg);
2899}
2900
d18811bb 2901static int opt_thread_count(const char *opt, const char *arg)
9c3d33d6 2902{
d18811bb 2903 thread_count= parse_number_or_die(opt, arg, OPT_INT64, 0, INT_MAX);
b250f9c6 2904#if !HAVE_THREADS
d8019eb5
AD
2905 if (verbose >= 0)
2906 fprintf(stderr, "Warning: not compiled with thread support, using thread emulation\n");
842b556a 2907#endif
d18811bb 2908 return 0;
9c3d33d6
MN
2909}
2910
ce1ee094
PR
2911static void opt_audio_sample_fmt(const char *arg)
2912{
2913 if (strcmp(arg, "list"))
2914 audio_sample_fmt = avcodec_get_sample_fmt(arg);
2915 else {
2916 list_fmts(avcodec_sample_fmt_string, SAMPLE_FMT_NB);
639e4ec8 2917 ffmpeg_exit(0);
ce1ee094
PR
2918 }
2919}
2920
c48da33c 2921static int opt_audio_rate(const char *opt, const char *arg)
85f07f22 2922{
c48da33c
SS
2923 audio_sample_rate = parse_number_or_die(opt, arg, OPT_INT64, 0, INT_MAX);
2924 return 0;
85f07f22
FB
2925}
2926
c48da33c 2927static int opt_audio_channels(const char *opt, const char *arg)
85f07f22 2928{
c48da33c
SS
2929 audio_channels = parse_number_or_die(opt, arg, OPT_INT64, 0, INT_MAX);
2930 return 0;
85f07f22
FB
2931}
2932
b29f97d1 2933static void opt_video_channel(const char *arg)
a5df11ab
FB
2934{
2935 video_channel = strtol(arg, NULL, 0);
2936}
2937
e3ee3283
AB
2938static void opt_video_standard(const char *arg)
2939{
2940 video_standard = av_strdup(arg);
2941}
2942
4a897224 2943static void opt_codec(int *pstream_copy, char **pcodec_name,
cf7fc795 2944 int codec_type, const char *arg)
85f07f22 2945{
4a897224 2946 av_freep(pcodec_name);
1629626f 2947 if (!strcmp(arg, "copy")) {
cf7fc795 2948 *pstream_copy = 1;
85f07f22 2949 } else {
4a897224 2950 *pcodec_name = av_strdup(arg);
85f07f22
FB
2951 }
2952}
2953
cf7fc795
FB
2954static void opt_audio_codec(const char *arg)
2955{
72415b2a 2956 opt_codec(&audio_stream_copy, &audio_codec_name, AVMEDIA_TYPE_AUDIO, arg);
cf7fc795
FB
2957}
2958
b2a2197e
MN
2959static void opt_audio_tag(const char *arg)
2960{
2961 char *tail;
2962 audio_codec_tag= strtol(arg, &tail, 0);
2963
2964 if(!tail || *tail)
2965 audio_codec_tag= arg[0] + (arg[1]<<8) + (arg[2]<<16) + (arg[3]<<24);
2966}
2967
2968static void opt_video_tag(const char *arg)
2969{
2970 char *tail;
2971 video_codec_tag= strtol(arg, &tail, 0);
2972
2973 if(!tail || *tail)
2974 video_codec_tag= arg[0] + (arg[1]<<8) + (arg[2]<<16) + (arg[3]<<24);
2975}
2976
b29f97d1 2977static void opt_video_codec(const char *arg)
85f07f22 2978{
72415b2a 2979 opt_codec(&video_stream_copy, &video_codec_name, AVMEDIA_TYPE_VIDEO, arg);
cf7fc795 2980}
85f07f22 2981
cf7fc795
FB
2982static void opt_subtitle_codec(const char *arg)
2983{
72415b2a 2984 opt_codec(&subtitle_stream_copy, &subtitle_codec_name, AVMEDIA_TYPE_SUBTITLE, arg);
85f07f22
FB
2985}
2986
27ad7d3a
BC
2987static void opt_subtitle_tag(const char *arg)
2988{
2989 char *tail;
2990 subtitle_codec_tag= strtol(arg, &tail, 0);
2991
2992 if(!tail || *tail)
2993 subtitle_codec_tag= arg[0] + (arg[1]<<8) + (arg[2]<<16) + (arg[3]<<24);
2994}
2995
b29f97d1 2996static void opt_map(const char *arg)
85f07f22
FB
2997{
2998 AVStreamMap *m;
815f98cc 2999 char *p;
85f07f22 3000
3a8e8824
AJ
3001 stream_maps = grow_array(stream_maps, sizeof(*stream_maps), &nb_stream_maps, nb_stream_maps + 1);
3002 m = &stream_maps[nb_stream_maps-1];
85f07f22 3003
815f98cc 3004 m->file_index = strtol(arg, &p, 0);
85f07f22
FB
3005 if (*p)
3006 p++;
a5dc85ef 3007
815f98cc 3008 m->stream_index = strtol(p, &p, 0);
b4a3389e
WG
3009 if (*p) {
3010 p++;
815f98cc 3011 m->sync_file_index = strtol(p, &p, 0);
b4a3389e
WG
3012 if (*p)
3013 p++;
815f98cc 3014 m->sync_stream_index = strtol(p, &p, 0);
b4a3389e
WG
3015 } else {
3016 m->sync_file_index = m->file_index;
3017 m->sync_stream_index = m->stream_index;
3018 }
85f07f22
FB
3019}
3020
0a38bafd
PB
3021static void opt_map_meta_data(const char *arg)
3022{
3023 AVMetaDataMap *m;
815f98cc 3024 char *p;
115329f1 3025
0a38bafd
PB
3026 m = &meta_data_maps[nb_meta_data_maps++];
3027
815f98cc 3028 m->out_file = strtol(arg, &p, 0);
0a38bafd
PB
3029 if (*p)
3030 p++;
3031
815f98cc 3032 m->in_file = strtol(p, &p, 0);
0a38bafd
PB
3033}
3034
8833f375
MN
3035static void opt_input_ts_scale(const char *arg)
3036{
3037 unsigned int stream;
3038 double scale;
3039 char *p;
3040
3041 stream = strtol(arg, &p, 0);
3042 if (*p)
3043 p++;
3044 scale= strtod(p, &p);
3045
3046 if(stream >= MAX_STREAMS)
639e4ec8 3047 ffmpeg_exit(1);
8833f375 3048
2c6958aa 3049 input_files_ts_scale[nb_input_files] = grow_array(input_files_ts_scale[nb_input_files], sizeof(*input_files_ts_scale[nb_input_files]), &nb_input_files_ts_scale[nb_input_files], stream + 1);
8833f375
MN
3050 input_files_ts_scale[nb_input_files][stream]= scale;
3051}
3052
b19221c8 3053static int opt_recording_time(const char *opt, const char *arg)
85f07f22 3054{
b19221c8
SS
3055 recording_time = parse_time_or_die(opt, arg, 1);
3056 return 0;
85f07f22
FB
3057}
3058
b19221c8 3059static int opt_start_time(const char *opt, const char *arg)
8831db5c 3060{
b19221c8
SS
3061 start_time = parse_time_or_die(opt, arg, 1);
3062 return 0;
8831db5c
MN
3063}
3064
25d34458 3065static int opt_recording_timestamp(const char *opt, const char *arg)
4568325a 3066{
25d34458 3067 recording_timestamp = parse_time_or_die(opt, arg, 0) / 1000000;
b19221c8 3068 return 0;
4568325a
RS
3069}
3070
b19221c8 3071static int opt_input_ts_offset(const char *opt, const char *arg)
a6a92a9a 3072{
b19221c8
SS
3073 input_ts_offset = parse_time_or_die(opt, arg, 1);
3074 return 0;
a6a92a9a
WG
3075}
3076
4e605bc3 3077static enum CodecID find_codec_or_die(const char *name, int type, int encoder, int strict)
4a897224 3078{
f73008d8 3079 const char *codec_string = encoder ? "encoder" : "decoder";
4a897224
NG
3080 AVCodec *codec;
3081
3082 if(!name)
3083 return CODEC_ID_NONE;
3084 codec = encoder ?
3085 avcodec_find_encoder_by_name(name) :
3086 avcodec_find_decoder_by_name(name);
3087 if(!codec) {
49a06a4d 3088 fprintf(stderr, "Unknown %s '%s'\n", codec_string, name);
639e4ec8 3089 ffmpeg_exit(1);
4a897224
NG
3090 }
3091 if(codec->type != type) {
49a06a4d 3092 fprintf(stderr, "Invalid %s type '%s'\n", codec_string, name);
639e4ec8 3093 ffmpeg_exit(1);
4a897224 3094 }
4e605bc3
JG
3095 if(codec->capabilities & CODEC_CAP_EXPERIMENTAL &&
3096 strict > FF_COMPLIANCE_EXPERIMENTAL) {
3097 fprintf(stderr, "%s '%s' is experimental and might produce bad "
3098 "results.\nAdd '-strict experimental' if you want to use it.\n",
3099 codec_string, codec->name);
770e50ae
JG
3100 codec = encoder ?
3101 avcodec_find_encoder(codec->id) :
3102 avcodec_find_decoder(codec->id);
3103 if (!(codec->capabilities & CODEC_CAP_EXPERIMENTAL))
3104 fprintf(stderr, "Or use the non experimental %s '%s'.\n",
3105 codec_string, codec->name);
639e4ec8 3106 ffmpeg_exit(1);
4e605bc3 3107 }
4a897224
NG
3108 return codec->id;
3109}
3110
b29f97d1 3111static void opt_input_file(const char *filename)
85f07f22
FB
3112{
3113 AVFormatContext *ic;
3114 AVFormatParameters params, *ap = &params;
a5abfd8f 3115 AVInputFormat *file_iformat = NULL;
14bea432 3116 int err, i, ret, rfps, rfps_base;
bd1b79a1 3117 int64_t timestamp;
85f07f22 3118
a5abfd8f 3119 if (last_asked_format) {
8c8bf9ec
SS
3120 if (!(file_iformat = av_find_input_format(last_asked_format))) {
3121 fprintf(stderr, "Unknown input format: '%s'\n", last_asked_format);