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