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