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