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