db video chunk in avi files support (idea by Dmitry Poplavsky <dima at thekompany...
[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 19#define HAVE_AV_CONFIG_H
ce2749d2 20#include "common.h"
daf8e955 21#include "avformat.h"
10d104e4 22#include "framehook.h"
d4ad24c1
FR
23/* usleep() */
24#include "os_support.h"
daf8e955 25
bdc4796f 26#ifndef CONFIG_WIN32
85f07f22
FB
27#include <unistd.h>
28#include <fcntl.h>
29#include <sys/ioctl.h>
85f07f22 30#include <sys/time.h>
85f07f22 31#include <termios.h>
5727b222 32#include <sys/resource.h>
bdc4796f 33#endif
f3ec2d46
SG
34#ifdef CONFIG_OS2
35#include <sys/types.h>
36#include <sys/select.h>
37#include <stdlib.h>
38#endif
bf5af568
FB
39#include <time.h>
40#include <ctype.h>
85f07f22 41
8aa1e3da
MN
42#if !defined(INFINITY) && defined(HUGE_VAL)
43#define INFINITY HUGE_VAL
44#endif
85f07f22 45
0c1a9eda 46#define MAXINT64 int64_t_C(0x7fffffffffffffff)
bdc4796f 47
85f07f22
FB
48typedef struct {
49 const char *name;
50 int flags;
51#define HAS_ARG 0x0001
52#define OPT_BOOL 0x0002
53#define OPT_EXPERT 0x0004
54#define OPT_STRING 0x0008
55 union {
b29f97d1 56 void (*func_arg)(const char *);
85f07f22
FB
57 int *int_arg;
58 char **str_arg;
59 } u;
60 const char *help;
61 const char *argname;
62} OptionDef;
63
64/* select an input stream for an output stream */
65typedef struct AVStreamMap {
66 int file_index;
67 int stream_index;
68} AVStreamMap;
69
70extern const OptionDef options[];
71
72void show_help(void);
73
74#define MAX_FILES 20
75
76static AVFormatContext *input_files[MAX_FILES];
77static int nb_input_files = 0;
78
79static AVFormatContext *output_files[MAX_FILES];
80static int nb_output_files = 0;
81
82static AVStreamMap stream_maps[MAX_FILES];
83static int nb_stream_maps;
84
79fdaa4c
FB
85static AVInputFormat *file_iformat;
86static AVOutputFormat *file_oformat;
817b23ff 87static AVImageFormat *image_format;
85f07f22
FB
88static int frame_width = 160;
89static int frame_height = 128;
ab6d194a
MN
90static int frame_topBand = 0;
91static int frame_bottomBand = 0;
92static int frame_leftBand = 0;
93static int frame_rightBand = 0;
14bea432
MN
94static int frame_rate = 25;
95static int frame_rate_base = 1;
3aa102be
MN
96static int video_bit_rate = 200*1000;
97static int video_bit_rate_tolerance = 4000*1000;
85f07f22 98static int video_qscale = 0;
3aa102be
MN
99static int video_qmin = 2;
100static int video_qmax = 31;
17a70fde
MN
101static int video_mb_qmin = 2;
102static int video_mb_qmax = 31;
9cdd6a24
MN
103static int video_qdiff = 3;
104static float video_qblur = 0.5;
105static float video_qcomp = 0.5;
ac2830ec 106#if 0 //experimental, (can be removed)
3aa102be
MN
107static float video_rc_qsquish=1.0;
108static float video_rc_qmod_amp=0;
109static int video_rc_qmod_freq=0;
ac2830ec 110#endif
3aa102be
MN
111static char *video_rc_override_string=NULL;
112static char *video_rc_eq="tex^qComp";
113static int video_rc_buffer_size=0;
114static float video_rc_buffer_aggressivity=1.0;
115static int video_rc_max_rate=0;
116static int video_rc_min_rate=0;
117static float video_rc_initial_cplx=0;
118static float video_b_qfactor = 1.25;
119static float video_b_qoffset = 1.25;
b3a391e8 120static float video_i_qfactor = -0.8;
3aa102be 121static float video_i_qoffset = 0.0;
3bea5386 122static int me_method = ME_EPZS;
85f07f22
FB
123static int video_disable = 0;
124static int video_codec_id = CODEC_ID_NONE;
125static int same_quality = 0;
bc6caae2 126static int b_frames = 0;
e4986da9 127static int use_hq = 0;
29da453b 128static int use_4mv = 0;
21e59552
MN
129/* Fx */
130static int use_aic = 0;
131static int use_umv = 0;
132/* /Fx */
133static int use_h263p_extra = 0;
cfcf0ffd 134static int do_deinterlace = 0;
4d2858de
MN
135static int workaround_bugs = FF_BUG_AUTODETECT;
136static int error_resilience = 2;
137static int error_concealment = 3;
463678ac 138static int dct_algo = 0;
2ad1516a 139static int idct_algo = 0;
1dbb6d90
MN
140static int use_part = 0;
141static int packet_size = 0;
f560dd82 142static int strict = 0;
59b571c1 143static int debug = 0;
85f07f22
FB
144
145static int gop_size = 12;
146static int intra_only = 0;
147static int audio_sample_rate = 44100;
148static int audio_bit_rate = 64000;
149static int audio_disable = 0;
150static int audio_channels = 1;
151static int audio_codec_id = CODEC_ID_NONE;
152
0c1a9eda 153static int64_t recording_time = 0;
85f07f22
FB
154static int file_overwrite = 0;
155static char *str_title = NULL;
156static char *str_author = NULL;
157static char *str_copyright = NULL;
158static char *str_comment = NULL;
5727b222 159static int do_benchmark = 0;
a0663ba4 160static int do_hex_dump = 0;
a38469e1 161static int do_play = 0;
43f1708f 162static int do_psnr = 0;
ce7c56c2 163static int do_vstats = 0;
5abdb4b1 164static int do_pass = 0;
b0368839 165static int bitexact = 0;
5abdb4b1 166static char *pass_logfilename = NULL;
1629626f
FB
167static int audio_stream_copy = 0;
168static int video_stream_copy = 0;
5abdb4b1 169
bdfcbbed
MK
170static int rate_emu = 0;
171
8aa3ee32 172static char *video_grab_format = "video4linux";
79a7c268 173static char *video_device = NULL;
a5df11ab 174static int video_channel = 0;
79a7c268 175
8aa3ee32 176static char *audio_grab_format = "audio_device";
79a7c268 177static char *audio_device = NULL;
8aa3ee32 178
5abdb4b1 179#define DEFAULT_PASS_LOGFILENAME "ffmpeg2pass"
85f07f22
FB
180
181typedef struct AVOutputStream {
182 int file_index; /* file index */
183 int index; /* stream index in the output file */
184 int source_index; /* AVInputStream index */
185 AVStream *st; /* stream in the output file */
ec5517d5
FB
186 int encoding_needed; /* true if encoding needed for this stream */
187 int frame_number;
188 /* input pts and corresponding output pts
189 for A/V sync */
190 double sync_ipts;
c11ef252 191 double sync_ipts_offset;
0c1a9eda 192 int64_t sync_opts;
85f07f22 193 /* video only */
34b10a57
D
194 int video_resample; /* video_resample and video_crop are mutually exclusive */
195 AVPicture pict_tmp; /* temporary image for resampling */
85f07f22 196 ImgReSampleContext *img_resample_ctx; /* for image resampling */
34b10a57
D
197
198 int video_crop; /* video_resample and video_crop are mutually exclusive */
199 int topBand; /* cropping area sizes */
200 int leftBand;
85f07f22
FB
201
202 /* audio only */
203 int audio_resample;
204 ReSampleContext *resample; /* for audio resampling */
205 FifoBuffer fifo; /* for compression: one audio fifo per codec */
5abdb4b1 206 FILE *logfile;
85f07f22
FB
207} AVOutputStream;
208
209typedef struct AVInputStream {
210 int file_index;
211 int index;
212 AVStream *st;
213 int discard; /* true if stream data should be discarded */
214 int decoding_needed; /* true if the packets must be decoded in 'raw_fifo' */
0c1a9eda 215 int64_t sample_index; /* current sample */
ec5517d5 216 int frame_decoded; /* true if a video or audio frame has been decoded */
bdfcbbed
MK
217
218 int64_t start; /* time when read started */
219 unsigned long frame; /* current frame */
85f07f22
FB
220} AVInputStream;
221
222typedef struct AVInputFile {
223 int eof_reached; /* true if eof reached */
224 int ist_index; /* index of first stream in ist_table */
225 int buffer_size; /* current total buffer size */
226 int buffer_size_max; /* buffer size at which we consider we can stop
227 buffering */
79fdaa4c 228 int nb_streams; /* nb streams we are aware of */
85f07f22
FB
229} AVInputFile;
230
bdc4796f
FB
231#ifndef CONFIG_WIN32
232
85f07f22
FB
233/* init terminal so that we can grab keys */
234static struct termios oldtty;
235
236static void term_exit(void)
237{
238 tcsetattr (0, TCSANOW, &oldtty);
239}
240
241static void term_init(void)
242{
243 struct termios tty;
244
245 tcgetattr (0, &tty);
246 oldtty = tty;
247
248 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
249 |INLCR|IGNCR|ICRNL|IXON);
250 tty.c_oflag |= OPOST;
251 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
252 tty.c_cflag &= ~(CSIZE|PARENB);
253 tty.c_cflag |= CS8;
254 tty.c_cc[VMIN] = 1;
255 tty.c_cc[VTIME] = 0;
256
257 tcsetattr (0, TCSANOW, &tty);
258
259 atexit(term_exit);
9ddd71fc
FR
260#ifdef CONFIG_BEOS_NETSERVER
261 fcntl(0, F_SETFL, fcntl(0, F_GETFL) | O_NONBLOCK);
262#endif
85f07f22
FB
263}
264
265/* read a key without blocking */
266static int read_key(void)
267{
9ddd71fc 268 int n = 1;
85f07f22 269 unsigned char ch;
9ddd71fc
FR
270#ifndef CONFIG_BEOS_NETSERVER
271 struct timeval tv;
85f07f22
FB
272 fd_set rfds;
273
274 FD_ZERO(&rfds);
275 FD_SET(0, &rfds);
276 tv.tv_sec = 0;
277 tv.tv_usec = 0;
278 n = select(1, &rfds, NULL, NULL, &tv);
9ddd71fc 279#endif
85f07f22 280 if (n > 0) {
cb09b2ed
PG
281 n = read(0, &ch, 1);
282 if (n == 1)
85f07f22 283 return ch;
cb09b2ed
PG
284
285 return n;
85f07f22
FB
286 }
287 return -1;
288}
289
a38469e1 290#else
85f07f22 291
a38469e1
FB
292/* no interactive support */
293static void term_exit(void)
85f07f22 294{
a38469e1 295}
85f07f22 296
a38469e1
FB
297static void term_init(void)
298{
299}
85f07f22 300
a38469e1
FB
301static int read_key(void)
302{
cb09b2ed 303 return 0;
85f07f22
FB
304}
305
a38469e1 306#endif
bdc4796f 307
b29f97d1 308static int read_ffserver_streams(AVFormatContext *s, const char *filename)
85f07f22 309{
79fdaa4c 310 int i, err;
85f07f22
FB
311 AVFormatContext *ic;
312
79fdaa4c
FB
313 err = av_open_input_file(&ic, filename, NULL, FFM_PACKET_SIZE, NULL);
314 if (err < 0)
315 return err;
85f07f22
FB
316 /* copy stream format */
317 s->nb_streams = ic->nb_streams;
318 for(i=0;i<ic->nb_streams;i++) {
319 AVStream *st;
1e491e29 320
85f07f22
FB
321 st = av_mallocz(sizeof(AVFormatContext));
322 memcpy(st, ic->streams[i], sizeof(AVStream));
323 s->streams[i] = st;
324 }
325
326 av_close_input_file(ic);
327 return 0;
328}
329
817b23ff 330#define MAX_AUDIO_PACKET_SIZE (128 * 1024)
85f07f22
FB
331
332static void do_audio_out(AVFormatContext *s,
333 AVOutputStream *ost,
334 AVInputStream *ist,
335 unsigned char *buf, int size)
336{
0c1a9eda
ZK
337 uint8_t *buftmp;
338 uint8_t audio_buf[2*MAX_AUDIO_PACKET_SIZE]; /* XXX: allocate it */
339 uint8_t audio_out[4*MAX_AUDIO_PACKET_SIZE]; /* XXX: allocate it - yep really WMA */
85f07f22
FB
340 int size_out, frame_bytes, ret;
341 AVCodecContext *enc;
342
343 enc = &ost->st->codec;
344
345 if (ost->audio_resample) {
346 buftmp = audio_buf;
347 size_out = audio_resample(ost->resample,
348 (short *)buftmp, (short *)buf,
349 size / (ist->st->codec.channels * 2));
350 size_out = size_out * enc->channels * 2;
351 } else {
352 buftmp = buf;
353 size_out = size;
354 }
355
356 /* now encode as many frames as possible */
a0663ba4 357 if (enc->frame_size > 1) {
85f07f22
FB
358 /* output resampled raw samples */
359 fifo_write(&ost->fifo, buftmp, size_out,
360 &ost->fifo.wptr);
361
362 frame_bytes = enc->frame_size * 2 * enc->channels;
363
364 while (fifo_read(&ost->fifo, audio_buf, frame_bytes,
365 &ost->fifo.rptr) == 0) {
a0663ba4
FB
366 ret = avcodec_encode_audio(enc, audio_out, sizeof(audio_out),
367 (short *)audio_buf);
ec5517d5 368 av_write_frame(s, ost->index, audio_out, ret);
85f07f22
FB
369 }
370 } else {
a0663ba4
FB
371 /* output a pcm frame */
372 /* XXX: change encoding codec API to avoid this ? */
373 switch(enc->codec->id) {
374 case CODEC_ID_PCM_S16LE:
375 case CODEC_ID_PCM_S16BE:
376 case CODEC_ID_PCM_U16LE:
377 case CODEC_ID_PCM_U16BE:
378 break;
379 default:
380 size_out = size_out >> 1;
381 break;
382 }
383 ret = avcodec_encode_audio(enc, audio_out, size_out,
ff29712a 384 (short *)buftmp);
ec5517d5 385 av_write_frame(s, ost->index, audio_out, ret);
85f07f22
FB
386 }
387}
388
10d104e4
PG
389static void pre_process_video_frame(AVInputStream *ist, AVPicture *picture, void **bufp)
390{
391 AVCodecContext *dec;
392 AVPicture *picture2;
393 AVPicture picture_tmp;
0c1a9eda 394 uint8_t *buf = 0;
10d104e4
PG
395
396 dec = &ist->st->codec;
397
398 /* deinterlace : must be done before any resize */
399 if (do_deinterlace) {
400 int size;
401
402 /* create temporary picture */
403 size = avpicture_get_size(dec->pix_fmt, dec->width, dec->height);
404 buf = av_malloc(size);
405 if (!buf)
406 return;
407
408 picture2 = &picture_tmp;
409 avpicture_fill(picture2, buf, dec->pix_fmt, dec->width, dec->height);
410
411 if (avpicture_deinterlace(picture2, picture,
412 dec->pix_fmt, dec->width, dec->height) < 0) {
413 /* if error, do not deinterlace */
414 av_free(buf);
415 buf = NULL;
416 picture2 = picture;
417 }
418 } else {
419 picture2 = picture;
420 }
421
422 frame_hook_process(picture2, dec->pix_fmt, dec->width, dec->height);
423
424 if (picture != picture2)
425 *picture = *picture2;
426 *bufp = buf;
427}
428
ec5517d5
FB
429/* we begin to correct av delay at this threshold */
430#define AV_DELAY_MAX 0.100
85f07f22
FB
431
432static void do_video_out(AVFormatContext *s,
433 AVOutputStream *ost,
434 AVInputStream *ist,
34b10a57 435 AVPicture *in_picture,
ec5517d5 436 int *frame_size, AVOutputStream *audio_sync)
85f07f22 437{
ec5517d5 438 int nb_frames, i, ret;
34b10a57
D
439 AVPicture *final_picture, *formatted_picture;
440 AVPicture picture_format_temp, picture_crop_temp;
0c1a9eda
ZK
441 static uint8_t *video_buffer;
442 uint8_t *buf = NULL, *buf1 = NULL;
cfcf0ffd 443 AVCodecContext *enc, *dec;
85f07f22 444
33a1f1a3 445#define VIDEO_BUFFER_SIZE (1024*1024)
33a1f1a3 446
85f07f22 447 enc = &ost->st->codec;
cfcf0ffd 448 dec = &ist->st->codec;
85f07f22 449
ec5517d5
FB
450 /* by default, we output a single frame */
451 nb_frames = 1;
452
204c0f48
PG
453 *frame_size = 0;
454
ec5517d5
FB
455 /* NOTE: the A/V sync is always done by considering the audio is
456 the master clock. It is suffisant for transcoding or playing,
457 but not for the general case */
458 if (audio_sync) {
459 /* compute the A-V delay and duplicate/remove frames if needed */
460 double adelta, vdelta, apts, vpts, av_delay;
461
462 if (audio_sync->sync_ipts != AV_NOPTS_VALUE &&
463 ost->sync_ipts != AV_NOPTS_VALUE) {
464
465 adelta = (double)(ost->st->pts.val - audio_sync->sync_opts) *
466 s->pts_num / s->pts_den;
467 apts = audio_sync->sync_ipts + adelta;
468
469 vdelta = (double)(ost->st->pts.val - ost->sync_opts) *
470 s->pts_num / s->pts_den;
471 vpts = ost->sync_ipts + vdelta;
472
473 av_delay = apts - vpts;
474 // printf("delay=%f\n", av_delay);
475 if (av_delay < -AV_DELAY_MAX)
476 nb_frames = 2;
477 else if (av_delay > AV_DELAY_MAX)
478 nb_frames = 0;
479 }
10d104e4
PG
480 } else {
481 double vdelta;
482
483 if (ost->sync_ipts != AV_NOPTS_VALUE) {
c11ef252 484 vdelta = (double)(ost->st->pts.val) * s->pts_num / s->pts_den - (ost->sync_ipts - ost->sync_ipts_offset);
be4ce157 485 if (vdelta < 100 && vdelta > -100 && ost->sync_ipts_offset) {
c11ef252
PG
486 if (vdelta < -AV_DELAY_MAX)
487 nb_frames = 2;
488 else if (vdelta > AV_DELAY_MAX)
489 nb_frames = 0;
490 } else {
491 ost->sync_ipts_offset -= vdelta;
be4ce157
PG
492 if (!ost->sync_ipts_offset)
493 ost->sync_ipts_offset = 0.000001; /* one microsecond */
c11ef252
PG
494 }
495
be4ce157 496#if defined(PJSG)
c11ef252
PG
497 {
498 static char *action[] = { "drop frame", "copy frame", "dup frame" };
499 printf("Input PTS %12.6f, output PTS %12.6f: %s\n",
500 (double) ost->sync_ipts, (double) ost->st->pts.val * s->pts_num / s->pts_den,
501 action[nb_frames]);
502 }
503#endif
10d104e4 504 }
ec5517d5 505 }
ec5517d5 506 if (nb_frames <= 0)
85f07f22 507 return;
ce7c56c2 508
cb09b2ed 509 if (!video_buffer)
ec5517d5
FB
510 video_buffer = av_malloc(VIDEO_BUFFER_SIZE);
511 if (!video_buffer)
512 return;
c04643a2 513
cfcf0ffd
FB
514 /* convert pixel format if needed */
515 if (enc->pix_fmt != dec->pix_fmt) {
516 int size;
517
518 /* create temporary picture */
519 size = avpicture_get_size(enc->pix_fmt, dec->width, dec->height);
0f1578af 520 buf = av_malloc(size);
cfcf0ffd
FB
521 if (!buf)
522 return;
34b10a57
D
523 formatted_picture = &picture_format_temp;
524 avpicture_fill(formatted_picture, buf, enc->pix_fmt, dec->width, dec->height);
cfcf0ffd 525
34b10a57
D
526 if (img_convert(formatted_picture, enc->pix_fmt,
527 in_picture, dec->pix_fmt,
cfcf0ffd
FB
528 dec->width, dec->height) < 0) {
529 fprintf(stderr, "pixel format conversion not handled\n");
530 goto the_end;
531 }
532 } else {
34b10a57 533 formatted_picture = in_picture;
cfcf0ffd
FB
534 }
535
536 /* XXX: resampling could be done before raw format convertion in
537 some cases to go faster */
538 /* XXX: only works for YUV420P */
85f07f22 539 if (ost->video_resample) {
34b10a57
D
540 final_picture = &ost->pict_tmp;
541 img_resample(ost->img_resample_ctx, final_picture, formatted_picture);
542 } else if (ost->video_crop) {
543 picture_crop_temp.data[0] = formatted_picture->data[0] +
544 (ost->topBand * formatted_picture->linesize[0]) + ost->leftBand;
545
546 picture_crop_temp.data[1] = formatted_picture->data[1] +
547 ((ost->topBand >> 1) * formatted_picture->linesize[1]) +
548 (ost->leftBand >> 1);
549
550 picture_crop_temp.data[2] = formatted_picture->data[2] +
551 ((ost->topBand >> 1) * formatted_picture->linesize[2]) +
552 (ost->leftBand >> 1);
553
554 picture_crop_temp.linesize[0] = formatted_picture->linesize[0];
555 picture_crop_temp.linesize[1] = formatted_picture->linesize[1];
556 picture_crop_temp.linesize[2] = formatted_picture->linesize[2];
557 final_picture = &picture_crop_temp;
85f07f22 558 } else {
34b10a57 559 final_picture = formatted_picture;
85f07f22 560 }
85f07f22
FB
561 /* duplicates frame if needed */
562 /* XXX: pb because no interleaving */
ec5517d5 563 for(i=0;i<nb_frames;i++) {
e8750b00
FR
564 if (s->oformat->flags & AVFMT_RAWPICTURE) {
565 /* raw pictures are written as AVPicture structure to
566 avoid any copies. We support temorarily the older
567 method. */
568 av_write_frame(s, ost->index,
569 (uint8_t *)final_picture, sizeof(AVPicture));
570 } else {
492cd3a9 571 AVFrame big_picture;
1e491e29 572
492cd3a9 573 memset(&big_picture, 0, sizeof(AVFrame));
34b10a57 574 *(AVPicture*)&big_picture= *final_picture;
1e491e29 575
85f07f22
FB
576 /* handles sameq here. This is not correct because it may
577 not be a global option */
578 if (same_quality) {
1e491e29
MN
579 big_picture.quality = ist->st->quality;
580 }else
581 big_picture.quality = ost->st->quality;
6dc96cb0 582
cfcf0ffd 583 ret = avcodec_encode_video(enc,
33a1f1a3 584 video_buffer, VIDEO_BUFFER_SIZE,
1e491e29 585 &big_picture);
44429457 586 //enc->frame_number = enc->real_pict_num;
ec5517d5 587 av_write_frame(s, ost->index, video_buffer, ret);
ce7c56c2 588 *frame_size = ret;
a5dc85ef 589 //fprintf(stderr,"\nFrame: %3d %3d size: %5d type: %d",
44429457 590 // enc->frame_number-1, enc->real_pict_num, ret,
a5dc85ef 591 // enc->pict_type);
5abdb4b1
FB
592 /* if two pass, output log */
593 if (ost->logfile && enc->stats_out) {
594 fprintf(ost->logfile, "%s", enc->stats_out);
595 }
85f07f22 596 }
ec5517d5 597 ost->frame_number++;
85f07f22 598 }
ec5517d5 599 the_end:
0f1578af
FB
600 av_free(buf);
601 av_free(buf1);
85f07f22
FB
602}
603
140cb663
MN
604static double psnr(double d){
605 if(d==0) return INFINITY;
b29f97d1 606 return -10.0*log(d)/log(10.0);
140cb663
MN
607}
608
ec5517d5
FB
609static void do_video_stats(AVFormatContext *os, AVOutputStream *ost,
610 int frame_size)
ce7c56c2
J
611{
612 static FILE *fvstats=NULL;
0c1a9eda 613 static int64_t total_size = 0;
ce7c56c2 614 char filename[40];
bf5af568
FB
615 time_t today2;
616 struct tm *today;
ce7c56c2
J
617 AVCodecContext *enc;
618 int frame_number;
0c1a9eda 619 int64_t ti;
ce7c56c2
J
620 double ti1, bitrate, avg_bitrate;
621
622 if (!fvstats) {
623 today2 = time(NULL);
624 today = localtime(&today2);
625 sprintf(filename, "vstats_%02d%02d%02d.log", today->tm_hour,
626 today->tm_min,
627 today->tm_sec);
628 fvstats = fopen(filename,"w");
629 if (!fvstats) {
630 perror("fopen");
631 exit(1);
632 }
633 }
634
635 ti = MAXINT64;
636 enc = &ost->st->codec;
637 total_size += frame_size;
638 if (enc->codec_type == CODEC_TYPE_VIDEO) {
ec5517d5 639 frame_number = ost->frame_number;
492cd3a9 640 fprintf(fvstats, "frame= %5d q= %2.1f ", frame_number, enc->coded_frame->quality);
140cb663 641 if (enc->flags&CODEC_FLAG_PSNR)
492cd3a9 642 fprintf(fvstats, "PSNR= %6.2f ", psnr(enc->coded_frame->error[0]/(enc->width*enc->height*255.0*255.0)));
ce7c56c2
J
643
644 fprintf(fvstats,"f_size= %6d ", frame_size);
ec5517d5
FB
645 /* compute pts value */
646 ti1 = (double)ost->st->pts.val * os->pts_num / os->pts_den;
ce7c56c2
J
647 if (ti1 < 0.01)
648 ti1 = 0.01;
649
14bea432 650 bitrate = (double)(frame_size * 8) * enc->frame_rate / enc->frame_rate_base / 1000.0;
ce7c56c2
J
651 avg_bitrate = (double)(total_size * 8) / ti1 / 1000.0;
652 fprintf(fvstats, "s_size= %8.0fkB time= %0.3f br= %7.1fkbits/s avg_br= %7.1fkbits/s ",
653 (double)total_size / 1024, ti1, bitrate, avg_bitrate);
492cd3a9 654 fprintf(fvstats,"type= %s\n", enc->coded_frame->key_frame == 1 ? "I" : "P");
ce7c56c2 655 }
ec5517d5
FB
656}
657
b29f97d1
ZK
658static void print_report(AVFormatContext **output_files,
659 AVOutputStream **ost_table, int nb_ostreams,
660 int is_last_report)
ec5517d5
FB
661{
662 char buf[1024];
663 AVOutputStream *ost;
664 AVFormatContext *oc, *os;
0c1a9eda 665 int64_t total_size;
ec5517d5
FB
666 AVCodecContext *enc;
667 int frame_number, vid, i;
668 double bitrate, ti1, pts;
0c1a9eda 669 static int64_t last_time = -1;
ec5517d5
FB
670
671 if (!is_last_report) {
0c1a9eda 672 int64_t cur_time;
ec5517d5
FB
673 /* display the report every 0.5 seconds */
674 cur_time = av_gettime();
675 if (last_time == -1) {
676 last_time = cur_time;
677 return;
678 }
679 if ((cur_time - last_time) < 500000)
680 return;
681 last_time = cur_time;
682 }
683
ce7c56c2 684
ec5517d5
FB
685 oc = output_files[0];
686
687 total_size = url_ftell(&oc->pb);
688
689 buf[0] = '\0';
690 ti1 = 1e10;
691 vid = 0;
692 for(i=0;i<nb_ostreams;i++) {
693 ost = ost_table[i];
694 os = output_files[ost->file_index];
695 enc = &ost->st->codec;
10d104e4 696 if (vid && enc->codec_type == CODEC_TYPE_VIDEO) {
1e491e29 697 sprintf(buf + strlen(buf), "q=%2.1f ",
492cd3a9 698 enc->coded_frame->quality);
10d104e4 699 }
ec5517d5
FB
700 if (!vid && enc->codec_type == CODEC_TYPE_VIDEO) {
701 frame_number = ost->frame_number;
1e491e29 702 sprintf(buf + strlen(buf), "frame=%5d q=%2.1f ",
492cd3a9 703 frame_number, enc->coded_frame ? enc->coded_frame->quality : 0);
140cb663 704 if (enc->flags&CODEC_FLAG_PSNR)
492cd3a9 705 sprintf(buf + strlen(buf), "PSNR= %6.2f ", psnr(enc->coded_frame->error[0]/(enc->width*enc->height*255.0*255.0)));
ec5517d5
FB
706 vid = 1;
707 }
708 /* compute min output value */
709 pts = (double)ost->st->pts.val * os->pts_num / os->pts_den;
5d9827bc 710 if ((pts < ti1) && (pts > 0))
ec5517d5
FB
711 ti1 = pts;
712 }
713 if (ti1 < 0.01)
714 ti1 = 0.01;
715 bitrate = (double)(total_size * 8) / ti1 / 1000.0;
716
717 sprintf(buf + strlen(buf),
718 "size=%8.0fkB time=%0.1f bitrate=%6.1fkbits/s",
719 (double)total_size / 1024, ti1, bitrate);
ce7c56c2 720
ec5517d5 721 fprintf(stderr, "%s ", buf);
ce7c56c2 722
ec5517d5
FB
723 if (is_last_report) {
724 fprintf(stderr, "\n");
725 } else {
726 fprintf(stderr, "\r");
727 fflush(stderr);
728 }
ce7c56c2
J
729}
730
85f07f22
FB
731/*
732 * The following code is the main loop of the file converter
733 */
734static int av_encode(AVFormatContext **output_files,
735 int nb_output_files,
736 AVFormatContext **input_files,
737 int nb_input_files,
738 AVStreamMap *stream_maps, int nb_stream_maps)
739{
ec5517d5 740 int ret, i, j, k, n, nb_istreams = 0, nb_ostreams = 0, pts_set;
85f07f22
FB
741 AVFormatContext *is, *os;
742 AVCodecContext *codec, *icodec;
743 AVOutputStream *ost, **ost_table = NULL;
744 AVInputStream *ist, **ist_table = NULL;
bdc4796f 745 AVInputFile *file_table;
51bd4565 746 AVFormatContext *stream_no_data;
cb09b2ed 747 int key;
bdc4796f 748
51bd4565 749 file_table= (AVInputFile*) av_mallocz(nb_input_files * sizeof(AVInputFile));
bdc4796f
FB
750 if (!file_table)
751 goto fail;
85f07f22 752
85f07f22
FB
753 /* input stream init */
754 j = 0;
755 for(i=0;i<nb_input_files;i++) {
756 is = input_files[i];
757 file_table[i].ist_index = j;
79fdaa4c 758 file_table[i].nb_streams = is->nb_streams;
85f07f22
FB
759 j += is->nb_streams;
760 }
761 nb_istreams = j;
762
763 ist_table = av_mallocz(nb_istreams * sizeof(AVInputStream *));
764 if (!ist_table)
bdc4796f 765 goto fail;
85f07f22
FB
766
767 for(i=0;i<nb_istreams;i++) {
768 ist = av_mallocz(sizeof(AVInputStream));
769 if (!ist)
770 goto fail;
771 ist_table[i] = ist;
772 }
773 j = 0;
774 for(i=0;i<nb_input_files;i++) {
775 is = input_files[i];
776 for(k=0;k<is->nb_streams;k++) {
777 ist = ist_table[j++];
778 ist->st = is->streams[k];
779 ist->file_index = i;
780 ist->index = k;
781 ist->discard = 1; /* the stream is discarded by default
782 (changed later) */
bdfcbbed
MK
783
784 if (ist->st->codec.rate_emu) {
785 ist->start = av_gettime();
786 ist->frame = 0;
787 }
85f07f22
FB
788 }
789 }
790
791 /* output stream init */
792 nb_ostreams = 0;
793 for(i=0;i<nb_output_files;i++) {
794 os = output_files[i];
795 nb_ostreams += os->nb_streams;
796 }
797 if (nb_stream_maps > 0 && nb_stream_maps != nb_ostreams) {
798 fprintf(stderr, "Number of stream maps must match number of output streams\n");
799 exit(1);
800 }
801
802 ost_table = av_mallocz(sizeof(AVOutputStream *) * nb_ostreams);
803 if (!ost_table)
804 goto fail;
805 for(i=0;i<nb_ostreams;i++) {
806 ost = av_mallocz(sizeof(AVOutputStream));
807 if (!ost)
808 goto fail;
809 ost_table[i] = ost;
810 }
811
812 n = 0;
813 for(k=0;k<nb_output_files;k++) {
814 os = output_files[k];
815 for(i=0;i<os->nb_streams;i++) {
816 int found;
817 ost = ost_table[n++];
818 ost->file_index = k;
819 ost->index = i;
820 ost->st = os->streams[i];
821 if (nb_stream_maps > 0) {
822 ost->source_index = file_table[stream_maps[n-1].file_index].ist_index +
823 stream_maps[n-1].stream_index;
824 } else {
825 /* get corresponding input stream index : we select the first one with the right type */
826 found = 0;
827 for(j=0;j<nb_istreams;j++) {
828 ist = ist_table[j];
829 if (ist->discard &&
830 ist->st->codec.codec_type == ost->st->codec.codec_type) {
831 ost->source_index = j;
832 found = 1;
833 }
834 }
835
836 if (!found) {
837 /* try again and reuse existing stream */
838 for(j=0;j<nb_istreams;j++) {
839 ist = ist_table[j];
840 if (ist->st->codec.codec_type == ost->st->codec.codec_type) {
841 ost->source_index = j;
842 found = 1;
843 }
844 }
845 if (!found) {
846 fprintf(stderr, "Could not find input stream matching output stream #%d.%d\n",
847 ost->file_index, ost->index);
848 exit(1);
849 }
850 }
851 }
852 ist = ist_table[ost->source_index];
853 ist->discard = 0;
854 }
855 }
856
85f07f22
FB
857 /* for each output stream, we compute the right encoding parameters */
858 for(i=0;i<nb_ostreams;i++) {
859 ost = ost_table[i];
860 ist = ist_table[ost->source_index];
861
862 codec = &ost->st->codec;
863 icodec = &ist->st->codec;
864
1629626f
FB
865 if (ost->st->stream_copy) {
866 /* if stream_copy is selected, no need to decode or encode */
867 codec->codec_id = icodec->codec_id;
868 codec->codec_type = icodec->codec_type;
869 codec->codec_tag = icodec->codec_tag;
870 codec->bit_rate = icodec->bit_rate;
871 switch(codec->codec_type) {
872 case CODEC_TYPE_AUDIO:
873 codec->sample_rate = icodec->sample_rate;
874 codec->channels = icodec->channels;
875 break;
876 case CODEC_TYPE_VIDEO:
877 codec->frame_rate = icodec->frame_rate;
14bea432 878 codec->frame_rate_base = icodec->frame_rate_base;
1629626f
FB
879 codec->width = icodec->width;
880 codec->height = icodec->height;
881 break;
882 default:
883 av_abort();
884 }
885 } else {
886 switch(codec->codec_type) {
887 case CODEC_TYPE_AUDIO:
85f07f22
FB
888 if (fifo_init(&ost->fifo, 2 * MAX_AUDIO_PACKET_SIZE))
889 goto fail;
1629626f 890
85f07f22
FB
891 if (codec->channels == icodec->channels &&
892 codec->sample_rate == icodec->sample_rate) {
893 ost->audio_resample = 0;
894 } else {
e0d2714a
J
895 if (codec->channels != icodec->channels &&
896 icodec->codec_id == CODEC_ID_AC3) {
897 /* Special case for 5:1 AC3 input */
898 /* and mono or stereo output */
6dc96cb0
J
899 /* Request specific number of channels */
900 icodec->channels = codec->channels;
901 if (codec->sample_rate == icodec->sample_rate)
902 ost->audio_resample = 0;
903 else {
904 ost->audio_resample = 1;
905 ost->resample = audio_resample_init(codec->channels, icodec->channels,
906 codec->sample_rate,
907 icodec->sample_rate);
908 }
e0d2714a
J
909 /* Request specific number of channels */
910 icodec->channels = codec->channels;
911 } else {
912 ost->audio_resample = 1;
913 ost->resample = audio_resample_init(codec->channels, icodec->channels,
85f07f22
FB
914 codec->sample_rate,
915 icodec->sample_rate);
e0d2714a 916 }
85f07f22
FB
917 }
918 ist->decoding_needed = 1;
919 ost->encoding_needed = 1;
1629626f
FB
920 break;
921 case CODEC_TYPE_VIDEO:
85f07f22 922 if (codec->width == icodec->width &&
34b10a57
D
923 codec->height == icodec->height &&
924 frame_topBand == 0 &&
925 frame_bottomBand == 0 &&
926 frame_leftBand == 0 &&
927 frame_rightBand == 0)
928 {
929 ost->video_resample = 0;
930 ost->video_crop = 0;
931 } else if ((codec->width == icodec->width -
932 (frame_leftBand + frame_rightBand)) &&
933 (codec->height == icodec->height -
934 (frame_topBand + frame_bottomBand)))
935 {
85f07f22 936 ost->video_resample = 0;
34b10a57
D
937 ost->video_crop = 1;
938 ost->topBand = frame_topBand;
939 ost->leftBand = frame_leftBand;
85f07f22 940 } else {
0c1a9eda 941 uint8_t *buf;
85f07f22 942 ost->video_resample = 1;
34b10a57 943 ost->video_crop = 0; // cropping is handled as part of resample
0f1578af 944 buf = av_malloc((codec->width * codec->height * 3) / 2);
85f07f22
FB
945 if (!buf)
946 goto fail;
947 ost->pict_tmp.data[0] = buf;
948 ost->pict_tmp.data[1] = ost->pict_tmp.data[0] + (codec->width * codec->height);
949 ost->pict_tmp.data[2] = ost->pict_tmp.data[1] + (codec->width * codec->height) / 4;
950 ost->pict_tmp.linesize[0] = codec->width;
951 ost->pict_tmp.linesize[1] = codec->width / 2;
952 ost->pict_tmp.linesize[2] = codec->width / 2;
953
ab6d194a 954 ost->img_resample_ctx = img_resample_full_init(
85f07f22 955 ost->st->codec.width, ost->st->codec.height,
ab6d194a
MN
956 ist->st->codec.width, ist->st->codec.height,
957 frame_topBand, frame_bottomBand,
958 frame_leftBand, frame_rightBand);
85f07f22
FB
959 }
960 ost->encoding_needed = 1;
961 ist->decoding_needed = 1;
1629626f
FB
962 break;
963 default:
964 av_abort();
85f07f22 965 }
1629626f
FB
966 /* two pass mode */
967 if (ost->encoding_needed &&
968 (codec->flags & (CODEC_FLAG_PASS1 | CODEC_FLAG_PASS2))) {
969 char logfilename[1024];
970 FILE *f;
971 int size;
972 char *logbuffer;
973
974 snprintf(logfilename, sizeof(logfilename), "%s-%d.log",
975 pass_logfilename ?
976 pass_logfilename : DEFAULT_PASS_LOGFILENAME, i);
977 if (codec->flags & CODEC_FLAG_PASS1) {
978 f = fopen(logfilename, "w");
979 if (!f) {
980 perror(logfilename);
981 exit(1);
982 }
983 ost->logfile = f;
984 } else {
985 /* read the log file */
986 f = fopen(logfilename, "r");
987 if (!f) {
988 perror(logfilename);
989 exit(1);
990 }
991 fseek(f, 0, SEEK_END);
992 size = ftell(f);
993 fseek(f, 0, SEEK_SET);
994 logbuffer = av_malloc(size + 1);
995 if (!logbuffer) {
996 fprintf(stderr, "Could not allocate log buffer\n");
997 exit(1);
998 }
999 fread(logbuffer, 1, size, f);
1000 fclose(f);
1001 logbuffer[size] = '\0';
1002 codec->stats_in = logbuffer;
5abdb4b1 1003 }
5abdb4b1
FB
1004 }
1005 }
85f07f22
FB
1006 }
1007
1629626f
FB
1008 /* dump the file output parameters - cannot be done before in case
1009 of stream copy */
1010 for(i=0;i<nb_output_files;i++) {
1011 dump_format(output_files[i], i, output_files[i]->filename, 1);
1012 }
1013
1014 /* dump the stream mapping */
1015 fprintf(stderr, "Stream mapping:\n");
1016 for(i=0;i<nb_ostreams;i++) {
1017 ost = ost_table[i];
1018 fprintf(stderr, " Stream #%d.%d -> #%d.%d\n",
1019 ist_table[ost->source_index]->file_index,
1020 ist_table[ost->source_index]->index,
1021 ost->file_index,
1022 ost->index);
1023 }
1024
85f07f22
FB
1025 /* open each encoder */
1026 for(i=0;i<nb_ostreams;i++) {
1027 ost = ost_table[i];
1028 if (ost->encoding_needed) {
1029 AVCodec *codec;
1030 codec = avcodec_find_encoder(ost->st->codec.codec_id);
1031 if (!codec) {
1032 fprintf(stderr, "Unsupported codec for output stream #%d.%d\n",
1033 ost->file_index, ost->index);
1034 exit(1);
1035 }
1036 if (avcodec_open(&ost->st->codec, codec) < 0) {
1037 fprintf(stderr, "Error while opening codec for stream #%d.%d - maybe incorrect parameters such as bit_rate, rate, width or height\n",
1038 ost->file_index, ost->index);
1039 exit(1);
1040 }
1041 }
1042 }
1043
1044 /* open each decoder */
1045 for(i=0;i<nb_istreams;i++) {
1046 ist = ist_table[i];
1047 if (ist->decoding_needed) {
1048 AVCodec *codec;
1049 codec = avcodec_find_decoder(ist->st->codec.codec_id);
1050 if (!codec) {
10d104e4
PG
1051 fprintf(stderr, "Unsupported codec (id=%d) for input stream #%d.%d\n",
1052 ist->st->codec.codec_id, ist->file_index, ist->index);
85f07f22
FB
1053 exit(1);
1054 }
1055 if (avcodec_open(&ist->st->codec, codec) < 0) {
1056 fprintf(stderr, "Error while opening codec for input stream #%d.%d\n",
1057 ist->file_index, ist->index);
1058 exit(1);
1059 }
6dc96cb0
J
1060 //if (ist->st->codec.codec_type == CODEC_TYPE_VIDEO)
1061 // ist->st->codec.flags |= CODEC_FLAG_REPEAT_FIELD;
ec5517d5 1062 ist->frame_decoded = 1;
85f07f22
FB
1063 }
1064 }
1065
1066 /* init pts */
1067 for(i=0;i<nb_istreams;i++) {
1068 ist = ist_table[i];
85f07f22
FB
1069 }
1070
1071 /* compute buffer size max (should use a complete heuristic) */
1072 for(i=0;i<nb_input_files;i++) {
1073 file_table[i].buffer_size_max = 2048;
1074 }
1075
1076 /* open files and write file headers */
1077 for(i=0;i<nb_output_files;i++) {
1078 os = output_files[i];
79fdaa4c 1079 if (av_write_header(os) < 0) {
a38469e1
FB
1080 fprintf(stderr, "Could not write header for output file #%d (incorrect codec paramters ?)\n", i);
1081 ret = -EINVAL;
1082 goto fail;
1083 }
85f07f22
FB
1084 }
1085
a38469e1
FB
1086#ifndef CONFIG_WIN32
1087 if (!do_play) {
1088 fprintf(stderr, "Press [q] to stop encoding\n");
1089 } else {
1090 fprintf(stderr, "Press [q] to stop playing\n");
1091 }
1092#endif
1093 term_init();
1094
51bd4565 1095 stream_no_data = 0;
cb09b2ed 1096 key = -1;
51bd4565 1097
85f07f22
FB
1098 for(;;) {
1099 int file_index, ist_index;
1100 AVPacket pkt;
0c1a9eda 1101 uint8_t *ptr;
85f07f22 1102 int len;
0c1a9eda 1103 uint8_t *data_buf;
85f07f22
FB
1104 int data_size, got_picture;
1105 AVPicture picture;
1106 short samples[AVCODEC_MAX_AUDIO_FRAME_SIZE / 2];
10d104e4 1107 void *buffer_to_free;
ec5517d5
FB
1108 double pts_min;
1109
85f07f22 1110 redo:
a38469e1 1111 /* if 'q' pressed, exits */
cb09b2ed
PG
1112 if (key) {
1113 /* read_key() returns 0 on EOF */
1114 key = read_key();
1115 if (key == 'q')
1116 break;
1117 }
a38469e1 1118
ec5517d5
FB
1119 /* select the stream that we must read now by looking at the
1120 smallest output pts */
85f07f22 1121 file_index = -1;
ec5517d5
FB
1122 pts_min = 1e10;
1123 for(i=0;i<nb_ostreams;i++) {
1124 double pts;
1125 ost = ost_table[i];
1126 os = output_files[ost->file_index];
1127 ist = ist_table[ost->source_index];
1128 pts = (double)ost->st->pts.val * os->pts_num / os->pts_den;
1129 if (!file_table[ist->file_index].eof_reached &&
1130 pts < pts_min) {
1131 pts_min = pts;
85f07f22
FB
1132 file_index = ist->file_index;
1133 }
1134 }
1135 /* if none, if is finished */
51bd4565 1136 if (file_index < 0) {
85f07f22 1137 break;
ec5517d5
FB
1138 }
1139
85f07f22 1140 /* finish if recording time exhausted */
ec5517d5 1141 if (recording_time > 0 && pts_min >= (recording_time / 1000000.0))
85f07f22 1142 break;
ec5517d5 1143
85f07f22 1144 /* read a packet from it and output it in the fifo */
85f07f22
FB
1145 is = input_files[file_index];
1146 if (av_read_packet(is, &pkt) < 0) {
1147 file_table[file_index].eof_reached = 1;
1148 continue;
1149 }
51bd4565
PG
1150 if (!pkt.size) {
1151 stream_no_data = is;
1152 } else {
1153 stream_no_data = 0;
1154 }
817b23ff
FB
1155 if (do_hex_dump) {
1156 printf("stream #%d, size=%d:\n", pkt.stream_index, pkt.size);
1157 av_hex_dump(pkt.data, pkt.size);
1158 }
79fdaa4c
FB
1159 /* the following test is needed in case new streams appear
1160 dynamically in stream : we ignore them */
1161 if (pkt.stream_index >= file_table[file_index].nb_streams)
bf5af568 1162 goto discard_packet;
85f07f22
FB
1163 ist_index = file_table[file_index].ist_index + pkt.stream_index;
1164 ist = ist_table[ist_index];
bf5af568
FB
1165 if (ist->discard)
1166 goto discard_packet;
85f07f22 1167
34b10a57 1168 // printf("read #%d.%d size=%d\n", ist->file_index, ist->index, pkt.size);
85f07f22
FB
1169
1170 len = pkt.size;
1171 ptr = pkt.data;
ec5517d5 1172 pts_set = 0;
85f07f22 1173 while (len > 0) {
0c1a9eda 1174 int64_t ipts;
ec5517d5
FB
1175
1176 ipts = AV_NOPTS_VALUE;
85f07f22
FB
1177
1178 /* decode the packet if needed */
1179 data_buf = NULL; /* fail safe */
1180 data_size = 0;
1181 if (ist->decoding_needed) {
ec5517d5
FB
1182 /* NOTE1: we only take into account the PTS if a new
1183 frame has begun (MPEG semantics) */
1184 /* NOTE2: even if the fraction is not initialized,
1185 av_frac_set can be used to set the integer part */
1186 if (ist->frame_decoded &&
1187 pkt.pts != AV_NOPTS_VALUE &&
1188 !pts_set) {
1189 ipts = pkt.pts;
1190 ist->frame_decoded = 0;
1191 pts_set = 1;
1192 }
1193
85f07f22
FB
1194 switch(ist->st->codec.codec_type) {
1195 case CODEC_TYPE_AUDIO:
a0663ba4
FB
1196 /* XXX: could avoid copy if PCM 16 bits with same
1197 endianness as CPU */
1198 ret = avcodec_decode_audio(&ist->st->codec, samples, &data_size,
1199 ptr, len);
1200 if (ret < 0)
1201 goto fail_decode;
afc80f59
J
1202 /* Some bug in mpeg audio decoder gives */
1203 /* data_size < 0, it seems they are overflows */
1204 if (data_size <= 0) {
a0663ba4
FB
1205 /* no audio frame */
1206 ptr += ret;
1207 len -= ret;
1208 continue;
85f07f22 1209 }
0c1a9eda 1210 data_buf = (uint8_t *)samples;
85f07f22
FB
1211 break;
1212 case CODEC_TYPE_VIDEO:
e8750b00 1213 {
492cd3a9 1214 AVFrame big_picture;
1e491e29 1215
85f07f22
FB
1216 data_size = (ist->st->codec.width * ist->st->codec.height * 3) / 2;
1217 ret = avcodec_decode_video(&ist->st->codec,
1e491e29
MN
1218 &big_picture, &got_picture, ptr, len);
1219 picture= *(AVPicture*)&big_picture;
1220 ist->st->quality= big_picture.quality;
85f07f22
FB
1221 if (ret < 0) {
1222 fail_decode:
1223 fprintf(stderr, "Error while decoding stream #%d.%d\n",
1224 ist->file_index, ist->index);
1225 av_free_packet(&pkt);
1226 goto redo;
1227 }
1228 if (!got_picture) {
1229 /* no picture yet */
1230 ptr += ret;
1231 len -= ret;
1232 continue;
1233 }
6dc96cb0 1234
85f07f22
FB
1235 }
1236 break;
1237 default:
1238 goto fail_decode;
1239 }
1240 } else {
1241 data_buf = ptr;
1242 data_size = len;
1243 ret = len;
1244 }
85f07f22
FB
1245 ptr += ret;
1246 len -= ret;
1247
10d104e4
PG
1248 buffer_to_free = 0;
1249 if (ist->st->codec.codec_type == CODEC_TYPE_VIDEO) {
1250 pre_process_video_frame(ist, &picture, &buffer_to_free);
1251 }
1252
ec5517d5
FB
1253 ist->frame_decoded = 1;
1254
bdfcbbed
MK
1255 /* frame rate emulation */
1256 if (ist->st->codec.rate_emu) {
14bea432 1257 int64_t pts = av_rescale((int64_t) ist->frame * ist->st->codec.frame_rate_base, 1000000, ist->st->codec.frame_rate);
bdfcbbed
MK
1258 int64_t now = av_gettime() - ist->start;
1259 if (pts > now)
1260 usleep(pts - now);
1261
1262 ist->frame++;
1263 }
1264
ec5517d5
FB
1265#if 0
1266 /* mpeg PTS deordering : if it is a P or I frame, the PTS
1267 is the one of the next displayed one */
1268 /* XXX: add mpeg4 too ? */
1269 if (ist->st->codec.codec_id == CODEC_ID_MPEG1VIDEO) {
1270 if (ist->st->codec.pict_type != B_TYPE) {
0c1a9eda 1271 int64_t tmp;
ec5517d5
FB
1272 tmp = ist->last_ip_pts;
1273 ist->last_ip_pts = ist->frac_pts.val;
1274 ist->frac_pts.val = tmp;
1275 }
1276 }
1277#endif
85f07f22 1278 /* transcode raw format, encode packets and output them */
ec5517d5 1279
85f07f22 1280 for(i=0;i<nb_ostreams;i++) {
ce7c56c2 1281 int frame_size;
ec5517d5 1282
85f07f22
FB
1283 ost = ost_table[i];
1284 if (ost->source_index == ist_index) {
1285 os = output_files[ost->file_index];
1286
ec5517d5
FB
1287 if (ipts != AV_NOPTS_VALUE) {
1288#if 0
1289 printf("%d: got pts=%f %f\n",
1290 i, pkt.pts / 90000.0,
1291 (ipts - ost->st->pts.val) / 90000.0);
1292#endif
1293 /* set the input output pts pairs */
1294 ost->sync_ipts = (double)ipts * is->pts_num /
1295 is->pts_den;
1296 /* XXX: take into account the various fifos,
1297 in particular for audio */
1298 ost->sync_opts = ost->st->pts.val;
10d104e4
PG
1299 //printf("ipts=%lld sync_ipts=%f sync_opts=%lld pts.val=%lld pkt.pts=%lld\n", ipts, ost->sync_ipts, ost->sync_opts, ost->st->pts.val, pkt.pts);
1300 } else {
1301 //printf("pts.val=%lld\n", ost->st->pts.val);
be4ce157 1302 ost->sync_ipts = AV_NOPTS_VALUE;
ec5517d5
FB
1303 }
1304
85f07f22
FB
1305 if (ost->encoding_needed) {
1306 switch(ost->st->codec.codec_type) {
1307 case CODEC_TYPE_AUDIO:
1308 do_audio_out(os, ost, ist, data_buf, data_size);
1309 break;
1310 case CODEC_TYPE_VIDEO:
ec5517d5
FB
1311 /* find an audio stream for synchro */
1312 {
1313 int i;
1314 AVOutputStream *audio_sync, *ost1;
1315 audio_sync = NULL;
1316 for(i=0;i<nb_ostreams;i++) {
1317 ost1 = ost_table[i];
1318 if (ost1->file_index == ost->file_index &&
1319 ost1->st->codec.codec_type == CODEC_TYPE_AUDIO) {
1320 audio_sync = ost1;
1321 break;
1322 }
1323 }
1324
1325 do_video_out(os, ost, ist, &picture, &frame_size, audio_sync);
204c0f48 1326 if (do_vstats && frame_size)
ec5517d5
FB
1327 do_video_stats(os, ost, frame_size);
1328 }
85f07f22 1329 break;
51bd4565 1330 default:
c04643a2 1331 av_abort();
85f07f22
FB
1332 }
1333 } else {
18531e52
MN
1334 AVFrame avframe;
1335
85f07f22 1336 /* no reencoding needed : output the packet directly */
10bb7023 1337 /* force the input stream PTS */
18531e52
MN
1338
1339 //XXX/FIXME set keyframe flag from demuxer (or optionally from decoder)
1340 memset(&avframe, 0, sizeof(AVFrame));
1341 ost->st->codec.coded_frame= &avframe;
1342
ec5517d5 1343 av_write_frame(os, ost->index, data_buf, data_size);
b2722d0a 1344 ost->st->codec.frame_number++;
9ce2f2b1 1345 ost->frame_number++;
85f07f22
FB
1346 }
1347 }
1348 }
10d104e4 1349 av_free(buffer_to_free);
ec5517d5 1350 ipts = AV_NOPTS_VALUE;
85f07f22 1351 }
bf5af568 1352 discard_packet:
85f07f22
FB
1353 av_free_packet(&pkt);
1354
ec5517d5
FB
1355 /* dump report by using the output first video and audio streams */
1356 print_report(output_files, ost_table, nb_ostreams, 0);
85f07f22 1357 }
a38469e1 1358 term_exit();
85f07f22
FB
1359
1360 /* dump report by using the first video and audio streams */
ec5517d5
FB
1361 print_report(output_files, ost_table, nb_ostreams, 1);
1362
85f07f22
FB
1363 /* close each encoder */
1364 for(i=0;i<nb_ostreams;i++) {
1365 ost = ost_table[i];
1366 if (ost->encoding_needed) {
5abdb4b1 1367 av_freep(&ost->st->codec.stats_in);
85f07f22
FB
1368 avcodec_close(&ost->st->codec);
1369 }
1370 }
1371
1372 /* close each decoder */
1373 for(i=0;i<nb_istreams;i++) {
1374 ist = ist_table[i];
1375 if (ist->decoding_needed) {
1376 avcodec_close(&ist->st->codec);
1377 }
1378 }
1379
1380
1381 /* write the trailer if needed and close file */
1382 for(i=0;i<nb_output_files;i++) {
1383 os = output_files[i];
79fdaa4c 1384 av_write_trailer(os);
85f07f22
FB
1385 }
1386 /* finished ! */
1387
1388 ret = 0;
1389 fail1:
0f1578af 1390 av_free(file_table);
bdc4796f 1391
85f07f22
FB
1392 if (ist_table) {
1393 for(i=0;i<nb_istreams;i++) {
1394 ist = ist_table[i];
0f1578af 1395 av_free(ist);
85f07f22 1396 }
0f1578af 1397 av_free(ist_table);
85f07f22
FB
1398 }
1399 if (ost_table) {
1400 for(i=0;i<nb_ostreams;i++) {
1401 ost = ost_table[i];
1402 if (ost) {
5abdb4b1
FB
1403 if (ost->logfile) {
1404 fclose(ost->logfile);
1405 ost->logfile = NULL;
1406 }
bf5af568
FB
1407 fifo_free(&ost->fifo); /* works even if fifo is not
1408 initialized but set to zero */
0f1578af 1409 av_free(ost->pict_tmp.data[0]);
85f07f22
FB
1410 if (ost->video_resample)
1411 img_resample_close(ost->img_resample_ctx);
1412 if (ost->audio_resample)
1413 audio_resample_close(ost->resample);
0f1578af 1414 av_free(ost);
85f07f22
FB
1415 }
1416 }
0f1578af 1417 av_free(ost_table);
85f07f22
FB
1418 }
1419 return ret;
1420 fail:
1421 ret = -ENOMEM;
1422 goto fail1;
1423}
1424
1425#if 0
1426int file_read(const char *filename)
1427{
1428 URLContext *h;
1429 unsigned char buffer[1024];
1430 int len, i;
1431
1432 if (url_open(&h, filename, O_RDONLY) < 0) {
1433 printf("could not open '%s'\n", filename);
1434 return -1;
1435 }
1436 for(;;) {
1437 len = url_read(h, buffer, sizeof(buffer));
1438 if (len <= 0)
1439 break;
1440 for(i=0;i<len;i++) putchar(buffer[i]);
1441 }
1442 url_close(h);
1443 return 0;
1444}
1445#endif
1446
b29f97d1 1447static void show_licence(void)
85f07f22
FB
1448{
1449 printf(
1450 "ffmpeg version " FFMPEG_VERSION "\n"
bf5af568
FB
1451 "Copyright (c) 2000, 2001, 2002 Fabrice Bellard\n"
1452 "This library is free software; you can redistribute it and/or\n"
1453 "modify it under the terms of the GNU Lesser General Public\n"
1454 "License as published by the Free Software Foundation; either\n"
1455 "version 2 of the License, or (at your option) any later version.\n"
85f07f22 1456 "\n"
bf5af568 1457 "This library is distributed in the hope that it will be useful,\n"
85f07f22 1458 "but WITHOUT ANY WARRANTY; without even the implied warranty of\n"
bf5af568
FB
1459 "MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n"
1460 "Lesser General Public License for more details.\n"
85f07f22 1461 "\n"
bf5af568
FB
1462 "You should have received a copy of the GNU Lesser General Public\n"
1463 "License along with this library; if not, write to the Free Software\n"
1464 "Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n"
85f07f22
FB
1465 );
1466 exit(1);
1467}
1468
b29f97d1 1469static void opt_image_format(const char *arg)
817b23ff
FB
1470{
1471 AVImageFormat *f;
1472
1473 for(f = first_image_format; f != NULL; f = f->next) {
1474 if (!strcmp(arg, f->name))
1475 break;
1476 }
1477 if (!f) {
1478 fprintf(stderr, "Unknown image format: '%s'\n", arg);
1479 exit(1);
1480 }
1481 image_format = f;
1482}
1483
b29f97d1 1484static void opt_format(const char *arg)
85f07f22 1485{
817b23ff
FB
1486 /* compatibility stuff for pgmyuv */
1487 if (!strcmp(arg, "pgmyuv")) {
1488 opt_image_format(arg);
1489 arg = "image";
1490 }
1491
79fdaa4c
FB
1492 file_iformat = av_find_input_format(arg);
1493 file_oformat = guess_format(arg, NULL, NULL);
1494 if (!file_iformat && !file_oformat) {
1495 fprintf(stderr, "Unknown input or output format: %s\n", arg);
85f07f22
FB
1496 exit(1);
1497 }
85f07f22
FB
1498}
1499
b29f97d1 1500static void opt_video_bitrate(const char *arg)
85f07f22
FB
1501{
1502 video_bit_rate = atoi(arg) * 1000;
1503}
1504
b29f97d1 1505static void opt_video_bitrate_tolerance(const char *arg)
9cdd6a24
MN
1506{
1507 video_bit_rate_tolerance = atoi(arg) * 1000;
1508}
1509
b29f97d1 1510static void opt_video_bitrate_max(const char *arg)
3aa102be
MN
1511{
1512 video_rc_max_rate = atoi(arg) * 1000;
1513}
1514
b29f97d1 1515static void opt_video_bitrate_min(const char *arg)
3aa102be
MN
1516{
1517 video_rc_min_rate = atoi(arg) * 1000;
1518}
1519
b29f97d1 1520static void opt_video_buffer_size(const char *arg)
946c8a12
MN
1521{
1522 video_rc_buffer_size = atoi(arg) * 1000;
1523}
1524
b29f97d1 1525static void opt_video_rc_eq(char *arg)
3aa102be
MN
1526{
1527 video_rc_eq = arg;
1528}
1529
b29f97d1 1530static void opt_video_rc_override_string(char *arg)
ac2830ec
MN
1531{
1532 video_rc_override_string = arg;
1533}
1534
3aa102be 1535
b29f97d1 1536static void opt_workaround_bugs(const char *arg)
fe670d09
MN
1537{
1538 workaround_bugs = atoi(arg);
1539}
1540
b29f97d1 1541static void opt_dct_algo(const char *arg)
463678ac
MN
1542{
1543 dct_algo = atoi(arg);
1544}
1545
b29f97d1 1546static void opt_idct_algo(const char *arg)
2ad1516a
MN
1547{
1548 idct_algo = atoi(arg);
1549}
1550
1551
b29f97d1 1552static void opt_error_resilience(const char *arg)
8409b8fe
MN
1553{
1554 error_resilience = atoi(arg);
1555}
1556
b29f97d1 1557static void opt_error_concealment(const char *arg)
4d2858de
MN
1558{
1559 error_concealment = atoi(arg);
1560}
1561
b29f97d1 1562static void opt_debug(const char *arg)
59b571c1
MN
1563{
1564 debug = atoi(arg);
1565}
4d2858de 1566
b29f97d1 1567static void opt_frame_rate(const char *arg)
85f07f22 1568{
14bea432
MN
1569 frame_rate_base = DEFAULT_FRAME_RATE_BASE; //FIXME not optimal
1570 frame_rate = (int)(strtod(arg, 0) * frame_rate_base + 0.5);
1571 //FIXME parse fractions
85f07f22
FB
1572}
1573
ab6d194a 1574
b29f97d1 1575static void opt_frame_crop_top(const char *arg)
ab6d194a
MN
1576{
1577 frame_topBand = atoi(arg);
1578 if (frame_topBand < 0) {
1579 fprintf(stderr, "Incorrect top crop size\n");
1580 exit(1);
1581 }
1582 if ((frame_topBand % 2) != 0) {
1583 fprintf(stderr, "Top crop size must be a multiple of 2\n");
1584 exit(1);
1585 }
1586 if ((frame_topBand) >= frame_height){
1587 fprintf(stderr, "Vertical crop dimensions are outside the range of the original image.\nRemember to crop first and scale second.\n");
1588 exit(1);
1589 }
1590 frame_height -= frame_topBand;
1591}
1592
b29f97d1 1593static void opt_frame_crop_bottom(const char *arg)
ab6d194a
MN
1594{
1595 frame_bottomBand = atoi(arg);
1596 if (frame_bottomBand < 0) {
1597 fprintf(stderr, "Incorrect bottom crop size\n");
1598 exit(1);
1599 }
1600 if ((frame_bottomBand % 2) != 0) {
1601 fprintf(stderr, "Bottom crop size must be a multiple of 2\n");
1602 exit(1);
1603 }
1604 if ((frame_bottomBand) >= frame_height){
1605 fprintf(stderr, "Vertical crop dimensions are outside the range of the original image.\nRemember to crop first and scale second.\n");
1606 exit(1);
1607 }
1608 frame_height -= frame_bottomBand;
1609}
1610
b29f97d1 1611static void opt_frame_crop_left(const char *arg)
ab6d194a
MN
1612{
1613 frame_leftBand = atoi(arg);
1614 if (frame_leftBand < 0) {
1615 fprintf(stderr, "Incorrect left crop size\n");
1616 exit(1);
1617 }
1618 if ((frame_leftBand % 2) != 0) {
1619 fprintf(stderr, "Left crop size must be a multiple of 2\n");
1620 exit(1);
1621 }
1622 if ((frame_leftBand) >= frame_width){
1623 fprintf(stderr, "Horizontal crop dimensions are outside the range of the original image.\nRemember to crop first and scale second.\n");
1624 exit(1);
1625 }
1626 frame_width -= frame_leftBand;
1627}
1628
b29f97d1 1629static void opt_frame_crop_right(const char *arg)
ab6d194a
MN
1630{
1631 frame_rightBand = atoi(arg);
1632 if (frame_rightBand < 0) {
1633 fprintf(stderr, "Incorrect right crop size\n");
1634 exit(1);
1635 }
1636 if ((frame_rightBand % 2) != 0) {
1637 fprintf(stderr, "Right crop size must be a multiple of 2\n");
1638 exit(1);
1639 }
1640 if ((frame_rightBand) >= frame_width){
1641 fprintf(stderr, "Horizontal crop dimensions are outside the range of the original image.\nRemember to crop first and scale second.\n");
1642 exit(1);
1643 }
1644 frame_width -= frame_rightBand;
1645}
1646
b29f97d1 1647static void opt_frame_size(const char *arg)
85f07f22
FB
1648{
1649 parse_image_size(&frame_width, &frame_height, arg);
1650 if (frame_width <= 0 || frame_height <= 0) {
1651 fprintf(stderr, "Incorrect frame size\n");
1652 exit(1);
1653 }
1654 if ((frame_width % 2) != 0 || (frame_height % 2) != 0) {
1655 fprintf(stderr, "Frame size must be a multiple of 2\n");
1656 exit(1);
1657 }
1658}
1659
b29f97d1 1660static void opt_gop_size(const char *arg)
85f07f22
FB
1661{
1662 gop_size = atoi(arg);
1663}
1664
b29f97d1 1665static void opt_b_frames(const char *arg)
bc6caae2
J
1666{
1667 b_frames = atoi(arg);
1668 if (b_frames > FF_MAX_B_FRAMES) {
1669 fprintf(stderr, "\nCannot have more than %d B frames, increase FF_MAX_B_FRAMES.\n", FF_MAX_B_FRAMES);
1670 exit(1);
1671 } else if (b_frames < 1) {
1672 fprintf(stderr, "\nNumber of B frames must be higher than 0\n");
1673 exit(1);
1674 }
1675}
1676
b29f97d1 1677static void opt_qscale(const char *arg)
85f07f22
FB
1678{
1679 video_qscale = atoi(arg);
1680 if (video_qscale < 0 ||
1681 video_qscale > 31) {
1682 fprintf(stderr, "qscale must be >= 1 and <= 31\n");
1683 exit(1);
1684 }
1685}
1686
b29f97d1 1687static void opt_qmin(const char *arg)
9cdd6a24
MN
1688{
1689 video_qmin = atoi(arg);
1690 if (video_qmin < 0 ||
1691 video_qmin > 31) {
1692 fprintf(stderr, "qmin must be >= 1 and <= 31\n");
1693 exit(1);
1694 }
1695}
1696
b29f97d1 1697static void opt_qmax(const char *arg)
9cdd6a24
MN
1698{
1699 video_qmax = atoi(arg);
1700 if (video_qmax < 0 ||
1701 video_qmax > 31) {
1702 fprintf(stderr, "qmax must be >= 1 and <= 31\n");
1703 exit(1);
1704 }
1705}
1706
b29f97d1 1707static void opt_mb_qmin(const char *arg)
17a70fde
MN
1708{
1709 video_mb_qmin = atoi(arg);
1710 if (video_mb_qmin < 0 ||
1711 video_mb_qmin > 31) {
1712 fprintf(stderr, "qmin must be >= 1 and <= 31\n");
1713 exit(1);
1714 }
1715}
1716
b29f97d1 1717static void opt_mb_qmax(const char *arg)
17a70fde
MN
1718{
1719 video_mb_qmax = atoi(arg);
1720 if (video_mb_qmax < 0 ||
1721 video_mb_qmax > 31) {
1722 fprintf(stderr, "qmax must be >= 1 and <= 31\n");
1723 exit(1);
1724 }
1725}
1726
b29f97d1 1727static void opt_qdiff(const char *arg)
9cdd6a24
MN
1728{
1729 video_qdiff = atoi(arg);
1730 if (video_qdiff < 0 ||
1731 video_qdiff > 31) {
1732 fprintf(stderr, "qdiff must be >= 1 and <= 31\n");
1733 exit(1);
1734 }
1735}
1736
b29f97d1 1737static void opt_qblur(const char *arg)
9cdd6a24
MN
1738{
1739 video_qblur = atof(arg);
1740}
1741
b29f97d1 1742static void opt_qcomp(const char *arg)
9cdd6a24
MN
1743{
1744 video_qcomp = atof(arg);
1745}
85f07f22 1746
b29f97d1 1747static void opt_rc_initial_cplx(const char *arg)
ac2830ec
MN
1748{
1749 video_rc_initial_cplx = atof(arg);
1750}
b29f97d1 1751static void opt_b_qfactor(const char *arg)
29700fa6
MN
1752{
1753 video_b_qfactor = atof(arg);
1754}
b29f97d1 1755static void opt_i_qfactor(const char *arg)
29700fa6
MN
1756{
1757 video_i_qfactor = atof(arg);
1758}
b29f97d1 1759static void opt_b_qoffset(const char *arg)
29700fa6
MN
1760{
1761 video_b_qoffset = atof(arg);
1762}
b29f97d1 1763static void opt_i_qoffset(const char *arg)
29700fa6
MN
1764{
1765 video_i_qoffset = atof(arg);
1766}
1767
b29f97d1 1768static void opt_packet_size(const char *arg)
1dbb6d90
MN
1769{
1770 packet_size= atoi(arg);
1771}
1772
b29f97d1 1773static void opt_strict(const char *arg)
f560dd82
MN
1774{
1775 strict= atoi(arg);
1776}
1777
b29f97d1 1778static void opt_audio_bitrate(const char *arg)
85f07f22
FB
1779{
1780 audio_bit_rate = atoi(arg) * 1000;
1781}
1782
b29f97d1 1783static void opt_audio_rate(const char *arg)
85f07f22
FB
1784{
1785 audio_sample_rate = atoi(arg);
1786}
1787
b29f97d1 1788static void opt_audio_channels(const char *arg)
85f07f22
FB
1789{
1790 audio_channels = atoi(arg);
1791}
1792
b29f97d1 1793static void opt_video_device(const char *arg)
85f07f22 1794{
e9a9e0c2 1795 video_device = av_strdup(arg);
85f07f22
FB
1796}
1797
b29f97d1 1798static void opt_video_channel(const char *arg)
a5df11ab
FB
1799{
1800 video_channel = strtol(arg, NULL, 0);
1801}
1802
b29f97d1 1803static void opt_audio_device(const char *arg)
85f07f22 1804{
e9a9e0c2 1805 audio_device = av_strdup(arg);
85f07f22
FB
1806}
1807
b29f97d1 1808static void opt_dv1394(const char *arg)
8aa3ee32
MK
1809{
1810 video_grab_format = "dv1394";
1501987b 1811 audio_grab_format = NULL;
8aa3ee32
MK
1812}
1813
b29f97d1 1814static void opt_audio_codec(const char *arg)
85f07f22
FB
1815{
1816 AVCodec *p;
1817
1629626f
FB
1818 if (!strcmp(arg, "copy")) {
1819 audio_stream_copy = 1;
85f07f22 1820 } else {
1629626f
FB
1821 p = first_avcodec;
1822 while (p) {
1823 if (!strcmp(p->name, arg) && p->type == CODEC_TYPE_AUDIO)
1824 break;
1825 p = p->next;
1826 }
1827 if (p == NULL) {
1828 fprintf(stderr, "Unknown audio codec '%s'\n", arg);
1829 exit(1);
1830 } else {
1831 audio_codec_id = p->id;
1832 }
85f07f22
FB
1833 }
1834}
1835
b29f97d1 1836static void add_frame_hooker(const char *arg)
10d104e4
PG
1837{
1838 int argc = 0;
1839 char *argv[64];
1840 int i;
e9a9e0c2 1841 char *args = av_strdup(arg);
10d104e4
PG
1842
1843 argv[0] = strtok(args, " ");
1844 while (argc < 62 && (argv[++argc] = strtok(NULL, " "))) {
1845 }
1846
1847 i = frame_hook_add(argc, argv);
1848
1849 if (i != 0) {
1850 fprintf(stderr, "Failed to add video hook function: %s\n", arg);
1851 exit(1);
1852 }
1853}
1854
85f07f22
FB
1855const char *motion_str[] = {
1856 "zero",
1857 "full",
1858 "log",
1859 "phods",
7084c149
MN
1860 "epzs",
1861 "x1",
85f07f22
FB
1862 NULL,
1863};
1864
b29f97d1 1865static void opt_motion_estimation(const char *arg)
85f07f22
FB
1866{
1867 const char **p;
1868 p = motion_str;
1869 for(;;) {
1870 if (!*p) {
1871 fprintf(stderr, "Unknown motion estimation method '%s'\n", arg);
1872 exit(1);
1873 }
1874 if (!strcmp(*p, arg))
1875 break;
1876 p++;
1877 }
101bea5f 1878 me_method = (p - motion_str) + 1;
85f07f22
FB
1879}
1880
b29f97d1 1881static void opt_video_codec(const char *arg)
85f07f22
FB
1882{
1883 AVCodec *p;
1884
1629626f
FB
1885 if (!strcmp(arg, "copy")) {
1886 video_stream_copy = 1;
85f07f22 1887 } else {
1629626f
FB
1888 p = first_avcodec;
1889 while (p) {
1890 if (!strcmp(p->name, arg) && p->type == CODEC_TYPE_VIDEO)
1891 break;
1892 p = p->next;
1893 }
1894 if (p == NULL) {
1895 fprintf(stderr, "Unknown video codec '%s'\n", arg);
1896 exit(1);
1897 } else {
1898 video_codec_id = p->id;
1899 }
85f07f22
FB
1900 }
1901}
1902
b29f97d1 1903static void opt_map(const char *arg)
85f07f22
FB
1904{
1905 AVStreamMap *m;
1906 const char *p;
1907
1908 p = arg;
1909 m = &stream_maps[nb_stream_maps++];
1910
1911 m->file_index = strtol(arg, (char **)&p, 0);
1912 if (*p)
1913 p++;
a5dc85ef
J
1914
1915 m->stream_index = strtol(p, (char **)&p, 0);
85f07f22
FB
1916}
1917
b29f97d1 1918static void opt_recording_time(const char *arg)
85f07f22
FB
1919{
1920 recording_time = parse_date(arg, 1);
1921}
1922
b29f97d1 1923static void print_error(const char *filename, int err)
919f448d 1924{
79fdaa4c
FB
1925 switch(err) {
1926 case AVERROR_NUMEXPECTED:
919f448d
FB
1927 fprintf(stderr, "%s: Incorrect image filename syntax.\n"
1928 "Use '%%d' to specify the image number:\n"
1929 " for img1.jpg, img2.jpg, ..., use 'img%%d.jpg';\n"
1930 " for img001.jpg, img002.jpg, ..., use 'img%%03d.jpg'.\n",
1931 filename);
79fdaa4c
FB
1932 break;
1933 case AVERROR_INVALIDDATA:
1934 fprintf(stderr, "%s: Error while parsing header\n", filename);
1935 break;
1936 case AVERROR_NOFMT:
1937 fprintf(stderr, "%s: Unknown format\n", filename);
1938 break;
1939 default:
1940 fprintf(stderr, "%s: Error while opening file\n", filename);
1941 break;
919f448d
FB
1942 }
1943}
85f07f22 1944
b29f97d1 1945static void opt_input_file(const char *filename)
85f07f22
FB
1946{
1947 AVFormatContext *ic;
1948 AVFormatParameters params, *ap = &params;
14bea432 1949 int err, i, ret, rfps, rfps_base;
85f07f22 1950
b242baa4
FB
1951 if (!strcmp(filename, "-"))
1952 filename = "pipe:";
1953
85f07f22 1954 /* get default parameters from command line */
79fdaa4c
FB
1955 memset(ap, 0, sizeof(*ap));
1956 ap->sample_rate = audio_sample_rate;
1957 ap->channels = audio_channels;
1958 ap->frame_rate = frame_rate;
14bea432 1959 ap->frame_rate_base = frame_rate_base;
79fdaa4c
FB
1960 ap->width = frame_width;
1961 ap->height = frame_height;
817b23ff 1962 ap->image_format = image_format;
79fdaa4c
FB
1963
1964 /* open the input file with generic libav function */
1965 err = av_open_input_file(&ic, filename, file_iformat, 0, ap);
85f07f22 1966 if (err < 0) {
79fdaa4c 1967 print_error(filename, err);
85f07f22
FB
1968 exit(1);
1969 }
1970
79fdaa4c
FB
1971 /* If not enough info to get the stream parameters, we decode the
1972 first frames to get it. (used in mpeg case for example) */
1973 ret = av_find_stream_info(ic);
85f07f22
FB
1974 if (ret < 0) {
1975 fprintf(stderr, "%s: could not find codec parameters\n", filename);
1976 exit(1);
1977 }
1978
1979 /* update the current parameters so that they match the one of the input stream */
1980 for(i=0;i<ic->nb_streams;i++) {
1981 AVCodecContext *enc = &ic->streams[i]->codec;
1982 switch(enc->codec_type) {
1983 case CODEC_TYPE_AUDIO:
e0d2714a 1984 //fprintf(stderr, "\nInput Audio channels: %d", enc->channels);
85f07f22
FB
1985 audio_channels = enc->channels;
1986 audio_sample_rate = enc->sample_rate;
1987 break;
1988 case CODEC_TYPE_VIDEO:
1989 frame_height = enc->height;
1990 frame_width = enc->width;
14bea432
MN
1991 rfps = ic->streams[i]->r_frame_rate;
1992 rfps_base = ic->streams[i]->r_frame_rate_base;
fe670d09 1993 enc->workaround_bugs = workaround_bugs;
8409b8fe 1994 enc->error_resilience = error_resilience;
4d2858de 1995 enc->error_concealment = error_concealment;
2ad1516a 1996 enc->idct_algo= idct_algo;
59b571c1 1997 enc->debug= debug;
d7425f59
MN
1998/* if(enc->codec->capabilities & CODEC_CAP_TRUNCATED)
1999 enc->flags|= CODEC_FLAG_TRUNCATED; */
2000 if(/*enc->codec_id==CODEC_ID_MPEG4 || */enc->codec_id==CODEC_ID_MPEG1VIDEO)
2001 enc->flags|= CODEC_FLAG_TRUNCATED;
b0368839
MN
2002
2003 if(bitexact)
2004 enc->flags|= CODEC_FLAG_BITEXACT;
d7425f59 2005
14bea432
MN
2006 assert(enc->frame_rate_base == rfps_base); // should be true for now
2007 if (enc->frame_rate != rfps) {
6dc96cb0 2008 fprintf(stderr,"\nSeems that stream %d comes from film source: %2.2f->%2.2f\n",
14bea432
MN
2009 i, (float)enc->frame_rate / enc->frame_rate_base,
2010 (float)rfps / rfps_base);
79fdaa4c 2011 }
bf5af568 2012 /* update the current frame rate to match the stream frame rate */
14bea432
MN
2013 frame_rate = rfps;
2014 frame_rate_base = rfps_base;
bdfcbbed
MK
2015
2016 enc->rate_emu = rate_emu;
85f07f22 2017 break;
51bd4565 2018 default:
c04643a2 2019 av_abort();
85f07f22
FB
2020 }
2021 }
2022
2023 input_files[nb_input_files] = ic;
2024 /* dump the file content */
2025 dump_format(ic, nb_input_files, filename, 0);
2026 nb_input_files++;
79fdaa4c
FB
2027 file_iformat = NULL;
2028 file_oformat = NULL;
817b23ff 2029 image_format = NULL;
bdfcbbed
MK
2030
2031 rate_emu = 0;
85f07f22
FB
2032}
2033
b29f97d1 2034static void check_audio_video_inputs(int *has_video_ptr, int *has_audio_ptr)
919f448d
FB
2035{
2036 int has_video, has_audio, i, j;
2037 AVFormatContext *ic;
2038
2039 has_video = 0;
2040 has_audio = 0;
2041 for(j=0;j<nb_input_files;j++) {
2042 ic = input_files[j];
2043 for(i=0;i<ic->nb_streams;i++) {
2044 AVCodecContext *enc = &ic->streams[i]->codec;
2045 switch(enc->codec_type) {
2046 case CODEC_TYPE_AUDIO:
2047 has_audio = 1;
2048 break;
2049 case CODEC_TYPE_VIDEO:
2050 has_video = 1;
2051 break;
51bd4565 2052 default:
c04643a2 2053 av_abort();
919f448d
FB
2054 }
2055 }
2056 }
2057 *has_video_ptr = has_video;
2058 *has_audio_ptr = has_audio;
2059}
2060
b29f97d1 2061static void opt_output_file(const char *filename)
85f07f22
FB
2062{
2063 AVStream *st;
2064 AVFormatContext *oc;
919f448d 2065 int use_video, use_audio, nb_streams, input_has_video, input_has_audio;
85f07f22 2066 int codec_id;
817b23ff 2067 AVFormatParameters params, *ap = &params;
85f07f22
FB
2068
2069 if (!strcmp(filename, "-"))
2070 filename = "pipe:";
2071
2072 oc = av_mallocz(sizeof(AVFormatContext));
2073
79fdaa4c
FB
2074 if (!file_oformat) {
2075 file_oformat = guess_format(NULL, filename, NULL);
2076 if (!file_oformat) {
2077 fprintf(stderr, "Unable for find a suitable output format for '%s'\n",
2078 filename);
2079 exit(1);
2080 }
85f07f22
FB
2081 }
2082
79fdaa4c 2083 oc->oformat = file_oformat;
85f07f22 2084
79fdaa4c 2085 if (!strcmp(file_oformat->name, "ffm") &&
85f07f22
FB
2086 strstart(filename, "http:", NULL)) {
2087 /* special case for files sent to ffserver: we get the stream
2088 parameters from ffserver */
2089 if (read_ffserver_streams(oc, filename) < 0) {
2090 fprintf(stderr, "Could not read stream parameters from '%s'\n", filename);
2091 exit(1);
2092 }
2093 } else {
79fdaa4c
FB
2094 use_video = file_oformat->video_codec != CODEC_ID_NONE;
2095 use_audio = file_oformat->audio_codec != CODEC_ID_NONE;
919f448d 2096
e30a2846
FB
2097 /* disable if no corresponding type found and at least one
2098 input file */
2099 if (nb_input_files > 0) {
2100 check_audio_video_inputs(&input_has_video, &input_has_audio);
2101 if (!input_has_video)
2102 use_video = 0;
2103 if (!input_has_audio)
2104 use_audio = 0;
2105 }
919f448d
FB
2106
2107 /* manual disable */
85f07f22
FB
2108 if (audio_disable) {
2109 use_audio = 0;
2110 }
2111 if (video_disable) {
2112 use_video = 0;
2113 }
2114
2115 nb_streams = 0;
2116 if (use_video) {
2117 AVCodecContext *video_enc;
2118
2119 st = av_mallocz(sizeof(AVStream));
2120 if (!st) {
2121 fprintf(stderr, "Could not alloc stream\n");
2122 exit(1);
2123 }
1e491e29 2124 avcodec_get_context_defaults(&st->codec);
85f07f22 2125
1629626f
FB
2126 video_enc = &st->codec;
2127 if (video_stream_copy) {
2128 st->stream_copy = 1;
2129 video_enc->codec_type = CODEC_TYPE_VIDEO;
2130 } else {
ac2830ec
MN
2131 char *p;
2132 int i;
2133
1629626f
FB
2134 codec_id = file_oformat->video_codec;
2135 if (video_codec_id != CODEC_ID_NONE)
2136 codec_id = video_codec_id;
2137
2138 video_enc->codec_id = codec_id;
2139
2140 video_enc->bit_rate = video_bit_rate;
2141 video_enc->bit_rate_tolerance = video_bit_rate_tolerance;
2142 video_enc->frame_rate = frame_rate;
14bea432 2143 video_enc->frame_rate_base = frame_rate_base;
1629626f
FB
2144
2145 video_enc->width = frame_width;
2146 video_enc->height = frame_height;
2147
2148 if (!intra_only)
2149 video_enc->gop_size = gop_size;
2150 else
2151 video_enc->gop_size = 0;
2152 if (video_qscale || same_quality) {
2153 video_enc->flags |= CODEC_FLAG_QSCALE;
1e491e29 2154 st->quality = video_qscale;
1629626f 2155 }
b0368839
MN
2156
2157 if(bitexact)
2158 video_enc->flags |= CODEC_FLAG_BITEXACT;
2159
1629626f
FB
2160 if (use_hq) {
2161 video_enc->flags |= CODEC_FLAG_HQ;
2162 }
21e59552
MN
2163 /* Fx */
2164 if (use_umv) {
2165 video_enc->flags |= CODEC_FLAG_H263P_UMV;
2166 }
2167 if (use_aic) {
2168 video_enc->flags |= CODEC_FLAG_H263P_AIC;
2169 }
2170 /* /Fx */
1629626f
FB
2171 if (use_4mv) {
2172 video_enc->flags |= CODEC_FLAG_HQ;
2173 video_enc->flags |= CODEC_FLAG_4MV;
2174 }
bc6caae2 2175
1629626f
FB
2176 if(use_part)
2177 video_enc->flags |= CODEC_FLAG_PART;
1dbb6d90
MN
2178
2179
1629626f 2180 if (b_frames) {
1629626f
FB
2181 video_enc->max_b_frames = b_frames;
2182 video_enc->b_frame_strategy = 0;
2183 video_enc->b_quant_factor = 2.0;
bc6caae2 2184 }
bc6caae2 2185
1629626f
FB
2186 video_enc->qmin = video_qmin;
2187 video_enc->qmax = video_qmax;
17a70fde
MN
2188 video_enc->mb_qmin = video_mb_qmin;
2189 video_enc->mb_qmax = video_mb_qmax;
1629626f
FB
2190 video_enc->max_qdiff = video_qdiff;
2191 video_enc->qblur = video_qblur;
2192 video_enc->qcompress = video_qcomp;
2193 video_enc->rc_eq = video_rc_eq;
59b571c1 2194 video_enc->debug= debug;
ac2830ec
MN
2195
2196 p= video_rc_override_string;
2197 for(i=0; p; i++){
2198 int start, end, q;
2199 int e=sscanf(p, "%d,%d,%d", &start, &end, &q);
2200 if(e!=3){
2201 fprintf(stderr, "error parsing rc_override\n");
2202 exit(1);
2203 }
2204 video_enc->rc_override=
47e2a6e6
FB
2205 av_realloc(video_enc->rc_override,
2206 sizeof(RcOverride)*(i+1));
ac2830ec
MN
2207 video_enc->rc_override[i].start_frame= start;
2208 video_enc->rc_override[i].end_frame = end;
2209 if(q>0){
2210 video_enc->rc_override[i].qscale= q;
2211 video_enc->rc_override[i].quality_factor= 1.0;
2212 }
2213 else{
2214 video_enc->rc_override[i].qscale= 0;
2215 video_enc->rc_override[i].quality_factor= -q/100.0;
2216 }
2217 p= strchr(p, '/');
2218 if(p) p++;
2219 }
2220 video_enc->rc_override_count=i;
2221
1629626f
FB
2222 video_enc->rc_max_rate = video_rc_max_rate;
2223 video_enc->rc_min_rate = video_rc_min_rate;
2224 video_enc->rc_buffer_size = video_rc_buffer_size;
2225 video_enc->rc_buffer_aggressivity= video_rc_buffer_aggressivity;
ac2830ec 2226 video_enc->rc_initial_cplx= video_rc_initial_cplx;
1629626f
FB
2227 video_enc->i_quant_factor = video_i_qfactor;
2228 video_enc->b_quant_factor = video_b_qfactor;
2229 video_enc->i_quant_offset = video_i_qoffset;
2230 video_enc->b_quant_offset = video_b_qoffset;
2231 video_enc->dct_algo = dct_algo;
2232 video_enc->idct_algo = idct_algo;
f560dd82 2233 video_enc->strict_std_compliance = strict;
1629626f
FB
2234 if(packet_size){
2235 video_enc->rtp_mode= 1;
2236 video_enc->rtp_payload_size= packet_size;
2237 }
9cdd6a24 2238
1629626f 2239 if (do_psnr)
140cb663 2240 video_enc->flags|= CODEC_FLAG_PSNR;
e4986da9 2241
1629626f 2242 video_enc->me_method = me_method;
5abdb4b1 2243
1629626f
FB
2244 /* two pass mode */
2245 if (do_pass) {
2246 if (do_pass == 1) {
2247 video_enc->flags |= CODEC_FLAG_PASS1;
2248 } else {
2249 video_enc->flags |= CODEC_FLAG_PASS2;
2250 }
5abdb4b1 2251 }
cfcf0ffd 2252 }
85f07f22
FB
2253 oc->streams[nb_streams] = st;
2254 nb_streams++;
2255 }
2256
2257 if (use_audio) {
2258 AVCodecContext *audio_enc;
2259
2260 st = av_mallocz(sizeof(AVStream));
2261 if (!st) {
2262 fprintf(stderr, "Could not alloc stream\n");
2263 exit(1);
2264 }
1e491e29 2265 avcodec_get_context_defaults(&st->codec);
1629626f 2266
85f07f22 2267 audio_enc = &st->codec;
85f07f22 2268 audio_enc->codec_type = CODEC_TYPE_AUDIO;
1629626f
FB
2269 if (audio_stream_copy) {
2270 st->stream_copy = 1;
2271 } else {
2272 codec_id = file_oformat->audio_codec;
2273 if (audio_codec_id != CODEC_ID_NONE)
2274 codec_id = audio_codec_id;
2275 audio_enc->codec_id = codec_id;
2276
2277 audio_enc->bit_rate = audio_bit_rate;
2278 audio_enc->sample_rate = audio_sample_rate;
2279 /* For audio codecs other than AC3 we limit */
2280 /* the number of coded channels to stereo */
2281 if (audio_channels > 2 && codec_id != CODEC_ID_AC3) {
2282 audio_enc->channels = 2;
2283 } else
2284 audio_enc->channels = audio_channels;
2285 }
85f07f22
FB
2286 oc->streams[nb_streams] = st;
2287 nb_streams++;
2288 }
2289
2290 oc->nb_streams = nb_streams;
2291
2292 if (!nb_streams) {
919f448d 2293 fprintf(stderr, "No audio or video streams available\n");
85f07f22
FB
2294 exit(1);
2295 }
2296
2297 if (str_title)
79fdaa4c 2298 pstrcpy(oc->title, sizeof(oc->title), str_title);
85f07f22 2299 if (str_author)
79fdaa4c 2300 pstrcpy(oc->author, sizeof(oc->author), str_author);
85f07f22 2301 if (str_copyright)
79fdaa4c 2302 pstrcpy(oc->copyright, sizeof(oc->copyright), str_copyright);
85f07f22 2303 if (str_comment)
79fdaa4c 2304 pstrcpy(oc->comment, sizeof(oc->comment), str_comment);
85f07f22
FB
2305 }
2306
1629626f 2307 output_files[nb_output_files++] = oc;
85f07f22
FB
2308
2309 strcpy(oc->filename, filename);
919f448d
FB
2310
2311 /* check filename in case of an image number is expected */
79fdaa4c
FB
2312 if (oc->oformat->flags & AVFMT_NEEDNUMBER) {
2313 if (filename_number_test(oc->filename) < 0) {
2314 print_error(oc->filename, AVERROR_NUMEXPECTED);
919f448d 2315 exit(1);
79fdaa4c 2316 }
919f448d
FB
2317 }
2318
79fdaa4c 2319 if (!(oc->oformat->flags & AVFMT_NOFILE)) {
85f07f22
FB
2320 /* test if it already exists to avoid loosing precious files */
2321 if (!file_overwrite &&
2322 (strchr(filename, ':') == NULL ||
2323 strstart(filename, "file:", NULL))) {
2324 if (url_exist(filename)) {
2325 int c;
2326
2327 printf("File '%s' already exists. Overwrite ? [y/N] ", filename);
2328 fflush(stdout);
2329 c = getchar();
2330 if (toupper(c) != 'Y') {
2331 fprintf(stderr, "Not overwriting - exiting\n");
2332 exit(1);
2333 }
2334 }
2335 }
2336
2337 /* open the file */
2338 if (url_fopen(&oc->pb, filename, URL_WRONLY) < 0) {
2339 fprintf(stderr, "Could not open '%s'\n", filename);
2340 exit(1);
2341 }
2342 }
2343
817b23ff
FB
2344 memset(ap, 0, sizeof(*ap));
2345 ap->image_format = image_format;
2346 if (av_set_parameters(oc, ap) < 0) {
2347 fprintf(stderr, "%s: Invalid encoding parameters\n",
2348 oc->filename);
2349 exit(1);
2350 }
2351
85f07f22 2352 /* reset some options */
79fdaa4c
FB
2353 file_oformat = NULL;
2354 file_iformat = NULL;
817b23ff 2355 image_format = NULL;
85f07f22
FB
2356 audio_disable = 0;
2357 video_disable = 0;
2358 audio_codec_id = CODEC_ID_NONE;
2359 video_codec_id = CODEC_ID_NONE;
1629626f
FB
2360 audio_stream_copy = 0;
2361 video_stream_copy = 0;
85f07f22
FB
2362}
2363
a38469e1 2364/* prepare dummy protocols for grab */
b29f97d1 2365static void prepare_grab(void)
a38469e1
FB
2366{
2367 int has_video, has_audio, i, j;
2368 AVFormatContext *oc;
2369 AVFormatContext *ic;
79a7c268 2370 AVFormatParameters vp1, *vp = &vp1;
a38469e1 2371 AVFormatParameters ap1, *ap = &ap1;
79a7c268 2372
a38469e1
FB
2373 /* see if audio/video inputs are needed */
2374 has_video = 0;
2375 has_audio = 0;
2376 memset(ap, 0, sizeof(*ap));
79a7c268 2377 memset(vp, 0, sizeof(*vp));
a38469e1
FB
2378 for(j=0;j<nb_output_files;j++) {
2379 oc = output_files[j];
2380 for(i=0;i<oc->nb_streams;i++) {
2381 AVCodecContext *enc = &oc->streams[i]->codec;
2382 switch(enc->codec_type) {
2383 case CODEC_TYPE_AUDIO:
2384 if (enc->sample_rate > ap->sample_rate)
2385 ap->sample_rate = enc->sample_rate;
2386 if (enc->channels > ap->channels)
2387 ap->channels = enc->channels;
2388 has_audio = 1;
2389 break;
2390 case CODEC_TYPE_VIDEO:
79a7c268
FB
2391 if (enc->width > vp->width)
2392 vp->width = enc->width;
2393 if (enc->height > vp->height)
2394 vp->height = enc->height;
14bea432
MN
2395
2396 assert(enc->frame_rate_base == DEFAULT_FRAME_RATE_BASE);
2397 if (enc->frame_rate > vp->frame_rate){
2398 vp->frame_rate = enc->frame_rate;
2399 vp->frame_rate_base = enc->frame_rate_base;
2400 }
a38469e1
FB
2401 has_video = 1;
2402 break;
51bd4565 2403 default:
c04643a2 2404 av_abort();
a38469e1
FB
2405 }
2406 }
2407 }
2408
2409 if (has_video == 0 && has_audio == 0) {
2410 fprintf(stderr, "Output file must have at least one audio or video stream\n");
2411 exit(1);
2412 }
2413
2414 if (has_video) {
79fdaa4c 2415 AVInputFormat *fmt1;
8aa3ee32 2416 fmt1 = av_find_input_format(video_grab_format);
a5df11ab
FB
2417 vp->device = video_device;
2418 vp->channel = video_channel;
79a7c268 2419 if (av_open_input_file(&ic, "", fmt1, 0, vp) < 0) {
bf5af568 2420 fprintf(stderr, "Could not find video grab device\n");
a38469e1
FB
2421 exit(1);
2422 }
79fdaa4c 2423 /* by now video grab has one stream */
14bea432
MN
2424 ic->streams[0]->r_frame_rate = vp->frame_rate;
2425 ic->streams[0]->r_frame_rate_base = vp->frame_rate_base;
a38469e1 2426 input_files[nb_input_files] = ic;
79a7c268 2427 dump_format(ic, nb_input_files, "", 0);
a38469e1
FB
2428 nb_input_files++;
2429 }
1501987b 2430 if (has_audio && audio_grab_format) {
79fdaa4c 2431 AVInputFormat *fmt1;
8aa3ee32 2432 fmt1 = av_find_input_format(audio_grab_format);
79a7c268 2433 ap->device = audio_device;
79fdaa4c 2434 if (av_open_input_file(&ic, "", fmt1, 0, ap) < 0) {
bf5af568 2435 fprintf(stderr, "Could not find audio grab device\n");
a38469e1
FB
2436 exit(1);
2437 }
2438 input_files[nb_input_files] = ic;
79a7c268 2439 dump_format(ic, nb_input_files, "", 0);
a38469e1
FB
2440 nb_input_files++;
2441 }
2442}
2443
a38469e1 2444/* open the necessary output devices for playing */
b29f97d1 2445static void prepare_play(void)
a38469e1 2446{
79a7c268 2447 int has_video, has_audio;
a38469e1 2448
79a7c268
FB
2449 check_audio_video_inputs(&has_video, &has_audio);
2450
2451 /* manual disable */
2452 if (audio_disable) {
2453 has_audio = 0;
2454 }
2455 if (video_disable) {
2456 has_video = 0;
2457 }
2458
2459 if (has_audio) {
2460 file_oformat = guess_format("audio_device", NULL, NULL);
2461 if (!file_oformat) {
2462 fprintf(stderr, "Could not find audio device\n");
2463 exit(1);
2464 }
3f07e605 2465 opt_output_file(audio_device?audio_device:"/dev/dsp");
79a7c268
FB
2466 }
2467
2468 if (has_video) {
2469 file_oformat = guess_format("framebuffer_device", NULL, NULL);
2470 if (!file_oformat) {
2471 fprintf(stderr, "Could not find framebuffer device\n");
2472 exit(1);
2473 }
2474 opt_output_file("");
2475 }
a38469e1
FB
2476}
2477
5abdb4b1 2478/* same option as mencoder */
b29f97d1 2479static void opt_pass(const char *pass_str)
5abdb4b1
FB
2480{
2481 int pass;
2482 pass = atoi(pass_str);
2483 if (pass != 1 && pass != 2) {
2484 fprintf(stderr, "pass number can be only 1 or 2\n");
2485 exit(1);
2486 }
2487 do_pass = pass;
2488}
a38469e1 2489
f3ec2d46 2490#if defined(CONFIG_WIN32) || defined(CONFIG_OS2)
0c1a9eda 2491static int64_t getutime(void)
5727b222 2492{
f3ec2d46 2493 return av_gettime();
5727b222 2494}
bdc4796f 2495#else
0c1a9eda 2496static int64_t getutime(void)
bdc4796f 2497{
f3ec2d46
SG
2498 struct rusage rusage;
2499
2500 getrusage(RUSAGE_SELF, &rusage);
2501 return (rusage.ru_utime.tv_sec * 1000000LL) + rusage.ru_utime.tv_usec;
bdc4796f
FB
2502}
2503#endif
5727b222 2504
79fdaa4c
FB
2505extern int ffm_nopts;
2506
b29f97d1 2507static void opt_bitexact(void)
79fdaa4c 2508{
b0368839 2509 bitexact=1;
79fdaa4c
FB
2510 /* disable generate of real time pts in ffm (need to be supressed anyway) */
2511 ffm_nopts = 1;
2512}
2513
b29f97d1 2514static void show_formats(void)
85f07f22 2515{
79fdaa4c
FB
2516 AVInputFormat *ifmt;
2517 AVOutputFormat *ofmt;
817b23ff 2518 AVImageFormat *image_fmt;
85f07f22
FB
2519 URLProtocol *up;
2520 AVCodec *p;
2521 const char **pp;
2522
817b23ff 2523 printf("Output audio/video file formats:");
79fdaa4c
FB
2524 for(ofmt = first_oformat; ofmt != NULL; ofmt = ofmt->next) {
2525 printf(" %s", ofmt->name);
85f07f22
FB
2526 }
2527 printf("\n");
817b23ff
FB
2528
2529 printf("Input audio/video file formats:");
79fdaa4c
FB
2530 for(ifmt = first_iformat; ifmt != NULL; ifmt = ifmt->next) {
2531 printf(" %s", ifmt->name);
85f07f22
FB
2532 }
2533 printf("\n");
2534
817b23ff
FB
2535 printf("Output image formats:");
2536 for(image_fmt = first_image_format; image_fmt != NULL;
2537 image_fmt = image_fmt->next) {
2538 if (image_fmt->img_write)
2539 printf(" %s", image_fmt->name);
2540 }
2541 printf("\n");
2542
2543 printf("Input image formats:");
2544 for(image_fmt = first_image_format; image_fmt != NULL;
2545 image_fmt = image_fmt->next) {
2546 if (image_fmt->img_read)
2547 printf(" %s", image_fmt->name);
2548 }
2549 printf("\n");
2550
85f07f22
FB
2551 printf("Codecs:\n");
2552 printf(" Encoders:");
2553 for(p = first_avcodec; p != NULL; p = p->next) {
2554 if (p->encode)
2555 printf(" %s", p->name);
2556 }
2557 printf("\n");
2558
2559 printf(" Decoders:");
2560 for(p = first_avcodec; p != NULL; p = p->next) {
2561 if (p->decode)
2562 printf(" %s", p->name);
2563 }
2564 printf("\n");
2565
2566 printf("Supported file protocols:");
2567 for(up = first_protocol; up != NULL; up = up->next)
2568 printf(" %s:", up->name);
2569 printf("\n");
2570
2571 printf("Frame size abbreviations: sqcif qcif cif 4cif\n");
2572 printf("Motion estimation methods:");
2573 pp = motion_str;
2574 while (*pp) {
2575 printf(" %s", *pp);
101bea5f 2576 if ((pp - motion_str + 1) == ME_ZERO)
85f07f22 2577 printf("(fastest)");
101bea5f 2578 else if ((pp - motion_str + 1) == ME_FULL)
85f07f22 2579 printf("(slowest)");
101bea5f 2580 else if ((pp - motion_str + 1) == ME_EPZS)
85f07f22
FB
2581 printf("(default)");
2582 pp++;
2583 }
2584 printf("\n");
2585 exit(1);
2586}
2587
2588void show_help(void)
2589{
a38469e1 2590 const char *prog;
85f07f22
FB
2591 const OptionDef *po;
2592 int i, expert;
a38469e1
FB
2593
2594 prog = do_play ? "ffplay" : "ffmpeg";
85f07f22 2595
bf5af568 2596 printf("%s version " FFMPEG_VERSION ", Copyright (c) 2000, 2001, 2002 Fabrice Bellard\n",
a38469e1
FB
2597 prog);
2598
2599 if (!do_play) {
2600 printf("usage: ffmpeg [[options] -i input_file]... {[options] outfile}...\n"
2601 "Hyper fast MPEG1/MPEG4/H263/RV and AC3/MPEG audio encoder\n");
2602 } else {
2603 printf("usage: ffplay [options] input_file...\n"
2604 "Simple audio player\n");
2605 }
2606
2607 printf("\n"
85f07f22
FB
2608 "Main options are:\n");
2609 for(i=0;i<2;i++) {
2610 if (i == 1)
2611 printf("\nAdvanced options are:\n");
2612 for(po = options; po->name != NULL; po++) {
2613 char buf[64];
2614 expert = (po->flags & OPT_EXPERT) != 0;
2615 if (expert == i) {
2616 strcpy(buf, po->name);
2617 if (po->flags & HAS_ARG) {
2618 strcat(buf, " ");
2619 strcat(buf, po->argname);
2620 }
2621 printf("-%-17s %s\n", buf, po->help);
2622 }
2623 }
2624 }
2625
2626 exit(1);
2627}
2628
2629const OptionDef options[] = {
bdc4796f
FB
2630 { "L", 0, {(void*)show_licence}, "show license" },
2631 { "h", 0, {(void*)show_help}, "show help" },
2632 { "formats", 0, {(void*)show_formats}, "show available formats, codecs, protocols, ..." },
2633 { "f", HAS_ARG, {(void*)opt_format}, "force format", "fmt" },
817b23ff 2634 { "img", HAS_ARG, {(void*)opt_image_format}, "force image format", "img_fmt" },
bdc4796f
FB
2635 { "i", HAS_ARG, {(void*)opt_input_file}, "input file name", "filename" },
2636 { "y", OPT_BOOL, {(void*)&file_overwrite}, "overwrite output files" },
2637 { "map", HAS_ARG | OPT_EXPERT, {(void*)opt_map}, "set input stream mapping", "file:stream" },
2638 { "t", HAS_ARG, {(void*)opt_recording_time}, "set the recording time", "duration" },
2639 { "title", HAS_ARG | OPT_STRING, {(void*)&str_title}, "set the title", "string" },
2640 { "author", HAS_ARG | OPT_STRING, {(void*)&str_author}, "set the author", "string" },
2641 { "copyright", HAS_ARG | OPT_STRING, {(void*)&str_copyright}, "set the copyright", "string" },
2642 { "comment", HAS_ARG | OPT_STRING, {(void*)&str_comment}, "set the comment", "string" },
5abdb4b1
FB
2643 { "pass", HAS_ARG, {(void*)&opt_pass}, "select the pass number (1 or 2)", "n" },
2644 { "passlogfile", HAS_ARG | OPT_STRING, {(void*)&pass_logfilename}, "select two pass log file name", "file" },
85f07f22 2645 /* video options */
bdc4796f
FB
2646 { "b", HAS_ARG, {(void*)opt_video_bitrate}, "set video bitrate (in kbit/s)", "bitrate" },
2647 { "r", HAS_ARG, {(void*)opt_frame_rate}, "set frame rate (in Hz)", "rate" },
bdfcbbed 2648 { "re", OPT_BOOL|OPT_EXPERT, {(void*)&rate_emu}, "read input at native frame rate" },
bdc4796f 2649 { "s", HAS_ARG, {(void*)opt_frame_size}, "set frame size (WxH or abbreviation)", "size" },
ab6d194a
MN
2650 { "croptop", HAS_ARG, {(void*)opt_frame_crop_top}, "set top crop band size (in pixels)", "size" },
2651 { "cropbottom", HAS_ARG, {(void*)opt_frame_crop_bottom}, "set bottom crop band size (in pixels)", "size" },
2652 { "cropleft", HAS_ARG, {(void*)opt_frame_crop_left}, "set left crop band size (in pixels)", "size" },
2653 { "cropright", HAS_ARG, {(void*)opt_frame_crop_right}, "set right crop band size (in pixels)", "size" },
bdc4796f
FB
2654 { "g", HAS_ARG | OPT_EXPERT, {(void*)opt_gop_size}, "set the group of picture size", "gop_size" },
2655 { "intra", OPT_BOOL | OPT_EXPERT, {(void*)&intra_only}, "use only intra frames"},
2656 { "vn", OPT_BOOL, {(void*)&video_disable}, "disable video" },
2657 { "qscale", HAS_ARG | OPT_EXPERT, {(void*)opt_qscale}, "use fixed video quantiser scale (VBR)", "q" },
9cdd6a24
MN
2658 { "qmin", HAS_ARG | OPT_EXPERT, {(void*)opt_qmin}, "min video quantiser scale (VBR)", "q" },
2659 { "qmax", HAS_ARG | OPT_EXPERT, {(void*)opt_qmax}, "max video quantiser scale (VBR)", "q" },
17a70fde
MN
2660 { "mbqmin", HAS_ARG | OPT_EXPERT, {(void*)opt_mb_qmin}, "min macroblock quantiser scale (VBR)", "q" },
2661 { "mbqmax", HAS_ARG | OPT_EXPERT, {(void*)opt_mb_qmax}, "max macroblock quantiser scale (VBR)", "q" },
9cdd6a24
MN
2662 { "qdiff", HAS_ARG | OPT_EXPERT, {(void*)opt_qdiff}, "max difference between the quantiser scale (VBR)", "q" },
2663 { "qblur", HAS_ARG | OPT_EXPERT, {(void*)opt_qblur}, "video quantiser scale blur (VBR)", "blur" },
2664 { "qcomp", HAS_ARG | OPT_EXPERT, {(void*)opt_qcomp}, "video quantiser scale compression (VBR)", "compression" },
ac2830ec 2665 { "rc_init_cplx", HAS_ARG | OPT_EXPERT, {(void*)opt_rc_initial_cplx}, "initial complexity for 1-pass encoding", "complexity" },
29700fa6
MN
2666 { "b_qfactor", HAS_ARG | OPT_EXPERT, {(void*)opt_b_qfactor}, "qp factor between p and b frames", "factor" },
2667 { "i_qfactor", HAS_ARG | OPT_EXPERT, {(void*)opt_i_qfactor}, "qp factor between p and i frames", "factor" },
2668 { "b_qoffset", HAS_ARG | OPT_EXPERT, {(void*)opt_b_qoffset}, "qp offset between p and b frames", "offset" },
2669 { "i_qoffset", HAS_ARG | OPT_EXPERT, {(void*)opt_i_qoffset}, "qp offset between p and i frames", "offset" },
59b571c1 2670// { "b_strategy", HAS_ARG | OPT_EXPERT, {(void*)opt_b_strategy}, "dynamic b frame selection strategy", "strategy" },
3aa102be 2671 { "rc_eq", HAS_ARG | OPT_EXPERT, {(void*)opt_video_rc_eq}, "", "equation" },
ac2830ec 2672 { "rc_override", HAS_ARG | OPT_EXPERT, {(void*)opt_video_rc_override_string}, "Rate control override", "qualities for specific intervals" },
9cdd6a24 2673 { "bt", HAS_ARG, {(void*)opt_video_bitrate_tolerance}, "set video bitrate tolerance (in kbit/s)", "tolerance" },
3aa102be
MN
2674 { "maxrate", HAS_ARG, {(void*)opt_video_bitrate_max}, "set max video bitrate tolerance (in kbit/s)", "bitrate" },
2675 { "minrate", HAS_ARG, {(void*)opt_video_bitrate_min}, "set min video bitrate tolerance (in kbit/s)", "bitrate" },
946c8a12 2676 { "bufsize", HAS_ARG, {(void*)opt_video_buffer_size}, "set ratecontrol buffere size (in kbit)", "size" },
bf5af568 2677 { "vd", HAS_ARG | OPT_EXPERT, {(void*)opt_video_device}, "set video grab device", "device" },
a5df11ab 2678 { "vc", HAS_ARG | OPT_EXPERT, {(void*)opt_video_channel}, "set video grab channel (DV1394 only)", "channel" },
79a7c268 2679 { "dv1394", OPT_EXPERT, {(void*)opt_dv1394}, "set DV1394 grab", "" },
1629626f 2680 { "vcodec", HAS_ARG | OPT_EXPERT, {(void*)opt_video_codec}, "force video codec ('copy' to copy stream)", "codec" },
bdc4796f 2681 { "me", HAS_ARG | OPT_EXPERT, {(void*)opt_motion_estimation}, "set motion estimation method",
85f07f22 2682 "method" },
463678ac 2683 { "dct_algo", HAS_ARG | OPT_EXPERT, {(void*)opt_dct_algo}, "set dct algo", "algo" },
2ad1516a 2684 { "idct_algo", HAS_ARG | OPT_EXPERT, {(void*)opt_idct_algo}, "set idct algo", "algo" },
8409b8fe 2685 { "er", HAS_ARG | OPT_EXPERT, {(void*)opt_error_resilience}, "set error resilience", "" },
59b571c1 2686 { "ec", HAS_ARG | OPT_EXPERT, {(void*)opt_error_concealment}, "set error concealment", "" },
bc6caae2 2687 { "bf", HAS_ARG | OPT_EXPERT, {(void*)opt_b_frames}, "use 'frames' B frames (only MPEG-4)", "frames" },
e4986da9 2688 { "hq", OPT_BOOL | OPT_EXPERT, {(void*)&use_hq}, "activate high quality settings" },
29da453b 2689 { "4mv", OPT_BOOL | OPT_EXPERT, {(void*)&use_4mv}, "use four motion vector by macroblock (only MPEG-4)" },
1dbb6d90 2690 { "part", OPT_BOOL | OPT_EXPERT, {(void*)&use_part}, "use data partitioning (only MPEG-4)" },
fe670d09 2691 { "bug", HAS_ARG | OPT_EXPERT, {(void*)opt_workaround_bugs}, "workaround not auto detected encoder bugs", "param" },
1dbb6d90 2692 { "ps", HAS_ARG | OPT_EXPERT, {(void*)opt_packet_size}, "packet size", "size in bits" },
f560dd82 2693 { "strict", HAS_ARG | OPT_EXPERT, {(void*)opt_strict}, "strictness", "how strictly to follow the standarts" },
bdc4796f 2694 { "sameq", OPT_BOOL, {(void*)&same_quality},
85f07f22 2695 "use same video quality as source (implies VBR)" },
1d366fce 2696 { "debug", HAS_ARG | OPT_EXPERT, {(void*)opt_debug}, "print specific debug info", "" },
85f07f22 2697 /* audio options */
bdc4796f
FB
2698 { "ab", HAS_ARG, {(void*)opt_audio_bitrate}, "set audio bitrate (in kbit/s)", "bitrate", },
2699 { "ar", HAS_ARG, {(void*)opt_audio_rate}, "set audio sampling rate (in Hz)", "rate" },
2700 { "ac", HAS_ARG, {(void*)opt_audio_channels}, "set number of audio channels", "channels" },
2701 { "an", OPT_BOOL, {(void*)&audio_disable}, "disable audio" },
bdc4796f 2702 { "ad", HAS_ARG | OPT_EXPERT, {(void*)opt_audio_device}, "set audio device", "device" },
1629626f 2703 { "acodec", HAS_ARG | OPT_EXPERT, {(void*)opt_audio_codec}, "force audio codec ('copy' to copy stream)", "codec" },
bdc4796f 2704 { "deinterlace", OPT_BOOL | OPT_EXPERT, {(void*)&do_deinterlace},
cfcf0ffd 2705 "deinterlace pictures" },
bdc4796f 2706 { "benchmark", OPT_BOOL | OPT_EXPERT, {(void*)&do_benchmark},
5727b222 2707 "add timings for benchmarking" },
a0663ba4
FB
2708 { "hex", OPT_BOOL | OPT_EXPERT, {(void*)&do_hex_dump},
2709 "dump each input packet" },
ce7c56c2
J
2710 { "psnr", OPT_BOOL | OPT_EXPERT, {(void*)&do_psnr}, "calculate PSNR of compressed frames" },
2711 { "vstats", OPT_BOOL | OPT_EXPERT, {(void*)&do_vstats}, "dump video coding statistics to file" },
79fdaa4c 2712 { "bitexact", OPT_EXPERT, {(void*)opt_bitexact}, "only use bit exact algorithms (for codec testing)" },
10d104e4 2713 { "vhook", HAS_ARG | OPT_EXPERT, {(void*)add_frame_hooker}, "insert video processing module", "module name and parameters" },
21e59552
MN
2714 /* Fx */
2715 { "aic", OPT_BOOL | OPT_EXPERT, {(void*)&use_aic}, "enable Advanced intra coding (h263+)" },
2716 { "umv", OPT_BOOL | OPT_EXPERT, {(void*)&use_umv}, "enable Unlimited Motion Vector (h263+)" },
2717 /* /Fx */
85f07f22
FB
2718 { NULL, },
2719};
2720
2721int main(int argc, char **argv)
2722{
2723 int optindex, i;
2724 const char *opt, *arg;
2725 const OptionDef *po;
0c1a9eda 2726 int64_t ti;
63b15e55 2727
2c4ae653 2728 av_register_all();
85f07f22 2729
a38469e1
FB
2730 /* detect if invoked as player */
2731 i = strlen(argv[0]);
2732 if (i >= 6 && !strcmp(argv[0] + i - 6, "ffplay"))
2733 do_play = 1;
2734
85f07f22
FB
2735 if (argc <= 1)
2736 show_help();
a38469e1
FB
2737
2738 /* parse options */
85f07f22
FB
2739 optindex = 1;
2740 while (optindex < argc) {
2741 opt = argv[optindex++];
2742
2743 if (opt[0] == '-' && opt[1] != '\0') {
2744 po = options;
2745 while (po->name != NULL) {
2746 if (!strcmp(opt + 1, po->name))
2747 break;
2748 po++;
2749 }
2750 if (!po->name) {
2751 fprintf(stderr, "%s: unrecognized option '%s'\n", argv[0], opt);
2752 exit(1);
2753 }
2754 arg = NULL;
10d104e4 2755 if (po->flags & HAS_ARG) {
85f07f22 2756 arg = argv[optindex++];
10d104e4
PG
2757 if (!arg) {
2758 fprintf(stderr, "%s: missing argument for option '%s'\n", argv[0], opt);
2759 exit(1);
2760 }
2761 }
85f07f22
FB
2762 if (po->flags & OPT_STRING) {
2763 char *str;
e9a9e0c2 2764 str = av_strdup(arg);
85f07f22
FB
2765 *po->u.str_arg = str;
2766 } else if (po->flags & OPT_BOOL) {
2767 *po->u.int_arg = 1;
2768 } else {
b29f97d1 2769 po->u.func_arg(arg);
85f07f22
FB
2770 }
2771 } else {
a38469e1
FB
2772 if (!do_play) {
2773 opt_output_file(opt);
2774 } else {
2775 opt_input_file(opt);
2776 }
85f07f22
FB
2777 }
2778 }
2779
2780
a38469e1
FB
2781 if (!do_play) {
2782 /* file converter / grab */
85f07f22
FB
2783 if (nb_output_files <= 0) {
2784 fprintf(stderr, "Must supply at least one output file\n");
2785 exit(1);
2786 }
a38469e1
FB
2787
2788 if (nb_input_files == 0) {
2789 prepare_grab();
5727b222 2790 }
a38469e1
FB
2791 } else {
2792 /* player */
2793 if (nb_input_files <= 0) {
2794 fprintf(stderr, "Must supply at least one input file\n");
2795 exit(1);
2796 }
2797 prepare_play();
2798 }
2799
2800 ti = getutime();
2801 av_encode(output_files, nb_output_files, input_files, nb_input_files,
2802 stream_maps, nb_stream_maps);
2803 ti = getutime() - ti;
2804 if (do_benchmark) {
2805 printf("bench: utime=%0.3fs\n", ti / 1000000.0);
85f07f22
FB
2806 }
2807
2808 /* close files */
2809 for(i=0;i<nb_output_files;i++) {
4fca59f2
ZK
2810 /* maybe av_close_output_file ??? */
2811 AVFormatContext *s = output_files[i];
2812 int j;
2813 if (!(s->oformat->flags & AVFMT_NOFILE))
2814 url_fclose(&s->pb);
2815 for(j=0;j<s->nb_streams;j++)
2816 av_free(s->streams[j]);
2817 av_free(s);
85f07f22 2818 }
79fdaa4c
FB
2819 for(i=0;i<nb_input_files;i++)
2820 av_close_input_file(input_files[i]);
85f07f22 2821
855ea723 2822 av_free_static();
db40a39a
MN
2823
2824
35e5fb06
RD
2825#ifdef POWERPC_TBL_PERFORMANCE_REPORT
2826 extern void powerpc_display_perf_report(void);
2827 powerpc_display_perf_report();
2828#endif /* POWERPC_TBL_PERFORMANCE_REPORT */
db40a39a 2829
85f07f22
FB
2830 return 0;
2831}