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