- Gracefully handle the case where not all the streams are requested/wanted
[libav.git] / ffmpeg.c
CommitLineData
85f07f22
FB
1/*
2 * FFmpeg main
01310af2 3 * Copyright (c) 2000-2003 Fabrice Bellard
85f07f22 4 *
bf5af568
FB
5 * This library is free software; you can redistribute it and/or
6 * modify it under the terms of the GNU Lesser General Public
7 * License as published by the Free Software Foundation; either
8 * version 2 of the License, or (at your option) any later version.
85f07f22 9 *
bf5af568 10 * This library is distributed in the hope that it will be useful,
85f07f22 11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
bf5af568
FB
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 * Lesser General Public License for more details.
85f07f22 14 *
bf5af568
FB
15 * You should have received a copy of the GNU Lesser General Public
16 * License along with this library; if not, write to the Free Software
17 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
85f07f22 18 */
daf8e955 19#define HAVE_AV_CONFIG_H
ce2749d2 20#include "common.h"
daf8e955 21#include "avformat.h"
10d104e4 22#include "framehook.h"
d4ad24c1
FR
23/* usleep() */
24#include "os_support.h"
daf8e955 25
bdc4796f 26#ifndef CONFIG_WIN32
85f07f22
FB
27#include <unistd.h>
28#include <fcntl.h>
29#include <sys/ioctl.h>
85f07f22 30#include <sys/time.h>
85f07f22 31#include <termios.h>
5727b222 32#include <sys/resource.h>
9680a722 33#include <signal.h>
bdc4796f 34#endif
f3ec2d46
SG
35#ifdef CONFIG_OS2
36#include <sys/types.h>
37#include <sys/select.h>
38#include <stdlib.h>
39#endif
bf5af568
FB
40#include <time.h>
41#include <ctype.h>
85f07f22 42
01310af2
FB
43#include "cmdutils.h"
44
8aa1e3da
MN
45#if !defined(INFINITY) && defined(HUGE_VAL)
46#define INFINITY HUGE_VAL
47#endif
85f07f22 48
0c1a9eda 49#define MAXINT64 int64_t_C(0x7fffffffffffffff)
bdc4796f 50
85f07f22
FB
51/* select an input stream for an output stream */
52typedef struct AVStreamMap {
53 int file_index;
54 int stream_index;
55} AVStreamMap;
56
57extern const OptionDef options[];
58
59void show_help(void);
60
61#define MAX_FILES 20
62
63static AVFormatContext *input_files[MAX_FILES];
64static int nb_input_files = 0;
65
66static AVFormatContext *output_files[MAX_FILES];
67static int nb_output_files = 0;
68
69static AVStreamMap stream_maps[MAX_FILES];
70static int nb_stream_maps;
71
79fdaa4c
FB
72static AVInputFormat *file_iformat;
73static AVOutputFormat *file_oformat;
817b23ff 74static AVImageFormat *image_format;
85f07f22
FB
75static int frame_width = 160;
76static int frame_height = 128;
880e8ba7 77static float frame_aspect_ratio = 0;
63167088 78static enum PixelFormat frame_pix_fmt = PIX_FMT_YUV420P;
ab6d194a
MN
79static int frame_topBand = 0;
80static int frame_bottomBand = 0;
81static int frame_leftBand = 0;
82static int frame_rightBand = 0;
14bea432
MN
83static int frame_rate = 25;
84static int frame_rate_base = 1;
3aa102be
MN
85static int video_bit_rate = 200*1000;
86static int video_bit_rate_tolerance = 4000*1000;
85f07f22 87static int video_qscale = 0;
3aa102be
MN
88static int video_qmin = 2;
89static int video_qmax = 31;
17a70fde
MN
90static int video_mb_qmin = 2;
91static int video_mb_qmax = 31;
9cdd6a24
MN
92static int video_qdiff = 3;
93static float video_qblur = 0.5;
94static float video_qcomp = 0.5;
ac2830ec 95#if 0 //experimental, (can be removed)
3aa102be
MN
96static float video_rc_qsquish=1.0;
97static float video_rc_qmod_amp=0;
98static int video_rc_qmod_freq=0;
ac2830ec 99#endif
3aa102be
MN
100static char *video_rc_override_string=NULL;
101static char *video_rc_eq="tex^qComp";
102static int video_rc_buffer_size=0;
103static float video_rc_buffer_aggressivity=1.0;
104static int video_rc_max_rate=0;
105static int video_rc_min_rate=0;
106static float video_rc_initial_cplx=0;
107static float video_b_qfactor = 1.25;
108static float video_b_qoffset = 1.25;
b3a391e8 109static float video_i_qfactor = -0.8;
3aa102be 110static float video_i_qoffset = 0.0;
3bea5386 111static int me_method = ME_EPZS;
85f07f22
FB
112static int video_disable = 0;
113static int video_codec_id = CODEC_ID_NONE;
114static int same_quality = 0;
bc6caae2 115static int b_frames = 0;
e4986da9 116static int use_hq = 0;
29da453b 117static int use_4mv = 0;
21e59552
MN
118/* Fx */
119static int use_aic = 0;
120static int use_umv = 0;
121/* /Fx */
cfcf0ffd 122static int do_deinterlace = 0;
4d2858de
MN
123static int workaround_bugs = FF_BUG_AUTODETECT;
124static int error_resilience = 2;
125static int error_concealment = 3;
463678ac 126static int dct_algo = 0;
2ad1516a 127static int idct_algo = 0;
1dbb6d90
MN
128static int use_part = 0;
129static int packet_size = 0;
f560dd82 130static int strict = 0;
59b571c1 131static int debug = 0;
85f07f22
FB
132
133static int gop_size = 12;
134static int intra_only = 0;
135static int audio_sample_rate = 44100;
136static int audio_bit_rate = 64000;
137static int audio_disable = 0;
138static int audio_channels = 1;
139static int audio_codec_id = CODEC_ID_NONE;
140
0c1a9eda 141static int64_t recording_time = 0;
85f07f22
FB
142static int file_overwrite = 0;
143static char *str_title = NULL;
144static char *str_author = NULL;
145static char *str_copyright = NULL;
146static char *str_comment = NULL;
5727b222 147static int do_benchmark = 0;
a0663ba4 148static int do_hex_dump = 0;
43f1708f 149static int do_psnr = 0;
ce7c56c2 150static int do_vstats = 0;
5abdb4b1 151static int do_pass = 0;
b0368839 152static int bitexact = 0;
5abdb4b1 153static char *pass_logfilename = NULL;
1629626f
FB
154static int audio_stream_copy = 0;
155static int video_stream_copy = 0;
5abdb4b1 156
bdfcbbed
MK
157static int rate_emu = 0;
158
8aa3ee32 159static char *video_grab_format = "video4linux";
79a7c268 160static char *video_device = NULL;
a5df11ab 161static int video_channel = 0;
e3ee3283 162static char *video_standard = "ntsc";
79a7c268 163
8aa3ee32 164static char *audio_grab_format = "audio_device";
79a7c268 165static char *audio_device = NULL;
8aa3ee32 166
5abdb4b1 167#define DEFAULT_PASS_LOGFILENAME "ffmpeg2pass"
85f07f22
FB
168
169typedef struct AVOutputStream {
170 int file_index; /* file index */
171 int index; /* stream index in the output file */
172 int source_index; /* AVInputStream index */
173 AVStream *st; /* stream in the output file */
ec5517d5
FB
174 int encoding_needed; /* true if encoding needed for this stream */
175 int frame_number;
176 /* input pts and corresponding output pts
177 for A/V sync */
178 double sync_ipts;
c11ef252 179 double sync_ipts_offset;
0c1a9eda 180 int64_t sync_opts;
85f07f22 181 /* video only */
34b10a57
D
182 int video_resample; /* video_resample and video_crop are mutually exclusive */
183 AVPicture pict_tmp; /* temporary image for resampling */
85f07f22 184 ImgReSampleContext *img_resample_ctx; /* for image resampling */
34b10a57
D
185
186 int video_crop; /* video_resample and video_crop are mutually exclusive */
187 int topBand; /* cropping area sizes */
188 int leftBand;
85f07f22
FB
189
190 /* audio only */
191 int audio_resample;
192 ReSampleContext *resample; /* for audio resampling */
193 FifoBuffer fifo; /* for compression: one audio fifo per codec */
5abdb4b1 194 FILE *logfile;
85f07f22
FB
195} AVOutputStream;
196
197typedef struct AVInputStream {
198 int file_index;
199 int index;
200 AVStream *st;
201 int discard; /* true if stream data should be discarded */
202 int decoding_needed; /* true if the packets must be decoded in 'raw_fifo' */
0c1a9eda 203 int64_t sample_index; /* current sample */
ec5517d5 204 int frame_decoded; /* true if a video or audio frame has been decoded */
bdfcbbed
MK
205
206 int64_t start; /* time when read started */
207 unsigned long frame; /* current frame */
85f07f22
FB
208} AVInputStream;
209
210typedef struct AVInputFile {
211 int eof_reached; /* true if eof reached */
212 int ist_index; /* index of first stream in ist_table */
213 int buffer_size; /* current total buffer size */
214 int buffer_size_max; /* buffer size at which we consider we can stop
215 buffering */
79fdaa4c 216 int nb_streams; /* nb streams we are aware of */
85f07f22
FB
217} AVInputFile;
218
bdc4796f
FB
219#ifndef CONFIG_WIN32
220
85f07f22
FB
221/* init terminal so that we can grab keys */
222static struct termios oldtty;
223
224static void term_exit(void)
225{
226 tcsetattr (0, TCSANOW, &oldtty);
227}
228
9680a722
RP
229static volatile sig_atomic_t received_sigterm = 0;
230
231static void
232sigterm_handler(int sig)
233{
234 received_sigterm = sig;
235 term_exit();
236}
237
85f07f22
FB
238static void term_init(void)
239{
240 struct termios tty;
241
242 tcgetattr (0, &tty);
243 oldtty = tty;
244
245 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
246 |INLCR|IGNCR|ICRNL|IXON);
247 tty.c_oflag |= OPOST;
248 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
249 tty.c_cflag &= ~(CSIZE|PARENB);
250 tty.c_cflag |= CS8;
251 tty.c_cc[VMIN] = 1;
252 tty.c_cc[VTIME] = 0;
253
254 tcsetattr (0, TCSANOW, &tty);
255
9680a722
RP
256 signal(SIGINT , sigterm_handler); /* Interrupt (ANSI). */
257 signal(SIGQUIT, sigterm_handler); /* Quit (POSIX). */
258 signal(SIGTERM, sigterm_handler); /* Termination (ANSI). */
259 /*
260 register a function to be called at normal program termination
261 */
85f07f22 262 atexit(term_exit);
9ddd71fc
FR
263#ifdef CONFIG_BEOS_NETSERVER
264 fcntl(0, F_SETFL, fcntl(0, F_GETFL) | O_NONBLOCK);
265#endif
85f07f22
FB
266}
267
268/* read a key without blocking */
269static int read_key(void)
270{
9ddd71fc 271 int n = 1;
85f07f22 272 unsigned char ch;
9ddd71fc
FR
273#ifndef CONFIG_BEOS_NETSERVER
274 struct timeval tv;
85f07f22
FB
275 fd_set rfds;
276
277 FD_ZERO(&rfds);
278 FD_SET(0, &rfds);
279 tv.tv_sec = 0;
280 tv.tv_usec = 0;
281 n = select(1, &rfds, NULL, NULL, &tv);
9ddd71fc 282#endif
85f07f22 283 if (n > 0) {
cb09b2ed
PG
284 n = read(0, &ch, 1);
285 if (n == 1)
85f07f22 286 return ch;
cb09b2ed
PG
287
288 return n;
85f07f22
FB
289 }
290 return -1;
291}
292
a38469e1 293#else
85f07f22 294
a38469e1
FB
295/* no interactive support */
296static void term_exit(void)
85f07f22 297{
a38469e1 298}
85f07f22 299
a38469e1
FB
300static void term_init(void)
301{
302}
85f07f22 303
a38469e1
FB
304static int read_key(void)
305{
cb09b2ed 306 return 0;
85f07f22
FB
307}
308
a38469e1 309#endif
bdc4796f 310
b29f97d1 311static int read_ffserver_streams(AVFormatContext *s, const char *filename)
85f07f22 312{
79fdaa4c 313 int i, err;
85f07f22
FB
314 AVFormatContext *ic;
315
79fdaa4c
FB
316 err = av_open_input_file(&ic, filename, NULL, FFM_PACKET_SIZE, NULL);
317 if (err < 0)
318 return err;
85f07f22
FB
319 /* copy stream format */
320 s->nb_streams = ic->nb_streams;
321 for(i=0;i<ic->nb_streams;i++) {
322 AVStream *st;
1e491e29 323
e1031171 324 st = av_mallocz(sizeof(AVStream));
85f07f22
FB
325 memcpy(st, ic->streams[i], sizeof(AVStream));
326 s->streams[i] = st;
327 }
328
329 av_close_input_file(ic);
330 return 0;
331}
332
817b23ff 333#define MAX_AUDIO_PACKET_SIZE (128 * 1024)
85f07f22
FB
334
335static void do_audio_out(AVFormatContext *s,
336 AVOutputStream *ost,
337 AVInputStream *ist,
338 unsigned char *buf, int size)
339{
0c1a9eda 340 uint8_t *buftmp;
d66c7abc
SC
341 static uint8_t *audio_buf = NULL;
342 static uint8_t *audio_out = NULL;
558eae03 343 const int audio_out_size= 4*MAX_AUDIO_PACKET_SIZE;
d66c7abc 344
85f07f22
FB
345 int size_out, frame_bytes, ret;
346 AVCodecContext *enc;
347
d66c7abc
SC
348 /* SC: dynamic allocation of buffers */
349 if (!audio_buf)
350 audio_buf = av_malloc(2*MAX_AUDIO_PACKET_SIZE);
351 if (!audio_out)
558eae03 352 audio_out = av_malloc(audio_out_size);
d66c7abc
SC
353 if (!audio_buf || !audio_out)
354 return; /* Should signal an error ! */
355
356
85f07f22
FB
357 enc = &ost->st->codec;
358
359 if (ost->audio_resample) {
360 buftmp = audio_buf;
361 size_out = audio_resample(ost->resample,
362 (short *)buftmp, (short *)buf,
363 size / (ist->st->codec.channels * 2));
364 size_out = size_out * enc->channels * 2;
365 } else {
366 buftmp = buf;
367 size_out = size;
368 }
369
370 /* now encode as many frames as possible */
a0663ba4 371 if (enc->frame_size > 1) {
85f07f22
FB
372 /* output resampled raw samples */
373 fifo_write(&ost->fifo, buftmp, size_out,
374 &ost->fifo.wptr);
375
376 frame_bytes = enc->frame_size * 2 * enc->channels;
377
378 while (fifo_read(&ost->fifo, audio_buf, frame_bytes,
379 &ost->fifo.rptr) == 0) {
558eae03 380 ret = avcodec_encode_audio(enc, audio_out, audio_out_size,
a0663ba4 381 (short *)audio_buf);
ec5517d5 382 av_write_frame(s, ost->index, audio_out, ret);
85f07f22
FB
383 }
384 } else {
a0663ba4
FB
385 /* output a pcm frame */
386 /* XXX: change encoding codec API to avoid this ? */
387 switch(enc->codec->id) {
388 case CODEC_ID_PCM_S16LE:
389 case CODEC_ID_PCM_S16BE:
390 case CODEC_ID_PCM_U16LE:
391 case CODEC_ID_PCM_U16BE:
392 break;
393 default:
394 size_out = size_out >> 1;
395 break;
396 }
397 ret = avcodec_encode_audio(enc, audio_out, size_out,
ff29712a 398 (short *)buftmp);
ec5517d5 399 av_write_frame(s, ost->index, audio_out, ret);
85f07f22
FB
400 }
401}
402
10d104e4
PG
403static void pre_process_video_frame(AVInputStream *ist, AVPicture *picture, void **bufp)
404{
405 AVCodecContext *dec;
406 AVPicture *picture2;
407 AVPicture picture_tmp;
0c1a9eda 408 uint8_t *buf = 0;
10d104e4
PG
409
410 dec = &ist->st->codec;
411
412 /* deinterlace : must be done before any resize */
413 if (do_deinterlace) {
414 int size;
415
416 /* create temporary picture */
417 size = avpicture_get_size(dec->pix_fmt, dec->width, dec->height);
418 buf = av_malloc(size);
419 if (!buf)
420 return;
421
422 picture2 = &picture_tmp;
423 avpicture_fill(picture2, buf, dec->pix_fmt, dec->width, dec->height);
424
425 if (avpicture_deinterlace(picture2, picture,
426 dec->pix_fmt, dec->width, dec->height) < 0) {
427 /* if error, do not deinterlace */
428 av_free(buf);
429 buf = NULL;
430 picture2 = picture;
431 }
432 } else {
433 picture2 = picture;
434 }
435
436 frame_hook_process(picture2, dec->pix_fmt, dec->width, dec->height);
437
438 if (picture != picture2)
439 *picture = *picture2;
440 *bufp = buf;
441}
442
ec5517d5
FB
443/* we begin to correct av delay at this threshold */
444#define AV_DELAY_MAX 0.100
85f07f22
FB
445
446static void do_video_out(AVFormatContext *s,
447 AVOutputStream *ost,
448 AVInputStream *ist,
34b10a57 449 AVPicture *in_picture,
ec5517d5 450 int *frame_size, AVOutputStream *audio_sync)
85f07f22 451{
ec5517d5 452 int nb_frames, i, ret;
34b10a57
D
453 AVPicture *final_picture, *formatted_picture;
454 AVPicture picture_format_temp, picture_crop_temp;
0c1a9eda
ZK
455 static uint8_t *video_buffer;
456 uint8_t *buf = NULL, *buf1 = NULL;
cfcf0ffd 457 AVCodecContext *enc, *dec;
85f07f22 458
33a1f1a3 459#define VIDEO_BUFFER_SIZE (1024*1024)
33a1f1a3 460
85f07f22 461 enc = &ost->st->codec;
cfcf0ffd 462 dec = &ist->st->codec;
85f07f22 463
ec5517d5
FB
464 /* by default, we output a single frame */
465 nb_frames = 1;
466
204c0f48
PG
467 *frame_size = 0;
468
ec5517d5
FB
469 /* NOTE: the A/V sync is always done by considering the audio is
470 the master clock. It is suffisant for transcoding or playing,
471 but not for the general case */
472 if (audio_sync) {
473 /* compute the A-V delay and duplicate/remove frames if needed */
474 double adelta, vdelta, apts, vpts, av_delay;
475
476 if (audio_sync->sync_ipts != AV_NOPTS_VALUE &&
477 ost->sync_ipts != AV_NOPTS_VALUE) {
478
479 adelta = (double)(ost->st->pts.val - audio_sync->sync_opts) *
480 s->pts_num / s->pts_den;
481 apts = audio_sync->sync_ipts + adelta;
482
483 vdelta = (double)(ost->st->pts.val - ost->sync_opts) *
484 s->pts_num / s->pts_den;
485 vpts = ost->sync_ipts + vdelta;
486
487 av_delay = apts - vpts;
488 // printf("delay=%f\n", av_delay);
489 if (av_delay < -AV_DELAY_MAX)
490 nb_frames = 2;
491 else if (av_delay > AV_DELAY_MAX)
492 nb_frames = 0;
493 }
10d104e4
PG
494 } else {
495 double vdelta;
496
497 if (ost->sync_ipts != AV_NOPTS_VALUE) {
c11ef252 498 vdelta = (double)(ost->st->pts.val) * s->pts_num / s->pts_den - (ost->sync_ipts - ost->sync_ipts_offset);
be4ce157 499 if (vdelta < 100 && vdelta > -100 && ost->sync_ipts_offset) {
c11ef252
PG
500 if (vdelta < -AV_DELAY_MAX)
501 nb_frames = 2;
502 else if (vdelta > AV_DELAY_MAX)
503 nb_frames = 0;
504 } else {
505 ost->sync_ipts_offset -= vdelta;
be4ce157
PG
506 if (!ost->sync_ipts_offset)
507 ost->sync_ipts_offset = 0.000001; /* one microsecond */
c11ef252
PG
508 }
509
be4ce157 510#if defined(PJSG)
c11ef252
PG
511 {
512 static char *action[] = { "drop frame", "copy frame", "dup frame" };
513 printf("Input PTS %12.6f, output PTS %12.6f: %s\n",
514 (double) ost->sync_ipts, (double) ost->st->pts.val * s->pts_num / s->pts_den,
515 action[nb_frames]);
516 }
517#endif
10d104e4 518 }
ec5517d5 519 }
ec5517d5 520 if (nb_frames <= 0)
85f07f22 521 return;
ce7c56c2 522
cb09b2ed 523 if (!video_buffer)
ec5517d5
FB
524 video_buffer = av_malloc(VIDEO_BUFFER_SIZE);
525 if (!video_buffer)
526 return;
c04643a2 527
cfcf0ffd
FB
528 /* convert pixel format if needed */
529 if (enc->pix_fmt != dec->pix_fmt) {
530 int size;
531
532 /* create temporary picture */
533 size = avpicture_get_size(enc->pix_fmt, dec->width, dec->height);
0f1578af 534 buf = av_malloc(size);
cfcf0ffd
FB
535 if (!buf)
536 return;
34b10a57
D
537 formatted_picture = &picture_format_temp;
538 avpicture_fill(formatted_picture, buf, enc->pix_fmt, dec->width, dec->height);
cfcf0ffd 539
34b10a57
D
540 if (img_convert(formatted_picture, enc->pix_fmt,
541 in_picture, dec->pix_fmt,
cfcf0ffd
FB
542 dec->width, dec->height) < 0) {
543 fprintf(stderr, "pixel format conversion not handled\n");
544 goto the_end;
545 }
546 } else {
34b10a57 547 formatted_picture = in_picture;
cfcf0ffd
FB
548 }
549
550 /* XXX: resampling could be done before raw format convertion in
551 some cases to go faster */
552 /* XXX: only works for YUV420P */
85f07f22 553 if (ost->video_resample) {
34b10a57
D
554 final_picture = &ost->pict_tmp;
555 img_resample(ost->img_resample_ctx, final_picture, formatted_picture);
556 } else if (ost->video_crop) {
557 picture_crop_temp.data[0] = formatted_picture->data[0] +
558 (ost->topBand * formatted_picture->linesize[0]) + ost->leftBand;
559
560 picture_crop_temp.data[1] = formatted_picture->data[1] +
561 ((ost->topBand >> 1) * formatted_picture->linesize[1]) +
562 (ost->leftBand >> 1);
563
564 picture_crop_temp.data[2] = formatted_picture->data[2] +
565 ((ost->topBand >> 1) * formatted_picture->linesize[2]) +
566 (ost->leftBand >> 1);
567
568 picture_crop_temp.linesize[0] = formatted_picture->linesize[0];
569 picture_crop_temp.linesize[1] = formatted_picture->linesize[1];
570 picture_crop_temp.linesize[2] = formatted_picture->linesize[2];
571 final_picture = &picture_crop_temp;
85f07f22 572 } else {
34b10a57 573 final_picture = formatted_picture;
85f07f22 574 }
85f07f22
FB
575 /* duplicates frame if needed */
576 /* XXX: pb because no interleaving */
ec5517d5 577 for(i=0;i<nb_frames;i++) {
e8750b00
FR
578 if (s->oformat->flags & AVFMT_RAWPICTURE) {
579 /* raw pictures are written as AVPicture structure to
580 avoid any copies. We support temorarily the older
581 method. */
582 av_write_frame(s, ost->index,
583 (uint8_t *)final_picture, sizeof(AVPicture));
584 } else {
492cd3a9 585 AVFrame big_picture;
1e491e29 586
492cd3a9 587 memset(&big_picture, 0, sizeof(AVFrame));
34b10a57 588 *(AVPicture*)&big_picture= *final_picture;
1e491e29 589
85f07f22
FB
590 /* handles sameq here. This is not correct because it may
591 not be a global option */
592 if (same_quality) {
1e491e29
MN
593 big_picture.quality = ist->st->quality;
594 }else
595 big_picture.quality = ost->st->quality;
6dc96cb0 596
cfcf0ffd 597 ret = avcodec_encode_video(enc,
33a1f1a3 598 video_buffer, VIDEO_BUFFER_SIZE,
1e491e29 599 &big_picture);
44429457 600 //enc->frame_number = enc->real_pict_num;
ec5517d5 601 av_write_frame(s, ost->index, video_buffer, ret);
ce7c56c2 602 *frame_size = ret;
a5dc85ef 603 //fprintf(stderr,"\nFrame: %3d %3d size: %5d type: %d",
44429457 604 // enc->frame_number-1, enc->real_pict_num, ret,
a5dc85ef 605 // enc->pict_type);
5abdb4b1
FB
606 /* if two pass, output log */
607 if (ost->logfile && enc->stats_out) {
608 fprintf(ost->logfile, "%s", enc->stats_out);
609 }
85f07f22 610 }
ec5517d5 611 ost->frame_number++;
85f07f22 612 }
ec5517d5 613 the_end:
0f1578af
FB
614 av_free(buf);
615 av_free(buf1);
85f07f22
FB
616}
617
140cb663
MN
618static double psnr(double d){
619 if(d==0) return INFINITY;
b29f97d1 620 return -10.0*log(d)/log(10.0);
140cb663
MN
621}
622
ec5517d5
FB
623static void do_video_stats(AVFormatContext *os, AVOutputStream *ost,
624 int frame_size)
ce7c56c2
J
625{
626 static FILE *fvstats=NULL;
0c1a9eda 627 static int64_t total_size = 0;
ce7c56c2 628 char filename[40];
bf5af568
FB
629 time_t today2;
630 struct tm *today;
ce7c56c2
J
631 AVCodecContext *enc;
632 int frame_number;
0c1a9eda 633 int64_t ti;
ce7c56c2
J
634 double ti1, bitrate, avg_bitrate;
635
636 if (!fvstats) {
637 today2 = time(NULL);
638 today = localtime(&today2);
639 sprintf(filename, "vstats_%02d%02d%02d.log", today->tm_hour,
640 today->tm_min,
641 today->tm_sec);
642 fvstats = fopen(filename,"w");
643 if (!fvstats) {
644 perror("fopen");
645 exit(1);
646 }
647 }
648
649 ti = MAXINT64;
650 enc = &ost->st->codec;
651 total_size += frame_size;
652 if (enc->codec_type == CODEC_TYPE_VIDEO) {
ec5517d5 653 frame_number = ost->frame_number;
492cd3a9 654 fprintf(fvstats, "frame= %5d q= %2.1f ", frame_number, enc->coded_frame->quality);
140cb663 655 if (enc->flags&CODEC_FLAG_PSNR)
492cd3a9 656 fprintf(fvstats, "PSNR= %6.2f ", psnr(enc->coded_frame->error[0]/(enc->width*enc->height*255.0*255.0)));
ce7c56c2
J
657
658 fprintf(fvstats,"f_size= %6d ", frame_size);
ec5517d5
FB
659 /* compute pts value */
660 ti1 = (double)ost->st->pts.val * os->pts_num / os->pts_den;
ce7c56c2
J
661 if (ti1 < 0.01)
662 ti1 = 0.01;
663
14bea432 664 bitrate = (double)(frame_size * 8) * enc->frame_rate / enc->frame_rate_base / 1000.0;
ce7c56c2
J
665 avg_bitrate = (double)(total_size * 8) / ti1 / 1000.0;
666 fprintf(fvstats, "s_size= %8.0fkB time= %0.3f br= %7.1fkbits/s avg_br= %7.1fkbits/s ",
667 (double)total_size / 1024, ti1, bitrate, avg_bitrate);
3db320ea 668 fprintf(fvstats,"type= %c\n", av_get_pict_type_char(enc->coded_frame->pict_type));
ce7c56c2 669 }
ec5517d5
FB
670}
671
b29f97d1
ZK
672static void print_report(AVFormatContext **output_files,
673 AVOutputStream **ost_table, int nb_ostreams,
674 int is_last_report)
ec5517d5
FB
675{
676 char buf[1024];
677 AVOutputStream *ost;
678 AVFormatContext *oc, *os;
0c1a9eda 679 int64_t total_size;
ec5517d5
FB
680 AVCodecContext *enc;
681 int frame_number, vid, i;
682 double bitrate, ti1, pts;
0c1a9eda 683 static int64_t last_time = -1;
ec5517d5
FB
684
685 if (!is_last_report) {
0c1a9eda 686 int64_t cur_time;
ec5517d5
FB
687 /* display the report every 0.5 seconds */
688 cur_time = av_gettime();
689 if (last_time == -1) {
690 last_time = cur_time;
691 return;
692 }
693 if ((cur_time - last_time) < 500000)
694 return;
695 last_time = cur_time;
696 }
697
ce7c56c2 698
ec5517d5
FB
699 oc = output_files[0];
700
701 total_size = url_ftell(&oc->pb);
702
703 buf[0] = '\0';
704 ti1 = 1e10;
705 vid = 0;
706 for(i=0;i<nb_ostreams;i++) {
707 ost = ost_table[i];
708 os = output_files[ost->file_index];
709 enc = &ost->st->codec;
10d104e4 710 if (vid && enc->codec_type == CODEC_TYPE_VIDEO) {
1e491e29 711 sprintf(buf + strlen(buf), "q=%2.1f ",
492cd3a9 712 enc->coded_frame->quality);
10d104e4 713 }
ec5517d5
FB
714 if (!vid && enc->codec_type == CODEC_TYPE_VIDEO) {
715 frame_number = ost->frame_number;
1e491e29 716 sprintf(buf + strlen(buf), "frame=%5d q=%2.1f ",
492cd3a9 717 frame_number, enc->coded_frame ? enc->coded_frame->quality : 0);
140cb663 718 if (enc->flags&CODEC_FLAG_PSNR)
492cd3a9 719 sprintf(buf + strlen(buf), "PSNR= %6.2f ", psnr(enc->coded_frame->error[0]/(enc->width*enc->height*255.0*255.0)));
ec5517d5
FB
720 vid = 1;
721 }
722 /* compute min output value */
723 pts = (double)ost->st->pts.val * os->pts_num / os->pts_den;
5d9827bc 724 if ((pts < ti1) && (pts > 0))
ec5517d5
FB
725 ti1 = pts;
726 }
727 if (ti1 < 0.01)
728 ti1 = 0.01;
729 bitrate = (double)(total_size * 8) / ti1 / 1000.0;
730
731 sprintf(buf + strlen(buf),
732 "size=%8.0fkB time=%0.1f bitrate=%6.1fkbits/s",
733 (double)total_size / 1024, ti1, bitrate);
ce7c56c2 734
ec5517d5 735 fprintf(stderr, "%s ", buf);
ce7c56c2 736
ec5517d5
FB
737 if (is_last_report) {
738 fprintf(stderr, "\n");
739 } else {
740 fprintf(stderr, "\r");
741 fflush(stderr);
742 }
ce7c56c2
J
743}
744
85f07f22
FB
745/*
746 * The following code is the main loop of the file converter
747 */
748static int av_encode(AVFormatContext **output_files,
749 int nb_output_files,
750 AVFormatContext **input_files,
751 int nb_input_files,
752 AVStreamMap *stream_maps, int nb_stream_maps)
753{
ec5517d5 754 int ret, i, j, k, n, nb_istreams = 0, nb_ostreams = 0, pts_set;
85f07f22
FB
755 AVFormatContext *is, *os;
756 AVCodecContext *codec, *icodec;
757 AVOutputStream *ost, **ost_table = NULL;
758 AVInputStream *ist, **ist_table = NULL;
bdc4796f 759 AVInputFile *file_table;
51bd4565 760 AVFormatContext *stream_no_data;
cb09b2ed 761 int key;
bdc4796f 762
51bd4565 763 file_table= (AVInputFile*) av_mallocz(nb_input_files * sizeof(AVInputFile));
bdc4796f
FB
764 if (!file_table)
765 goto fail;
85f07f22 766
85f07f22
FB
767 /* input stream init */
768 j = 0;
769 for(i=0;i<nb_input_files;i++) {
770 is = input_files[i];
771 file_table[i].ist_index = j;
79fdaa4c 772 file_table[i].nb_streams = is->nb_streams;
85f07f22
FB
773 j += is->nb_streams;
774 }
775 nb_istreams = j;
776
777 ist_table = av_mallocz(nb_istreams * sizeof(AVInputStream *));
778 if (!ist_table)
bdc4796f 779 goto fail;
85f07f22
FB
780
781 for(i=0;i<nb_istreams;i++) {
782 ist = av_mallocz(sizeof(AVInputStream));
783 if (!ist)
784 goto fail;
785 ist_table[i] = ist;
786 }
787 j = 0;
788 for(i=0;i<nb_input_files;i++) {
789 is = input_files[i];
790 for(k=0;k<is->nb_streams;k++) {
791 ist = ist_table[j++];
792 ist->st = is->streams[k];
793 ist->file_index = i;
794 ist->index = k;
795 ist->discard = 1; /* the stream is discarded by default
796 (changed later) */
bdfcbbed
MK
797
798 if (ist->st->codec.rate_emu) {
799 ist->start = av_gettime();
800 ist->frame = 0;
801 }
85f07f22
FB
802 }
803 }
804
805 /* output stream init */
806 nb_ostreams = 0;
807 for(i=0;i<nb_output_files;i++) {
808 os = output_files[i];
809 nb_ostreams += os->nb_streams;
810 }
811 if (nb_stream_maps > 0 && nb_stream_maps != nb_ostreams) {
812 fprintf(stderr, "Number of stream maps must match number of output streams\n");
813 exit(1);
814 }
815
bd073980
BF
816 /* Sanity check the mapping args -- do the input files & streams exist? */
817 for(i=0;i<nb_stream_maps;i++) {
818 int fi = stream_maps[i].file_index;
819 int si = stream_maps[i].stream_index;
820
821 if (fi < 0 || fi > nb_input_files - 1 ||
822 si < 0 || si > file_table[fi].nb_streams - 1) {
823 fprintf(stderr,"Could not find input stream #%d.%d\n", fi, si);
824 exit(1);
825 }
826 }
827
85f07f22
FB
828 ost_table = av_mallocz(sizeof(AVOutputStream *) * nb_ostreams);
829 if (!ost_table)
830 goto fail;
831 for(i=0;i<nb_ostreams;i++) {
832 ost = av_mallocz(sizeof(AVOutputStream));
833 if (!ost)
834 goto fail;
835 ost_table[i] = ost;
836 }
837
838 n = 0;
839 for(k=0;k<nb_output_files;k++) {
840 os = output_files[k];
841 for(i=0;i<os->nb_streams;i++) {
842 int found;
843 ost = ost_table[n++];
844 ost->file_index = k;
845 ost->index = i;
846 ost->st = os->streams[i];
847 if (nb_stream_maps > 0) {
848 ost->source_index = file_table[stream_maps[n-1].file_index].ist_index +
849 stream_maps[n-1].stream_index;
bd073980
BF
850
851 /* Sanity check that the stream types match */
852 if (ist_table[ost->source_index]->st->codec.codec_type != ost->st->codec.codec_type) {
853 fprintf(stderr, "Codec type mismatch for mapping #%d.%d -> #%d.%d\n",
854 stream_maps[n-1].file_index, stream_maps[n-1].stream_index,
855 ost->file_index, ost->index);
856 exit(1);
857 }
858
85f07f22
FB
859 } else {
860 /* get corresponding input stream index : we select the first one with the right type */
861 found = 0;
862 for(j=0;j<nb_istreams;j++) {
863 ist = ist_table[j];
864 if (ist->discard &&
865 ist->st->codec.codec_type == ost->st->codec.codec_type) {
866 ost->source_index = j;
867 found = 1;
868 }
869 }
870
871 if (!found) {
872 /* try again and reuse existing stream */
873 for(j=0;j<nb_istreams;j++) {
874 ist = ist_table[j];
875 if (ist->st->codec.codec_type == ost->st->codec.codec_type) {
876 ost->source_index = j;
877 found = 1;
878 }
879 }
880 if (!found) {
881 fprintf(stderr, "Could not find input stream matching output stream #%d.%d\n",
882 ost->file_index, ost->index);
883 exit(1);
884 }
885 }
886 }
887 ist = ist_table[ost->source_index];
888 ist->discard = 0;
889 }
890 }
891
85f07f22
FB
892 /* for each output stream, we compute the right encoding parameters */
893 for(i=0;i<nb_ostreams;i++) {
894 ost = ost_table[i];
895 ist = ist_table[ost->source_index];
896
897 codec = &ost->st->codec;
898 icodec = &ist->st->codec;
899
1629626f
FB
900 if (ost->st->stream_copy) {
901 /* if stream_copy is selected, no need to decode or encode */
902 codec->codec_id = icodec->codec_id;
903 codec->codec_type = icodec->codec_type;
904 codec->codec_tag = icodec->codec_tag;
905 codec->bit_rate = icodec->bit_rate;
906 switch(codec->codec_type) {
907 case CODEC_TYPE_AUDIO:
908 codec->sample_rate = icodec->sample_rate;
909 codec->channels = icodec->channels;
910 break;
911 case CODEC_TYPE_VIDEO:
912 codec->frame_rate = icodec->frame_rate;
14bea432 913 codec->frame_rate_base = icodec->frame_rate_base;
1629626f
FB
914 codec->width = icodec->width;
915 codec->height = icodec->height;
916 break;
917 default:
918 av_abort();
919 }
920 } else {
921 switch(codec->codec_type) {
922 case CODEC_TYPE_AUDIO:
85f07f22
FB
923 if (fifo_init(&ost->fifo, 2 * MAX_AUDIO_PACKET_SIZE))
924 goto fail;
1629626f 925
85f07f22
FB
926 if (codec->channels == icodec->channels &&
927 codec->sample_rate == icodec->sample_rate) {
928 ost->audio_resample = 0;
929 } else {
e0d2714a
J
930 if (codec->channels != icodec->channels &&
931 icodec->codec_id == CODEC_ID_AC3) {
932 /* Special case for 5:1 AC3 input */
933 /* and mono or stereo output */
6dc96cb0
J
934 /* Request specific number of channels */
935 icodec->channels = codec->channels;
936 if (codec->sample_rate == icodec->sample_rate)
937 ost->audio_resample = 0;
938 else {
939 ost->audio_resample = 1;
940 ost->resample = audio_resample_init(codec->channels, icodec->channels,
941 codec->sample_rate,
942 icodec->sample_rate);
943 }
e0d2714a
J
944 /* Request specific number of channels */
945 icodec->channels = codec->channels;
946 } else {
947 ost->audio_resample = 1;
948 ost->resample = audio_resample_init(codec->channels, icodec->channels,
85f07f22
FB
949 codec->sample_rate,
950 icodec->sample_rate);
e0d2714a 951 }
85f07f22
FB
952 }
953 ist->decoding_needed = 1;
954 ost->encoding_needed = 1;
1629626f
FB
955 break;
956 case CODEC_TYPE_VIDEO:
85f07f22 957 if (codec->width == icodec->width &&
34b10a57
D
958 codec->height == icodec->height &&
959 frame_topBand == 0 &&
960 frame_bottomBand == 0 &&
961 frame_leftBand == 0 &&
962 frame_rightBand == 0)
963 {
964 ost->video_resample = 0;
965 ost->video_crop = 0;
966 } else if ((codec->width == icodec->width -
967 (frame_leftBand + frame_rightBand)) &&
968 (codec->height == icodec->height -
969 (frame_topBand + frame_bottomBand)))
970 {
85f07f22 971 ost->video_resample = 0;
34b10a57
D
972 ost->video_crop = 1;
973 ost->topBand = frame_topBand;
974 ost->leftBand = frame_leftBand;
85f07f22 975 } else {
0c1a9eda 976 uint8_t *buf;
85f07f22 977 ost->video_resample = 1;
34b10a57 978 ost->video_crop = 0; // cropping is handled as part of resample
0f1578af 979 buf = av_malloc((codec->width * codec->height * 3) / 2);
85f07f22
FB
980 if (!buf)
981 goto fail;
982 ost->pict_tmp.data[0] = buf;
983 ost->pict_tmp.data[1] = ost->pict_tmp.data[0] + (codec->width * codec->height);
984 ost->pict_tmp.data[2] = ost->pict_tmp.data[1] + (codec->width * codec->height) / 4;
985 ost->pict_tmp.linesize[0] = codec->width;
986 ost->pict_tmp.linesize[1] = codec->width / 2;
987 ost->pict_tmp.linesize[2] = codec->width / 2;
988
ab6d194a 989 ost->img_resample_ctx = img_resample_full_init(
85f07f22 990 ost->st->codec.width, ost->st->codec.height,
ab6d194a
MN
991 ist->st->codec.width, ist->st->codec.height,
992 frame_topBand, frame_bottomBand,
993 frame_leftBand, frame_rightBand);
85f07f22
FB
994 }
995 ost->encoding_needed = 1;
996 ist->decoding_needed = 1;
1629626f
FB
997 break;
998 default:
999 av_abort();
85f07f22 1000 }
1629626f
FB
1001 /* two pass mode */
1002 if (ost->encoding_needed &&
1003 (codec->flags & (CODEC_FLAG_PASS1 | CODEC_FLAG_PASS2))) {
1004 char logfilename[1024];
1005 FILE *f;
1006 int size;
1007 char *logbuffer;
1008
1009 snprintf(logfilename, sizeof(logfilename), "%s-%d.log",
1010 pass_logfilename ?
1011 pass_logfilename : DEFAULT_PASS_LOGFILENAME, i);
1012 if (codec->flags & CODEC_FLAG_PASS1) {
1013 f = fopen(logfilename, "w");
1014 if (!f) {
1015 perror(logfilename);
1016 exit(1);
1017 }
1018 ost->logfile = f;
1019 } else {
1020 /* read the log file */
1021 f = fopen(logfilename, "r");
1022 if (!f) {
1023 perror(logfilename);
1024 exit(1);
1025 }
1026 fseek(f, 0, SEEK_END);
1027 size = ftell(f);
1028 fseek(f, 0, SEEK_SET);
1029 logbuffer = av_malloc(size + 1);
1030 if (!logbuffer) {
1031 fprintf(stderr, "Could not allocate log buffer\n");
1032 exit(1);
1033 }
1034 fread(logbuffer, 1, size, f);
1035 fclose(f);
1036 logbuffer[size] = '\0';
1037 codec->stats_in = logbuffer;
5abdb4b1 1038 }
5abdb4b1
FB
1039 }
1040 }
85f07f22
FB
1041 }
1042
1629626f
FB
1043 /* dump the file output parameters - cannot be done before in case
1044 of stream copy */
1045 for(i=0;i<nb_output_files;i++) {
1046 dump_format(output_files[i], i, output_files[i]->filename, 1);
1047 }
1048
1049 /* dump the stream mapping */
1050 fprintf(stderr, "Stream mapping:\n");
1051 for(i=0;i<nb_ostreams;i++) {
1052 ost = ost_table[i];
1053 fprintf(stderr, " Stream #%d.%d -> #%d.%d\n",
1054 ist_table[ost->source_index]->file_index,
1055 ist_table[ost->source_index]->index,
1056 ost->file_index,
1057 ost->index);
1058 }
1059
85f07f22
FB
1060 /* open each encoder */
1061 for(i=0;i<nb_ostreams;i++) {
1062 ost = ost_table[i];
1063 if (ost->encoding_needed) {
1064 AVCodec *codec;
1065 codec = avcodec_find_encoder(ost->st->codec.codec_id);
1066 if (!codec) {
1067 fprintf(stderr, "Unsupported codec for output stream #%d.%d\n",
1068 ost->file_index, ost->index);
1069 exit(1);
1070 }
1071 if (avcodec_open(&ost->st->codec, codec) < 0) {
1072 fprintf(stderr, "Error while opening codec for stream #%d.%d - maybe incorrect parameters such as bit_rate, rate, width or height\n",
1073 ost->file_index, ost->index);
1074 exit(1);
1075 }
1076 }
1077 }
1078
1079 /* open each decoder */
1080 for(i=0;i<nb_istreams;i++) {
1081 ist = ist_table[i];
1082 if (ist->decoding_needed) {
1083 AVCodec *codec;
1084 codec = avcodec_find_decoder(ist->st->codec.codec_id);
1085 if (!codec) {
10d104e4
PG
1086 fprintf(stderr, "Unsupported codec (id=%d) for input stream #%d.%d\n",
1087 ist->st->codec.codec_id, ist->file_index, ist->index);
85f07f22
FB
1088 exit(1);
1089 }
1090 if (avcodec_open(&ist->st->codec, codec) < 0) {
1091 fprintf(stderr, "Error while opening codec for input stream #%d.%d\n",
1092 ist->file_index, ist->index);
1093 exit(1);
1094 }
6dc96cb0
J
1095 //if (ist->st->codec.codec_type == CODEC_TYPE_VIDEO)
1096 // ist->st->codec.flags |= CODEC_FLAG_REPEAT_FIELD;
ec5517d5 1097 ist->frame_decoded = 1;
85f07f22
FB
1098 }
1099 }
1100
1101 /* init pts */
1102 for(i=0;i<nb_istreams;i++) {
1103 ist = ist_table[i];
85f07f22
FB
1104 }
1105
1106 /* compute buffer size max (should use a complete heuristic) */
1107 for(i=0;i<nb_input_files;i++) {
1108 file_table[i].buffer_size_max = 2048;
1109 }
1110
1111 /* open files and write file headers */
1112 for(i=0;i<nb_output_files;i++) {
1113 os = output_files[i];
79fdaa4c 1114 if (av_write_header(os) < 0) {
a38469e1
FB
1115 fprintf(stderr, "Could not write header for output file #%d (incorrect codec paramters ?)\n", i);
1116 ret = -EINVAL;
1117 goto fail;
1118 }
85f07f22
FB
1119 }
1120
a38469e1 1121#ifndef CONFIG_WIN32
01310af2 1122 fprintf(stderr, "Press [q] to stop encoding\n");
a38469e1
FB
1123#endif
1124 term_init();
1125
51bd4565 1126 stream_no_data = 0;
cb09b2ed 1127 key = -1;
51bd4565 1128
85f07f22
FB
1129 for(;;) {
1130 int file_index, ist_index;
1131 AVPacket pkt;
0c1a9eda 1132 uint8_t *ptr;
85f07f22 1133 int len;
0c1a9eda 1134 uint8_t *data_buf;
85f07f22
FB
1135 int data_size, got_picture;
1136 AVPicture picture;
1137 short samples[AVCODEC_MAX_AUDIO_FRAME_SIZE / 2];
10d104e4 1138 void *buffer_to_free;
ec5517d5
FB
1139 double pts_min;
1140
85f07f22 1141 redo:
a38469e1 1142 /* if 'q' pressed, exits */
cb09b2ed
PG
1143 if (key) {
1144 /* read_key() returns 0 on EOF */
1145 key = read_key();
1146 if (key == 'q')
1147 break;
1148 }
a38469e1 1149
ec5517d5
FB
1150 /* select the stream that we must read now by looking at the
1151 smallest output pts */
85f07f22 1152 file_index = -1;
ec5517d5
FB
1153 pts_min = 1e10;
1154 for(i=0;i<nb_ostreams;i++) {
1155 double pts;
1156 ost = ost_table[i];
1157 os = output_files[ost->file_index];
1158 ist = ist_table[ost->source_index];
1159 pts = (double)ost->st->pts.val * os->pts_num / os->pts_den;
1160 if (!file_table[ist->file_index].eof_reached &&
1161 pts < pts_min) {
1162 pts_min = pts;
85f07f22
FB
1163 file_index = ist->file_index;
1164 }
1165 }
1166 /* if none, if is finished */
51bd4565 1167 if (file_index < 0) {
85f07f22 1168 break;
ec5517d5
FB
1169 }
1170
85f07f22 1171 /* finish if recording time exhausted */
ec5517d5 1172 if (recording_time > 0 && pts_min >= (recording_time / 1000000.0))
85f07f22 1173 break;
ec5517d5 1174
85f07f22 1175 /* read a packet from it and output it in the fifo */
85f07f22
FB
1176 is = input_files[file_index];
1177 if (av_read_packet(is, &pkt) < 0) {
1178 file_table[file_index].eof_reached = 1;
1179 continue;
1180 }
51bd4565
PG
1181 if (!pkt.size) {
1182 stream_no_data = is;
1183 } else {
1184 stream_no_data = 0;
1185 }
817b23ff
FB
1186 if (do_hex_dump) {
1187 printf("stream #%d, size=%d:\n", pkt.stream_index, pkt.size);
1188 av_hex_dump(pkt.data, pkt.size);
1189 }
79fdaa4c
FB
1190 /* the following test is needed in case new streams appear
1191 dynamically in stream : we ignore them */
1192 if (pkt.stream_index >= file_table[file_index].nb_streams)
bf5af568 1193 goto discard_packet;
85f07f22
FB
1194 ist_index = file_table[file_index].ist_index + pkt.stream_index;
1195 ist = ist_table[ist_index];
bf5af568
FB
1196 if (ist->discard)
1197 goto discard_packet;
85f07f22 1198
34b10a57 1199 // printf("read #%d.%d size=%d\n", ist->file_index, ist->index, pkt.size);
85f07f22
FB
1200
1201 len = pkt.size;
1202 ptr = pkt.data;
ec5517d5 1203 pts_set = 0;
85f07f22 1204 while (len > 0) {
0c1a9eda 1205 int64_t ipts;
ec5517d5
FB
1206
1207 ipts = AV_NOPTS_VALUE;
85f07f22
FB
1208
1209 /* decode the packet if needed */
1210 data_buf = NULL; /* fail safe */
1211 data_size = 0;
1212 if (ist->decoding_needed) {
ec5517d5
FB
1213 /* NOTE1: we only take into account the PTS if a new
1214 frame has begun (MPEG semantics) */
1215 /* NOTE2: even if the fraction is not initialized,
1216 av_frac_set can be used to set the integer part */
1217 if (ist->frame_decoded &&
1218 pkt.pts != AV_NOPTS_VALUE &&
1219 !pts_set) {
1220 ipts = pkt.pts;
1221 ist->frame_decoded = 0;
1222 pts_set = 1;
1223 }
1224
85f07f22
FB
1225 switch(ist->st->codec.codec_type) {
1226 case CODEC_TYPE_AUDIO:
a0663ba4
FB
1227 /* XXX: could avoid copy if PCM 16 bits with same
1228 endianness as CPU */
1229 ret = avcodec_decode_audio(&ist->st->codec, samples, &data_size,
1230 ptr, len);
1231 if (ret < 0)
1232 goto fail_decode;
afc80f59
J
1233 /* Some bug in mpeg audio decoder gives */
1234 /* data_size < 0, it seems they are overflows */
1235 if (data_size <= 0) {
a0663ba4
FB
1236 /* no audio frame */
1237 ptr += ret;
1238 len -= ret;
1239 continue;
85f07f22 1240 }
0c1a9eda 1241 data_buf = (uint8_t *)samples;
85f07f22
FB
1242 break;
1243 case CODEC_TYPE_VIDEO:
e8750b00 1244 {
492cd3a9 1245 AVFrame big_picture;
1e491e29 1246
85f07f22
FB
1247 data_size = (ist->st->codec.width * ist->st->codec.height * 3) / 2;
1248 ret = avcodec_decode_video(&ist->st->codec,
1e491e29
MN
1249 &big_picture, &got_picture, ptr, len);
1250 picture= *(AVPicture*)&big_picture;
1251 ist->st->quality= big_picture.quality;
85f07f22
FB
1252 if (ret < 0) {
1253 fail_decode:
1254 fprintf(stderr, "Error while decoding stream #%d.%d\n",
1255 ist->file_index, ist->index);
1256 av_free_packet(&pkt);
1257 goto redo;
1258 }
1259 if (!got_picture) {
1260 /* no picture yet */
1261 ptr += ret;
1262 len -= ret;
1263 continue;
1264 }
6dc96cb0 1265
85f07f22
FB
1266 }
1267 break;
1268 default:
1269 goto fail_decode;
1270 }
1271 } else {
1272 data_buf = ptr;
1273 data_size = len;
1274 ret = len;
1275 }
85f07f22
FB
1276 ptr += ret;
1277 len -= ret;
1278
10d104e4
PG
1279 buffer_to_free = 0;
1280 if (ist->st->codec.codec_type == CODEC_TYPE_VIDEO) {
1281 pre_process_video_frame(ist, &picture, &buffer_to_free);
1282 }
1283
ec5517d5
FB
1284 ist->frame_decoded = 1;
1285
bdfcbbed
MK
1286 /* frame rate emulation */
1287 if (ist->st->codec.rate_emu) {
14bea432 1288 int64_t pts = av_rescale((int64_t) ist->frame * ist->st->codec.frame_rate_base, 1000000, ist->st->codec.frame_rate);
bdfcbbed
MK
1289 int64_t now = av_gettime() - ist->start;
1290 if (pts > now)
1291 usleep(pts - now);
1292
1293 ist->frame++;
1294 }
1295
ec5517d5
FB
1296#if 0
1297 /* mpeg PTS deordering : if it is a P or I frame, the PTS
1298 is the one of the next displayed one */
1299 /* XXX: add mpeg4 too ? */
1300 if (ist->st->codec.codec_id == CODEC_ID_MPEG1VIDEO) {
1301 if (ist->st->codec.pict_type != B_TYPE) {
0c1a9eda 1302 int64_t tmp;
ec5517d5
FB
1303 tmp = ist->last_ip_pts;
1304 ist->last_ip_pts = ist->frac_pts.val;
1305 ist->frac_pts.val = tmp;
1306 }
1307 }
1308#endif
85f07f22 1309 /* transcode raw format, encode packets and output them */
ec5517d5 1310
85f07f22 1311 for(i=0;i<nb_ostreams;i++) {
ce7c56c2 1312 int frame_size;
ec5517d5 1313
85f07f22
FB
1314 ost = ost_table[i];
1315 if (ost->source_index == ist_index) {
1316 os = output_files[ost->file_index];
1317
ec5517d5
FB
1318 if (ipts != AV_NOPTS_VALUE) {
1319#if 0
1320 printf("%d: got pts=%f %f\n",
1321 i, pkt.pts / 90000.0,
1322 (ipts - ost->st->pts.val) / 90000.0);
1323#endif
1324 /* set the input output pts pairs */
1325 ost->sync_ipts = (double)ipts * is->pts_num /
1326 is->pts_den;
1327 /* XXX: take into account the various fifos,
1328 in particular for audio */
1329 ost->sync_opts = ost->st->pts.val;
10d104e4
PG
1330 //printf("ipts=%lld sync_ipts=%f sync_opts=%lld pts.val=%lld pkt.pts=%lld\n", ipts, ost->sync_ipts, ost->sync_opts, ost->st->pts.val, pkt.pts);
1331 } else {
1332 //printf("pts.val=%lld\n", ost->st->pts.val);
be4ce157 1333 ost->sync_ipts = AV_NOPTS_VALUE;
ec5517d5
FB
1334 }
1335
85f07f22
FB
1336 if (ost->encoding_needed) {
1337 switch(ost->st->codec.codec_type) {
1338 case CODEC_TYPE_AUDIO:
1339 do_audio_out(os, ost, ist, data_buf, data_size);
1340 break;
1341 case CODEC_TYPE_VIDEO:
ec5517d5
FB
1342 /* find an audio stream for synchro */
1343 {
1344 int i;
1345 AVOutputStream *audio_sync, *ost1;
1346 audio_sync = NULL;
1347 for(i=0;i<nb_ostreams;i++) {
1348 ost1 = ost_table[i];
1349 if (ost1->file_index == ost->file_index &&
1350 ost1->st->codec.codec_type == CODEC_TYPE_AUDIO) {
1351 audio_sync = ost1;
1352 break;
1353 }
1354 }
1355
1356 do_video_out(os, ost, ist, &picture, &frame_size, audio_sync);
204c0f48 1357 if (do_vstats && frame_size)
ec5517d5
FB
1358 do_video_stats(os, ost, frame_size);
1359 }
85f07f22 1360 break;
51bd4565 1361 default:
c04643a2 1362 av_abort();
85f07f22
FB
1363 }
1364 } else {
18531e52
MN
1365 AVFrame avframe;
1366
85f07f22 1367 /* no reencoding needed : output the packet directly */
10bb7023 1368 /* force the input stream PTS */
18531e52 1369
18531e52
MN
1370 memset(&avframe, 0, sizeof(AVFrame));
1371 ost->st->codec.coded_frame= &avframe;
e738cee9 1372 avframe.key_frame = pkt.flags & PKT_FLAG_KEY;
18531e52 1373
ec5517d5 1374 av_write_frame(os, ost->index, data_buf, data_size);
b2722d0a 1375 ost->st->codec.frame_number++;
9ce2f2b1 1376 ost->frame_number++;
85f07f22
FB
1377 }
1378 }
1379 }
10d104e4 1380 av_free(buffer_to_free);
ec5517d5 1381 ipts = AV_NOPTS_VALUE;
85f07f22 1382 }
bf5af568 1383 discard_packet:
85f07f22
FB
1384 av_free_packet(&pkt);
1385
ec5517d5
FB
1386 /* dump report by using the output first video and audio streams */
1387 print_report(output_files, ost_table, nb_ostreams, 0);
85f07f22 1388 }
a38469e1 1389 term_exit();
85f07f22
FB
1390
1391 /* dump report by using the first video and audio streams */
ec5517d5
FB
1392 print_report(output_files, ost_table, nb_ostreams, 1);
1393
85f07f22
FB
1394 /* close each encoder */
1395 for(i=0;i<nb_ostreams;i++) {
1396 ost = ost_table[i];
1397 if (ost->encoding_needed) {
5abdb4b1 1398 av_freep(&ost->st->codec.stats_in);
85f07f22
FB
1399 avcodec_close(&ost->st->codec);
1400 }
1401 }
1402
1403 /* close each decoder */
1404 for(i=0;i<nb_istreams;i++) {
1405 ist = ist_table[i];
1406 if (ist->decoding_needed) {
1407 avcodec_close(&ist->st->codec);
1408 }
1409 }
1410
1411
1412 /* write the trailer if needed and close file */
1413 for(i=0;i<nb_output_files;i++) {
1414 os = output_files[i];
79fdaa4c 1415 av_write_trailer(os);
85f07f22
FB
1416 }
1417 /* finished ! */
1418
1419 ret = 0;
1420 fail1:
0f1578af 1421 av_free(file_table);
bdc4796f 1422
85f07f22
FB
1423 if (ist_table) {
1424 for(i=0;i<nb_istreams;i++) {
1425 ist = ist_table[i];
0f1578af 1426 av_free(ist);
85f07f22 1427 }
0f1578af 1428 av_free(ist_table);
85f07f22
FB
1429 }
1430 if (ost_table) {
1431 for(i=0;i<nb_ostreams;i++) {
1432 ost = ost_table[i];
1433 if (ost) {
5abdb4b1
FB
1434 if (ost->logfile) {
1435 fclose(ost->logfile);
1436 ost->logfile = NULL;
1437 }
bf5af568
FB
1438 fifo_free(&ost->fifo); /* works even if fifo is not
1439 initialized but set to zero */
0f1578af 1440 av_free(ost->pict_tmp.data[0]);
85f07f22
FB
1441 if (ost->video_resample)
1442 img_resample_close(ost->img_resample_ctx);
1443 if (ost->audio_resample)
1444 audio_resample_close(ost->resample);
0f1578af 1445 av_free(ost);
85f07f22
FB
1446 }
1447 }
0f1578af 1448 av_free(ost_table);
85f07f22
FB
1449 }
1450 return ret;
1451 fail:
1452 ret = -ENOMEM;
1453 goto fail1;
1454}
1455
1456#if 0
1457int file_read(const char *filename)
1458{
1459 URLContext *h;
1460 unsigned char buffer[1024];
1461 int len, i;
1462
1463 if (url_open(&h, filename, O_RDONLY) < 0) {
1464 printf("could not open '%s'\n", filename);
1465 return -1;
1466 }
1467 for(;;) {
1468 len = url_read(h, buffer, sizeof(buffer));
1469 if (len <= 0)
1470 break;
1471 for(i=0;i<len;i++) putchar(buffer[i]);
1472 }
1473 url_close(h);
1474 return 0;
1475}
1476#endif
1477
b29f97d1 1478static void show_licence(void)
85f07f22
FB
1479{
1480 printf(
1481 "ffmpeg version " FFMPEG_VERSION "\n"
bf5af568
FB
1482 "Copyright (c) 2000, 2001, 2002 Fabrice Bellard\n"
1483 "This library is free software; you can redistribute it and/or\n"
1484 "modify it under the terms of the GNU Lesser General Public\n"
1485 "License as published by the Free Software Foundation; either\n"
1486 "version 2 of the License, or (at your option) any later version.\n"
85f07f22 1487 "\n"
bf5af568 1488 "This library is distributed in the hope that it will be useful,\n"
85f07f22 1489 "but WITHOUT ANY WARRANTY; without even the implied warranty of\n"
bf5af568
FB
1490 "MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n"
1491 "Lesser General Public License for more details.\n"
85f07f22 1492 "\n"
bf5af568
FB
1493 "You should have received a copy of the GNU Lesser General Public\n"
1494 "License along with this library; if not, write to the Free Software\n"
1495 "Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n"
85f07f22
FB
1496 );
1497 exit(1);
1498}
1499
b29f97d1 1500static void opt_image_format(const char *arg)
817b23ff
FB
1501{
1502 AVImageFormat *f;
1503
1504 for(f = first_image_format; f != NULL; f = f->next) {
1505 if (!strcmp(arg, f->name))
1506 break;
1507 }
1508 if (!f) {
1509 fprintf(stderr, "Unknown image format: '%s'\n", arg);
1510 exit(1);
1511 }
1512 image_format = f;
1513}
1514
b29f97d1 1515static void opt_format(const char *arg)
85f07f22 1516{
817b23ff
FB
1517 /* compatibility stuff for pgmyuv */
1518 if (!strcmp(arg, "pgmyuv")) {
1519 opt_image_format(arg);
1520 arg = "image";
1521 }
1522
79fdaa4c
FB
1523 file_iformat = av_find_input_format(arg);
1524 file_oformat = guess_format(arg, NULL, NULL);
1525 if (!file_iformat && !file_oformat) {
1526 fprintf(stderr, "Unknown input or output format: %s\n", arg);
85f07f22
FB
1527 exit(1);
1528 }
85f07f22
FB
1529}
1530
b29f97d1 1531static void opt_video_bitrate(const char *arg)
85f07f22
FB
1532{
1533 video_bit_rate = atoi(arg) * 1000;
1534}
1535
b29f97d1 1536static void opt_video_bitrate_tolerance(const char *arg)
9cdd6a24
MN
1537{
1538 video_bit_rate_tolerance = atoi(arg) * 1000;
1539}
1540
b29f97d1 1541static void opt_video_bitrate_max(const char *arg)
3aa102be
MN
1542{
1543 video_rc_max_rate = atoi(arg) * 1000;
1544}
1545
b29f97d1 1546static void opt_video_bitrate_min(const char *arg)
3aa102be
MN
1547{
1548 video_rc_min_rate = atoi(arg) * 1000;
1549}
1550
b29f97d1 1551static void opt_video_buffer_size(const char *arg)
946c8a12
MN
1552{
1553 video_rc_buffer_size = atoi(arg) * 1000;
1554}
1555
b29f97d1 1556static void opt_video_rc_eq(char *arg)
3aa102be
MN
1557{
1558 video_rc_eq = arg;
1559}
1560
b29f97d1 1561static void opt_video_rc_override_string(char *arg)
ac2830ec
MN
1562{
1563 video_rc_override_string = arg;
1564}
1565
3aa102be 1566
b29f97d1 1567static void opt_workaround_bugs(const char *arg)
fe670d09
MN
1568{
1569 workaround_bugs = atoi(arg);
1570}
1571
b29f97d1 1572static void opt_dct_algo(const char *arg)
463678ac
MN
1573{
1574 dct_algo = atoi(arg);
1575}
1576
b29f97d1 1577static void opt_idct_algo(const char *arg)
2ad1516a
MN
1578{
1579 idct_algo = atoi(arg);
1580}
1581
1582
b29f97d1 1583static void opt_error_resilience(const char *arg)
8409b8fe
MN
1584{
1585 error_resilience = atoi(arg);
1586}
1587
b29f97d1 1588static void opt_error_concealment(const char *arg)
4d2858de
MN
1589{
1590 error_concealment = atoi(arg);
1591}
1592
b29f97d1 1593static void opt_debug(const char *arg)
59b571c1
MN
1594{
1595 debug = atoi(arg);
1596}
4d2858de 1597
b29f97d1 1598static void opt_frame_rate(const char *arg)
85f07f22 1599{
14bea432
MN
1600 frame_rate_base = DEFAULT_FRAME_RATE_BASE; //FIXME not optimal
1601 frame_rate = (int)(strtod(arg, 0) * frame_rate_base + 0.5);
1602 //FIXME parse fractions
85f07f22
FB
1603}
1604
ab6d194a 1605
b29f97d1 1606static void opt_frame_crop_top(const char *arg)
ab6d194a
MN
1607{
1608 frame_topBand = atoi(arg);
1609 if (frame_topBand < 0) {
1610 fprintf(stderr, "Incorrect top crop size\n");
1611 exit(1);
1612 }
1613 if ((frame_topBand % 2) != 0) {
1614 fprintf(stderr, "Top crop size must be a multiple of 2\n");
1615 exit(1);
1616 }
1617 if ((frame_topBand) >= frame_height){
1618 fprintf(stderr, "Vertical crop dimensions are outside the range of the original image.\nRemember to crop first and scale second.\n");
1619 exit(1);
1620 }
1621 frame_height -= frame_topBand;
1622}
1623
b29f97d1 1624static void opt_frame_crop_bottom(const char *arg)
ab6d194a
MN
1625{
1626 frame_bottomBand = atoi(arg);
1627 if (frame_bottomBand < 0) {
1628 fprintf(stderr, "Incorrect bottom crop size\n");
1629 exit(1);
1630 }
1631 if ((frame_bottomBand % 2) != 0) {
1632 fprintf(stderr, "Bottom crop size must be a multiple of 2\n");
1633 exit(1);
1634 }
1635 if ((frame_bottomBand) >= frame_height){
1636 fprintf(stderr, "Vertical crop dimensions are outside the range of the original image.\nRemember to crop first and scale second.\n");
1637 exit(1);
1638 }
1639 frame_height -= frame_bottomBand;
1640}
1641
b29f97d1 1642static void opt_frame_crop_left(const char *arg)
ab6d194a
MN
1643{
1644 frame_leftBand = atoi(arg);
1645 if (frame_leftBand < 0) {
1646 fprintf(stderr, "Incorrect left crop size\n");
1647 exit(1);
1648 }
1649 if ((frame_leftBand % 2) != 0) {
1650 fprintf(stderr, "Left crop size must be a multiple of 2\n");
1651 exit(1);
1652 }
1653 if ((frame_leftBand) >= frame_width){
1654 fprintf(stderr, "Horizontal crop dimensions are outside the range of the original image.\nRemember to crop first and scale second.\n");
1655 exit(1);
1656 }
1657 frame_width -= frame_leftBand;
1658}
1659
b29f97d1 1660static void opt_frame_crop_right(const char *arg)
ab6d194a
MN
1661{
1662 frame_rightBand = atoi(arg);
1663 if (frame_rightBand < 0) {
1664 fprintf(stderr, "Incorrect right crop size\n");
1665 exit(1);
1666 }
1667 if ((frame_rightBand % 2) != 0) {
1668 fprintf(stderr, "Right crop size must be a multiple of 2\n");
1669 exit(1);
1670 }
1671 if ((frame_rightBand) >= frame_width){
1672 fprintf(stderr, "Horizontal crop dimensions are outside the range of the original image.\nRemember to crop first and scale second.\n");
1673 exit(1);
1674 }
1675 frame_width -= frame_rightBand;
1676}
1677
b29f97d1 1678static void opt_frame_size(const char *arg)
85f07f22
FB
1679{
1680 parse_image_size(&frame_width, &frame_height, arg);
1681 if (frame_width <= 0 || frame_height <= 0) {
1682 fprintf(stderr, "Incorrect frame size\n");
1683 exit(1);
1684 }
1685 if ((frame_width % 2) != 0 || (frame_height % 2) != 0) {
1686 fprintf(stderr, "Frame size must be a multiple of 2\n");
1687 exit(1);
1688 }
1689}
1690
63167088
RS
1691static void opt_frame_pix_fmt(const char *arg)
1692{
1693 frame_pix_fmt = avcodec_get_pix_fmt(arg);
1694}
1695
5fe03e38
RS
1696static void opt_frame_aspect_ratio(const char *arg)
1697{
1698 int x = 0, y = 0;
1699 double ar = 0;
1700 const char *p;
1701
1702 p = strchr(arg, ':');
1703 if (p) {
1704 x = strtol(arg, (char **)&arg, 10);
1705 if (arg == p)
1706 y = strtol(arg+1, (char **)&arg, 10);
1707 if (x > 0 && y > 0)
1708 ar = (double)x / (double)y;
1709 } else
1710 ar = strtod(arg, (char **)&arg);
1711
1712 if (!ar) {
1713 fprintf(stderr, "Incorrect aspect ratio specification.\n");
1714 exit(1);
1715 }
1716 frame_aspect_ratio = ar;
1717}
1718
b29f97d1 1719static void opt_gop_size(const char *arg)
85f07f22
FB
1720{
1721 gop_size = atoi(arg);
1722}
1723
b29f97d1 1724static void opt_b_frames(const char *arg)
bc6caae2
J
1725{
1726 b_frames = atoi(arg);
1727 if (b_frames > FF_MAX_B_FRAMES) {
1728 fprintf(stderr, "\nCannot have more than %d B frames, increase FF_MAX_B_FRAMES.\n", FF_MAX_B_FRAMES);
1729 exit(1);
1730 } else if (b_frames < 1) {
1731 fprintf(stderr, "\nNumber of B frames must be higher than 0\n");
1732 exit(1);
1733 }
1734}
1735
b29f97d1 1736static void opt_qscale(const char *arg)
85f07f22
FB
1737{
1738 video_qscale = atoi(arg);
1739 if (video_qscale < 0 ||
1740 video_qscale > 31) {
1741 fprintf(stderr, "qscale must be >= 1 and <= 31\n");
1742 exit(1);
1743 }
1744}
1745
b29f97d1 1746static void opt_qmin(const char *arg)
9cdd6a24
MN
1747{
1748 video_qmin = atoi(arg);
1749 if (video_qmin < 0 ||
1750 video_qmin > 31) {
1751 fprintf(stderr, "qmin must be >= 1 and <= 31\n");
1752 exit(1);
1753 }
1754}
1755
b29f97d1 1756static void opt_qmax(const char *arg)
9cdd6a24
MN
1757{
1758 video_qmax = atoi(arg);
1759 if (video_qmax < 0 ||
1760 video_qmax > 31) {
1761 fprintf(stderr, "qmax must be >= 1 and <= 31\n");
1762 exit(1);
1763 }
1764}
1765
b29f97d1 1766static void opt_mb_qmin(const char *arg)
17a70fde
MN
1767{
1768 video_mb_qmin = atoi(arg);
1769 if (video_mb_qmin < 0 ||
1770 video_mb_qmin > 31) {
1771 fprintf(stderr, "qmin must be >= 1 and <= 31\n");
1772 exit(1);
1773 }
1774}
1775
b29f97d1 1776static void opt_mb_qmax(const char *arg)
17a70fde
MN
1777{
1778 video_mb_qmax = atoi(arg);
1779 if (video_mb_qmax < 0 ||
1780 video_mb_qmax > 31) {
1781 fprintf(stderr, "qmax must be >= 1 and <= 31\n");
1782 exit(1);
1783 }
1784}
1785
b29f97d1 1786static void opt_qdiff(const char *arg)
9cdd6a24
MN
1787{
1788 video_qdiff = atoi(arg);
1789 if (video_qdiff < 0 ||
1790 video_qdiff > 31) {
1791 fprintf(stderr, "qdiff must be >= 1 and <= 31\n");
1792 exit(1);
1793 }
1794}
1795
b29f97d1 1796static void opt_qblur(const char *arg)
9cdd6a24
MN
1797{
1798 video_qblur = atof(arg);
1799}
1800
b29f97d1 1801static void opt_qcomp(const char *arg)
9cdd6a24
MN
1802{
1803 video_qcomp = atof(arg);
1804}
85f07f22 1805
b29f97d1 1806static void opt_rc_initial_cplx(const char *arg)
ac2830ec
MN
1807{
1808 video_rc_initial_cplx = atof(arg);
1809}
b29f97d1 1810static void opt_b_qfactor(const char *arg)
29700fa6
MN
1811{
1812 video_b_qfactor = atof(arg);
1813}
b29f97d1 1814static void opt_i_qfactor(const char *arg)
29700fa6
MN
1815{
1816 video_i_qfactor = atof(arg);
1817}
b29f97d1 1818static void opt_b_qoffset(const char *arg)
29700fa6
MN
1819{
1820 video_b_qoffset = atof(arg);
1821}
b29f97d1 1822static void opt_i_qoffset(const char *arg)
29700fa6
MN
1823{
1824 video_i_qoffset = atof(arg);
1825}
1826
b29f97d1 1827static void opt_packet_size(const char *arg)
1dbb6d90
MN
1828{
1829 packet_size= atoi(arg);
1830}
1831
b29f97d1 1832static void opt_strict(const char *arg)
f560dd82
MN
1833{
1834 strict= atoi(arg);
1835}
1836
b29f97d1 1837static void opt_audio_bitrate(const char *arg)
85f07f22
FB
1838{
1839 audio_bit_rate = atoi(arg) * 1000;
1840}
1841
b29f97d1 1842static void opt_audio_rate(const char *arg)
85f07f22
FB
1843{
1844 audio_sample_rate = atoi(arg);
1845}
1846
b29f97d1 1847static void opt_audio_channels(const char *arg)
85f07f22
FB
1848{
1849 audio_channels = atoi(arg);
1850}
1851
b29f97d1 1852static void opt_video_device(const char *arg)
85f07f22 1853{
e9a9e0c2 1854 video_device = av_strdup(arg);
85f07f22
FB
1855}
1856
b29f97d1 1857static void opt_video_channel(const char *arg)
a5df11ab
FB
1858{
1859 video_channel = strtol(arg, NULL, 0);
1860}
1861
e3ee3283
AB
1862static void opt_video_standard(const char *arg)
1863{
1864 video_standard = av_strdup(arg);
1865}
1866
b29f97d1 1867static void opt_audio_device(const char *arg)
85f07f22 1868{
e9a9e0c2 1869 audio_device = av_strdup(arg);
85f07f22
FB
1870}
1871
b29f97d1 1872static void opt_dv1394(const char *arg)
8aa3ee32
MK
1873{
1874 video_grab_format = "dv1394";
1501987b 1875 audio_grab_format = NULL;
8aa3ee32
MK
1876}
1877
b29f97d1 1878static void opt_audio_codec(const char *arg)
85f07f22
FB
1879{
1880 AVCodec *p;
1881
1629626f
FB
1882 if (!strcmp(arg, "copy")) {
1883 audio_stream_copy = 1;
85f07f22 1884 } else {
1629626f
FB
1885 p = first_avcodec;
1886 while (p) {
1887 if (!strcmp(p->name, arg) && p->type == CODEC_TYPE_AUDIO)
1888 break;
1889 p = p->next;
1890 }
1891 if (p == NULL) {
1892 fprintf(stderr, "Unknown audio codec '%s'\n", arg);
1893 exit(1);
1894 } else {
1895 audio_codec_id = p->id;
1896 }
85f07f22
FB
1897 }
1898}
1899
b29f97d1 1900static void add_frame_hooker(const char *arg)
10d104e4
PG
1901{
1902 int argc = 0;
1903 char *argv[64];
1904 int i;
e9a9e0c2 1905 char *args = av_strdup(arg);
10d104e4
PG
1906
1907 argv[0] = strtok(args, " ");
1908 while (argc < 62 && (argv[++argc] = strtok(NULL, " "))) {
1909 }
1910
1911 i = frame_hook_add(argc, argv);
1912
1913 if (i != 0) {
1914 fprintf(stderr, "Failed to add video hook function: %s\n", arg);
1915 exit(1);
1916 }
1917}
1918
85f07f22
FB
1919const char *motion_str[] = {
1920 "zero",
1921 "full",
1922 "log",
1923 "phods",
7084c149
MN
1924 "epzs",
1925 "x1",
85f07f22
FB
1926 NULL,
1927};
1928
b29f97d1 1929static void opt_motion_estimation(const char *arg)
85f07f22
FB
1930{
1931 const char **p;
1932 p = motion_str;
1933 for(;;) {
1934 if (!*p) {
1935 fprintf(stderr, "Unknown motion estimation method '%s'\n", arg);
1936 exit(1);
1937 }
1938 if (!strcmp(*p, arg))
1939 break;
1940 p++;
1941 }
101bea5f 1942 me_method = (p - motion_str) + 1;
85f07f22
FB
1943}
1944
b29f97d1 1945static void opt_video_codec(const char *arg)
85f07f22
FB
1946{
1947 AVCodec *p;
1948
1629626f
FB
1949 if (!strcmp(arg, "copy")) {
1950 video_stream_copy = 1;
85f07f22 1951 } else {
1629626f
FB
1952 p = first_avcodec;
1953 while (p) {
1954 if (!strcmp(p->name, arg) && p->type == CODEC_TYPE_VIDEO)
1955 break;
1956 p = p->next;
1957 }
1958 if (p == NULL) {
1959 fprintf(stderr, "Unknown video codec '%s'\n", arg);
1960 exit(1);
1961 } else {
1962 video_codec_id = p->id;
1963 }
85f07f22
FB
1964 }
1965}
1966
b29f97d1 1967static void opt_map(const char *arg)
85f07f22
FB
1968{
1969 AVStreamMap *m;
1970 const char *p;
1971
1972 p = arg;
1973 m = &stream_maps[nb_stream_maps++];
1974
1975 m->file_index = strtol(arg, (char **)&p, 0);
1976 if (*p)
1977 p++;
a5dc85ef
J
1978
1979 m->stream_index = strtol(p, (char **)&p, 0);
85f07f22
FB
1980}
1981
b29f97d1 1982static void opt_recording_time(const char *arg)
85f07f22
FB
1983{
1984 recording_time = parse_date(arg, 1);
1985}
1986
b29f97d1 1987static void opt_input_file(const char *filename)
85f07f22
FB
1988{
1989 AVFormatContext *ic;
1990 AVFormatParameters params, *ap = &params;
14bea432 1991 int err, i, ret, rfps, rfps_base;
85f07f22 1992
b242baa4
FB
1993 if (!strcmp(filename, "-"))
1994 filename = "pipe:";
1995
85f07f22 1996 /* get default parameters from command line */
79fdaa4c
FB
1997 memset(ap, 0, sizeof(*ap));
1998 ap->sample_rate = audio_sample_rate;
1999 ap->channels = audio_channels;
2000 ap->frame_rate = frame_rate;
14bea432 2001 ap->frame_rate_base = frame_rate_base;
79fdaa4c
FB
2002 ap->width = frame_width;
2003 ap->height = frame_height;
817b23ff 2004 ap->image_format = image_format;
63167088 2005 ap->pix_fmt = frame_pix_fmt;
79fdaa4c
FB
2006
2007 /* open the input file with generic libav function */
2008 err = av_open_input_file(&ic, filename, file_iformat, 0, ap);
85f07f22 2009 if (err < 0) {
79fdaa4c 2010 print_error(filename, err);
85f07f22
FB
2011 exit(1);
2012 }
2013
79fdaa4c
FB
2014 /* If not enough info to get the stream parameters, we decode the
2015 first frames to get it. (used in mpeg case for example) */
2016 ret = av_find_stream_info(ic);
85f07f22
FB
2017 if (ret < 0) {
2018 fprintf(stderr, "%s: could not find codec parameters\n", filename);
2019 exit(1);
2020 }
2021
2022 /* update the current parameters so that they match the one of the input stream */
2023 for(i=0;i<ic->nb_streams;i++) {
2024 AVCodecContext *enc = &ic->streams[i]->codec;
2025 switch(enc->codec_type) {
2026 case CODEC_TYPE_AUDIO:
e0d2714a 2027 //fprintf(stderr, "\nInput Audio channels: %d", enc->channels);
85f07f22
FB
2028 audio_channels = enc->channels;
2029 audio_sample_rate = enc->sample_rate;
2030 break;
2031 case CODEC_TYPE_VIDEO:
2032 frame_height = enc->height;
2033 frame_width = enc->width;
880e8ba7 2034 frame_aspect_ratio = enc->aspect_ratio;
63167088 2035 frame_pix_fmt = enc->pix_fmt;
14bea432
MN
2036 rfps = ic->streams[i]->r_frame_rate;
2037 rfps_base = ic->streams[i]->r_frame_rate_base;
fe670d09 2038 enc->workaround_bugs = workaround_bugs;
8409b8fe 2039 enc->error_resilience = error_resilience;
4d2858de 2040 enc->error_concealment = error_concealment;
2ad1516a 2041 enc->idct_algo= idct_algo;
59b571c1 2042 enc->debug= debug;
d7425f59
MN
2043/* if(enc->codec->capabilities & CODEC_CAP_TRUNCATED)
2044 enc->flags|= CODEC_FLAG_TRUNCATED; */
0da71265 2045 if(/*enc->codec_id==CODEC_ID_MPEG4 || */enc->codec_id==CODEC_ID_MPEG1VIDEO || enc->codec_id==CODEC_ID_H264)
d7425f59 2046 enc->flags|= CODEC_FLAG_TRUNCATED;
b0368839
MN
2047
2048 if(bitexact)
2049 enc->flags|= CODEC_FLAG_BITEXACT;
d7425f59 2050
14bea432
MN
2051 assert(enc->frame_rate_base == rfps_base); // should be true for now
2052 if (enc->frame_rate != rfps) {
6dc96cb0 2053 fprintf(stderr,"\nSeems that stream %d comes from film source: %2.2f->%2.2f\n",
14bea432
MN
2054 i, (float)enc->frame_rate / enc->frame_rate_base,
2055 (float)rfps / rfps_base);
79fdaa4c 2056 }
bf5af568 2057 /* update the current frame rate to match the stream frame rate */
14bea432
MN
2058 frame_rate = rfps;
2059 frame_rate_base = rfps_base;
bdfcbbed
MK
2060
2061 enc->rate_emu = rate_emu;
85f07f22 2062 break;
51bd4565 2063 default:
c04643a2 2064 av_abort();
85f07f22
FB
2065 }
2066 }
2067
2068 input_files[nb_input_files] = ic;
2069 /* dump the file content */
2070 dump_format(ic, nb_input_files, filename, 0);
2071 nb_input_files++;
79fdaa4c
FB
2072 file_iformat = NULL;
2073 file_oformat = NULL;
817b23ff 2074 image_format = NULL;
bdfcbbed
MK
2075
2076 rate_emu = 0;
85f07f22
FB
2077}
2078
b29f97d1 2079static void check_audio_video_inputs(int *has_video_ptr, int *has_audio_ptr)
919f448d
FB
2080{
2081 int has_video, has_audio, i, j;
2082 AVFormatContext *ic;
2083
2084 has_video = 0;
2085 has_audio = 0;
2086 for(j=0;j<nb_input_files;j++) {
2087 ic = input_files[j];
2088 for(i=0;i<ic->nb_streams;i++) {
2089 AVCodecContext *enc = &ic->streams[i]->codec;
2090 switch(enc->codec_type) {
2091 case CODEC_TYPE_AUDIO:
2092 has_audio = 1;
2093 break;
2094 case CODEC_TYPE_VIDEO:
2095 has_video = 1;
2096 break;
51bd4565 2097 default:
c04643a2 2098 av_abort();
919f448d
FB
2099 }
2100 }
2101 }
2102 *has_video_ptr = has_video;
2103 *has_audio_ptr = has_audio;
2104}
2105
b29f97d1 2106static void opt_output_file(const char *filename)
85f07f22
FB
2107{
2108 AVStream *st;
2109 AVFormatContext *oc;
919f448d 2110 int use_video, use_audio, nb_streams, input_has_video, input_has_audio;
85f07f22 2111 int codec_id;
817b23ff 2112 AVFormatParameters params, *ap = &params;
85f07f22
FB
2113
2114 if (!strcmp(filename, "-"))
2115 filename = "pipe:";
2116
2117 oc = av_mallocz(sizeof(AVFormatContext));
2118
79fdaa4c
FB
2119 if (!file_oformat) {
2120 file_oformat = guess_format(NULL, filename, NULL);
2121 if (!file_oformat) {
2122 fprintf(stderr, "Unable for find a suitable output format for '%s'\n",
2123 filename);
2124 exit(1);
2125 }
85f07f22
FB
2126 }
2127
79fdaa4c 2128 oc->oformat = file_oformat;
85f07f22 2129
79fdaa4c 2130 if (!strcmp(file_oformat->name, "ffm") &&
85f07f22
FB
2131 strstart(filename, "http:", NULL)) {
2132 /* special case for files sent to ffserver: we get the stream
2133 parameters from ffserver */
2134 if (read_ffserver_streams(oc, filename) < 0) {
2135 fprintf(stderr, "Could not read stream parameters from '%s'\n", filename);
2136 exit(1);
2137 }
2138 } else {
79fdaa4c
FB
2139 use_video = file_oformat->video_codec != CODEC_ID_NONE;
2140 use_audio = file_oformat->audio_codec != CODEC_ID_NONE;
919f448d 2141
e30a2846
FB
2142 /* disable if no corresponding type found and at least one
2143 input file */
2144 if (nb_input_files > 0) {
2145 check_audio_video_inputs(&input_has_video, &input_has_audio);
2146 if (!input_has_video)
2147 use_video = 0;
2148 if (!input_has_audio)
2149 use_audio = 0;
2150 }
919f448d
FB
2151
2152 /* manual disable */
85f07f22
FB
2153 if (audio_disable) {
2154 use_audio = 0;
2155 }
2156 if (video_disable) {
2157 use_video = 0;
2158 }
2159
2160 nb_streams = 0;
2161 if (use_video) {
2162 AVCodecContext *video_enc;
2163
2164 st = av_mallocz(sizeof(AVStream));
2165 if (!st) {
2166 fprintf(stderr, "Could not alloc stream\n");
2167 exit(1);
2168 }
1e491e29 2169 avcodec_get_context_defaults(&st->codec);
85f07f22 2170
1629626f
FB
2171 video_enc = &st->codec;
2172 if (video_stream_copy) {
2173 st->stream_copy = 1;
2174 video_enc->codec_type = CODEC_TYPE_VIDEO;
2175 } else {
ac2830ec
MN
2176 char *p;
2177 int i;
2178
1629626f
FB
2179 codec_id = file_oformat->video_codec;
2180 if (video_codec_id != CODEC_ID_NONE)
2181 codec_id = video_codec_id;
2182
2183 video_enc->codec_id = codec_id;
2184
2185 video_enc->bit_rate = video_bit_rate;
2186 video_enc->bit_rate_tolerance = video_bit_rate_tolerance;
2187 video_enc->frame_rate = frame_rate;
14bea432 2188 video_enc->frame_rate_base = frame_rate_base;
1629626f
FB
2189
2190 video_enc->width = frame_width;
2191 video_enc->height = frame_height;
880e8ba7 2192 video_enc->aspect_ratio = frame_aspect_ratio;
63167088 2193 video_enc->pix_fmt = frame_pix_fmt;
1629626f
FB
2194
2195 if (!intra_only)
2196 video_enc->gop_size = gop_size;
2197 else
2198 video_enc->gop_size = 0;
2199 if (video_qscale || same_quality) {
2200 video_enc->flags |= CODEC_FLAG_QSCALE;
1e491e29 2201 st->quality = video_qscale;
1629626f 2202 }
b0368839
MN
2203
2204 if(bitexact)
2205 video_enc->flags |= CODEC_FLAG_BITEXACT;
2206
1629626f
FB
2207 if (use_hq) {
2208 video_enc->flags |= CODEC_FLAG_HQ;
2209 }
21e59552
MN
2210 /* Fx */
2211 if (use_umv) {
2212 video_enc->flags |= CODEC_FLAG_H263P_UMV;
2213 }
2214 if (use_aic) {
2215 video_enc->flags |= CODEC_FLAG_H263P_AIC;
2216 }
2217 /* /Fx */
1629626f
FB
2218 if (use_4mv) {
2219 video_enc->flags |= CODEC_FLAG_HQ;
2220 video_enc->flags |= CODEC_FLAG_4MV;
2221 }
bc6caae2 2222
1629626f
FB
2223 if(use_part)
2224 video_enc->flags |= CODEC_FLAG_PART;
1dbb6d90
MN
2225
2226
1629626f 2227 if (b_frames) {
1629626f
FB
2228 video_enc->max_b_frames = b_frames;
2229 video_enc->b_frame_strategy = 0;
2230 video_enc->b_quant_factor = 2.0;
bc6caae2 2231 }
bc6caae2 2232
1629626f
FB
2233 video_enc->qmin = video_qmin;
2234 video_enc->qmax = video_qmax;
17a70fde
MN
2235 video_enc->mb_qmin = video_mb_qmin;
2236 video_enc->mb_qmax = video_mb_qmax;
1629626f
FB
2237 video_enc->max_qdiff = video_qdiff;
2238 video_enc->qblur = video_qblur;
2239 video_enc->qcompress = video_qcomp;
2240 video_enc->rc_eq = video_rc_eq;
59b571c1 2241 video_enc->debug= debug;
ac2830ec
MN
2242
2243 p= video_rc_override_string;
2244 for(i=0; p; i++){
2245 int start, end, q;
2246 int e=sscanf(p, "%d,%d,%d", &start, &end, &q);
2247 if(e!=3){
2248 fprintf(stderr, "error parsing rc_override\n");
2249 exit(1);
2250 }
2251 video_enc->rc_override=
47e2a6e6
FB
2252 av_realloc(video_enc->rc_override,
2253 sizeof(RcOverride)*(i+1));
ac2830ec
MN
2254 video_enc->rc_override[i].start_frame= start;
2255 video_enc->rc_override[i].end_frame = end;
2256 if(q>0){
2257 video_enc->rc_override[i].qscale= q;
2258 video_enc->rc_override[i].quality_factor= 1.0;
2259 }
2260 else{
2261 video_enc->rc_override[i].qscale= 0;
2262 video_enc->rc_override[i].quality_factor= -q/100.0;
2263 }
2264 p= strchr(p, '/');
2265 if(p) p++;
2266 }
2267 video_enc->rc_override_count=i;
2268
1629626f
FB
2269 video_enc->rc_max_rate = video_rc_max_rate;
2270 video_enc->rc_min_rate = video_rc_min_rate;
2271 video_enc->rc_buffer_size = video_rc_buffer_size;
2272 video_enc->rc_buffer_aggressivity= video_rc_buffer_aggressivity;
ac2830ec 2273 video_enc->rc_initial_cplx= video_rc_initial_cplx;
1629626f
FB
2274 video_enc->i_quant_factor = video_i_qfactor;
2275 video_enc->b_quant_factor = video_b_qfactor;
2276 video_enc->i_quant_offset = video_i_qoffset;
2277 video_enc->b_quant_offset = video_b_qoffset;
2278 video_enc->dct_algo = dct_algo;
2279 video_enc->idct_algo = idct_algo;
f560dd82 2280 video_enc->strict_std_compliance = strict;
1629626f
FB
2281 if(packet_size){
2282 video_enc->rtp_mode= 1;
2283 video_enc->rtp_payload_size= packet_size;
2284 }
9cdd6a24 2285
1629626f 2286 if (do_psnr)
140cb663 2287 video_enc->flags|= CODEC_FLAG_PSNR;
e4986da9 2288
1629626f 2289 video_enc->me_method = me_method;
5abdb4b1 2290
1629626f
FB
2291 /* two pass mode */
2292 if (do_pass) {
2293 if (do_pass == 1) {
2294 video_enc->flags |= CODEC_FLAG_PASS1;
2295 } else {
2296 video_enc->flags |= CODEC_FLAG_PASS2;
2297 }
5abdb4b1 2298 }
cfcf0ffd 2299 }
85f07f22
FB
2300 oc->streams[nb_streams] = st;
2301 nb_streams++;
2302 }
2303
2304 if (use_audio) {
2305 AVCodecContext *audio_enc;
2306
2307 st = av_mallocz(sizeof(AVStream));
2308 if (!st) {
2309 fprintf(stderr, "Could not alloc stream\n");
2310 exit(1);
2311 }
1e491e29 2312 avcodec_get_context_defaults(&st->codec);
1629626f 2313
85f07f22 2314 audio_enc = &st->codec;
85f07f22 2315 audio_enc->codec_type = CODEC_TYPE_AUDIO;
1629626f
FB
2316 if (audio_stream_copy) {
2317 st->stream_copy = 1;
2318 } else {
2319 codec_id = file_oformat->audio_codec;
2320 if (audio_codec_id != CODEC_ID_NONE)
2321 codec_id = audio_codec_id;
2322 audio_enc->codec_id = codec_id;
2323
2324 audio_enc->bit_rate = audio_bit_rate;
2325 audio_enc->sample_rate = audio_sample_rate;
2326 /* For audio codecs other than AC3 we limit */
2327 /* the number of coded channels to stereo */
2328 if (audio_channels > 2 && codec_id != CODEC_ID_AC3) {
2329 audio_enc->channels = 2;
2330 } else
2331 audio_enc->channels = audio_channels;
2332 }
85f07f22
FB
2333 oc->streams[nb_streams] = st;
2334 nb_streams++;
2335 }
2336
2337 oc->nb_streams = nb_streams;
2338
2339 if (!nb_streams) {
919f448d 2340 fprintf(stderr, "No audio or video streams available\n");
85f07f22
FB
2341 exit(1);
2342 }
2343
2344 if (str_title)
79fdaa4c 2345 pstrcpy(oc->title, sizeof(oc->title), str_title);
85f07f22 2346 if (str_author)
79fdaa4c 2347 pstrcpy(oc->author, sizeof(oc->author), str_author);
85f07f22 2348 if (str_copyright)
79fdaa4c 2349 pstrcpy(oc->copyright, sizeof(oc->copyright), str_copyright);
85f07f22 2350 if (str_comment)
79fdaa4c 2351 pstrcpy(oc->comment, sizeof(oc->comment), str_comment);
85f07f22
FB
2352 }
2353
1629626f 2354 output_files[nb_output_files++] = oc;
85f07f22
FB
2355
2356 strcpy(oc->filename, filename);
919f448d
FB
2357
2358 /* check filename in case of an image number is expected */
79fdaa4c
FB
2359 if (oc->oformat->flags & AVFMT_NEEDNUMBER) {
2360 if (filename_number_test(oc->filename) < 0) {
2361 print_error(oc->filename, AVERROR_NUMEXPECTED);
919f448d 2362 exit(1);
79fdaa4c 2363 }
919f448d
FB
2364 }
2365
79fdaa4c 2366 if (!(oc->oformat->flags & AVFMT_NOFILE)) {
85f07f22
FB
2367 /* test if it already exists to avoid loosing precious files */
2368 if (!file_overwrite &&
2369 (strchr(filename, ':') == NULL ||
2370 strstart(filename, "file:", NULL))) {
2371 if (url_exist(filename)) {
2372 int c;
2373
2374 printf("File '%s' already exists. Overwrite ? [y/N] ", filename);
2375 fflush(stdout);
2376 c = getchar();
2377 if (toupper(c) != 'Y') {
2378 fprintf(stderr, "Not overwriting - exiting\n");
2379 exit(1);
2380 }
2381 }
2382 }
2383
2384 /* open the file */
2385 if (url_fopen(&oc->pb, filename, URL_WRONLY) < 0) {
2386 fprintf(stderr, "Could not open '%s'\n", filename);
2387 exit(1);
2388 }
2389 }
2390
817b23ff
FB
2391 memset(ap, 0, sizeof(*ap));
2392 ap->image_format = image_format;
2393 if (av_set_parameters(oc, ap) < 0) {
2394 fprintf(stderr, "%s: Invalid encoding parameters\n",
2395 oc->filename);
2396 exit(1);
2397 }
2398
85f07f22 2399 /* reset some options */
79fdaa4c
FB
2400 file_oformat = NULL;
2401 file_iformat = NULL;
817b23ff 2402 image_format = NULL;
85f07f22
FB
2403 audio_disable = 0;
2404 video_disable = 0;
2405 audio_codec_id = CODEC_ID_NONE;
2406 video_codec_id = CODEC_ID_NONE;
1629626f
FB
2407 audio_stream_copy = 0;
2408 video_stream_copy = 0;
85f07f22
FB
2409}
2410
a38469e1 2411/* prepare dummy protocols for grab */
b29f97d1 2412static void prepare_grab(void)
a38469e1
FB
2413{
2414 int has_video, has_audio, i, j;
2415 AVFormatContext *oc;
2416 AVFormatContext *ic;
79a7c268 2417 AVFormatParameters vp1, *vp = &vp1;
a38469e1 2418 AVFormatParameters ap1, *ap = &ap1;
79a7c268 2419
a38469e1
FB
2420 /* see if audio/video inputs are needed */
2421 has_video = 0;
2422 has_audio = 0;
2423 memset(ap, 0, sizeof(*ap));
79a7c268 2424 memset(vp, 0, sizeof(*vp));
a38469e1
FB
2425 for(j=0;j<nb_output_files;j++) {
2426 oc = output_files[j];
2427 for(i=0;i<oc->nb_streams;i++) {
2428 AVCodecContext *enc = &oc->streams[i]->codec;
2429 switch(enc->codec_type) {
2430 case CODEC_TYPE_AUDIO:
2431 if (enc->sample_rate > ap->sample_rate)
2432 ap->sample_rate = enc->sample_rate;
2433 if (enc->channels > ap->channels)
2434 ap->channels = enc->channels;
2435 has_audio = 1;
2436 break;
2437 case CODEC_TYPE_VIDEO:
79a7c268
FB
2438 if (enc->width > vp->width)
2439 vp->width = enc->width;
2440 if (enc->height > vp->height)
2441 vp->height = enc->height;
14bea432
MN
2442
2443 assert(enc->frame_rate_base == DEFAULT_FRAME_RATE_BASE);
2444 if (enc->frame_rate > vp->frame_rate){
2445 vp->frame_rate = enc->frame_rate;
2446 vp->frame_rate_base = enc->frame_rate_base;
2447 }
a38469e1
FB
2448 has_video = 1;
2449 break;
51bd4565 2450 default:
c04643a2 2451 av_abort();
a38469e1
FB
2452 }
2453 }
2454 }
2455
2456 if (has_video == 0 && has_audio == 0) {
2457 fprintf(stderr, "Output file must have at least one audio or video stream\n");
2458 exit(1);
2459 }
2460
2461 if (has_video) {
79fdaa4c 2462 AVInputFormat *fmt1;
8aa3ee32 2463 fmt1 = av_find_input_format(video_grab_format);
a5df11ab
FB
2464 vp->device = video_device;
2465 vp->channel = video_channel;
e3ee3283 2466 vp->standard = video_standard;
79a7c268 2467 if (av_open_input_file(&ic, "", fmt1, 0, vp) < 0) {
bf5af568 2468 fprintf(stderr, "Could not find video grab device\n");
a38469e1
FB
2469 exit(1);
2470 }
79fdaa4c 2471 /* by now video grab has one stream */
14bea432
MN
2472 ic->streams[0]->r_frame_rate = vp->frame_rate;
2473 ic->streams[0]->r_frame_rate_base = vp->frame_rate_base;
a38469e1 2474 input_files[nb_input_files] = ic;
79a7c268 2475 dump_format(ic, nb_input_files, "", 0);
a38469e1
FB
2476 nb_input_files++;
2477 }
1501987b 2478 if (has_audio && audio_grab_format) {
79fdaa4c 2479 AVInputFormat *fmt1;
8aa3ee32 2480 fmt1 = av_find_input_format(audio_grab_format);
79a7c268 2481 ap->device = audio_device;
79fdaa4c 2482 if (av_open_input_file(&ic, "", fmt1, 0, ap) < 0) {
bf5af568 2483 fprintf(stderr, "Could not find audio grab device\n");
a38469e1
FB
2484 exit(1);
2485 }
2486 input_files[nb_input_files] = ic;
79a7c268 2487 dump_format(ic, nb_input_files, "", 0);
a38469e1
FB
2488 nb_input_files++;
2489 }
2490}
2491
5abdb4b1 2492/* same option as mencoder */
b29f97d1 2493static void opt_pass(const char *pass_str)
5abdb4b1
FB
2494{
2495 int pass;
2496 pass = atoi(pass_str);
2497 if (pass != 1 && pass != 2) {
2498 fprintf(stderr, "pass number can be only 1 or 2\n");
2499 exit(1);
2500 }
2501 do_pass = pass;
2502}
a38469e1 2503
f3ec2d46 2504#if defined(CONFIG_WIN32) || defined(CONFIG_OS2)
0c1a9eda 2505static int64_t getutime(void)
5727b222 2506{
f3ec2d46 2507 return av_gettime();
5727b222 2508}
bdc4796f 2509#else
0c1a9eda 2510static int64_t getutime(void)
bdc4796f 2511{
f3ec2d46
SG
2512 struct rusage rusage;
2513
2514 getrusage(RUSAGE_SELF, &rusage);
2515 return (rusage.ru_utime.tv_sec * 1000000LL) + rusage.ru_utime.tv_usec;
bdc4796f
FB
2516}
2517#endif
5727b222 2518
79fdaa4c
FB
2519extern int ffm_nopts;
2520
b29f97d1 2521static void opt_bitexact(void)
79fdaa4c 2522{
b0368839 2523 bitexact=1;
79fdaa4c
FB
2524 /* disable generate of real time pts in ffm (need to be supressed anyway) */
2525 ffm_nopts = 1;
2526}
2527
b29f97d1 2528static void show_formats(void)
85f07f22 2529{
79fdaa4c
FB
2530 AVInputFormat *ifmt;
2531 AVOutputFormat *ofmt;
817b23ff 2532 AVImageFormat *image_fmt;
85f07f22
FB
2533 URLProtocol *up;
2534 AVCodec *p;
2535 const char **pp;
2536
817b23ff 2537 printf("Output audio/video file formats:");
79fdaa4c
FB
2538 for(ofmt = first_oformat; ofmt != NULL; ofmt = ofmt->next) {
2539 printf(" %s", ofmt->name);
85f07f22
FB
2540 }
2541 printf("\n");
817b23ff
FB
2542
2543 printf("Input audio/video file formats:");
79fdaa4c
FB
2544 for(ifmt = first_iformat; ifmt != NULL; ifmt = ifmt->next) {
2545 printf(" %s", ifmt->name);
85f07f22
FB
2546 }
2547 printf("\n");
2548
817b23ff
FB
2549 printf("Output image formats:");
2550 for(image_fmt = first_image_format; image_fmt != NULL;
2551 image_fmt = image_fmt->next) {
2552 if (image_fmt->img_write)
2553 printf(" %s", image_fmt->name);
2554 }
2555 printf("\n");
2556
2557 printf("Input image formats:");
2558 for(image_fmt = first_image_format; image_fmt != NULL;
2559 image_fmt = image_fmt->next) {
2560 if (image_fmt->img_read)
2561 printf(" %s", image_fmt->name);
2562 }
2563 printf("\n");
2564
85f07f22
FB
2565 printf("Codecs:\n");
2566 printf(" Encoders:");
2567 for(p = first_avcodec; p != NULL; p = p->next) {
2568 if (p->encode)
2569 printf(" %s", p->name);
2570 }
2571 printf("\n");
2572
2573 printf(" Decoders:");
2574 for(p = first_avcodec; p != NULL; p = p->next) {
2575 if (p->decode)
2576 printf(" %s", p->name);
2577 }
2578 printf("\n");
2579
2580 printf("Supported file protocols:");
2581 for(up = first_protocol; up != NULL; up = up->next)
2582 printf(" %s:", up->name);
2583 printf("\n");
2584
2585 printf("Frame size abbreviations: sqcif qcif cif 4cif\n");
2586 printf("Motion estimation methods:");
2587 pp = motion_str;
2588 while (*pp) {
2589 printf(" %s", *pp);
101bea5f 2590 if ((pp - motion_str + 1) == ME_ZERO)
85f07f22 2591 printf("(fastest)");
101bea5f 2592 else if ((pp - motion_str + 1) == ME_FULL)
85f07f22 2593 printf("(slowest)");
101bea5f 2594 else if ((pp - motion_str + 1) == ME_EPZS)
85f07f22
FB
2595 printf("(default)");
2596 pp++;
2597 }
2598 printf("\n");
2599 exit(1);
2600}
2601
85f07f22 2602const OptionDef options[] = {
bdc4796f
FB
2603 { "L", 0, {(void*)show_licence}, "show license" },
2604 { "h", 0, {(void*)show_help}, "show help" },
2605 { "formats", 0, {(void*)show_formats}, "show available formats, codecs, protocols, ..." },
2606 { "f", HAS_ARG, {(void*)opt_format}, "force format", "fmt" },
817b23ff 2607 { "img", HAS_ARG, {(void*)opt_image_format}, "force image format", "img_fmt" },
bdc4796f
FB
2608 { "i", HAS_ARG, {(void*)opt_input_file}, "input file name", "filename" },
2609 { "y", OPT_BOOL, {(void*)&file_overwrite}, "overwrite output files" },
2610 { "map", HAS_ARG | OPT_EXPERT, {(void*)opt_map}, "set input stream mapping", "file:stream" },
2611 { "t", HAS_ARG, {(void*)opt_recording_time}, "set the recording time", "duration" },
2612 { "title", HAS_ARG | OPT_STRING, {(void*)&str_title}, "set the title", "string" },
2613 { "author", HAS_ARG | OPT_STRING, {(void*)&str_author}, "set the author", "string" },
2614 { "copyright", HAS_ARG | OPT_STRING, {(void*)&str_copyright}, "set the copyright", "string" },
2615 { "comment", HAS_ARG | OPT_STRING, {(void*)&str_comment}, "set the comment", "string" },
5abdb4b1
FB
2616 { "pass", HAS_ARG, {(void*)&opt_pass}, "select the pass number (1 or 2)", "n" },
2617 { "passlogfile", HAS_ARG | OPT_STRING, {(void*)&pass_logfilename}, "select two pass log file name", "file" },
85f07f22 2618 /* video options */
bdc4796f
FB
2619 { "b", HAS_ARG, {(void*)opt_video_bitrate}, "set video bitrate (in kbit/s)", "bitrate" },
2620 { "r", HAS_ARG, {(void*)opt_frame_rate}, "set frame rate (in Hz)", "rate" },
bdfcbbed 2621 { "re", OPT_BOOL|OPT_EXPERT, {(void*)&rate_emu}, "read input at native frame rate" },
bdc4796f 2622 { "s", HAS_ARG, {(void*)opt_frame_size}, "set frame size (WxH or abbreviation)", "size" },
5fe03e38 2623 { "aspect", HAS_ARG, {(void*)opt_frame_aspect_ratio}, "set aspect ratio (4:3, 16:9 or 1.3333, 1.7777)", "aspect" },
63167088 2624 { "pix_fmt", HAS_ARG | OPT_EXPERT, {(void*)opt_frame_pix_fmt}, "set pixel format", "format" },
ab6d194a
MN
2625 { "croptop", HAS_ARG, {(void*)opt_frame_crop_top}, "set top crop band size (in pixels)", "size" },
2626 { "cropbottom", HAS_ARG, {(void*)opt_frame_crop_bottom}, "set bottom crop band size (in pixels)", "size" },
2627 { "cropleft", HAS_ARG, {(void*)opt_frame_crop_left}, "set left crop band size (in pixels)", "size" },
2628 { "cropright", HAS_ARG, {(void*)opt_frame_crop_right}, "set right crop band size (in pixels)", "size" },
bdc4796f
FB
2629 { "g", HAS_ARG | OPT_EXPERT, {(void*)opt_gop_size}, "set the group of picture size", "gop_size" },
2630 { "intra", OPT_BOOL | OPT_EXPERT, {(void*)&intra_only}, "use only intra frames"},
2631 { "vn", OPT_BOOL, {(void*)&video_disable}, "disable video" },
2632 { "qscale", HAS_ARG | OPT_EXPERT, {(void*)opt_qscale}, "use fixed video quantiser scale (VBR)", "q" },
9cdd6a24
MN
2633 { "qmin", HAS_ARG | OPT_EXPERT, {(void*)opt_qmin}, "min video quantiser scale (VBR)", "q" },
2634 { "qmax", HAS_ARG | OPT_EXPERT, {(void*)opt_qmax}, "max video quantiser scale (VBR)", "q" },
17a70fde
MN
2635 { "mbqmin", HAS_ARG | OPT_EXPERT, {(void*)opt_mb_qmin}, "min macroblock quantiser scale (VBR)", "q" },
2636 { "mbqmax", HAS_ARG | OPT_EXPERT, {(void*)opt_mb_qmax}, "max macroblock quantiser scale (VBR)", "q" },
9cdd6a24
MN
2637 { "qdiff", HAS_ARG | OPT_EXPERT, {(void*)opt_qdiff}, "max difference between the quantiser scale (VBR)", "q" },
2638 { "qblur", HAS_ARG | OPT_EXPERT, {(void*)opt_qblur}, "video quantiser scale blur (VBR)", "blur" },
2639 { "qcomp", HAS_ARG | OPT_EXPERT, {(void*)opt_qcomp}, "video quantiser scale compression (VBR)", "compression" },
ac2830ec 2640 { "rc_init_cplx", HAS_ARG | OPT_EXPERT, {(void*)opt_rc_initial_cplx}, "initial complexity for 1-pass encoding", "complexity" },
29700fa6
MN
2641 { "b_qfactor", HAS_ARG | OPT_EXPERT, {(void*)opt_b_qfactor}, "qp factor between p and b frames", "factor" },
2642 { "i_qfactor", HAS_ARG | OPT_EXPERT, {(void*)opt_i_qfactor}, "qp factor between p and i frames", "factor" },
2643 { "b_qoffset", HAS_ARG | OPT_EXPERT, {(void*)opt_b_qoffset}, "qp offset between p and b frames", "offset" },
2644 { "i_qoffset", HAS_ARG | OPT_EXPERT, {(void*)opt_i_qoffset}, "qp offset between p and i frames", "offset" },
59b571c1 2645// { "b_strategy", HAS_ARG | OPT_EXPERT, {(void*)opt_b_strategy}, "dynamic b frame selection strategy", "strategy" },
3aa102be 2646 { "rc_eq", HAS_ARG | OPT_EXPERT, {(void*)opt_video_rc_eq}, "", "equation" },
ac2830ec 2647 { "rc_override", HAS_ARG | OPT_EXPERT, {(void*)opt_video_rc_override_string}, "Rate control override", "qualities for specific intervals" },
9cdd6a24 2648 { "bt", HAS_ARG, {(void*)opt_video_bitrate_tolerance}, "set video bitrate tolerance (in kbit/s)", "tolerance" },
3aa102be
MN
2649 { "maxrate", HAS_ARG, {(void*)opt_video_bitrate_max}, "set max video bitrate tolerance (in kbit/s)", "bitrate" },
2650 { "minrate", HAS_ARG, {(void*)opt_video_bitrate_min}, "set min video bitrate tolerance (in kbit/s)", "bitrate" },
946c8a12 2651 { "bufsize", HAS_ARG, {(void*)opt_video_buffer_size}, "set ratecontrol buffere size (in kbit)", "size" },
bf5af568 2652 { "vd", HAS_ARG | OPT_EXPERT, {(void*)opt_video_device}, "set video grab device", "device" },
a5df11ab 2653 { "vc", HAS_ARG | OPT_EXPERT, {(void*)opt_video_channel}, "set video grab channel (DV1394 only)", "channel" },
e3ee3283 2654 { "tvstd", HAS_ARG | OPT_EXPERT, {(void*)opt_video_standard}, "set television standard (NTSC, PAL (SECAM))", "standard" },
79a7c268 2655 { "dv1394", OPT_EXPERT, {(void*)opt_dv1394}, "set DV1394 grab", "" },
1629626f 2656 { "vcodec", HAS_ARG | OPT_EXPERT, {(void*)opt_video_codec}, "force video codec ('copy' to copy stream)", "codec" },
bdc4796f 2657 { "me", HAS_ARG | OPT_EXPERT, {(void*)opt_motion_estimation}, "set motion estimation method",
85f07f22 2658 "method" },
463678ac 2659 { "dct_algo", HAS_ARG | OPT_EXPERT, {(void*)opt_dct_algo}, "set dct algo", "algo" },
2ad1516a 2660 { "idct_algo", HAS_ARG | OPT_EXPERT, {(void*)opt_idct_algo}, "set idct algo", "algo" },
8409b8fe 2661 { "er", HAS_ARG | OPT_EXPERT, {(void*)opt_error_resilience}, "set error resilience", "" },
59b571c1 2662 { "ec", HAS_ARG | OPT_EXPERT, {(void*)opt_error_concealment}, "set error concealment", "" },
bc6caae2 2663 { "bf", HAS_ARG | OPT_EXPERT, {(void*)opt_b_frames}, "use 'frames' B frames (only MPEG-4)", "frames" },
e4986da9 2664 { "hq", OPT_BOOL | OPT_EXPERT, {(void*)&use_hq}, "activate high quality settings" },
29da453b 2665 { "4mv", OPT_BOOL | OPT_EXPERT, {(void*)&use_4mv}, "use four motion vector by macroblock (only MPEG-4)" },
1dbb6d90 2666 { "part", OPT_BOOL | OPT_EXPERT, {(void*)&use_part}, "use data partitioning (only MPEG-4)" },
fe670d09 2667 { "bug", HAS_ARG | OPT_EXPERT, {(void*)opt_workaround_bugs}, "workaround not auto detected encoder bugs", "param" },
1dbb6d90 2668 { "ps", HAS_ARG | OPT_EXPERT, {(void*)opt_packet_size}, "packet size", "size in bits" },
f560dd82 2669 { "strict", HAS_ARG | OPT_EXPERT, {(void*)opt_strict}, "strictness", "how strictly to follow the standarts" },
bdc4796f 2670 { "sameq", OPT_BOOL, {(void*)&same_quality},
85f07f22 2671 "use same video quality as source (implies VBR)" },
1d366fce 2672 { "debug", HAS_ARG | OPT_EXPERT, {(void*)opt_debug}, "print specific debug info", "" },
85f07f22 2673 /* audio options */
bdc4796f
FB
2674 { "ab", HAS_ARG, {(void*)opt_audio_bitrate}, "set audio bitrate (in kbit/s)", "bitrate", },
2675 { "ar", HAS_ARG, {(void*)opt_audio_rate}, "set audio sampling rate (in Hz)", "rate" },
2676 { "ac", HAS_ARG, {(void*)opt_audio_channels}, "set number of audio channels", "channels" },
2677 { "an", OPT_BOOL, {(void*)&audio_disable}, "disable audio" },
bdc4796f 2678 { "ad", HAS_ARG | OPT_EXPERT, {(void*)opt_audio_device}, "set audio device", "device" },
1629626f 2679 { "acodec", HAS_ARG | OPT_EXPERT, {(void*)opt_audio_codec}, "force audio codec ('copy' to copy stream)", "codec" },
bdc4796f 2680 { "deinterlace", OPT_BOOL | OPT_EXPERT, {(void*)&do_deinterlace},
cfcf0ffd 2681 "deinterlace pictures" },
bdc4796f 2682 { "benchmark", OPT_BOOL | OPT_EXPERT, {(void*)&do_benchmark},
5727b222 2683 "add timings for benchmarking" },
a0663ba4
FB
2684 { "hex", OPT_BOOL | OPT_EXPERT, {(void*)&do_hex_dump},
2685 "dump each input packet" },
ce7c56c2
J
2686 { "psnr", OPT_BOOL | OPT_EXPERT, {(void*)&do_psnr}, "calculate PSNR of compressed frames" },
2687 { "vstats", OPT_BOOL | OPT_EXPERT, {(void*)&do_vstats}, "dump video coding statistics to file" },
79fdaa4c 2688 { "bitexact", OPT_EXPERT, {(void*)opt_bitexact}, "only use bit exact algorithms (for codec testing)" },
10d104e4 2689 { "vhook", HAS_ARG | OPT_EXPERT, {(void*)add_frame_hooker}, "insert video processing module", "module name and parameters" },
21e59552
MN
2690 /* Fx */
2691 { "aic", OPT_BOOL | OPT_EXPERT, {(void*)&use_aic}, "enable Advanced intra coding (h263+)" },
2692 { "umv", OPT_BOOL | OPT_EXPERT, {(void*)&use_umv}, "enable Unlimited Motion Vector (h263+)" },
2693 /* /Fx */
85f07f22
FB
2694 { NULL, },
2695};
2696
01310af2
FB
2697void show_help(void)
2698{
2699 printf("ffmpeg version " FFMPEG_VERSION ", Copyright (c) 2000, 2001, 2002 Fabrice Bellard\n");
2700 printf("usage: ffmpeg [[options] -i input_file]... {[options] outfile}...\n"
2701 "Hyper fast Audio and Video encoder\n");
2702 printf("\n");
2703 show_help_options(options);
2704 exit(1);
2705}
2706
2707void parse_arg_file(const char *filename)
2708{
2709 opt_output_file(filename);
2710}
2711
85f07f22
FB
2712int main(int argc, char **argv)
2713{
01310af2 2714 int i;
0c1a9eda 2715 int64_t ti;
63b15e55 2716
2c4ae653 2717 av_register_all();
85f07f22
FB
2718
2719 if (argc <= 1)
2720 show_help();
a38469e1
FB
2721
2722 /* parse options */
01310af2 2723 parse_options(argc, argv, options);
85f07f22 2724
01310af2
FB
2725 /* file converter / grab */
2726 if (nb_output_files <= 0) {
2727 fprintf(stderr, "Must supply at least one output file\n");
2728 exit(1);
2729 }
2730
2731 if (nb_input_files == 0) {
2732 prepare_grab();
a38469e1
FB
2733 }
2734
2735 ti = getutime();
2736 av_encode(output_files, nb_output_files, input_files, nb_input_files,
2737 stream_maps, nb_stream_maps);
2738 ti = getutime() - ti;
2739 if (do_benchmark) {
2740 printf("bench: utime=%0.3fs\n", ti / 1000000.0);
85f07f22
FB
2741 }
2742
2743 /* close files */
2744 for(i=0;i<nb_output_files;i++) {
4fca59f2
ZK
2745 /* maybe av_close_output_file ??? */
2746 AVFormatContext *s = output_files[i];
2747 int j;
2748 if (!(s->oformat->flags & AVFMT_NOFILE))
2749 url_fclose(&s->pb);
2750 for(j=0;j<s->nb_streams;j++)
2751 av_free(s->streams[j]);
2752 av_free(s);
85f07f22 2753 }
79fdaa4c
FB
2754 for(i=0;i<nb_input_files;i++)
2755 av_close_input_file(input_files[i]);
85f07f22 2756
855ea723 2757 av_free_static();
db40a39a
MN
2758
2759
e45a2872 2760#ifdef POWERPC_PERFORMANCE_REPORT
35e5fb06
RD
2761 extern void powerpc_display_perf_report(void);
2762 powerpc_display_perf_report();
e45a2872 2763#endif /* POWERPC_PERFORMANCE_REPORT */
db40a39a 2764
9680a722
RP
2765#ifndef CONFIG_WIN32
2766 if (received_sigterm) {
2767 fprintf(stderr,
2768 "Received signal %d: terminating.\n",
2769 (int) received_sigterm);
2770 exit (255);
2771 }
2772#endif
2773 exit(0); /* not all OS-es handle main() return value */
85f07f22
FB
2774 return 0;
2775}