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