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