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