fixing memalign
[libav.git] / ffmpeg.c
CommitLineData
85f07f22
FB
1/*
2 * FFmpeg main
bf5af568 3 * Copyright (c) 2000, 2001, 2002 Fabrice Bellard
85f07f22 4 *
bf5af568
FB
5 * This library is free software; you can redistribute it and/or
6 * modify it under the terms of the GNU Lesser General Public
7 * License as published by the Free Software Foundation; either
8 * version 2 of the License, or (at your option) any later version.
85f07f22 9 *
bf5af568 10 * This library is distributed in the hope that it will be useful,
85f07f22 11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
bf5af568
FB
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 * Lesser General Public License for more details.
85f07f22 14 *
bf5af568
FB
15 * You should have received a copy of the GNU Lesser General Public
16 * License along with this library; if not, write to the Free Software
17 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
85f07f22 18 */
daf8e955
FB
19#define HAVE_AV_CONFIG_H
20#include "avformat.h"
6dc96cb0 21#include "tick.h"
daf8e955 22
bdc4796f 23#ifndef CONFIG_WIN32
85f07f22
FB
24#include <unistd.h>
25#include <fcntl.h>
26#include <sys/ioctl.h>
85f07f22 27#include <sys/time.h>
85f07f22 28#include <termios.h>
5727b222 29#include <sys/resource.h>
bdc4796f 30#endif
27a5e8b8
FR
31#ifdef __BEOS__
32/* for snooze() */
33#include <OS.h>
34#endif
bf5af568
FB
35#include <time.h>
36#include <ctype.h>
85f07f22 37
85f07f22 38
bdc4796f
FB
39#define MAXINT64 INT64_C(0x7fffffffffffffff)
40
85f07f22
FB
41typedef struct {
42 const char *name;
43 int flags;
44#define HAS_ARG 0x0001
45#define OPT_BOOL 0x0002
46#define OPT_EXPERT 0x0004
47#define OPT_STRING 0x0008
48 union {
49 void (*func_arg)();
50 int *int_arg;
51 char **str_arg;
52 } u;
53 const char *help;
54 const char *argname;
55} OptionDef;
56
57/* select an input stream for an output stream */
58typedef struct AVStreamMap {
59 int file_index;
60 int stream_index;
61} AVStreamMap;
62
63extern const OptionDef options[];
64
65void show_help(void);
66
67#define MAX_FILES 20
68
69static AVFormatContext *input_files[MAX_FILES];
70static int nb_input_files = 0;
71
72static AVFormatContext *output_files[MAX_FILES];
73static int nb_output_files = 0;
74
75static AVStreamMap stream_maps[MAX_FILES];
76static int nb_stream_maps;
77
79fdaa4c
FB
78static AVInputFormat *file_iformat;
79static AVOutputFormat *file_oformat;
85f07f22
FB
80static int frame_width = 160;
81static int frame_height = 128;
ab6d194a
MN
82static int frame_topBand = 0;
83static int frame_bottomBand = 0;
84static int frame_leftBand = 0;
85static int frame_rightBand = 0;
85f07f22 86static int frame_rate = 25 * FRAME_RATE_BASE;
3aa102be
MN
87static int video_bit_rate = 200*1000;
88static int video_bit_rate_tolerance = 4000*1000;
85f07f22 89static int video_qscale = 0;
3aa102be
MN
90static int video_qmin = 2;
91static int video_qmax = 31;
9cdd6a24
MN
92static int video_qdiff = 3;
93static float video_qblur = 0.5;
94static float video_qcomp = 0.5;
3aa102be
MN
95static float video_rc_qsquish=1.0;
96static float video_rc_qmod_amp=0;
97static int video_rc_qmod_freq=0;
98static char *video_rc_override_string=NULL;
99static char *video_rc_eq="tex^qComp";
100static int video_rc_buffer_size=0;
101static float video_rc_buffer_aggressivity=1.0;
102static int video_rc_max_rate=0;
103static int video_rc_min_rate=0;
104static float video_rc_initial_cplx=0;
105static float video_b_qfactor = 1.25;
106static float video_b_qoffset = 1.25;
107static float video_i_qfactor = 0.8;
108static float video_i_qoffset = 0.0;
101bea5f 109static int me_method = 0;
85f07f22
FB
110static int video_disable = 0;
111static int video_codec_id = CODEC_ID_NONE;
112static int same_quality = 0;
bc6caae2 113static int b_frames = 0;
e4986da9 114static int use_hq = 0;
29da453b 115static int use_4mv = 0;
cfcf0ffd 116static int do_deinterlace = 0;
fe670d09 117static int workaround_bugs = 0;
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
FB
1550
1551void opt_audio_bitrate(const char *arg)
1552{
1553 audio_bit_rate = atoi(arg) * 1000;
1554}
1555
1556void opt_audio_rate(const char *arg)
1557{
1558 audio_sample_rate = atoi(arg);
1559}
1560
1561void opt_audio_channels(const char *arg)
1562{
1563 audio_channels = atoi(arg);
1564}
1565
1566void opt_video_device(const char *arg)
1567{
1568 v4l_device = strdup(arg);
1569}
1570
1571void opt_audio_device(const char *arg)
1572{
1573 audio_device = strdup(arg);
1574}
1575
1576void opt_audio_codec(const char *arg)
1577{
1578 AVCodec *p;
1579
1580 p = first_avcodec;
1581 while (p) {
1582 if (!strcmp(p->name, arg) && p->type == CODEC_TYPE_AUDIO)
1583 break;
1584 p = p->next;
1585 }
1586 if (p == NULL) {
1587 fprintf(stderr, "Unknown audio codec '%s'\n", arg);
1588 exit(1);
1589 } else {
1590 audio_codec_id = p->id;
1591 }
1592}
1593
1594const char *motion_str[] = {
1595 "zero",
1596 "full",
1597 "log",
1598 "phods",
7084c149
MN
1599 "epzs",
1600 "x1",
85f07f22
FB
1601 NULL,
1602};
1603
1604void opt_motion_estimation(const char *arg)
1605{
1606 const char **p;
1607 p = motion_str;
1608 for(;;) {
1609 if (!*p) {
1610 fprintf(stderr, "Unknown motion estimation method '%s'\n", arg);
1611 exit(1);
1612 }
1613 if (!strcmp(*p, arg))
1614 break;
1615 p++;
1616 }
101bea5f 1617 me_method = (p - motion_str) + 1;
85f07f22
FB
1618}
1619
1620void opt_video_codec(const char *arg)
1621{
1622 AVCodec *p;
1623
1624 p = first_avcodec;
1625 while (p) {
1626 if (!strcmp(p->name, arg) && p->type == CODEC_TYPE_VIDEO)
1627 break;
1628 p = p->next;
1629 }
1630 if (p == NULL) {
1631 fprintf(stderr, "Unknown video codec '%s'\n", arg);
1632 exit(1);
1633 } else {
1634 video_codec_id = p->id;
1635 }
1636}
1637
1638void opt_map(const char *arg)
1639{
1640 AVStreamMap *m;
1641 const char *p;
1642
1643 p = arg;
1644 m = &stream_maps[nb_stream_maps++];
1645
1646 m->file_index = strtol(arg, (char **)&p, 0);
1647 if (*p)
1648 p++;
a5dc85ef
J
1649
1650 m->stream_index = strtol(p, (char **)&p, 0);
85f07f22
FB
1651}
1652
1653void opt_recording_time(const char *arg)
1654{
1655 recording_time = parse_date(arg, 1);
1656}
1657
79fdaa4c 1658void print_error(const char *filename, int err)
919f448d 1659{
79fdaa4c
FB
1660 switch(err) {
1661 case AVERROR_NUMEXPECTED:
919f448d
FB
1662 fprintf(stderr, "%s: Incorrect image filename syntax.\n"
1663 "Use '%%d' to specify the image number:\n"
1664 " for img1.jpg, img2.jpg, ..., use 'img%%d.jpg';\n"
1665 " for img001.jpg, img002.jpg, ..., use 'img%%03d.jpg'.\n",
1666 filename);
79fdaa4c
FB
1667 break;
1668 case AVERROR_INVALIDDATA:
1669 fprintf(stderr, "%s: Error while parsing header\n", filename);
1670 break;
1671 case AVERROR_NOFMT:
1672 fprintf(stderr, "%s: Unknown format\n", filename);
1673 break;
1674 default:
1675 fprintf(stderr, "%s: Error while opening file\n", filename);
1676 break;
919f448d
FB
1677 }
1678}
85f07f22
FB
1679
1680void opt_input_file(const char *filename)
1681{
1682 AVFormatContext *ic;
1683 AVFormatParameters params, *ap = &params;
6dc96cb0 1684 int err, i, ret, rfps;
85f07f22 1685
85f07f22 1686 /* get default parameters from command line */
79fdaa4c
FB
1687 memset(ap, 0, sizeof(*ap));
1688 ap->sample_rate = audio_sample_rate;
1689 ap->channels = audio_channels;
1690 ap->frame_rate = frame_rate;
1691 ap->width = frame_width;
1692 ap->height = frame_height;
1693
1694 /* open the input file with generic libav function */
1695 err = av_open_input_file(&ic, filename, file_iformat, 0, ap);
85f07f22 1696 if (err < 0) {
79fdaa4c 1697 print_error(filename, err);
85f07f22
FB
1698 exit(1);
1699 }
1700
79fdaa4c
FB
1701 /* If not enough info to get the stream parameters, we decode the
1702 first frames to get it. (used in mpeg case for example) */
1703 ret = av_find_stream_info(ic);
85f07f22
FB
1704 if (ret < 0) {
1705 fprintf(stderr, "%s: could not find codec parameters\n", filename);
1706 exit(1);
1707 }
1708
1709 /* update the current parameters so that they match the one of the input stream */
1710 for(i=0;i<ic->nb_streams;i++) {
1711 AVCodecContext *enc = &ic->streams[i]->codec;
1712 switch(enc->codec_type) {
1713 case CODEC_TYPE_AUDIO:
e0d2714a 1714 //fprintf(stderr, "\nInput Audio channels: %d", enc->channels);
85f07f22
FB
1715 audio_channels = enc->channels;
1716 audio_sample_rate = enc->sample_rate;
1717 break;
1718 case CODEC_TYPE_VIDEO:
1719 frame_height = enc->height;
1720 frame_width = enc->width;
79fdaa4c 1721 rfps = ic->streams[i]->r_frame_rate;
fe670d09 1722 enc->workaround_bugs = workaround_bugs;
8409b8fe 1723 enc->error_resilience = error_resilience;
79fdaa4c 1724 if (enc->frame_rate != rfps) {
6dc96cb0
J
1725 fprintf(stderr,"\nSeems that stream %d comes from film source: %2.2f->%2.2f\n",
1726 i, (float)enc->frame_rate / FRAME_RATE_BASE,
1727 (float)rfps / FRAME_RATE_BASE);
79fdaa4c 1728 }
bf5af568
FB
1729 /* update the current frame rate to match the stream frame rate */
1730 frame_rate = rfps;
85f07f22 1731 break;
51bd4565 1732 default:
c04643a2 1733 av_abort();
85f07f22
FB
1734 }
1735 }
1736
1737 input_files[nb_input_files] = ic;
1738 /* dump the file content */
1739 dump_format(ic, nb_input_files, filename, 0);
1740 nb_input_files++;
79fdaa4c
FB
1741 file_iformat = NULL;
1742 file_oformat = NULL;
85f07f22
FB
1743}
1744
919f448d
FB
1745void check_audio_video_inputs(int *has_video_ptr, int *has_audio_ptr)
1746{
1747 int has_video, has_audio, i, j;
1748 AVFormatContext *ic;
1749
1750 has_video = 0;
1751 has_audio = 0;
1752 for(j=0;j<nb_input_files;j++) {
1753 ic = input_files[j];
1754 for(i=0;i<ic->nb_streams;i++) {
1755 AVCodecContext *enc = &ic->streams[i]->codec;
1756 switch(enc->codec_type) {
1757 case CODEC_TYPE_AUDIO:
1758 has_audio = 1;
1759 break;
1760 case CODEC_TYPE_VIDEO:
1761 has_video = 1;
1762 break;
51bd4565 1763 default:
c04643a2 1764 av_abort();
919f448d
FB
1765 }
1766 }
1767 }
1768 *has_video_ptr = has_video;
1769 *has_audio_ptr = has_audio;
1770}
1771
85f07f22
FB
1772void opt_output_file(const char *filename)
1773{
1774 AVStream *st;
1775 AVFormatContext *oc;
919f448d 1776 int use_video, use_audio, nb_streams, input_has_video, input_has_audio;
85f07f22
FB
1777 int codec_id;
1778
1779 if (!strcmp(filename, "-"))
1780 filename = "pipe:";
1781
1782 oc = av_mallocz(sizeof(AVFormatContext));
1783
79fdaa4c
FB
1784 if (!file_oformat) {
1785 file_oformat = guess_format(NULL, filename, NULL);
1786 if (!file_oformat) {
1787 fprintf(stderr, "Unable for find a suitable output format for '%s'\n",
1788 filename);
1789 exit(1);
1790 }
85f07f22
FB
1791 }
1792
79fdaa4c 1793 oc->oformat = file_oformat;
85f07f22 1794
79fdaa4c 1795 if (!strcmp(file_oformat->name, "ffm") &&
85f07f22
FB
1796 strstart(filename, "http:", NULL)) {
1797 /* special case for files sent to ffserver: we get the stream
1798 parameters from ffserver */
1799 if (read_ffserver_streams(oc, filename) < 0) {
1800 fprintf(stderr, "Could not read stream parameters from '%s'\n", filename);
1801 exit(1);
1802 }
1803 } else {
79fdaa4c
FB
1804 use_video = file_oformat->video_codec != CODEC_ID_NONE;
1805 use_audio = file_oformat->audio_codec != CODEC_ID_NONE;
919f448d 1806
e30a2846
FB
1807 /* disable if no corresponding type found and at least one
1808 input file */
1809 if (nb_input_files > 0) {
1810 check_audio_video_inputs(&input_has_video, &input_has_audio);
1811 if (!input_has_video)
1812 use_video = 0;
1813 if (!input_has_audio)
1814 use_audio = 0;
1815 }
919f448d
FB
1816
1817 /* manual disable */
85f07f22
FB
1818 if (audio_disable) {
1819 use_audio = 0;
1820 }
1821 if (video_disable) {
1822 use_video = 0;
1823 }
1824
1825 nb_streams = 0;
1826 if (use_video) {
1827 AVCodecContext *video_enc;
1828
1829 st = av_mallocz(sizeof(AVStream));
1830 if (!st) {
1831 fprintf(stderr, "Could not alloc stream\n");
1832 exit(1);
1833 }
1834 video_enc = &st->codec;
1835
79fdaa4c 1836 codec_id = file_oformat->video_codec;
85f07f22
FB
1837 if (video_codec_id != CODEC_ID_NONE)
1838 codec_id = video_codec_id;
1839
1840 video_enc->codec_id = codec_id;
1841 video_enc->codec_type = CODEC_TYPE_VIDEO;
1842
1843 video_enc->bit_rate = video_bit_rate;
9cdd6a24 1844 video_enc->bit_rate_tolerance = video_bit_rate_tolerance;
85f07f22
FB
1845 video_enc->frame_rate = frame_rate;
1846
1847 video_enc->width = frame_width;
1848 video_enc->height = frame_height;
1849 if (!intra_only)
1850 video_enc->gop_size = gop_size;
1851 else
1852 video_enc->gop_size = 0;
1853 if (video_qscale || same_quality) {
1854 video_enc->flags |= CODEC_FLAG_QSCALE;
1855 video_enc->quality = video_qscale;
1856 }
9cdd6a24 1857
e4986da9
J
1858 if (use_hq) {
1859 video_enc->flags |= CODEC_FLAG_HQ;
1860 }
1861
29da453b
J
1862 if (use_4mv) {
1863 video_enc->flags |= CODEC_FLAG_HQ;
1864 video_enc->flags |= CODEC_FLAG_4MV;
1865 }
bc6caae2
J
1866
1867 if (b_frames) {
1868 if (codec_id != CODEC_ID_MPEG4) {
1869 fprintf(stderr, "\nB frames encoding only supported by MPEG-4.\n");
1870 exit(1);
1871 }
1872 video_enc->max_b_frames = b_frames;
1873 video_enc->b_frame_strategy = 0;
1874 video_enc->b_quant_factor = 2.0;
1875 }
1876
1877 video_enc->qmin = video_qmin;
1878 video_enc->qmax = video_qmax;
1879 video_enc->max_qdiff = video_qdiff;
1880 video_enc->qblur = video_qblur;
1881 video_enc->qcompress = video_qcomp;
3aa102be
MN
1882 video_enc->rc_eq = video_rc_eq;
1883 video_enc->rc_max_rate = video_rc_max_rate;
1884 video_enc->rc_min_rate = video_rc_min_rate;
1885 video_enc->rc_buffer_size = video_rc_buffer_size;
1886 video_enc->i_quant_factor = video_i_qfactor;
1887 video_enc->b_quant_factor = video_b_qfactor;
1888 video_enc->i_quant_offset = video_i_qoffset;
1889 video_enc->b_quant_offset = video_b_qoffset;
463678ac 1890 video_enc->dct_algo = dct_algo;
9cdd6a24 1891
43f1708f
J
1892 if (do_psnr)
1893 video_enc->get_psnr = 1;
1894 else
1895 video_enc->get_psnr = 0;
e4986da9 1896
101bea5f 1897 video_enc->me_method = me_method;
e4986da9 1898
cfcf0ffd 1899 /* XXX: need to find a way to set codec parameters */
79fdaa4c 1900 if (oc->oformat->flags & AVFMT_RGB24) {
cfcf0ffd
FB
1901 video_enc->pix_fmt = PIX_FMT_RGB24;
1902 }
85f07f22
FB
1903
1904 oc->streams[nb_streams] = st;
1905 nb_streams++;
1906 }
1907
1908 if (use_audio) {
1909 AVCodecContext *audio_enc;
1910
1911 st = av_mallocz(sizeof(AVStream));
1912 if (!st) {
1913 fprintf(stderr, "Could not alloc stream\n");
1914 exit(1);
1915 }
1916 audio_enc = &st->codec;
79fdaa4c 1917 codec_id = file_oformat->audio_codec;
85f07f22
FB
1918 if (audio_codec_id != CODEC_ID_NONE)
1919 codec_id = audio_codec_id;
1920 audio_enc->codec_id = codec_id;
1921 audio_enc->codec_type = CODEC_TYPE_AUDIO;
1922
1923 audio_enc->bit_rate = audio_bit_rate;
1924 audio_enc->sample_rate = audio_sample_rate;
e0d2714a
J
1925 /* For audio codecs other than AC3 we limit */
1926 /* the number of coded channels to stereo */
1927 if (audio_channels > 2 && codec_id != CODEC_ID_AC3) {
1928 audio_enc->channels = 2;
1929 } else
1930 audio_enc->channels = audio_channels;
85f07f22
FB
1931 oc->streams[nb_streams] = st;
1932 nb_streams++;
1933 }
1934
1935 oc->nb_streams = nb_streams;
1936
1937 if (!nb_streams) {
919f448d 1938 fprintf(stderr, "No audio or video streams available\n");
85f07f22
FB
1939 exit(1);
1940 }
1941
1942 if (str_title)
79fdaa4c 1943 pstrcpy(oc->title, sizeof(oc->title), str_title);
85f07f22 1944 if (str_author)
79fdaa4c 1945 pstrcpy(oc->author, sizeof(oc->author), str_author);
85f07f22 1946 if (str_copyright)
79fdaa4c 1947 pstrcpy(oc->copyright, sizeof(oc->copyright), str_copyright);
85f07f22 1948 if (str_comment)
79fdaa4c 1949 pstrcpy(oc->comment, sizeof(oc->comment), str_comment);
85f07f22
FB
1950 }
1951
1952 output_files[nb_output_files] = oc;
1953 /* dump the file content */
1954 dump_format(oc, nb_output_files, filename, 1);
1955 nb_output_files++;
1956
1957 strcpy(oc->filename, filename);
919f448d
FB
1958
1959 /* check filename in case of an image number is expected */
79fdaa4c
FB
1960 if (oc->oformat->flags & AVFMT_NEEDNUMBER) {
1961 if (filename_number_test(oc->filename) < 0) {
1962 print_error(oc->filename, AVERROR_NUMEXPECTED);
919f448d 1963 exit(1);
79fdaa4c 1964 }
919f448d
FB
1965 }
1966
79fdaa4c 1967 if (!(oc->oformat->flags & AVFMT_NOFILE)) {
85f07f22
FB
1968 /* test if it already exists to avoid loosing precious files */
1969 if (!file_overwrite &&
1970 (strchr(filename, ':') == NULL ||
1971 strstart(filename, "file:", NULL))) {
1972 if (url_exist(filename)) {
1973 int c;
1974
1975 printf("File '%s' already exists. Overwrite ? [y/N] ", filename);
1976 fflush(stdout);
1977 c = getchar();
1978 if (toupper(c) != 'Y') {
1979 fprintf(stderr, "Not overwriting - exiting\n");
1980 exit(1);
1981 }
1982 }
1983 }
1984
1985 /* open the file */
1986 if (url_fopen(&oc->pb, filename, URL_WRONLY) < 0) {
1987 fprintf(stderr, "Could not open '%s'\n", filename);
1988 exit(1);
1989 }
1990 }
1991
1992 /* reset some options */
79fdaa4c
FB
1993 file_oformat = NULL;
1994 file_iformat = NULL;
85f07f22
FB
1995 audio_disable = 0;
1996 video_disable = 0;
1997 audio_codec_id = CODEC_ID_NONE;
1998 video_codec_id = CODEC_ID_NONE;
1999}
2000
a38469e1
FB
2001/* prepare dummy protocols for grab */
2002void prepare_grab(void)
2003{
2004 int has_video, has_audio, i, j;
2005 AVFormatContext *oc;
2006 AVFormatContext *ic;
2007 AVFormatParameters ap1, *ap = &ap1;
2008
2009 /* see if audio/video inputs are needed */
2010 has_video = 0;
2011 has_audio = 0;
2012 memset(ap, 0, sizeof(*ap));
2013 for(j=0;j<nb_output_files;j++) {
2014 oc = output_files[j];
2015 for(i=0;i<oc->nb_streams;i++) {
2016 AVCodecContext *enc = &oc->streams[i]->codec;
2017 switch(enc->codec_type) {
2018 case CODEC_TYPE_AUDIO:
2019 if (enc->sample_rate > ap->sample_rate)
2020 ap->sample_rate = enc->sample_rate;
2021 if (enc->channels > ap->channels)
2022 ap->channels = enc->channels;
2023 has_audio = 1;
2024 break;
2025 case CODEC_TYPE_VIDEO:
2026 if (enc->width > ap->width)
2027 ap->width = enc->width;
2028 if (enc->height > ap->height)
2029 ap->height = enc->height;
2030 if (enc->frame_rate > ap->frame_rate)
2031 ap->frame_rate = enc->frame_rate;
2032 has_video = 1;
2033 break;
51bd4565 2034 default:
c04643a2 2035 av_abort();
a38469e1
FB
2036 }
2037 }
2038 }
2039
2040 if (has_video == 0 && has_audio == 0) {
2041 fprintf(stderr, "Output file must have at least one audio or video stream\n");
2042 exit(1);
2043 }
2044
2045 if (has_video) {
79fdaa4c
FB
2046 AVInputFormat *fmt1;
2047 fmt1 = av_find_input_format("video_grab_device");
2048 if (av_open_input_file(&ic, "", fmt1, 0, ap) < 0) {
bf5af568 2049 fprintf(stderr, "Could not find video grab device\n");
a38469e1
FB
2050 exit(1);
2051 }
79fdaa4c
FB
2052 /* by now video grab has one stream */
2053 ic->streams[0]->r_frame_rate = ap->frame_rate;
a38469e1
FB
2054 input_files[nb_input_files] = ic;
2055 dump_format(ic, nb_input_files, v4l_device, 0);
2056 nb_input_files++;
2057 }
2058 if (has_audio) {
79fdaa4c
FB
2059 AVInputFormat *fmt1;
2060 fmt1 = av_find_input_format("audio_device");
2061 if (av_open_input_file(&ic, "", fmt1, 0, ap) < 0) {
bf5af568 2062 fprintf(stderr, "Could not find audio grab device\n");
a38469e1
FB
2063 exit(1);
2064 }
2065 input_files[nb_input_files] = ic;
2066 dump_format(ic, nb_input_files, audio_device, 0);
2067 nb_input_files++;
2068 }
2069}
2070
a38469e1
FB
2071/* open the necessary output devices for playing */
2072void prepare_play(void)
2073{
bf5af568
FB
2074 file_iformat = NULL;
2075 file_oformat = guess_format("audio_device", NULL, NULL);
2076 if (!file_oformat) {
a38469e1
FB
2077 fprintf(stderr, "Could not find audio device\n");
2078 exit(1);
2079 }
2080
2081 opt_output_file(audio_device);
2082}
2083
2084
bdc4796f 2085#ifndef CONFIG_WIN32
5727b222
FB
2086INT64 getutime(void)
2087{
2088 struct rusage rusage;
2089
2090 getrusage(RUSAGE_SELF, &rusage);
2091 return (rusage.ru_utime.tv_sec * 1000000LL) + rusage.ru_utime.tv_usec;
2092}
bdc4796f
FB
2093#else
2094INT64 getutime(void)
2095{
2c4ae653 2096 return av_gettime();
bdc4796f
FB
2097}
2098#endif
5727b222 2099
79fdaa4c
FB
2100extern int ffm_nopts;
2101
2102void opt_bitexact(void)
2103{
2104 avcodec_set_bit_exact();
2105 /* disable generate of real time pts in ffm (need to be supressed anyway) */
2106 ffm_nopts = 1;
2107}
2108
85f07f22
FB
2109void show_formats(void)
2110{
79fdaa4c
FB
2111 AVInputFormat *ifmt;
2112 AVOutputFormat *ofmt;
85f07f22
FB
2113 URLProtocol *up;
2114 AVCodec *p;
2115 const char **pp;
2116
2117 printf("File formats:\n");
2118 printf(" Encoding:");
79fdaa4c
FB
2119 for(ofmt = first_oformat; ofmt != NULL; ofmt = ofmt->next) {
2120 printf(" %s", ofmt->name);
85f07f22
FB
2121 }
2122 printf("\n");
2123 printf(" Decoding:");
79fdaa4c
FB
2124 for(ifmt = first_iformat; ifmt != NULL; ifmt = ifmt->next) {
2125 printf(" %s", ifmt->name);
85f07f22
FB
2126 }
2127 printf("\n");
2128
2129 printf("Codecs:\n");
2130 printf(" Encoders:");
2131 for(p = first_avcodec; p != NULL; p = p->next) {
2132 if (p->encode)
2133 printf(" %s", p->name);
2134 }
2135 printf("\n");
2136
2137 printf(" Decoders:");
2138 for(p = first_avcodec; p != NULL; p = p->next) {
2139 if (p->decode)
2140 printf(" %s", p->name);
2141 }
2142 printf("\n");
2143
2144 printf("Supported file protocols:");
2145 for(up = first_protocol; up != NULL; up = up->next)
2146 printf(" %s:", up->name);
2147 printf("\n");
2148
2149 printf("Frame size abbreviations: sqcif qcif cif 4cif\n");
2150 printf("Motion estimation methods:");
2151 pp = motion_str;
2152 while (*pp) {
2153 printf(" %s", *pp);
101bea5f 2154 if ((pp - motion_str + 1) == ME_ZERO)
85f07f22 2155 printf("(fastest)");
101bea5f 2156 else if ((pp - motion_str + 1) == ME_FULL)
85f07f22 2157 printf("(slowest)");
101bea5f 2158 else if ((pp - motion_str + 1) == ME_EPZS)
85f07f22
FB
2159 printf("(default)");
2160 pp++;
2161 }
2162 printf("\n");
2163 exit(1);
2164}
2165
2166void show_help(void)
2167{
a38469e1 2168 const char *prog;
85f07f22
FB
2169 const OptionDef *po;
2170 int i, expert;
a38469e1
FB
2171
2172 prog = do_play ? "ffplay" : "ffmpeg";
85f07f22 2173
bf5af568 2174 printf("%s version " FFMPEG_VERSION ", Copyright (c) 2000, 2001, 2002 Fabrice Bellard\n",
a38469e1
FB
2175 prog);
2176
2177 if (!do_play) {
2178 printf("usage: ffmpeg [[options] -i input_file]... {[options] outfile}...\n"
2179 "Hyper fast MPEG1/MPEG4/H263/RV and AC3/MPEG audio encoder\n");
2180 } else {
2181 printf("usage: ffplay [options] input_file...\n"
2182 "Simple audio player\n");
2183 }
2184
2185 printf("\n"
85f07f22
FB
2186 "Main options are:\n");
2187 for(i=0;i<2;i++) {
2188 if (i == 1)
2189 printf("\nAdvanced options are:\n");
2190 for(po = options; po->name != NULL; po++) {
2191 char buf[64];
2192 expert = (po->flags & OPT_EXPERT) != 0;
2193 if (expert == i) {
2194 strcpy(buf, po->name);
2195 if (po->flags & HAS_ARG) {
2196 strcat(buf, " ");
2197 strcat(buf, po->argname);
2198 }
2199 printf("-%-17s %s\n", buf, po->help);
2200 }
2201 }
2202 }
2203
2204 exit(1);
2205}
2206
2207const OptionDef options[] = {
bdc4796f
FB
2208 { "L", 0, {(void*)show_licence}, "show license" },
2209 { "h", 0, {(void*)show_help}, "show help" },
2210 { "formats", 0, {(void*)show_formats}, "show available formats, codecs, protocols, ..." },
2211 { "f", HAS_ARG, {(void*)opt_format}, "force format", "fmt" },
0b97443a 2212 { "vcd", OPT_BOOL, {(void*)&mpeg_vcd}, "output Video CD MPEG-PS compliant file" },
bdc4796f
FB
2213 { "i", HAS_ARG, {(void*)opt_input_file}, "input file name", "filename" },
2214 { "y", OPT_BOOL, {(void*)&file_overwrite}, "overwrite output files" },
2215 { "map", HAS_ARG | OPT_EXPERT, {(void*)opt_map}, "set input stream mapping", "file:stream" },
2216 { "t", HAS_ARG, {(void*)opt_recording_time}, "set the recording time", "duration" },
2217 { "title", HAS_ARG | OPT_STRING, {(void*)&str_title}, "set the title", "string" },
2218 { "author", HAS_ARG | OPT_STRING, {(void*)&str_author}, "set the author", "string" },
2219 { "copyright", HAS_ARG | OPT_STRING, {(void*)&str_copyright}, "set the copyright", "string" },
2220 { "comment", HAS_ARG | OPT_STRING, {(void*)&str_comment}, "set the comment", "string" },
85f07f22 2221 /* video options */
bdc4796f
FB
2222 { "b", HAS_ARG, {(void*)opt_video_bitrate}, "set video bitrate (in kbit/s)", "bitrate" },
2223 { "r", HAS_ARG, {(void*)opt_frame_rate}, "set frame rate (in Hz)", "rate" },
2224 { "s", HAS_ARG, {(void*)opt_frame_size}, "set frame size (WxH or abbreviation)", "size" },
ab6d194a
MN
2225 { "croptop", HAS_ARG, {(void*)opt_frame_crop_top}, "set top crop band size (in pixels)", "size" },
2226 { "cropbottom", HAS_ARG, {(void*)opt_frame_crop_bottom}, "set bottom crop band size (in pixels)", "size" },
2227 { "cropleft", HAS_ARG, {(void*)opt_frame_crop_left}, "set left crop band size (in pixels)", "size" },
2228 { "cropright", HAS_ARG, {(void*)opt_frame_crop_right}, "set right crop band size (in pixels)", "size" },
bdc4796f
FB
2229 { "g", HAS_ARG | OPT_EXPERT, {(void*)opt_gop_size}, "set the group of picture size", "gop_size" },
2230 { "intra", OPT_BOOL | OPT_EXPERT, {(void*)&intra_only}, "use only intra frames"},
2231 { "vn", OPT_BOOL, {(void*)&video_disable}, "disable video" },
2232 { "qscale", HAS_ARG | OPT_EXPERT, {(void*)opt_qscale}, "use fixed video quantiser scale (VBR)", "q" },
9cdd6a24
MN
2233 { "qmin", HAS_ARG | OPT_EXPERT, {(void*)opt_qmin}, "min video quantiser scale (VBR)", "q" },
2234 { "qmax", HAS_ARG | OPT_EXPERT, {(void*)opt_qmax}, "max video quantiser scale (VBR)", "q" },
2235 { "qdiff", HAS_ARG | OPT_EXPERT, {(void*)opt_qdiff}, "max difference between the quantiser scale (VBR)", "q" },
2236 { "qblur", HAS_ARG | OPT_EXPERT, {(void*)opt_qblur}, "video quantiser scale blur (VBR)", "blur" },
2237 { "qcomp", HAS_ARG | OPT_EXPERT, {(void*)opt_qcomp}, "video quantiser scale compression (VBR)", "compression" },
3aa102be 2238 { "rc_eq", HAS_ARG | OPT_EXPERT, {(void*)opt_video_rc_eq}, "", "equation" },
9cdd6a24 2239 { "bt", HAS_ARG, {(void*)opt_video_bitrate_tolerance}, "set video bitrate tolerance (in kbit/s)", "tolerance" },
3aa102be
MN
2240 { "maxrate", HAS_ARG, {(void*)opt_video_bitrate_max}, "set max video bitrate tolerance (in kbit/s)", "bitrate" },
2241 { "minrate", HAS_ARG, {(void*)opt_video_bitrate_min}, "set min video bitrate tolerance (in kbit/s)", "bitrate" },
bf5af568 2242 { "vd", HAS_ARG | OPT_EXPERT, {(void*)opt_video_device}, "set video grab device", "device" },
bdc4796f
FB
2243 { "vcodec", HAS_ARG | OPT_EXPERT, {(void*)opt_video_codec}, "force video codec", "codec" },
2244 { "me", HAS_ARG | OPT_EXPERT, {(void*)opt_motion_estimation}, "set motion estimation method",
85f07f22 2245 "method" },
463678ac 2246 { "dct_algo", HAS_ARG | OPT_EXPERT, {(void*)opt_dct_algo}, "set dct algo", "algo" },
8409b8fe 2247 { "er", HAS_ARG | OPT_EXPERT, {(void*)opt_error_resilience}, "set error resilience", "" },
bc6caae2 2248 { "bf", HAS_ARG | OPT_EXPERT, {(void*)opt_b_frames}, "use 'frames' B frames (only MPEG-4)", "frames" },
e4986da9 2249 { "hq", OPT_BOOL | OPT_EXPERT, {(void*)&use_hq}, "activate high quality settings" },
29da453b 2250 { "4mv", OPT_BOOL | OPT_EXPERT, {(void*)&use_4mv}, "use four motion vector by macroblock (only MPEG-4)" },
fe670d09 2251 { "bug", HAS_ARG | OPT_EXPERT, {(void*)opt_workaround_bugs}, "workaround not auto detected encoder bugs", "param" },
bdc4796f 2252 { "sameq", OPT_BOOL, {(void*)&same_quality},
85f07f22
FB
2253 "use same video quality as source (implies VBR)" },
2254 /* audio options */
bdc4796f
FB
2255 { "ab", HAS_ARG, {(void*)opt_audio_bitrate}, "set audio bitrate (in kbit/s)", "bitrate", },
2256 { "ar", HAS_ARG, {(void*)opt_audio_rate}, "set audio sampling rate (in Hz)", "rate" },
2257 { "ac", HAS_ARG, {(void*)opt_audio_channels}, "set number of audio channels", "channels" },
2258 { "an", OPT_BOOL, {(void*)&audio_disable}, "disable audio" },
bdc4796f 2259 { "ad", HAS_ARG | OPT_EXPERT, {(void*)opt_audio_device}, "set audio device", "device" },
bdc4796f
FB
2260 { "acodec", HAS_ARG | OPT_EXPERT, {(void*)opt_audio_codec}, "force audio codec", "codec" },
2261 { "deinterlace", OPT_BOOL | OPT_EXPERT, {(void*)&do_deinterlace},
cfcf0ffd 2262 "deinterlace pictures" },
bdc4796f 2263 { "benchmark", OPT_BOOL | OPT_EXPERT, {(void*)&do_benchmark},
5727b222 2264 "add timings for benchmarking" },
a0663ba4
FB
2265 { "hex", OPT_BOOL | OPT_EXPERT, {(void*)&do_hex_dump},
2266 "dump each input packet" },
ce7c56c2
J
2267 { "psnr", OPT_BOOL | OPT_EXPERT, {(void*)&do_psnr}, "calculate PSNR of compressed frames" },
2268 { "vstats", OPT_BOOL | OPT_EXPERT, {(void*)&do_vstats}, "dump video coding statistics to file" },
79fdaa4c 2269 { "bitexact", OPT_EXPERT, {(void*)opt_bitexact}, "only use bit exact algorithms (for codec testing)" },
85f07f22
FB
2270 { NULL, },
2271};
2272
2273int main(int argc, char **argv)
2274{
2275 int optindex, i;
2276 const char *opt, *arg;
2277 const OptionDef *po;
a38469e1 2278 INT64 ti;
85f07f22 2279
2c4ae653 2280 av_register_all();
85f07f22 2281
a38469e1
FB
2282 /* detect if invoked as player */
2283 i = strlen(argv[0]);
2284 if (i >= 6 && !strcmp(argv[0] + i - 6, "ffplay"))
2285 do_play = 1;
2286
85f07f22
FB
2287 if (argc <= 1)
2288 show_help();
a38469e1
FB
2289
2290 /* parse options */
85f07f22
FB
2291 optindex = 1;
2292 while (optindex < argc) {
2293 opt = argv[optindex++];
2294
2295 if (opt[0] == '-' && opt[1] != '\0') {
2296 po = options;
2297 while (po->name != NULL) {
2298 if (!strcmp(opt + 1, po->name))
2299 break;
2300 po++;
2301 }
2302 if (!po->name) {
2303 fprintf(stderr, "%s: unrecognized option '%s'\n", argv[0], opt);
2304 exit(1);
2305 }
2306 arg = NULL;
2307 if (po->flags & HAS_ARG)
2308 arg = argv[optindex++];
2309 if (po->flags & OPT_STRING) {
2310 char *str;
2311 str = strdup(arg);
2312 *po->u.str_arg = str;
2313 } else if (po->flags & OPT_BOOL) {
2314 *po->u.int_arg = 1;
2315 } else {
2316 po->u.func_arg(arg);
2317 }
2318 } else {
a38469e1
FB
2319 if (!do_play) {
2320 opt_output_file(opt);
2321 } else {
2322 opt_input_file(opt);
2323 }
85f07f22
FB
2324 }
2325 }
2326
2327
a38469e1
FB
2328 if (!do_play) {
2329 /* file converter / grab */
85f07f22
FB
2330 if (nb_output_files <= 0) {
2331 fprintf(stderr, "Must supply at least one output file\n");
2332 exit(1);
2333 }
a38469e1
FB
2334
2335 if (nb_input_files == 0) {
2336 prepare_grab();
5727b222 2337 }
a38469e1
FB
2338 } else {
2339 /* player */
2340 if (nb_input_files <= 0) {
2341 fprintf(stderr, "Must supply at least one input file\n");
2342 exit(1);
2343 }
2344 prepare_play();
2345 }
2346
2347 ti = getutime();
2348 av_encode(output_files, nb_output_files, input_files, nb_input_files,
2349 stream_maps, nb_stream_maps);
2350 ti = getutime() - ti;
2351 if (do_benchmark) {
2352 printf("bench: utime=%0.3fs\n", ti / 1000000.0);
85f07f22
FB
2353 }
2354
2355 /* close files */
2356 for(i=0;i<nb_output_files;i++) {
79fdaa4c 2357 if (!(output_files[i]->oformat->flags & AVFMT_NOFILE))
85f07f22
FB
2358 url_fclose(&output_files[i]->pb);
2359 }
79fdaa4c
FB
2360 for(i=0;i<nb_input_files;i++)
2361 av_close_input_file(input_files[i]);
85f07f22
FB
2362
2363 return 0;
2364}