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