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