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