parsing resync header extension support
[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
FB
19#define HAVE_AV_CONFIG_H
20#include "avformat.h"
6dc96cb0 21#include "tick.h"
daf8e955 22
bdc4796f 23#ifndef CONFIG_WIN32
85f07f22
FB
24#include <unistd.h>
25#include <fcntl.h>
26#include <sys/ioctl.h>
85f07f22 27#include <sys/time.h>
85f07f22 28#include <termios.h>
5727b222 29#include <sys/resource.h>
bdc4796f 30#endif
27a5e8b8
FR
31#ifdef __BEOS__
32/* for snooze() */
33#include <OS.h>
34#endif
bf5af568
FB
35#include <time.h>
36#include <ctype.h>
85f07f22 37
85f07f22 38
bdc4796f
FB
39#define MAXINT64 INT64_C(0x7fffffffffffffff)
40
85f07f22
FB
41typedef struct {
42 const char *name;
43 int flags;
44#define HAS_ARG 0x0001
45#define OPT_BOOL 0x0002
46#define OPT_EXPERT 0x0004
47#define OPT_STRING 0x0008
48 union {
49 void (*func_arg)();
50 int *int_arg;
51 char **str_arg;
52 } u;
53 const char *help;
54 const char *argname;
55} OptionDef;
56
57/* select an input stream for an output stream */
58typedef struct AVStreamMap {
59 int file_index;
60 int stream_index;
61} AVStreamMap;
62
63extern const OptionDef options[];
64
65void show_help(void);
66
67#define MAX_FILES 20
68
69static AVFormatContext *input_files[MAX_FILES];
70static int nb_input_files = 0;
71
72static AVFormatContext *output_files[MAX_FILES];
73static int nb_output_files = 0;
74
75static AVStreamMap stream_maps[MAX_FILES];
76static int nb_stream_maps;
77
79fdaa4c
FB
78static AVInputFormat *file_iformat;
79static AVOutputFormat *file_oformat;
85f07f22
FB
80static int frame_width = 160;
81static int frame_height = 128;
ab6d194a
MN
82static int frame_topBand = 0;
83static int frame_bottomBand = 0;
84static int frame_leftBand = 0;
85static int frame_rightBand = 0;
85f07f22 86static int frame_rate = 25 * FRAME_RATE_BASE;
3aa102be
MN
87static int video_bit_rate = 200*1000;
88static int video_bit_rate_tolerance = 4000*1000;
85f07f22 89static int video_qscale = 0;
3aa102be
MN
90static int video_qmin = 2;
91static int video_qmax = 31;
9cdd6a24
MN
92static int video_qdiff = 3;
93static float video_qblur = 0.5;
94static float video_qcomp = 0.5;
3aa102be
MN
95static float video_rc_qsquish=1.0;
96static float video_rc_qmod_amp=0;
97static int video_rc_qmod_freq=0;
98static char *video_rc_override_string=NULL;
99static char *video_rc_eq="tex^qComp";
100static int video_rc_buffer_size=0;
101static float video_rc_buffer_aggressivity=1.0;
102static int video_rc_max_rate=0;
103static int video_rc_min_rate=0;
104static float video_rc_initial_cplx=0;
105static float video_b_qfactor = 1.25;
106static float video_b_qoffset = 1.25;
107static float video_i_qfactor = 0.8;
108static float video_i_qoffset = 0.0;
101bea5f 109static int me_method = 0;
85f07f22
FB
110static int video_disable = 0;
111static int video_codec_id = CODEC_ID_NONE;
112static int same_quality = 0;
bc6caae2 113static int b_frames = 0;
e4986da9 114static int use_hq = 0;
29da453b 115static int use_4mv = 0;
cfcf0ffd 116static int do_deinterlace = 0;
fe670d09 117static int workaround_bugs = 0;
463678ac 118static int dct_algo = 0;
85f07f22
FB
119
120static int gop_size = 12;
121static int intra_only = 0;
122static int audio_sample_rate = 44100;
123static int audio_bit_rate = 64000;
124static int audio_disable = 0;
125static int audio_channels = 1;
126static int audio_codec_id = CODEC_ID_NONE;
127
128static INT64 recording_time = 0;
129static int file_overwrite = 0;
130static char *str_title = NULL;
131static char *str_author = NULL;
132static char *str_copyright = NULL;
133static char *str_comment = NULL;
5727b222 134static int do_benchmark = 0;
a0663ba4 135static int do_hex_dump = 0;
a38469e1 136static int do_play = 0;
43f1708f 137static int do_psnr = 0;
ce7c56c2 138static int do_vstats = 0;
0b97443a 139static int mpeg_vcd = 0;
85f07f22 140
bf5af568
FB
141#ifndef CONFIG_AUDIO_OSS
142const char *audio_device = "none";
143#endif
144#ifndef CONFIG_VIDEO4LINUX
145const char *v4l_device = "none";
146#endif
147
85f07f22
FB
148typedef struct AVOutputStream {
149 int file_index; /* file index */
150 int index; /* stream index in the output file */
151 int source_index; /* AVInputStream index */
152 AVStream *st; /* stream in the output file */
153 int encoding_needed; /* true if encoding needed for this stream */
154
85f07f22
FB
155 /* video only */
156 AVPicture pict_tmp; /* temporary image for resizing */
157 int video_resample;
158 ImgReSampleContext *img_resample_ctx; /* for image resampling */
159
160 /* audio only */
161 int audio_resample;
162 ReSampleContext *resample; /* for audio resampling */
163 FifoBuffer fifo; /* for compression: one audio fifo per codec */
164} AVOutputStream;
165
166typedef struct AVInputStream {
167 int file_index;
168 int index;
169 AVStream *st;
170 int discard; /* true if stream data should be discarded */
171 int decoding_needed; /* true if the packets must be decoded in 'raw_fifo' */
6dc96cb0
J
172 Ticker pts_ticker; /* Ticker for PTS calculation */
173 int ticker_inited; /* to signal if the ticker was initialized */
85f07f22 174 INT64 pts; /* current pts */
51bd4565 175 int pts_increment; /* expected pts increment for next packet */
85f07f22
FB
176 int frame_number; /* current frame */
177 INT64 sample_index; /* current sample */
178} AVInputStream;
179
180typedef struct AVInputFile {
181 int eof_reached; /* true if eof reached */
182 int ist_index; /* index of first stream in ist_table */
183 int buffer_size; /* current total buffer size */
184 int buffer_size_max; /* buffer size at which we consider we can stop
185 buffering */
79fdaa4c 186 int nb_streams; /* nb streams we are aware of */
85f07f22
FB
187} AVInputFile;
188
bdc4796f
FB
189#ifndef CONFIG_WIN32
190
85f07f22
FB
191/* init terminal so that we can grab keys */
192static struct termios oldtty;
193
194static void term_exit(void)
195{
196 tcsetattr (0, TCSANOW, &oldtty);
197}
198
199static void term_init(void)
200{
201 struct termios tty;
202
203 tcgetattr (0, &tty);
204 oldtty = tty;
205
206 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
207 |INLCR|IGNCR|ICRNL|IXON);
208 tty.c_oflag |= OPOST;
209 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
210 tty.c_cflag &= ~(CSIZE|PARENB);
211 tty.c_cflag |= CS8;
212 tty.c_cc[VMIN] = 1;
213 tty.c_cc[VTIME] = 0;
214
215 tcsetattr (0, TCSANOW, &tty);
216
217 atexit(term_exit);
218}
219
220/* read a key without blocking */
221static int read_key(void)
222{
223 struct timeval tv;
224 int n;
225 unsigned char ch;
226 fd_set rfds;
227
228 FD_ZERO(&rfds);
229 FD_SET(0, &rfds);
230 tv.tv_sec = 0;
231 tv.tv_usec = 0;
232 n = select(1, &rfds, NULL, NULL, &tv);
233 if (n > 0) {
cb09b2ed
PG
234 n = read(0, &ch, 1);
235 if (n == 1)
85f07f22 236 return ch;
cb09b2ed
PG
237
238 return n;
85f07f22
FB
239 }
240 return -1;
241}
242
a38469e1 243#else
85f07f22 244
a38469e1
FB
245/* no interactive support */
246static void term_exit(void)
85f07f22 247{
a38469e1 248}
85f07f22 249
a38469e1
FB
250static void term_init(void)
251{
252}
85f07f22 253
a38469e1
FB
254static int read_key(void)
255{
cb09b2ed 256 return 0;
85f07f22
FB
257}
258
a38469e1 259#endif
bdc4796f 260
85f07f22
FB
261int read_ffserver_streams(AVFormatContext *s, const char *filename)
262{
79fdaa4c 263 int i, err;
85f07f22
FB
264 AVFormatContext *ic;
265
79fdaa4c
FB
266 err = av_open_input_file(&ic, filename, NULL, FFM_PACKET_SIZE, NULL);
267 if (err < 0)
268 return err;
85f07f22
FB
269 /* copy stream format */
270 s->nb_streams = ic->nb_streams;
271 for(i=0;i<ic->nb_streams;i++) {
272 AVStream *st;
273 st = av_mallocz(sizeof(AVFormatContext));
274 memcpy(st, ic->streams[i], sizeof(AVStream));
275 s->streams[i] = st;
276 }
277
278 av_close_input_file(ic);
279 return 0;
280}
281
282#define MAX_AUDIO_PACKET_SIZE 16384
283
284static void do_audio_out(AVFormatContext *s,
285 AVOutputStream *ost,
286 AVInputStream *ist,
287 unsigned char *buf, int size)
288{
289 UINT8 *buftmp;
290 UINT8 audio_buf[2*MAX_AUDIO_PACKET_SIZE]; /* XXX: allocate it */
291 UINT8 audio_out[MAX_AUDIO_PACKET_SIZE]; /* XXX: allocate it */
292 int size_out, frame_bytes, ret;
293 AVCodecContext *enc;
294
295 enc = &ost->st->codec;
296
297 if (ost->audio_resample) {
298 buftmp = audio_buf;
299 size_out = audio_resample(ost->resample,
300 (short *)buftmp, (short *)buf,
301 size / (ist->st->codec.channels * 2));
302 size_out = size_out * enc->channels * 2;
303 } else {
304 buftmp = buf;
305 size_out = size;
306 }
307
308 /* now encode as many frames as possible */
a0663ba4 309 if (enc->frame_size > 1) {
85f07f22
FB
310 /* output resampled raw samples */
311 fifo_write(&ost->fifo, buftmp, size_out,
312 &ost->fifo.wptr);
313
314 frame_bytes = enc->frame_size * 2 * enc->channels;
315
316 while (fifo_read(&ost->fifo, audio_buf, frame_bytes,
317 &ost->fifo.rptr) == 0) {
a0663ba4
FB
318 ret = avcodec_encode_audio(enc, audio_out, sizeof(audio_out),
319 (short *)audio_buf);
79fdaa4c 320 s->oformat->write_packet(s, ost->index, audio_out, ret, 0);
85f07f22
FB
321 }
322 } else {
a0663ba4
FB
323 /* output a pcm frame */
324 /* XXX: change encoding codec API to avoid this ? */
325 switch(enc->codec->id) {
326 case CODEC_ID_PCM_S16LE:
327 case CODEC_ID_PCM_S16BE:
328 case CODEC_ID_PCM_U16LE:
329 case CODEC_ID_PCM_U16BE:
330 break;
331 default:
332 size_out = size_out >> 1;
333 break;
334 }
335 ret = avcodec_encode_audio(enc, audio_out, size_out,
336 (short *)buftmp);
79fdaa4c 337 s->oformat->write_packet(s, ost->index, audio_out, ret, 0);
85f07f22
FB
338 }
339}
340
341/* write a picture to a raw mux */
cfcf0ffd
FB
342static void write_picture(AVFormatContext *s, int index, AVPicture *picture,
343 int pix_fmt, int w, int h)
85f07f22
FB
344{
345 UINT8 *buf, *src, *dest;
346 int size, j, i;
cfcf0ffd 347
85f07f22
FB
348 /* XXX: not efficient, should add test if we can take
349 directly the AVPicture */
cfcf0ffd
FB
350 switch(pix_fmt) {
351 case PIX_FMT_YUV420P:
5b0ad91b 352 size = avpicture_get_size(pix_fmt, w, h);
0f1578af 353 buf = av_malloc(size);
5b0ad91b
J
354 if (!buf)
355 return;
cfcf0ffd
FB
356 dest = buf;
357 for(i=0;i<3;i++) {
358 if (i == 1) {
359 w >>= 1;
360 h >>= 1;
361 }
362 src = picture->data[i];
363 for(j=0;j<h;j++) {
364 memcpy(dest, src, w);
365 dest += w;
366 src += picture->linesize[i];
367 }
368 }
369 break;
370 case PIX_FMT_YUV422P:
371 size = (w * h) * 2;
0f1578af 372 buf = av_malloc(size);
5b0ad91b
J
373 if (!buf)
374 return;
cfcf0ffd
FB
375 dest = buf;
376 for(i=0;i<3;i++) {
377 if (i == 1) {
378 w >>= 1;
379 }
380 src = picture->data[i];
381 for(j=0;j<h;j++) {
382 memcpy(dest, src, w);
383 dest += w;
384 src += picture->linesize[i];
385 }
386 }
387 break;
388 case PIX_FMT_YUV444P:
389 size = (w * h) * 3;
0f1578af 390 buf = av_malloc(size);
5b0ad91b
J
391 if (!buf)
392 return;
cfcf0ffd
FB
393 dest = buf;
394 for(i=0;i<3;i++) {
395 src = picture->data[i];
396 for(j=0;j<h;j++) {
397 memcpy(dest, src, w);
398 dest += w;
399 src += picture->linesize[i];
400 }
401 }
402 break;
403 case PIX_FMT_YUV422:
404 size = (w * h) * 2;
0f1578af 405 buf = av_malloc(size);
5b0ad91b
J
406 if (!buf)
407 return;
cfcf0ffd
FB
408 dest = buf;
409 src = picture->data[0];
410 for(j=0;j<h;j++) {
411 memcpy(dest, src, w * 2);
412 dest += w * 2;
413 src += picture->linesize[0];
85f07f22 414 }
cfcf0ffd
FB
415 break;
416 case PIX_FMT_RGB24:
417 case PIX_FMT_BGR24:
418 size = (w * h) * 3;
0f1578af 419 buf = av_malloc(size);
5b0ad91b
J
420 if (!buf)
421 return;
cfcf0ffd
FB
422 dest = buf;
423 src = picture->data[0];
85f07f22 424 for(j=0;j<h;j++) {
cfcf0ffd
FB
425 memcpy(dest, src, w * 3);
426 dest += w * 3;
427 src += picture->linesize[0];
85f07f22 428 }
cfcf0ffd
FB
429 break;
430 default:
431 return;
85f07f22 432 }
79fdaa4c 433 s->oformat->write_packet(s, index, buf, size, 0);
0f1578af 434 av_free(buf);
85f07f22
FB
435}
436
437
438static void do_video_out(AVFormatContext *s,
439 AVOutputStream *ost,
440 AVInputStream *ist,
ce7c56c2
J
441 AVPicture *picture1,
442 int *frame_size)
85f07f22 443{
6dc96cb0 444 int n1, n2, nb, i, ret, frame_number, dec_frame_rate;
cfcf0ffd
FB
445 AVPicture *picture, *picture2, *pict;
446 AVPicture picture_tmp1, picture_tmp2;
cb09b2ed 447 static UINT8 *video_buffer;
cfcf0ffd
FB
448 UINT8 *buf = NULL, *buf1 = NULL;
449 AVCodecContext *enc, *dec;
85f07f22 450
33a1f1a3 451#define VIDEO_BUFFER_SIZE (1024*1024)
33a1f1a3 452
85f07f22 453 enc = &ost->st->codec;
cfcf0ffd 454 dec = &ist->st->codec;
85f07f22
FB
455
456 frame_number = ist->frame_number;
6dc96cb0 457 dec_frame_rate = ist->st->r_frame_rate;
79fdaa4c 458 // fprintf(stderr, "\n%d", dec_frame_rate);
85f07f22 459 /* first drop frame if needed */
6dc96cb0
J
460 n1 = ((INT64)frame_number * enc->frame_rate) / dec_frame_rate;
461 n2 = (((INT64)frame_number + 1) * enc->frame_rate) / dec_frame_rate;
85f07f22 462 nb = n2 - n1;
ce7c56c2 463 if (nb <= 0)
85f07f22 464 return;
ce7c56c2 465
cb09b2ed
PG
466 if (!video_buffer)
467 video_buffer= av_malloc(VIDEO_BUFFER_SIZE);
c04643a2
PG
468 if(!video_buffer) return;
469
cfcf0ffd
FB
470 /* deinterlace : must be done before any resize */
471 if (do_deinterlace) {
472 int size;
473
474 /* create temporary picture */
475 size = avpicture_get_size(dec->pix_fmt, dec->width, dec->height);
0f1578af 476 buf1 = av_malloc(size);
cfcf0ffd
FB
477 if (!buf1)
478 return;
479
480 picture2 = &picture_tmp2;
481 avpicture_fill(picture2, buf1, dec->pix_fmt, dec->width, dec->height);
482
483 if (avpicture_deinterlace(picture2, picture1,
484 dec->pix_fmt, dec->width, dec->height) < 0) {
485 /* if error, do not deinterlace */
0f1578af 486 av_free(buf1);
cfcf0ffd
FB
487 buf1 = NULL;
488 picture2 = picture1;
489 }
490 } else {
491 picture2 = picture1;
492 }
493
494 /* convert pixel format if needed */
495 if (enc->pix_fmt != dec->pix_fmt) {
496 int size;
497
498 /* create temporary picture */
499 size = avpicture_get_size(enc->pix_fmt, dec->width, dec->height);
0f1578af 500 buf = av_malloc(size);
cfcf0ffd
FB
501 if (!buf)
502 return;
503 pict = &picture_tmp1;
504 avpicture_fill(pict, buf, enc->pix_fmt, dec->width, dec->height);
505
506 if (img_convert(pict, enc->pix_fmt,
507 picture2, dec->pix_fmt,
508 dec->width, dec->height) < 0) {
509 fprintf(stderr, "pixel format conversion not handled\n");
510 goto the_end;
511 }
512 } else {
513 pict = picture2;
514 }
515
516 /* XXX: resampling could be done before raw format convertion in
517 some cases to go faster */
518 /* XXX: only works for YUV420P */
85f07f22
FB
519 if (ost->video_resample) {
520 picture = &ost->pict_tmp;
521 img_resample(ost->img_resample_ctx, picture, pict);
522 } else {
523 picture = pict;
524 }
6dc96cb0 525 nb=1;
85f07f22
FB
526 /* duplicates frame if needed */
527 /* XXX: pb because no interleaving */
528 for(i=0;i<nb;i++) {
529 if (enc->codec_id != CODEC_ID_RAWVIDEO) {
530 /* handles sameq here. This is not correct because it may
531 not be a global option */
532 if (same_quality) {
cfcf0ffd 533 enc->quality = dec->quality;
85f07f22 534 }
6dc96cb0 535
cfcf0ffd 536 ret = avcodec_encode_video(enc,
33a1f1a3 537 video_buffer, VIDEO_BUFFER_SIZE,
85f07f22 538 picture);
44429457 539 //enc->frame_number = enc->real_pict_num;
79fdaa4c 540 s->oformat->write_packet(s, ost->index, video_buffer, ret, 0);
ce7c56c2 541 *frame_size = ret;
a5dc85ef 542 //fprintf(stderr,"\nFrame: %3d %3d size: %5d type: %d",
44429457 543 // enc->frame_number-1, enc->real_pict_num, ret,
a5dc85ef 544 // enc->pict_type);
85f07f22 545 } else {
cfcf0ffd 546 write_picture(s, ost->index, picture, enc->pix_fmt, enc->width, enc->height);
85f07f22
FB
547 }
548 }
cfcf0ffd 549 the_end:
0f1578af
FB
550 av_free(buf);
551 av_free(buf1);
85f07f22
FB
552}
553
ce7c56c2
J
554static void do_video_stats(AVOutputStream *ost,
555 AVInputStream *ist,
556 int frame_size)
557{
558 static FILE *fvstats=NULL;
559 static INT64 total_size = 0;
ce7c56c2 560 char filename[40];
bf5af568
FB
561 time_t today2;
562 struct tm *today;
ce7c56c2
J
563 AVCodecContext *enc;
564 int frame_number;
565 INT64 ti;
566 double ti1, bitrate, avg_bitrate;
567
568 if (!fvstats) {
569 today2 = time(NULL);
570 today = localtime(&today2);
571 sprintf(filename, "vstats_%02d%02d%02d.log", today->tm_hour,
572 today->tm_min,
573 today->tm_sec);
574 fvstats = fopen(filename,"w");
575 if (!fvstats) {
576 perror("fopen");
577 exit(1);
578 }
579 }
580
581 ti = MAXINT64;
582 enc = &ost->st->codec;
583 total_size += frame_size;
584 if (enc->codec_type == CODEC_TYPE_VIDEO) {
585 frame_number = ist->frame_number;
586 fprintf(fvstats, "frame= %5d q= %2d ", frame_number, enc->quality);
587 if (do_psnr)
588 fprintf(fvstats, "PSNR= %6.2f ", enc->psnr_y);
589
590 fprintf(fvstats,"f_size= %6d ", frame_size);
591 /* compute min pts value */
592 if (!ist->discard && ist->pts < ti) {
593 ti = ist->pts;
594 }
595 ti1 = (double)ti / 1000000.0;
596 if (ti1 < 0.01)
597 ti1 = 0.01;
598
599 bitrate = (double)(frame_size * 8) * enc->frame_rate / FRAME_RATE_BASE / 1000.0;
600 avg_bitrate = (double)(total_size * 8) / ti1 / 1000.0;
601 fprintf(fvstats, "s_size= %8.0fkB time= %0.3f br= %7.1fkbits/s avg_br= %7.1fkbits/s ",
602 (double)total_size / 1024, ti1, bitrate, avg_bitrate);
603 fprintf(fvstats,"type= %s\n", enc->key_frame == 1 ? "I" : "P");
604 }
605
606
607
608}
609
85f07f22
FB
610/*
611 * The following code is the main loop of the file converter
612 */
613static int av_encode(AVFormatContext **output_files,
614 int nb_output_files,
615 AVFormatContext **input_files,
616 int nb_input_files,
617 AVStreamMap *stream_maps, int nb_stream_maps)
618{
bdc4796f 619 int ret, i, j, k, n, nb_istreams = 0, nb_ostreams = 0;
85f07f22
FB
620 AVFormatContext *is, *os;
621 AVCodecContext *codec, *icodec;
622 AVOutputStream *ost, **ost_table = NULL;
623 AVInputStream *ist, **ist_table = NULL;
624 INT64 min_pts, start_time;
bdc4796f 625 AVInputFile *file_table;
51bd4565 626 AVFormatContext *stream_no_data;
cb09b2ed 627 int key;
bdc4796f 628
51bd4565 629 file_table= (AVInputFile*) av_mallocz(nb_input_files * sizeof(AVInputFile));
bdc4796f
FB
630 if (!file_table)
631 goto fail;
85f07f22 632
85f07f22
FB
633 /* input stream init */
634 j = 0;
635 for(i=0;i<nb_input_files;i++) {
636 is = input_files[i];
637 file_table[i].ist_index = j;
79fdaa4c 638 file_table[i].nb_streams = is->nb_streams;
85f07f22
FB
639 j += is->nb_streams;
640 }
641 nb_istreams = j;
642
643 ist_table = av_mallocz(nb_istreams * sizeof(AVInputStream *));
644 if (!ist_table)
bdc4796f 645 goto fail;
85f07f22
FB
646
647 for(i=0;i<nb_istreams;i++) {
648 ist = av_mallocz(sizeof(AVInputStream));
649 if (!ist)
650 goto fail;
651 ist_table[i] = ist;
652 }
653 j = 0;
654 for(i=0;i<nb_input_files;i++) {
655 is = input_files[i];
656 for(k=0;k<is->nb_streams;k++) {
657 ist = ist_table[j++];
658 ist->st = is->streams[k];
659 ist->file_index = i;
660 ist->index = k;
661 ist->discard = 1; /* the stream is discarded by default
662 (changed later) */
663 }
664 }
665
666 /* output stream init */
667 nb_ostreams = 0;
668 for(i=0;i<nb_output_files;i++) {
669 os = output_files[i];
670 nb_ostreams += os->nb_streams;
0b97443a
J
671 if (mpeg_vcd)
672 os->flags |= AVF_FLAG_VCD;
85f07f22
FB
673 }
674 if (nb_stream_maps > 0 && nb_stream_maps != nb_ostreams) {
675 fprintf(stderr, "Number of stream maps must match number of output streams\n");
676 exit(1);
677 }
678
679 ost_table = av_mallocz(sizeof(AVOutputStream *) * nb_ostreams);
680 if (!ost_table)
681 goto fail;
682 for(i=0;i<nb_ostreams;i++) {
683 ost = av_mallocz(sizeof(AVOutputStream));
684 if (!ost)
685 goto fail;
686 ost_table[i] = ost;
687 }
688
689 n = 0;
690 for(k=0;k<nb_output_files;k++) {
691 os = output_files[k];
692 for(i=0;i<os->nb_streams;i++) {
693 int found;
694 ost = ost_table[n++];
695 ost->file_index = k;
696 ost->index = i;
697 ost->st = os->streams[i];
698 if (nb_stream_maps > 0) {
699 ost->source_index = file_table[stream_maps[n-1].file_index].ist_index +
700 stream_maps[n-1].stream_index;
701 } else {
702 /* get corresponding input stream index : we select the first one with the right type */
703 found = 0;
704 for(j=0;j<nb_istreams;j++) {
705 ist = ist_table[j];
706 if (ist->discard &&
707 ist->st->codec.codec_type == ost->st->codec.codec_type) {
708 ost->source_index = j;
709 found = 1;
710 }
711 }
712
713 if (!found) {
714 /* try again and reuse existing stream */
715 for(j=0;j<nb_istreams;j++) {
716 ist = ist_table[j];
717 if (ist->st->codec.codec_type == ost->st->codec.codec_type) {
718 ost->source_index = j;
719 found = 1;
720 }
721 }
722 if (!found) {
723 fprintf(stderr, "Could not find input stream matching output stream #%d.%d\n",
724 ost->file_index, ost->index);
725 exit(1);
726 }
727 }
728 }
729 ist = ist_table[ost->source_index];
730 ist->discard = 0;
731 }
732 }
733
734 /* dump the stream mapping */
735 fprintf(stderr, "Stream mapping:\n");
736 for(i=0;i<nb_ostreams;i++) {
737 ost = ost_table[i];
738 fprintf(stderr, " Stream #%d.%d -> #%d.%d\n",
739 ist_table[ost->source_index]->file_index,
740 ist_table[ost->source_index]->index,
741 ost->file_index,
742 ost->index);
743 }
744
745 /* for each output stream, we compute the right encoding parameters */
746 for(i=0;i<nb_ostreams;i++) {
747 ost = ost_table[i];
748 ist = ist_table[ost->source_index];
749
750 codec = &ost->st->codec;
751 icodec = &ist->st->codec;
752
753 switch(codec->codec_type) {
754 case CODEC_TYPE_AUDIO:
755 /* check if same codec with same parameters. If so, no
756 reencoding is needed */
757 if (codec->codec_id == icodec->codec_id &&
758 codec->bit_rate == icodec->bit_rate &&
759 codec->sample_rate == icodec->sample_rate &&
760 codec->channels == icodec->channels) {
761 /* no reencoding */
10bb7023
J
762 /* use the same frame size */
763 codec->frame_size = icodec->frame_size;
764 //codec->frame_size = 8*icodec->sample_rate*icodec->frame_size/
765 // icodec->bit_rate;
766 //fprintf(stderr,"\nFrame size: %d", codec->frame_size);
85f07f22
FB
767 } else {
768 if (fifo_init(&ost->fifo, 2 * MAX_AUDIO_PACKET_SIZE))
769 goto fail;
770
771 if (codec->channels == icodec->channels &&
772 codec->sample_rate == icodec->sample_rate) {
773 ost->audio_resample = 0;
774 } else {
e0d2714a
J
775 if (codec->channels != icodec->channels &&
776 icodec->codec_id == CODEC_ID_AC3) {
777 /* Special case for 5:1 AC3 input */
778 /* and mono or stereo output */
6dc96cb0
J
779 /* Request specific number of channels */
780 icodec->channels = codec->channels;
781 if (codec->sample_rate == icodec->sample_rate)
782 ost->audio_resample = 0;
783 else {
784 ost->audio_resample = 1;
785 ost->resample = audio_resample_init(codec->channels, icodec->channels,
786 codec->sample_rate,
787 icodec->sample_rate);
788 }
e0d2714a
J
789 /* Request specific number of channels */
790 icodec->channels = codec->channels;
791 } else {
792 ost->audio_resample = 1;
793 ost->resample = audio_resample_init(codec->channels, icodec->channels,
85f07f22
FB
794 codec->sample_rate,
795 icodec->sample_rate);
e0d2714a 796 }
85f07f22
FB
797 }
798 ist->decoding_needed = 1;
799 ost->encoding_needed = 1;
800 }
801 break;
802 case CODEC_TYPE_VIDEO:
803 /* check if same codec with same parameters. If so, no
804 reencoding is needed */
805 if (codec->codec_id == icodec->codec_id &&
806 codec->bit_rate == icodec->bit_rate &&
807 codec->frame_rate == icodec->frame_rate &&
808 codec->width == icodec->width &&
809 codec->height == icodec->height) {
810 /* no reencoding */
811 } else {
812 if (codec->width == icodec->width &&
813 codec->height == icodec->height) {
814 ost->video_resample = 0;
815 } else {
816 UINT8 *buf;
817 ost->video_resample = 1;
0f1578af 818 buf = av_malloc((codec->width * codec->height * 3) / 2);
85f07f22
FB
819 if (!buf)
820 goto fail;
821 ost->pict_tmp.data[0] = buf;
822 ost->pict_tmp.data[1] = ost->pict_tmp.data[0] + (codec->width * codec->height);
823 ost->pict_tmp.data[2] = ost->pict_tmp.data[1] + (codec->width * codec->height) / 4;
824 ost->pict_tmp.linesize[0] = codec->width;
825 ost->pict_tmp.linesize[1] = codec->width / 2;
826 ost->pict_tmp.linesize[2] = codec->width / 2;
827
ab6d194a 828 ost->img_resample_ctx = img_resample_full_init(
85f07f22 829 ost->st->codec.width, ost->st->codec.height,
ab6d194a
MN
830 ist->st->codec.width, ist->st->codec.height,
831 frame_topBand, frame_bottomBand,
832 frame_leftBand, frame_rightBand);
85f07f22
FB
833 }
834 ost->encoding_needed = 1;
835 ist->decoding_needed = 1;
836 }
837 break;
51bd4565 838 default:
c04643a2 839 av_abort();
85f07f22
FB
840 }
841 }
842
843 /* open each encoder */
844 for(i=0;i<nb_ostreams;i++) {
845 ost = ost_table[i];
846 if (ost->encoding_needed) {
847 AVCodec *codec;
848 codec = avcodec_find_encoder(ost->st->codec.codec_id);
849 if (!codec) {
850 fprintf(stderr, "Unsupported codec for output stream #%d.%d\n",
851 ost->file_index, ost->index);
852 exit(1);
853 }
854 if (avcodec_open(&ost->st->codec, codec) < 0) {
855 fprintf(stderr, "Error while opening codec for stream #%d.%d - maybe incorrect parameters such as bit_rate, rate, width or height\n",
856 ost->file_index, ost->index);
857 exit(1);
858 }
859 }
860 }
861
862 /* open each decoder */
863 for(i=0;i<nb_istreams;i++) {
864 ist = ist_table[i];
865 if (ist->decoding_needed) {
866 AVCodec *codec;
867 codec = avcodec_find_decoder(ist->st->codec.codec_id);
868 if (!codec) {
869 fprintf(stderr, "Unsupported codec for input stream #%d.%d\n",
870 ist->file_index, ist->index);
871 exit(1);
872 }
873 if (avcodec_open(&ist->st->codec, codec) < 0) {
874 fprintf(stderr, "Error while opening codec for input stream #%d.%d\n",
875 ist->file_index, ist->index);
876 exit(1);
877 }
6dc96cb0
J
878 //if (ist->st->codec.codec_type == CODEC_TYPE_VIDEO)
879 // ist->st->codec.flags |= CODEC_FLAG_REPEAT_FIELD;
85f07f22
FB
880 }
881 }
882
883 /* init pts */
884 for(i=0;i<nb_istreams;i++) {
885 ist = ist_table[i];
886 ist->pts = 0;
887 ist->frame_number = 0;
888 }
889
890 /* compute buffer size max (should use a complete heuristic) */
891 for(i=0;i<nb_input_files;i++) {
892 file_table[i].buffer_size_max = 2048;
893 }
894
895 /* open files and write file headers */
896 for(i=0;i<nb_output_files;i++) {
897 os = output_files[i];
79fdaa4c 898 if (av_write_header(os) < 0) {
a38469e1
FB
899 fprintf(stderr, "Could not write header for output file #%d (incorrect codec paramters ?)\n", i);
900 ret = -EINVAL;
901 goto fail;
902 }
85f07f22
FB
903 }
904
a38469e1
FB
905#ifndef CONFIG_WIN32
906 if (!do_play) {
907 fprintf(stderr, "Press [q] to stop encoding\n");
908 } else {
909 fprintf(stderr, "Press [q] to stop playing\n");
910 }
911#endif
912 term_init();
913
2c4ae653 914 start_time = av_gettime();
85f07f22 915 min_pts = 0;
51bd4565 916 stream_no_data = 0;
cb09b2ed 917 key = -1;
51bd4565 918
85f07f22
FB
919 for(;;) {
920 int file_index, ist_index;
921 AVPacket pkt;
922 UINT8 *ptr;
923 int len;
924 UINT8 *data_buf;
925 int data_size, got_picture;
926 AVPicture picture;
927 short samples[AVCODEC_MAX_AUDIO_FRAME_SIZE / 2];
928
85f07f22 929 redo:
a38469e1 930 /* if 'q' pressed, exits */
cb09b2ed
PG
931 if (key) {
932 /* read_key() returns 0 on EOF */
933 key = read_key();
934 if (key == 'q')
935 break;
936 }
a38469e1
FB
937
938 /* select the input file with the smallest pts */
85f07f22 939 file_index = -1;
bdc4796f 940 min_pts = MAXINT64;
85f07f22
FB
941 for(i=0;i<nb_istreams;i++) {
942 ist = ist_table[i];
51bd4565
PG
943 /* For some reason, the pts_increment code breaks q estimation?!? */
944 if (!ist->discard && !file_table[ist->file_index].eof_reached &&
945 ist->pts /* + ist->pts_increment */ < min_pts && input_files[ist->file_index] != stream_no_data) {
946 min_pts = ist->pts /* + ist->pts_increment */;
85f07f22
FB
947 file_index = ist->file_index;
948 }
949 }
950 /* if none, if is finished */
51bd4565
PG
951 if (file_index < 0) {
952 if (stream_no_data) {
3f027ca7
FB
953#ifndef CONFIG_WIN32 /* no usleep in VisualC ? */
954#ifdef __BEOS__
955 snooze(10 * 1000); /* mmu_man */ /* in microsec */
956#elif defined(__CYGWIN__)
957 usleep(10 * 1000);
958#else
51bd4565
PG
959 struct timespec ts;
960
961 ts.tv_sec = 0;
962 ts.tv_nsec = 1000 * 1000 * 10;
963 nanosleep(&ts, 0);
27a5e8b8 964#endif
bf5af568 965#endif
51bd4565
PG
966 stream_no_data = 0;
967 continue;
968 }
85f07f22 969 break;
51bd4565 970 }
85f07f22
FB
971 /* finish if recording time exhausted */
972 if (recording_time > 0 && min_pts >= recording_time)
973 break;
974 /* read a packet from it and output it in the fifo */
85f07f22
FB
975 is = input_files[file_index];
976 if (av_read_packet(is, &pkt) < 0) {
977 file_table[file_index].eof_reached = 1;
978 continue;
979 }
51bd4565
PG
980 if (!pkt.size) {
981 stream_no_data = is;
982 } else {
983 stream_no_data = 0;
984 }
79fdaa4c
FB
985 /* the following test is needed in case new streams appear
986 dynamically in stream : we ignore them */
987 if (pkt.stream_index >= file_table[file_index].nb_streams)
bf5af568 988 goto discard_packet;
85f07f22
FB
989 ist_index = file_table[file_index].ist_index + pkt.stream_index;
990 ist = ist_table[ist_index];
bf5af568
FB
991 if (ist->discard)
992 goto discard_packet;
85f07f22 993
51bd4565
PG
994 if (pkt.flags & PKT_FLAG_DROPPED_FRAME)
995 ist->frame_number++;
996
a0663ba4
FB
997 if (do_hex_dump) {
998 printf("stream #%d, size=%d:\n", pkt.stream_index, pkt.size);
79fdaa4c 999 av_hex_dump(pkt.data, pkt.size);
a0663ba4 1000 }
85f07f22
FB
1001
1002 // printf("read #%d.%d size=%d\n", ist->file_index, ist->index, pkt.size);
1003
1004 len = pkt.size;
1005 ptr = pkt.data;
1006 while (len > 0) {
1007
1008 /* decode the packet if needed */
1009 data_buf = NULL; /* fail safe */
1010 data_size = 0;
1011 if (ist->decoding_needed) {
1012 switch(ist->st->codec.codec_type) {
1013 case CODEC_TYPE_AUDIO:
a0663ba4
FB
1014 /* XXX: could avoid copy if PCM 16 bits with same
1015 endianness as CPU */
1016 ret = avcodec_decode_audio(&ist->st->codec, samples, &data_size,
1017 ptr, len);
1018 if (ret < 0)
1019 goto fail_decode;
afc80f59
J
1020 /* Some bug in mpeg audio decoder gives */
1021 /* data_size < 0, it seems they are overflows */
1022 if (data_size <= 0) {
a0663ba4
FB
1023 /* no audio frame */
1024 ptr += ret;
1025 len -= ret;
1026 continue;
85f07f22 1027 }
a0663ba4 1028 data_buf = (UINT8 *)samples;
85f07f22
FB
1029 break;
1030 case CODEC_TYPE_VIDEO:
1031 if (ist->st->codec.codec_id == CODEC_ID_RAWVIDEO) {
1032 int size;
1033 size = (ist->st->codec.width * ist->st->codec.height);
cfcf0ffd
FB
1034 avpicture_fill(&picture, ptr,
1035 ist->st->codec.pix_fmt,
1036 ist->st->codec.width,
1037 ist->st->codec.height);
85f07f22
FB
1038 ret = len;
1039 } else {
1040 data_size = (ist->st->codec.width * ist->st->codec.height * 3) / 2;
1041 ret = avcodec_decode_video(&ist->st->codec,
1042 &picture, &got_picture, ptr, len);
1043 if (ret < 0) {
1044 fail_decode:
1045 fprintf(stderr, "Error while decoding stream #%d.%d\n",
1046 ist->file_index, ist->index);
1047 av_free_packet(&pkt);
1048 goto redo;
1049 }
1050 if (!got_picture) {
1051 /* no picture yet */
1052 ptr += ret;
1053 len -= ret;
1054 continue;
1055 }
6dc96cb0 1056
85f07f22
FB
1057 }
1058 break;
1059 default:
1060 goto fail_decode;
1061 }
1062 } else {
1063 data_buf = ptr;
1064 data_size = len;
1065 ret = len;
1066 }
6dc96cb0
J
1067 /* init tickers */
1068 if (!ist->ticker_inited) {
1069 switch (ist->st->codec.codec_type) {
1070 case CODEC_TYPE_AUDIO:
1071 ticker_init(&ist->pts_ticker,
1072 (INT64)ist->st->codec.sample_rate,
1073 (INT64)(1000000));
1074 ist->ticker_inited = 1;
1075 break;
1076 case CODEC_TYPE_VIDEO:
1077 ticker_init(&ist->pts_ticker,
1078 (INT64)ist->st->r_frame_rate,
1079 ((INT64)1000000 * FRAME_RATE_BASE));
1080 ist->ticker_inited = 1;
1081 break;
1082 default:
c04643a2 1083 av_abort();
6dc96cb0
J
1084 }
1085 }
85f07f22
FB
1086 /* update pts */
1087 switch(ist->st->codec.codec_type) {
1088 case CODEC_TYPE_AUDIO:
6dc96cb0 1089 //ist->pts = (INT64)1000000 * ist->sample_index / ist->st->codec.sample_rate;
cbadbf19 1090 ist->pts = ticker_abs(&ist->pts_ticker, ist->sample_index);
85f07f22 1091 ist->sample_index += data_size / (2 * ist->st->codec.channels);
51bd4565 1092 ist->pts_increment = (INT64) (data_size / (2 * ist->st->codec.channels)) * 1000000 / ist->st->codec.sample_rate;
85f07f22
FB
1093 break;
1094 case CODEC_TYPE_VIDEO:
1095 ist->frame_number++;
6dc96cb0
J
1096 //ist->pts = ((INT64)ist->frame_number * 1000000 * FRAME_RATE_BASE) /
1097 // ist->st->codec.frame_rate;
cbadbf19 1098 ist->pts = ticker_abs(&ist->pts_ticker, ist->frame_number);
51bd4565
PG
1099 ist->pts_increment = ((INT64) 1000000 * FRAME_RATE_BASE) /
1100 ist->st->codec.frame_rate;
85f07f22 1101 break;
51bd4565 1102 default:
c04643a2 1103 av_abort();
85f07f22
FB
1104 }
1105 ptr += ret;
1106 len -= ret;
1107
1108 /* transcode raw format, encode packets and output them */
1109
1110 for(i=0;i<nb_ostreams;i++) {
ce7c56c2 1111 int frame_size;
85f07f22
FB
1112 ost = ost_table[i];
1113 if (ost->source_index == ist_index) {
1114 os = output_files[ost->file_index];
1115
1116 if (ost->encoding_needed) {
1117 switch(ost->st->codec.codec_type) {
1118 case CODEC_TYPE_AUDIO:
1119 do_audio_out(os, ost, ist, data_buf, data_size);
1120 break;
1121 case CODEC_TYPE_VIDEO:
ce7c56c2
J
1122 do_video_out(os, ost, ist, &picture, &frame_size);
1123 if (do_vstats)
1124 do_video_stats(ost, ist, frame_size);
85f07f22 1125 break;
51bd4565 1126 default:
c04643a2 1127 av_abort();
85f07f22
FB
1128 }
1129 } else {
1130 /* no reencoding needed : output the packet directly */
10bb7023 1131 /* force the input stream PTS */
79fdaa4c 1132 os->oformat->write_packet(os, ost->index, data_buf, data_size, pkt.pts);
85f07f22
FB
1133 }
1134 }
1135 }
1136 }
bf5af568 1137 discard_packet:
85f07f22
FB
1138 av_free_packet(&pkt);
1139
1140 /* dump report by using the first video and audio streams */
1141 {
1142 char buf[1024];
1143 AVFormatContext *oc;
1144 INT64 total_size, ti;
1145 AVCodecContext *enc;
1146 int frame_number, vid;
1147 double bitrate, ti1;
1148 static INT64 last_time;
1149
1150 if ((min_pts - last_time) >= 500000) {
1151 last_time = min_pts;
1152
1153 oc = output_files[0];
1154
1155 total_size = url_ftell(&oc->pb);
1156
1157 buf[0] = '\0';
bdc4796f 1158 ti = MAXINT64;
85f07f22
FB
1159 vid = 0;
1160 for(i=0;i<nb_ostreams;i++) {
1161 ost = ost_table[i];
1162 enc = &ost->st->codec;
1163 ist = ist_table[ost->source_index];
1164 if (!vid && enc->codec_type == CODEC_TYPE_VIDEO) {
1165 frame_number = ist->frame_number;
1166 sprintf(buf + strlen(buf), "frame=%5d q=%2d ",
1167 frame_number, enc->quality);
43f1708f
J
1168 if (do_psnr)
1169 sprintf(buf + strlen(buf), "PSNR=%6.2f ", enc->psnr_y);
85f07f22
FB
1170 vid = 1;
1171 }
1172 /* compute min pts value */
1173 if (!ist->discard && ist->pts < ti) {
1174 ti = ist->pts;
1175 }
1176 }
1177
bdc4796f 1178 ti1 = (double)ti / 1000000.0;
ce7c56c2
J
1179 if (ti1 < 0.01)
1180 ti1 = 0.01;
85f07f22
FB
1181 bitrate = (double)(total_size * 8) / ti1 / 1000.0;
1182
bdc4796f
FB
1183 sprintf(buf + strlen(buf),
1184 "size=%8.0fkB time=%0.1f bitrate=%6.1fkbits/s",
1185 (double)total_size / 1024, ti1, bitrate);
85f07f22 1186
ce7c56c2 1187 fprintf(stderr, "%s \r", buf);
85f07f22
FB
1188 fflush(stderr);
1189 }
1190 }
1191 }
a38469e1 1192 term_exit();
85f07f22
FB
1193
1194 /* dump report by using the first video and audio streams */
1195 {
1196 char buf[1024];
1197 AVFormatContext *oc;
1198 INT64 total_size, ti;
1199 AVCodecContext *enc;
1200 int frame_number, vid;
1201 double bitrate, ti1;
1202
1203 oc = output_files[0];
1204
1205 total_size = url_ftell(&oc->pb);
1206
1207 buf[0] = '\0';
bdc4796f 1208 ti = MAXINT64;
85f07f22
FB
1209 vid = 0;
1210 for(i=0;i<nb_ostreams;i++) {
1211 ost = ost_table[i];
1212 enc = &ost->st->codec;
1213 ist = ist_table[ost->source_index];
1214 if (!vid && enc->codec_type == CODEC_TYPE_VIDEO) {
1215 frame_number = ist->frame_number;
1216 sprintf(buf + strlen(buf), "frame=%5d q=%2d ",
1217 frame_number, enc->quality);
43f1708f
J
1218 if (do_psnr)
1219 sprintf(buf + strlen(buf), "PSNR=%6.2f ", enc->psnr_y);
85f07f22
FB
1220 vid = 1;
1221 }
1222 /* compute min pts value */
1223 if (!ist->discard && ist->pts < ti) {
1224 ti = ist->pts;
1225 }
1226 }
1227
1228 ti1 = ti / 1000000.0;
ce7c56c2
J
1229 if (ti1 < 0.01)
1230 ti1 = 0.01;
85f07f22
FB
1231 bitrate = (double)(total_size * 8) / ti1 / 1000.0;
1232
bdc4796f
FB
1233 sprintf(buf + strlen(buf),
1234 "size=%8.0fkB time=%0.1f bitrate=%6.1fkbits/s",
1235 (double)total_size / 1024, ti1, bitrate);
85f07f22 1236
ce7c56c2 1237 fprintf(stderr, "%s \n", buf);
85f07f22
FB
1238 }
1239 /* close each encoder */
1240 for(i=0;i<nb_ostreams;i++) {
1241 ost = ost_table[i];
1242 if (ost->encoding_needed) {
1243 avcodec_close(&ost->st->codec);
1244 }
1245 }
1246
1247 /* close each decoder */
1248 for(i=0;i<nb_istreams;i++) {
1249 ist = ist_table[i];
1250 if (ist->decoding_needed) {
1251 avcodec_close(&ist->st->codec);
1252 }
1253 }
1254
1255
1256 /* write the trailer if needed and close file */
1257 for(i=0;i<nb_output_files;i++) {
1258 os = output_files[i];
79fdaa4c 1259 av_write_trailer(os);
85f07f22
FB
1260 }
1261 /* finished ! */
1262
1263 ret = 0;
1264 fail1:
0f1578af 1265 av_free(file_table);
bdc4796f 1266
85f07f22
FB
1267 if (ist_table) {
1268 for(i=0;i<nb_istreams;i++) {
1269 ist = ist_table[i];
0f1578af 1270 av_free(ist);
85f07f22 1271 }
0f1578af 1272 av_free(ist_table);
85f07f22
FB
1273 }
1274 if (ost_table) {
1275 for(i=0;i<nb_ostreams;i++) {
1276 ost = ost_table[i];
1277 if (ost) {
bf5af568
FB
1278 fifo_free(&ost->fifo); /* works even if fifo is not
1279 initialized but set to zero */
0f1578af 1280 av_free(ost->pict_tmp.data[0]);
85f07f22
FB
1281 if (ost->video_resample)
1282 img_resample_close(ost->img_resample_ctx);
1283 if (ost->audio_resample)
1284 audio_resample_close(ost->resample);
0f1578af 1285 av_free(ost);
85f07f22
FB
1286 }
1287 }
0f1578af 1288 av_free(ost_table);
85f07f22
FB
1289 }
1290 return ret;
1291 fail:
1292 ret = -ENOMEM;
1293 goto fail1;
1294}
1295
1296#if 0
1297int file_read(const char *filename)
1298{
1299 URLContext *h;
1300 unsigned char buffer[1024];
1301 int len, i;
1302
1303 if (url_open(&h, filename, O_RDONLY) < 0) {
1304 printf("could not open '%s'\n", filename);
1305 return -1;
1306 }
1307 for(;;) {
1308 len = url_read(h, buffer, sizeof(buffer));
1309 if (len <= 0)
1310 break;
1311 for(i=0;i<len;i++) putchar(buffer[i]);
1312 }
1313 url_close(h);
1314 return 0;
1315}
1316#endif
1317
1318void show_licence(void)
1319{
1320 printf(
1321 "ffmpeg version " FFMPEG_VERSION "\n"
bf5af568
FB
1322 "Copyright (c) 2000, 2001, 2002 Fabrice Bellard\n"
1323 "This library is free software; you can redistribute it and/or\n"
1324 "modify it under the terms of the GNU Lesser General Public\n"
1325 "License as published by the Free Software Foundation; either\n"
1326 "version 2 of the License, or (at your option) any later version.\n"
85f07f22 1327 "\n"
bf5af568 1328 "This library is distributed in the hope that it will be useful,\n"
85f07f22 1329 "but WITHOUT ANY WARRANTY; without even the implied warranty of\n"
bf5af568
FB
1330 "MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n"
1331 "Lesser General Public License for more details.\n"
85f07f22 1332 "\n"
bf5af568
FB
1333 "You should have received a copy of the GNU Lesser General Public\n"
1334 "License along with this library; if not, write to the Free Software\n"
1335 "Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n"
85f07f22
FB
1336 );
1337 exit(1);
1338}
1339
1340void opt_format(const char *arg)
1341{
79fdaa4c
FB
1342 file_iformat = av_find_input_format(arg);
1343 file_oformat = guess_format(arg, NULL, NULL);
1344 if (!file_iformat && !file_oformat) {
1345 fprintf(stderr, "Unknown input or output format: %s\n", arg);
85f07f22
FB
1346 exit(1);
1347 }
85f07f22
FB
1348}
1349
1350void opt_video_bitrate(const char *arg)
1351{
1352 video_bit_rate = atoi(arg) * 1000;
1353}
1354
9cdd6a24
MN
1355void opt_video_bitrate_tolerance(const char *arg)
1356{
1357 video_bit_rate_tolerance = atoi(arg) * 1000;
1358}
1359
3aa102be
MN
1360void opt_video_bitrate_max(const char *arg)
1361{
1362 video_rc_max_rate = atoi(arg) * 1000;
1363}
1364
1365void opt_video_bitrate_min(const char *arg)
1366{
1367 video_rc_min_rate = atoi(arg) * 1000;
1368}
1369
1370void opt_video_rc_eq(char *arg)
1371{
1372 video_rc_eq = arg;
1373}
1374
1375
fe670d09
MN
1376void opt_workaround_bugs(const char *arg)
1377{
1378 workaround_bugs = atoi(arg);
1379}
1380
463678ac
MN
1381void opt_dct_algo(const char *arg)
1382{
1383 dct_algo = atoi(arg);
1384}
1385
85f07f22
FB
1386void opt_frame_rate(const char *arg)
1387{
1388 frame_rate = (int)(strtod(arg, 0) * FRAME_RATE_BASE);
1389}
1390
ab6d194a
MN
1391
1392void opt_frame_crop_top(const char *arg)
1393{
1394 frame_topBand = atoi(arg);
1395 if (frame_topBand < 0) {
1396 fprintf(stderr, "Incorrect top crop size\n");
1397 exit(1);
1398 }
1399 if ((frame_topBand % 2) != 0) {
1400 fprintf(stderr, "Top crop size must be a multiple of 2\n");
1401 exit(1);
1402 }
1403 if ((frame_topBand) >= frame_height){
1404 fprintf(stderr, "Vertical crop dimensions are outside the range of the original image.\nRemember to crop first and scale second.\n");
1405 exit(1);
1406 }
1407 frame_height -= frame_topBand;
1408}
1409
1410void opt_frame_crop_bottom(const char *arg)
1411{
1412 frame_bottomBand = atoi(arg);
1413 if (frame_bottomBand < 0) {
1414 fprintf(stderr, "Incorrect bottom crop size\n");
1415 exit(1);
1416 }
1417 if ((frame_bottomBand % 2) != 0) {
1418 fprintf(stderr, "Bottom crop size must be a multiple of 2\n");
1419 exit(1);
1420 }
1421 if ((frame_bottomBand) >= frame_height){
1422 fprintf(stderr, "Vertical crop dimensions are outside the range of the original image.\nRemember to crop first and scale second.\n");
1423 exit(1);
1424 }
1425 frame_height -= frame_bottomBand;
1426}
1427
1428void opt_frame_crop_left(const char *arg)
1429{
1430 frame_leftBand = atoi(arg);
1431 if (frame_leftBand < 0) {
1432 fprintf(stderr, "Incorrect left crop size\n");
1433 exit(1);
1434 }
1435 if ((frame_leftBand % 2) != 0) {
1436 fprintf(stderr, "Left crop size must be a multiple of 2\n");
1437 exit(1);
1438 }
1439 if ((frame_leftBand) >= frame_width){
1440 fprintf(stderr, "Horizontal crop dimensions are outside the range of the original image.\nRemember to crop first and scale second.\n");
1441 exit(1);
1442 }
1443 frame_width -= frame_leftBand;
1444}
1445
1446void opt_frame_crop_right(const char *arg)
1447{
1448 frame_rightBand = atoi(arg);
1449 if (frame_rightBand < 0) {
1450 fprintf(stderr, "Incorrect right crop size\n");
1451 exit(1);
1452 }
1453 if ((frame_rightBand % 2) != 0) {
1454 fprintf(stderr, "Right crop size must be a multiple of 2\n");
1455 exit(1);
1456 }
1457 if ((frame_rightBand) >= frame_width){
1458 fprintf(stderr, "Horizontal crop dimensions are outside the range of the original image.\nRemember to crop first and scale second.\n");
1459 exit(1);
1460 }
1461 frame_width -= frame_rightBand;
1462}
1463
85f07f22
FB
1464void opt_frame_size(const char *arg)
1465{
1466 parse_image_size(&frame_width, &frame_height, arg);
1467 if (frame_width <= 0 || frame_height <= 0) {
1468 fprintf(stderr, "Incorrect frame size\n");
1469 exit(1);
1470 }
1471 if ((frame_width % 2) != 0 || (frame_height % 2) != 0) {
1472 fprintf(stderr, "Frame size must be a multiple of 2\n");
1473 exit(1);
1474 }
1475}
1476
1477void opt_gop_size(const char *arg)
1478{
1479 gop_size = atoi(arg);
1480}
1481
bc6caae2
J
1482void opt_b_frames(const char *arg)
1483{
1484 b_frames = atoi(arg);
1485 if (b_frames > FF_MAX_B_FRAMES) {
1486 fprintf(stderr, "\nCannot have more than %d B frames, increase FF_MAX_B_FRAMES.\n", FF_MAX_B_FRAMES);
1487 exit(1);
1488 } else if (b_frames < 1) {
1489 fprintf(stderr, "\nNumber of B frames must be higher than 0\n");
1490 exit(1);
1491 }
1492}
1493
85f07f22
FB
1494void opt_qscale(const char *arg)
1495{
1496 video_qscale = atoi(arg);
1497 if (video_qscale < 0 ||
1498 video_qscale > 31) {
1499 fprintf(stderr, "qscale must be >= 1 and <= 31\n");
1500 exit(1);
1501 }
1502}
1503
9cdd6a24
MN
1504void opt_qmin(const char *arg)
1505{
1506 video_qmin = atoi(arg);
1507 if (video_qmin < 0 ||
1508 video_qmin > 31) {
1509 fprintf(stderr, "qmin must be >= 1 and <= 31\n");
1510 exit(1);
1511 }
1512}
1513
1514void opt_qmax(const char *arg)
1515{
1516 video_qmax = atoi(arg);
1517 if (video_qmax < 0 ||
1518 video_qmax > 31) {
1519 fprintf(stderr, "qmax must be >= 1 and <= 31\n");
1520 exit(1);
1521 }
1522}
1523
1524void opt_qdiff(const char *arg)
1525{
1526 video_qdiff = atoi(arg);
1527 if (video_qdiff < 0 ||
1528 video_qdiff > 31) {
1529 fprintf(stderr, "qdiff must be >= 1 and <= 31\n");
1530 exit(1);
1531 }
1532}
1533
1534void opt_qblur(const char *arg)
1535{
1536 video_qblur = atof(arg);
1537}
1538
1539void opt_qcomp(const char *arg)
1540{
1541 video_qcomp = atof(arg);
1542}
85f07f22
FB
1543
1544void opt_audio_bitrate(const char *arg)
1545{
1546 audio_bit_rate = atoi(arg) * 1000;
1547}
1548
1549void opt_audio_rate(const char *arg)
1550{
1551 audio_sample_rate = atoi(arg);
1552}
1553
1554void opt_audio_channels(const char *arg)
1555{
1556 audio_channels = atoi(arg);
1557}
1558
1559void opt_video_device(const char *arg)
1560{
1561 v4l_device = strdup(arg);
1562}
1563
1564void opt_audio_device(const char *arg)
1565{
1566 audio_device = strdup(arg);
1567}
1568
1569void opt_audio_codec(const char *arg)
1570{
1571 AVCodec *p;
1572
1573 p = first_avcodec;
1574 while (p) {
1575 if (!strcmp(p->name, arg) && p->type == CODEC_TYPE_AUDIO)
1576 break;
1577 p = p->next;
1578 }
1579 if (p == NULL) {
1580 fprintf(stderr, "Unknown audio codec '%s'\n", arg);
1581 exit(1);
1582 } else {
1583 audio_codec_id = p->id;
1584 }
1585}
1586
1587const char *motion_str[] = {
1588 "zero",
1589 "full",
1590 "log",
1591 "phods",
7084c149
MN
1592 "epzs",
1593 "x1",
85f07f22
FB
1594 NULL,
1595};
1596
1597void opt_motion_estimation(const char *arg)
1598{
1599 const char **p;
1600 p = motion_str;
1601 for(;;) {
1602 if (!*p) {
1603 fprintf(stderr, "Unknown motion estimation method '%s'\n", arg);
1604 exit(1);
1605 }
1606 if (!strcmp(*p, arg))
1607 break;
1608 p++;
1609 }
101bea5f 1610 me_method = (p - motion_str) + 1;
85f07f22
FB
1611}
1612
1613void opt_video_codec(const char *arg)
1614{
1615 AVCodec *p;
1616
1617 p = first_avcodec;
1618 while (p) {
1619 if (!strcmp(p->name, arg) && p->type == CODEC_TYPE_VIDEO)
1620 break;
1621 p = p->next;
1622 }
1623 if (p == NULL) {
1624 fprintf(stderr, "Unknown video codec '%s'\n", arg);
1625 exit(1);
1626 } else {
1627 video_codec_id = p->id;
1628 }
1629}
1630
1631void opt_map(const char *arg)
1632{
1633 AVStreamMap *m;
1634 const char *p;
1635
1636 p = arg;
1637 m = &stream_maps[nb_stream_maps++];
1638
1639 m->file_index = strtol(arg, (char **)&p, 0);
1640 if (*p)
1641 p++;
a5dc85ef
J
1642
1643 m->stream_index = strtol(p, (char **)&p, 0);
85f07f22
FB
1644}
1645
1646void opt_recording_time(const char *arg)
1647{
1648 recording_time = parse_date(arg, 1);
1649}
1650
79fdaa4c 1651void print_error(const char *filename, int err)
919f448d 1652{
79fdaa4c
FB
1653 switch(err) {
1654 case AVERROR_NUMEXPECTED:
919f448d
FB
1655 fprintf(stderr, "%s: Incorrect image filename syntax.\n"
1656 "Use '%%d' to specify the image number:\n"
1657 " for img1.jpg, img2.jpg, ..., use 'img%%d.jpg';\n"
1658 " for img001.jpg, img002.jpg, ..., use 'img%%03d.jpg'.\n",
1659 filename);
79fdaa4c
FB
1660 break;
1661 case AVERROR_INVALIDDATA:
1662 fprintf(stderr, "%s: Error while parsing header\n", filename);
1663 break;
1664 case AVERROR_NOFMT:
1665 fprintf(stderr, "%s: Unknown format\n", filename);
1666 break;
1667 default:
1668 fprintf(stderr, "%s: Error while opening file\n", filename);
1669 break;
919f448d
FB
1670 }
1671}
85f07f22
FB
1672
1673void opt_input_file(const char *filename)
1674{
1675 AVFormatContext *ic;
1676 AVFormatParameters params, *ap = &params;
6dc96cb0 1677 int err, i, ret, rfps;
85f07f22 1678
85f07f22 1679 /* get default parameters from command line */
79fdaa4c
FB
1680 memset(ap, 0, sizeof(*ap));
1681 ap->sample_rate = audio_sample_rate;
1682 ap->channels = audio_channels;
1683 ap->frame_rate = frame_rate;
1684 ap->width = frame_width;
1685 ap->height = frame_height;
1686
1687 /* open the input file with generic libav function */
1688 err = av_open_input_file(&ic, filename, file_iformat, 0, ap);
85f07f22 1689 if (err < 0) {
79fdaa4c 1690 print_error(filename, err);
85f07f22
FB
1691 exit(1);
1692 }
1693
79fdaa4c
FB
1694 /* If not enough info to get the stream parameters, we decode the
1695 first frames to get it. (used in mpeg case for example) */
1696 ret = av_find_stream_info(ic);
85f07f22
FB
1697 if (ret < 0) {
1698 fprintf(stderr, "%s: could not find codec parameters\n", filename);
1699 exit(1);
1700 }
1701
1702 /* update the current parameters so that they match the one of the input stream */
1703 for(i=0;i<ic->nb_streams;i++) {
1704 AVCodecContext *enc = &ic->streams[i]->codec;
1705 switch(enc->codec_type) {
1706 case CODEC_TYPE_AUDIO:
e0d2714a 1707 //fprintf(stderr, "\nInput Audio channels: %d", enc->channels);
85f07f22
FB
1708 audio_channels = enc->channels;
1709 audio_sample_rate = enc->sample_rate;
1710 break;
1711 case CODEC_TYPE_VIDEO:
1712 frame_height = enc->height;
1713 frame_width = enc->width;
79fdaa4c 1714 rfps = ic->streams[i]->r_frame_rate;
fe670d09 1715 enc->workaround_bugs = workaround_bugs;
79fdaa4c 1716 if (enc->frame_rate != rfps) {
6dc96cb0
J
1717 fprintf(stderr,"\nSeems that stream %d comes from film source: %2.2f->%2.2f\n",
1718 i, (float)enc->frame_rate / FRAME_RATE_BASE,
1719 (float)rfps / FRAME_RATE_BASE);
79fdaa4c 1720 }
bf5af568
FB
1721 /* update the current frame rate to match the stream frame rate */
1722 frame_rate = rfps;
85f07f22 1723 break;
51bd4565 1724 default:
c04643a2 1725 av_abort();
85f07f22
FB
1726 }
1727 }
1728
1729 input_files[nb_input_files] = ic;
1730 /* dump the file content */
1731 dump_format(ic, nb_input_files, filename, 0);
1732 nb_input_files++;
79fdaa4c
FB
1733 file_iformat = NULL;
1734 file_oformat = NULL;
85f07f22
FB
1735}
1736
919f448d
FB
1737void check_audio_video_inputs(int *has_video_ptr, int *has_audio_ptr)
1738{
1739 int has_video, has_audio, i, j;
1740 AVFormatContext *ic;
1741
1742 has_video = 0;
1743 has_audio = 0;
1744 for(j=0;j<nb_input_files;j++) {
1745 ic = input_files[j];
1746 for(i=0;i<ic->nb_streams;i++) {
1747 AVCodecContext *enc = &ic->streams[i]->codec;
1748 switch(enc->codec_type) {
1749 case CODEC_TYPE_AUDIO:
1750 has_audio = 1;
1751 break;
1752 case CODEC_TYPE_VIDEO:
1753 has_video = 1;
1754 break;
51bd4565 1755 default:
c04643a2 1756 av_abort();
919f448d
FB
1757 }
1758 }
1759 }
1760 *has_video_ptr = has_video;
1761 *has_audio_ptr = has_audio;
1762}
1763
85f07f22
FB
1764void opt_output_file(const char *filename)
1765{
1766 AVStream *st;
1767 AVFormatContext *oc;
919f448d 1768 int use_video, use_audio, nb_streams, input_has_video, input_has_audio;
85f07f22
FB
1769 int codec_id;
1770
1771 if (!strcmp(filename, "-"))
1772 filename = "pipe:";
1773
1774 oc = av_mallocz(sizeof(AVFormatContext));
1775
79fdaa4c
FB
1776 if (!file_oformat) {
1777 file_oformat = guess_format(NULL, filename, NULL);
1778 if (!file_oformat) {
1779 fprintf(stderr, "Unable for find a suitable output format for '%s'\n",
1780 filename);
1781 exit(1);
1782 }
85f07f22
FB
1783 }
1784
79fdaa4c 1785 oc->oformat = file_oformat;
85f07f22 1786
79fdaa4c 1787 if (!strcmp(file_oformat->name, "ffm") &&
85f07f22
FB
1788 strstart(filename, "http:", NULL)) {
1789 /* special case for files sent to ffserver: we get the stream
1790 parameters from ffserver */
1791 if (read_ffserver_streams(oc, filename) < 0) {
1792 fprintf(stderr, "Could not read stream parameters from '%s'\n", filename);
1793 exit(1);
1794 }
1795 } else {
79fdaa4c
FB
1796 use_video = file_oformat->video_codec != CODEC_ID_NONE;
1797 use_audio = file_oformat->audio_codec != CODEC_ID_NONE;
919f448d 1798
e30a2846
FB
1799 /* disable if no corresponding type found and at least one
1800 input file */
1801 if (nb_input_files > 0) {
1802 check_audio_video_inputs(&input_has_video, &input_has_audio);
1803 if (!input_has_video)
1804 use_video = 0;
1805 if (!input_has_audio)
1806 use_audio = 0;
1807 }
919f448d
FB
1808
1809 /* manual disable */
85f07f22
FB
1810 if (audio_disable) {
1811 use_audio = 0;
1812 }
1813 if (video_disable) {
1814 use_video = 0;
1815 }
1816
1817 nb_streams = 0;
1818 if (use_video) {
1819 AVCodecContext *video_enc;
1820
1821 st = av_mallocz(sizeof(AVStream));
1822 if (!st) {
1823 fprintf(stderr, "Could not alloc stream\n");
1824 exit(1);
1825 }
1826 video_enc = &st->codec;
1827
79fdaa4c 1828 codec_id = file_oformat->video_codec;
85f07f22
FB
1829 if (video_codec_id != CODEC_ID_NONE)
1830 codec_id = video_codec_id;
1831
1832 video_enc->codec_id = codec_id;
1833 video_enc->codec_type = CODEC_TYPE_VIDEO;
1834
1835 video_enc->bit_rate = video_bit_rate;
9cdd6a24 1836 video_enc->bit_rate_tolerance = video_bit_rate_tolerance;
85f07f22
FB
1837 video_enc->frame_rate = frame_rate;
1838
1839 video_enc->width = frame_width;
1840 video_enc->height = frame_height;
1841 if (!intra_only)
1842 video_enc->gop_size = gop_size;
1843 else
1844 video_enc->gop_size = 0;
1845 if (video_qscale || same_quality) {
1846 video_enc->flags |= CODEC_FLAG_QSCALE;
1847 video_enc->quality = video_qscale;
1848 }
9cdd6a24 1849
e4986da9
J
1850 if (use_hq) {
1851 video_enc->flags |= CODEC_FLAG_HQ;
1852 }
1853
29da453b
J
1854 if (use_4mv) {
1855 video_enc->flags |= CODEC_FLAG_HQ;
1856 video_enc->flags |= CODEC_FLAG_4MV;
1857 }
bc6caae2
J
1858
1859 if (b_frames) {
1860 if (codec_id != CODEC_ID_MPEG4) {
1861 fprintf(stderr, "\nB frames encoding only supported by MPEG-4.\n");
1862 exit(1);
1863 }
1864 video_enc->max_b_frames = b_frames;
1865 video_enc->b_frame_strategy = 0;
1866 video_enc->b_quant_factor = 2.0;
1867 }
1868
1869 video_enc->qmin = video_qmin;
1870 video_enc->qmax = video_qmax;
1871 video_enc->max_qdiff = video_qdiff;
1872 video_enc->qblur = video_qblur;
1873 video_enc->qcompress = video_qcomp;
3aa102be
MN
1874 video_enc->rc_eq = video_rc_eq;
1875 video_enc->rc_max_rate = video_rc_max_rate;
1876 video_enc->rc_min_rate = video_rc_min_rate;
1877 video_enc->rc_buffer_size = video_rc_buffer_size;
1878 video_enc->i_quant_factor = video_i_qfactor;
1879 video_enc->b_quant_factor = video_b_qfactor;
1880 video_enc->i_quant_offset = video_i_qoffset;
1881 video_enc->b_quant_offset = video_b_qoffset;
463678ac 1882 video_enc->dct_algo = dct_algo;
9cdd6a24 1883
43f1708f
J
1884 if (do_psnr)
1885 video_enc->get_psnr = 1;
1886 else
1887 video_enc->get_psnr = 0;
e4986da9 1888
101bea5f 1889 video_enc->me_method = me_method;
e4986da9 1890
cfcf0ffd 1891 /* XXX: need to find a way to set codec parameters */
79fdaa4c 1892 if (oc->oformat->flags & AVFMT_RGB24) {
cfcf0ffd
FB
1893 video_enc->pix_fmt = PIX_FMT_RGB24;
1894 }
85f07f22
FB
1895
1896 oc->streams[nb_streams] = st;
1897 nb_streams++;
1898 }
1899
1900 if (use_audio) {
1901 AVCodecContext *audio_enc;
1902
1903 st = av_mallocz(sizeof(AVStream));
1904 if (!st) {
1905 fprintf(stderr, "Could not alloc stream\n");
1906 exit(1);
1907 }
1908 audio_enc = &st->codec;
79fdaa4c 1909 codec_id = file_oformat->audio_codec;
85f07f22
FB
1910 if (audio_codec_id != CODEC_ID_NONE)
1911 codec_id = audio_codec_id;
1912 audio_enc->codec_id = codec_id;
1913 audio_enc->codec_type = CODEC_TYPE_AUDIO;
1914
1915 audio_enc->bit_rate = audio_bit_rate;
1916 audio_enc->sample_rate = audio_sample_rate;
e0d2714a
J
1917 /* For audio codecs other than AC3 we limit */
1918 /* the number of coded channels to stereo */
1919 if (audio_channels > 2 && codec_id != CODEC_ID_AC3) {
1920 audio_enc->channels = 2;
1921 } else
1922 audio_enc->channels = audio_channels;
85f07f22
FB
1923 oc->streams[nb_streams] = st;
1924 nb_streams++;
1925 }
1926
1927 oc->nb_streams = nb_streams;
1928
1929 if (!nb_streams) {
919f448d 1930 fprintf(stderr, "No audio or video streams available\n");
85f07f22
FB
1931 exit(1);
1932 }
1933
1934 if (str_title)
79fdaa4c 1935 pstrcpy(oc->title, sizeof(oc->title), str_title);
85f07f22 1936 if (str_author)
79fdaa4c 1937 pstrcpy(oc->author, sizeof(oc->author), str_author);
85f07f22 1938 if (str_copyright)
79fdaa4c 1939 pstrcpy(oc->copyright, sizeof(oc->copyright), str_copyright);
85f07f22 1940 if (str_comment)
79fdaa4c 1941 pstrcpy(oc->comment, sizeof(oc->comment), str_comment);
85f07f22
FB
1942 }
1943
1944 output_files[nb_output_files] = oc;
1945 /* dump the file content */
1946 dump_format(oc, nb_output_files, filename, 1);
1947 nb_output_files++;
1948
1949 strcpy(oc->filename, filename);
919f448d
FB
1950
1951 /* check filename in case of an image number is expected */
79fdaa4c
FB
1952 if (oc->oformat->flags & AVFMT_NEEDNUMBER) {
1953 if (filename_number_test(oc->filename) < 0) {
1954 print_error(oc->filename, AVERROR_NUMEXPECTED);
919f448d 1955 exit(1);
79fdaa4c 1956 }
919f448d
FB
1957 }
1958
79fdaa4c 1959 if (!(oc->oformat->flags & AVFMT_NOFILE)) {
85f07f22
FB
1960 /* test if it already exists to avoid loosing precious files */
1961 if (!file_overwrite &&
1962 (strchr(filename, ':') == NULL ||
1963 strstart(filename, "file:", NULL))) {
1964 if (url_exist(filename)) {
1965 int c;
1966
1967 printf("File '%s' already exists. Overwrite ? [y/N] ", filename);
1968 fflush(stdout);
1969 c = getchar();
1970 if (toupper(c) != 'Y') {
1971 fprintf(stderr, "Not overwriting - exiting\n");
1972 exit(1);
1973 }
1974 }
1975 }
1976
1977 /* open the file */
1978 if (url_fopen(&oc->pb, filename, URL_WRONLY) < 0) {
1979 fprintf(stderr, "Could not open '%s'\n", filename);
1980 exit(1);
1981 }
1982 }
1983
1984 /* reset some options */
79fdaa4c
FB
1985 file_oformat = NULL;
1986 file_iformat = NULL;
85f07f22
FB
1987 audio_disable = 0;
1988 video_disable = 0;
1989 audio_codec_id = CODEC_ID_NONE;
1990 video_codec_id = CODEC_ID_NONE;
1991}
1992
a38469e1
FB
1993/* prepare dummy protocols for grab */
1994void prepare_grab(void)
1995{
1996 int has_video, has_audio, i, j;
1997 AVFormatContext *oc;
1998 AVFormatContext *ic;
1999 AVFormatParameters ap1, *ap = &ap1;
2000
2001 /* see if audio/video inputs are needed */
2002 has_video = 0;
2003 has_audio = 0;
2004 memset(ap, 0, sizeof(*ap));
2005 for(j=0;j<nb_output_files;j++) {
2006 oc = output_files[j];
2007 for(i=0;i<oc->nb_streams;i++) {
2008 AVCodecContext *enc = &oc->streams[i]->codec;
2009 switch(enc->codec_type) {
2010 case CODEC_TYPE_AUDIO:
2011 if (enc->sample_rate > ap->sample_rate)
2012 ap->sample_rate = enc->sample_rate;
2013 if (enc->channels > ap->channels)
2014 ap->channels = enc->channels;
2015 has_audio = 1;
2016 break;
2017 case CODEC_TYPE_VIDEO:
2018 if (enc->width > ap->width)
2019 ap->width = enc->width;
2020 if (enc->height > ap->height)
2021 ap->height = enc->height;
2022 if (enc->frame_rate > ap->frame_rate)
2023 ap->frame_rate = enc->frame_rate;
2024 has_video = 1;
2025 break;
51bd4565 2026 default:
c04643a2 2027 av_abort();
a38469e1
FB
2028 }
2029 }
2030 }
2031
2032 if (has_video == 0 && has_audio == 0) {
2033 fprintf(stderr, "Output file must have at least one audio or video stream\n");
2034 exit(1);
2035 }
2036
2037 if (has_video) {
79fdaa4c
FB
2038 AVInputFormat *fmt1;
2039 fmt1 = av_find_input_format("video_grab_device");
2040 if (av_open_input_file(&ic, "", fmt1, 0, ap) < 0) {
bf5af568 2041 fprintf(stderr, "Could not find video grab device\n");
a38469e1
FB
2042 exit(1);
2043 }
79fdaa4c
FB
2044 /* by now video grab has one stream */
2045 ic->streams[0]->r_frame_rate = ap->frame_rate;
a38469e1
FB
2046 input_files[nb_input_files] = ic;
2047 dump_format(ic, nb_input_files, v4l_device, 0);
2048 nb_input_files++;
2049 }
2050 if (has_audio) {
79fdaa4c
FB
2051 AVInputFormat *fmt1;
2052 fmt1 = av_find_input_format("audio_device");
2053 if (av_open_input_file(&ic, "", fmt1, 0, ap) < 0) {
bf5af568 2054 fprintf(stderr, "Could not find audio grab device\n");
a38469e1
FB
2055 exit(1);
2056 }
2057 input_files[nb_input_files] = ic;
2058 dump_format(ic, nb_input_files, audio_device, 0);
2059 nb_input_files++;
2060 }
2061}
2062
a38469e1
FB
2063/* open the necessary output devices for playing */
2064void prepare_play(void)
2065{
bf5af568
FB
2066 file_iformat = NULL;
2067 file_oformat = guess_format("audio_device", NULL, NULL);
2068 if (!file_oformat) {
a38469e1
FB
2069 fprintf(stderr, "Could not find audio device\n");
2070 exit(1);
2071 }
2072
2073 opt_output_file(audio_device);
2074}
2075
2076
bdc4796f 2077#ifndef CONFIG_WIN32
5727b222
FB
2078INT64 getutime(void)
2079{
2080 struct rusage rusage;
2081
2082 getrusage(RUSAGE_SELF, &rusage);
2083 return (rusage.ru_utime.tv_sec * 1000000LL) + rusage.ru_utime.tv_usec;
2084}
bdc4796f
FB
2085#else
2086INT64 getutime(void)
2087{
2c4ae653 2088 return av_gettime();
bdc4796f
FB
2089}
2090#endif
5727b222 2091
79fdaa4c
FB
2092extern int ffm_nopts;
2093
2094void opt_bitexact(void)
2095{
2096 avcodec_set_bit_exact();
2097 /* disable generate of real time pts in ffm (need to be supressed anyway) */
2098 ffm_nopts = 1;
2099}
2100
85f07f22
FB
2101void show_formats(void)
2102{
79fdaa4c
FB
2103 AVInputFormat *ifmt;
2104 AVOutputFormat *ofmt;
85f07f22
FB
2105 URLProtocol *up;
2106 AVCodec *p;
2107 const char **pp;
2108
2109 printf("File formats:\n");
2110 printf(" Encoding:");
79fdaa4c
FB
2111 for(ofmt = first_oformat; ofmt != NULL; ofmt = ofmt->next) {
2112 printf(" %s", ofmt->name);
85f07f22
FB
2113 }
2114 printf("\n");
2115 printf(" Decoding:");
79fdaa4c
FB
2116 for(ifmt = first_iformat; ifmt != NULL; ifmt = ifmt->next) {
2117 printf(" %s", ifmt->name);
85f07f22
FB
2118 }
2119 printf("\n");
2120
2121 printf("Codecs:\n");
2122 printf(" Encoders:");
2123 for(p = first_avcodec; p != NULL; p = p->next) {
2124 if (p->encode)
2125 printf(" %s", p->name);
2126 }
2127 printf("\n");
2128
2129 printf(" Decoders:");
2130 for(p = first_avcodec; p != NULL; p = p->next) {
2131 if (p->decode)
2132 printf(" %s", p->name);
2133 }
2134 printf("\n");
2135
2136 printf("Supported file protocols:");
2137 for(up = first_protocol; up != NULL; up = up->next)
2138 printf(" %s:", up->name);
2139 printf("\n");
2140
2141 printf("Frame size abbreviations: sqcif qcif cif 4cif\n");
2142 printf("Motion estimation methods:");
2143 pp = motion_str;
2144 while (*pp) {
2145 printf(" %s", *pp);
101bea5f 2146 if ((pp - motion_str + 1) == ME_ZERO)
85f07f22 2147 printf("(fastest)");
101bea5f 2148 else if ((pp - motion_str + 1) == ME_FULL)
85f07f22 2149 printf("(slowest)");
101bea5f 2150 else if ((pp - motion_str + 1) == ME_EPZS)
85f07f22
FB
2151 printf("(default)");
2152 pp++;
2153 }
2154 printf("\n");
2155 exit(1);
2156}
2157
2158void show_help(void)
2159{
a38469e1 2160 const char *prog;
85f07f22
FB
2161 const OptionDef *po;
2162 int i, expert;
a38469e1
FB
2163
2164 prog = do_play ? "ffplay" : "ffmpeg";
85f07f22 2165
bf5af568 2166 printf("%s version " FFMPEG_VERSION ", Copyright (c) 2000, 2001, 2002 Fabrice Bellard\n",
a38469e1
FB
2167 prog);
2168
2169 if (!do_play) {
2170 printf("usage: ffmpeg [[options] -i input_file]... {[options] outfile}...\n"
2171 "Hyper fast MPEG1/MPEG4/H263/RV and AC3/MPEG audio encoder\n");
2172 } else {
2173 printf("usage: ffplay [options] input_file...\n"
2174 "Simple audio player\n");
2175 }
2176
2177 printf("\n"
85f07f22
FB
2178 "Main options are:\n");
2179 for(i=0;i<2;i++) {
2180 if (i == 1)
2181 printf("\nAdvanced options are:\n");
2182 for(po = options; po->name != NULL; po++) {
2183 char buf[64];
2184 expert = (po->flags & OPT_EXPERT) != 0;
2185 if (expert == i) {
2186 strcpy(buf, po->name);
2187 if (po->flags & HAS_ARG) {
2188 strcat(buf, " ");
2189 strcat(buf, po->argname);
2190 }
2191 printf("-%-17s %s\n", buf, po->help);
2192 }
2193 }
2194 }
2195
2196 exit(1);
2197}
2198
2199const OptionDef options[] = {
bdc4796f
FB
2200 { "L", 0, {(void*)show_licence}, "show license" },
2201 { "h", 0, {(void*)show_help}, "show help" },
2202 { "formats", 0, {(void*)show_formats}, "show available formats, codecs, protocols, ..." },
2203 { "f", HAS_ARG, {(void*)opt_format}, "force format", "fmt" },
0b97443a 2204 { "vcd", OPT_BOOL, {(void*)&mpeg_vcd}, "output Video CD MPEG-PS compliant file" },
bdc4796f
FB
2205 { "i", HAS_ARG, {(void*)opt_input_file}, "input file name", "filename" },
2206 { "y", OPT_BOOL, {(void*)&file_overwrite}, "overwrite output files" },
2207 { "map", HAS_ARG | OPT_EXPERT, {(void*)opt_map}, "set input stream mapping", "file:stream" },
2208 { "t", HAS_ARG, {(void*)opt_recording_time}, "set the recording time", "duration" },
2209 { "title", HAS_ARG | OPT_STRING, {(void*)&str_title}, "set the title", "string" },
2210 { "author", HAS_ARG | OPT_STRING, {(void*)&str_author}, "set the author", "string" },
2211 { "copyright", HAS_ARG | OPT_STRING, {(void*)&str_copyright}, "set the copyright", "string" },
2212 { "comment", HAS_ARG | OPT_STRING, {(void*)&str_comment}, "set the comment", "string" },
85f07f22 2213 /* video options */
bdc4796f
FB
2214 { "b", HAS_ARG, {(void*)opt_video_bitrate}, "set video bitrate (in kbit/s)", "bitrate" },
2215 { "r", HAS_ARG, {(void*)opt_frame_rate}, "set frame rate (in Hz)", "rate" },
2216 { "s", HAS_ARG, {(void*)opt_frame_size}, "set frame size (WxH or abbreviation)", "size" },
ab6d194a
MN
2217 { "croptop", HAS_ARG, {(void*)opt_frame_crop_top}, "set top crop band size (in pixels)", "size" },
2218 { "cropbottom", HAS_ARG, {(void*)opt_frame_crop_bottom}, "set bottom crop band size (in pixels)", "size" },
2219 { "cropleft", HAS_ARG, {(void*)opt_frame_crop_left}, "set left crop band size (in pixels)", "size" },
2220 { "cropright", HAS_ARG, {(void*)opt_frame_crop_right}, "set right crop band size (in pixels)", "size" },
bdc4796f
FB
2221 { "g", HAS_ARG | OPT_EXPERT, {(void*)opt_gop_size}, "set the group of picture size", "gop_size" },
2222 { "intra", OPT_BOOL | OPT_EXPERT, {(void*)&intra_only}, "use only intra frames"},
2223 { "vn", OPT_BOOL, {(void*)&video_disable}, "disable video" },
2224 { "qscale", HAS_ARG | OPT_EXPERT, {(void*)opt_qscale}, "use fixed video quantiser scale (VBR)", "q" },
9cdd6a24
MN
2225 { "qmin", HAS_ARG | OPT_EXPERT, {(void*)opt_qmin}, "min video quantiser scale (VBR)", "q" },
2226 { "qmax", HAS_ARG | OPT_EXPERT, {(void*)opt_qmax}, "max video quantiser scale (VBR)", "q" },
2227 { "qdiff", HAS_ARG | OPT_EXPERT, {(void*)opt_qdiff}, "max difference between the quantiser scale (VBR)", "q" },
2228 { "qblur", HAS_ARG | OPT_EXPERT, {(void*)opt_qblur}, "video quantiser scale blur (VBR)", "blur" },
2229 { "qcomp", HAS_ARG | OPT_EXPERT, {(void*)opt_qcomp}, "video quantiser scale compression (VBR)", "compression" },
3aa102be 2230 { "rc_eq", HAS_ARG | OPT_EXPERT, {(void*)opt_video_rc_eq}, "", "equation" },
9cdd6a24 2231 { "bt", HAS_ARG, {(void*)opt_video_bitrate_tolerance}, "set video bitrate tolerance (in kbit/s)", "tolerance" },
3aa102be
MN
2232 { "maxrate", HAS_ARG, {(void*)opt_video_bitrate_max}, "set max video bitrate tolerance (in kbit/s)", "bitrate" },
2233 { "minrate", HAS_ARG, {(void*)opt_video_bitrate_min}, "set min video bitrate tolerance (in kbit/s)", "bitrate" },
bf5af568 2234 { "vd", HAS_ARG | OPT_EXPERT, {(void*)opt_video_device}, "set video grab device", "device" },
bdc4796f
FB
2235 { "vcodec", HAS_ARG | OPT_EXPERT, {(void*)opt_video_codec}, "force video codec", "codec" },
2236 { "me", HAS_ARG | OPT_EXPERT, {(void*)opt_motion_estimation}, "set motion estimation method",
85f07f22 2237 "method" },
463678ac 2238 { "dct_algo", HAS_ARG | OPT_EXPERT, {(void*)opt_dct_algo}, "set dct algo", "algo" },
bc6caae2 2239 { "bf", HAS_ARG | OPT_EXPERT, {(void*)opt_b_frames}, "use 'frames' B frames (only MPEG-4)", "frames" },
e4986da9 2240 { "hq", OPT_BOOL | OPT_EXPERT, {(void*)&use_hq}, "activate high quality settings" },
29da453b 2241 { "4mv", OPT_BOOL | OPT_EXPERT, {(void*)&use_4mv}, "use four motion vector by macroblock (only MPEG-4)" },
fe670d09 2242 { "bug", HAS_ARG | OPT_EXPERT, {(void*)opt_workaround_bugs}, "workaround not auto detected encoder bugs", "param" },
bdc4796f 2243 { "sameq", OPT_BOOL, {(void*)&same_quality},
85f07f22
FB
2244 "use same video quality as source (implies VBR)" },
2245 /* audio options */
bdc4796f
FB
2246 { "ab", HAS_ARG, {(void*)opt_audio_bitrate}, "set audio bitrate (in kbit/s)", "bitrate", },
2247 { "ar", HAS_ARG, {(void*)opt_audio_rate}, "set audio sampling rate (in Hz)", "rate" },
2248 { "ac", HAS_ARG, {(void*)opt_audio_channels}, "set number of audio channels", "channels" },
2249 { "an", OPT_BOOL, {(void*)&audio_disable}, "disable audio" },
bdc4796f 2250 { "ad", HAS_ARG | OPT_EXPERT, {(void*)opt_audio_device}, "set audio device", "device" },
bdc4796f
FB
2251 { "acodec", HAS_ARG | OPT_EXPERT, {(void*)opt_audio_codec}, "force audio codec", "codec" },
2252 { "deinterlace", OPT_BOOL | OPT_EXPERT, {(void*)&do_deinterlace},
cfcf0ffd 2253 "deinterlace pictures" },
bdc4796f 2254 { "benchmark", OPT_BOOL | OPT_EXPERT, {(void*)&do_benchmark},
5727b222 2255 "add timings for benchmarking" },
a0663ba4
FB
2256 { "hex", OPT_BOOL | OPT_EXPERT, {(void*)&do_hex_dump},
2257 "dump each input packet" },
ce7c56c2
J
2258 { "psnr", OPT_BOOL | OPT_EXPERT, {(void*)&do_psnr}, "calculate PSNR of compressed frames" },
2259 { "vstats", OPT_BOOL | OPT_EXPERT, {(void*)&do_vstats}, "dump video coding statistics to file" },
79fdaa4c 2260 { "bitexact", OPT_EXPERT, {(void*)opt_bitexact}, "only use bit exact algorithms (for codec testing)" },
85f07f22
FB
2261 { NULL, },
2262};
2263
2264int main(int argc, char **argv)
2265{
2266 int optindex, i;
2267 const char *opt, *arg;
2268 const OptionDef *po;
a38469e1 2269 INT64 ti;
85f07f22 2270
2c4ae653 2271 av_register_all();
85f07f22 2272
a38469e1
FB
2273 /* detect if invoked as player */
2274 i = strlen(argv[0]);
2275 if (i >= 6 && !strcmp(argv[0] + i - 6, "ffplay"))
2276 do_play = 1;
2277
85f07f22
FB
2278 if (argc <= 1)
2279 show_help();
a38469e1
FB
2280
2281 /* parse options */
85f07f22
FB
2282 optindex = 1;
2283 while (optindex < argc) {
2284 opt = argv[optindex++];
2285
2286 if (opt[0] == '-' && opt[1] != '\0') {
2287 po = options;
2288 while (po->name != NULL) {
2289 if (!strcmp(opt + 1, po->name))
2290 break;
2291 po++;
2292 }
2293 if (!po->name) {
2294 fprintf(stderr, "%s: unrecognized option '%s'\n", argv[0], opt);
2295 exit(1);
2296 }
2297 arg = NULL;
2298 if (po->flags & HAS_ARG)
2299 arg = argv[optindex++];
2300 if (po->flags & OPT_STRING) {
2301 char *str;
2302 str = strdup(arg);
2303 *po->u.str_arg = str;
2304 } else if (po->flags & OPT_BOOL) {
2305 *po->u.int_arg = 1;
2306 } else {
2307 po->u.func_arg(arg);
2308 }
2309 } else {
a38469e1
FB
2310 if (!do_play) {
2311 opt_output_file(opt);
2312 } else {
2313 opt_input_file(opt);
2314 }
85f07f22
FB
2315 }
2316 }
2317
2318
a38469e1
FB
2319 if (!do_play) {
2320 /* file converter / grab */
85f07f22
FB
2321 if (nb_output_files <= 0) {
2322 fprintf(stderr, "Must supply at least one output file\n");
2323 exit(1);
2324 }
a38469e1
FB
2325
2326 if (nb_input_files == 0) {
2327 prepare_grab();
5727b222 2328 }
a38469e1
FB
2329 } else {
2330 /* player */
2331 if (nb_input_files <= 0) {
2332 fprintf(stderr, "Must supply at least one input file\n");
2333 exit(1);
2334 }
2335 prepare_play();
2336 }
2337
2338 ti = getutime();
2339 av_encode(output_files, nb_output_files, input_files, nb_input_files,
2340 stream_maps, nb_stream_maps);
2341 ti = getutime() - ti;
2342 if (do_benchmark) {
2343 printf("bench: utime=%0.3fs\n", ti / 1000000.0);
85f07f22
FB
2344 }
2345
2346 /* close files */
2347 for(i=0;i<nb_output_files;i++) {
79fdaa4c 2348 if (!(output_files[i]->oformat->flags & AVFMT_NOFILE))
85f07f22
FB
2349 url_fclose(&output_files[i]->pb);
2350 }
79fdaa4c
FB
2351 for(i=0;i<nb_input_files;i++)
2352 av_close_input_file(input_files[i]);
85f07f22
FB
2353
2354 return 0;
2355}