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