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