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