Statistics
| Branch: | Revision:

ffmpeg / ffmpeg.c @ 5d43635e

History | View | Annotate | Download (102 KB)

1
/*
2
 * FFmpeg main 
3
 * Copyright (c) 2000-2003 Fabrice Bellard
4
 *
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.
9
 *
10
 * This library is distributed in the hope that it will be useful,
11
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13
 * Lesser General Public License for more details.
14
 *
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
18
 */
19
#define HAVE_AV_CONFIG_H
20
#include "avformat.h"
21
#include "framehook.h"
22

    
23
#ifndef CONFIG_WIN32
24
#include <unistd.h>
25
#include <fcntl.h>
26
#include <sys/ioctl.h>
27
#include <sys/time.h>
28
#include <termios.h>
29
#include <sys/resource.h>
30
#include <signal.h>
31
#endif
32
#ifdef CONFIG_OS2
33
#include <sys/types.h>
34
#include <sys/select.h>
35
#include <stdlib.h>
36
#endif
37
#include <time.h>
38

    
39
#include "cmdutils.h"
40

    
41
#if !defined(INFINITY) && defined(HUGE_VAL)
42
#define INFINITY HUGE_VAL
43
#endif
44

    
45
/* select an input stream for an output stream */
46
typedef struct AVStreamMap {
47
    int file_index;
48
    int stream_index;
49
} AVStreamMap;
50

    
51
extern const OptionDef options[];
52

    
53
static void show_help(void);
54
static void show_license(void);
55

    
56
#define MAX_FILES 20
57

    
58
static AVFormatContext *input_files[MAX_FILES];
59
static int nb_input_files = 0;
60

    
61
static AVFormatContext *output_files[MAX_FILES];
62
static int nb_output_files = 0;
63

    
64
static AVStreamMap stream_maps[MAX_FILES];
65
static int nb_stream_maps;
66

    
67
static AVInputFormat *file_iformat;
68
static AVOutputFormat *file_oformat;
69
static AVImageFormat *image_format;
70
static int frame_width  = 160;
71
static int frame_height = 128;
72
static float frame_aspect_ratio = 0;
73
static enum PixelFormat frame_pix_fmt = PIX_FMT_YUV420P;
74
static int frame_topBand  = 0;
75
static int frame_bottomBand = 0;
76
static int frame_leftBand  = 0;
77
static int frame_rightBand = 0;
78
static int frame_rate = 25;
79
static int frame_rate_base = 1;
80
static int video_bit_rate = 200*1000;
81
static int video_bit_rate_tolerance = 4000*1000;
82
static float video_qscale = 0;
83
static int video_qmin = 2;
84
static int video_qmax = 31;
85
static int video_mb_qmin = 2;
86
static int video_mb_qmax = 31;
87
static int video_qdiff = 3;
88
static float video_qblur = 0.5;
89
static float video_qcomp = 0.5;
90
static uint16_t *intra_matrix = NULL;
91
static uint16_t *inter_matrix = NULL;
92
#if 0 //experimental, (can be removed)
93
static float video_rc_qsquish=1.0;
94
static float video_rc_qmod_amp=0;
95
static int video_rc_qmod_freq=0;
96
#endif
97
static char *video_rc_override_string=NULL;
98
static char *video_rc_eq="tex^qComp";
99
static int video_rc_buffer_size=0;
100
static float video_rc_buffer_aggressivity=1.0;
101
static int video_rc_max_rate=0;
102
static int video_rc_min_rate=0;
103
static float video_rc_initial_cplx=0;
104
static float video_b_qfactor = 1.25;
105
static float video_b_qoffset = 1.25;
106
static float video_i_qfactor = -0.8;
107
static float video_i_qoffset = 0.0;
108
static int me_method = ME_EPZS;
109
static int video_disable = 0;
110
static int video_codec_id = CODEC_ID_NONE;
111
static int same_quality = 0;
112
static int b_frames = 0;
113
static int mb_decision = FF_MB_DECISION_SIMPLE;
114
static int mb_cmp = FF_CMP_SAD;
115
static int sub_cmp = FF_CMP_SAD;
116
static int cmp = FF_CMP_SAD;
117
static int use_4mv = 0;
118
static int use_obmc = 0;
119
static int use_aic = 0;
120
static int use_aiv = 0;
121
static int use_umv = 0;
122
static int do_deinterlace = 0;
123
static int do_interlace = 0;
124
static int workaround_bugs = FF_BUG_AUTODETECT;
125
static int error_resilience = 2;
126
static int error_concealment = 3;
127
static int dct_algo = 0;
128
static int idct_algo = 0;
129
static int use_part = 0;
130
static int packet_size = 0;
131
static int error_rate = 0;
132
static int strict = 0;
133
static int debug = 0;
134
extern int loop_input; /* currently a hack */
135

    
136
static int gop_size = 12;
137
static int intra_only = 0;
138
static int audio_sample_rate = 44100;
139
static int audio_bit_rate = 64000;
140
static int audio_disable = 0;
141
static int audio_channels = 1;
142
static int audio_codec_id = CODEC_ID_NONE;
143

    
144
static int64_t recording_time = 0;
145
static int64_t start_time = 0;
146
static int file_overwrite = 0;
147
static char *str_title = NULL;
148
static char *str_author = NULL;
149
static char *str_copyright = NULL;
150
static char *str_comment = NULL;
151
static int do_benchmark = 0;
152
static int do_hex_dump = 0;
153
static int do_pkt_dump = 0;
154
static int do_psnr = 0;
155
static int do_vstats = 0;
156
static int do_pass = 0;
157
static int bitexact = 0;
158
static char *pass_logfilename = NULL;
159
static int audio_stream_copy = 0;
160
static int video_stream_copy = 0;
161

    
162
static int rate_emu = 0;
163

    
164
static char *video_grab_format = "video4linux";
165
static char *video_device = NULL;
166
static int  video_channel = 0;
167
static char *video_standard = "ntsc";
168

    
169
static char *audio_grab_format = "audio_device";
170
static char *audio_device = NULL;
171

    
172
static int using_stdin = 0;
173
static int using_vhook = 0;
174
static int verbose = 1;
175

    
176
#define DEFAULT_PASS_LOGFILENAME "ffmpeg2pass"
177

    
178
typedef struct AVOutputStream {
179
    int file_index;          /* file index */
180
    int index;               /* stream index in the output file */
181
    int source_index;        /* AVInputStream index */
182
    AVStream *st;            /* stream in the output file */
183
    int encoding_needed;     /* true if encoding needed for this stream */
184
    int frame_number;
185
    /* input pts and corresponding output pts
186
       for A/V sync */
187
    double sync_ipts;
188
    double sync_ipts_offset;
189
    int64_t sync_opts;
190
    /* video only */
191
    int video_resample;      /* video_resample and video_crop are mutually exclusive */
192
    AVPicture pict_tmp;      /* temporary image for resampling */
193
    ImgReSampleContext *img_resample_ctx; /* for image resampling */
194

    
195
    int video_crop;          /* video_resample and video_crop are mutually exclusive */
196
    int topBand;             /* cropping area sizes */
197
    int leftBand;
198
    
199
    /* audio only */
200
    int audio_resample;
201
    ReSampleContext *resample; /* for audio resampling */
202
    FifoBuffer fifo;     /* for compression: one audio fifo per codec */
203
    FILE *logfile;
204
} AVOutputStream;
205

    
206
typedef struct AVInputStream {
207
    int file_index;
208
    int index;
209
    AVStream *st;
210
    int discard;             /* true if stream data should be discarded */
211
    int decoding_needed;     /* true if the packets must be decoded in 'raw_fifo' */
212
    int64_t sample_index;      /* current sample */
213

    
214
    int64_t       start;     /* time when read started */
215
    unsigned long frame;     /* current frame */
216
    int64_t       next_pts;  /* synthetic pts for cases where pkt.pts
217
                                is not defined */
218
    int64_t       pts;       /* current pts */
219
} AVInputStream;
220

    
221
typedef struct AVInputFile {
222
    int eof_reached;      /* true if eof reached */
223
    int ist_index;        /* index of first stream in ist_table */
224
    int buffer_size;      /* current total buffer size */
225
    int buffer_size_max;  /* buffer size at which we consider we can stop
226
                             buffering */
227
    int nb_streams;       /* nb streams we are aware of */
228
} AVInputFile;
229

    
230
#ifndef CONFIG_WIN32
231

    
232
/* init terminal so that we can grab keys */
233
static struct termios oldtty;
234

    
235
static void term_exit(void)
236
{
237
    tcsetattr (0, TCSANOW, &oldtty);
238
}
239

    
240
static volatile sig_atomic_t received_sigterm = 0;
241

    
242
static void
243
sigterm_handler(int sig)
244
{
245
    received_sigterm = sig;
246
    term_exit();
247
}
248

    
249
static void term_init(void)
250
{
251
    struct termios tty;
252

    
253
    tcgetattr (0, &tty);
254
    oldtty = tty;
255

    
256
    tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
257
                          |INLCR|IGNCR|ICRNL|IXON);
258
    tty.c_oflag |= OPOST;
259
    tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
260
    tty.c_cflag &= ~(CSIZE|PARENB);
261
    tty.c_cflag |= CS8;
262
    tty.c_cc[VMIN] = 1;
263
    tty.c_cc[VTIME] = 0;
264
    
265
    tcsetattr (0, TCSANOW, &tty);
266

    
267
    signal(SIGINT , sigterm_handler); /* Interrupt (ANSI).  */
268
    signal(SIGQUIT, sigterm_handler); /* Quit (POSIX).  */
269
    signal(SIGTERM, sigterm_handler); /* Termination (ANSI).  */
270
    /*
271
    register a function to be called at normal program termination
272
    */
273
    atexit(term_exit);
274
#ifdef CONFIG_BEOS_NETSERVER
275
    fcntl(0, F_SETFL, fcntl(0, F_GETFL) | O_NONBLOCK);
276
#endif
277
}
278

    
279
/* read a key without blocking */
280
static int read_key(void)
281
{
282
    int n = 1;
283
    unsigned char ch;
284
#ifndef CONFIG_BEOS_NETSERVER
285
    struct timeval tv;
286
    fd_set rfds;
287

    
288
    FD_ZERO(&rfds);
289
    FD_SET(0, &rfds);
290
    tv.tv_sec = 0;
291
    tv.tv_usec = 0;
292
    n = select(1, &rfds, NULL, NULL, &tv);
293
#endif
294
    if (n > 0) {
295
        n = read(0, &ch, 1);
296
        if (n == 1)
297
            return ch;
298

    
299
        return n;
300
    }
301
    return -1;
302
}
303

    
304
#else
305

    
306
static volatile int received_sigterm = 0;
307

    
308
/* no interactive support */
309
static void term_exit(void)
310
{
311
}
312

    
313
static void term_init(void)
314
{
315
}
316

    
317
static int read_key(void)
318
{
319
    return 0;
320
}
321

    
322
#endif
323

    
324
static int read_ffserver_streams(AVFormatContext *s, const char *filename)
325
{
326
    int i, err;
327
    AVFormatContext *ic;
328

    
329
    err = av_open_input_file(&ic, filename, NULL, FFM_PACKET_SIZE, NULL);
330
    if (err < 0)
331
        return err;
332
    /* copy stream format */
333
    s->nb_streams = ic->nb_streams;
334
    for(i=0;i<ic->nb_streams;i++) {
335
        AVStream *st;
336

    
337
        st = av_mallocz(sizeof(AVStream));
338
        memcpy(st, ic->streams[i], sizeof(AVStream));
339
        s->streams[i] = st;
340
    }
341

    
342
    av_close_input_file(ic);
343
    return 0;
344
}
345

    
346
#define MAX_AUDIO_PACKET_SIZE (128 * 1024)
347

    
348
static void do_audio_out(AVFormatContext *s, 
349
                         AVOutputStream *ost, 
350
                         AVInputStream *ist,
351
                         unsigned char *buf, int size)
352
{
353
    uint8_t *buftmp;
354
    static uint8_t *audio_buf = NULL;
355
    static uint8_t *audio_out = NULL;
356
    const int audio_out_size= 4*MAX_AUDIO_PACKET_SIZE;
357

    
358
    int size_out, frame_bytes, ret;
359
    AVCodecContext *enc;
360

    
361
    /* SC: dynamic allocation of buffers */
362
    if (!audio_buf)
363
        audio_buf = av_malloc(2*MAX_AUDIO_PACKET_SIZE);
364
    if (!audio_out)
365
        audio_out = av_malloc(audio_out_size);
366
    if (!audio_buf || !audio_out)
367
        return;               /* Should signal an error ! */
368

    
369
    
370
    enc = &ost->st->codec;
371

    
372
    if (ost->audio_resample) {
373
        buftmp = audio_buf;
374
        size_out = audio_resample(ost->resample, 
375
                                  (short *)buftmp, (short *)buf,
376
                                  size / (ist->st->codec.channels * 2));
377
        size_out = size_out * enc->channels * 2;
378
    } else {
379
        buftmp = buf;
380
        size_out = size;
381
    }
382

    
383
    /* now encode as many frames as possible */
384
    if (enc->frame_size > 1) {
385
        /* output resampled raw samples */
386
        fifo_write(&ost->fifo, buftmp, size_out, 
387
                   &ost->fifo.wptr);
388

    
389
        frame_bytes = enc->frame_size * 2 * enc->channels;
390
        
391
        while (fifo_read(&ost->fifo, audio_buf, frame_bytes, 
392
                     &ost->fifo.rptr) == 0) {
393
            ret = avcodec_encode_audio(enc, audio_out, audio_out_size, 
394
                                       (short *)audio_buf);
395
            av_write_frame(s, ost->index, audio_out, ret);
396
        }
397
    } else {
398
        /* output a pcm frame */
399
        /* XXX: change encoding codec API to avoid this ? */
400
        switch(enc->codec->id) {
401
        case CODEC_ID_PCM_S16LE:
402
        case CODEC_ID_PCM_S16BE:
403
        case CODEC_ID_PCM_U16LE:
404
        case CODEC_ID_PCM_U16BE:
405
            break;
406
        default:
407
            size_out = size_out >> 1;
408
            break;
409
        }
410
        ret = avcodec_encode_audio(enc, audio_out, size_out, 
411
                                   (short *)buftmp);
412
        av_write_frame(s, ost->index, audio_out, ret);
413
    }
414
}
415

    
416
static void pre_process_video_frame(AVInputStream *ist, AVPicture *picture, void **bufp)
417
{
418
    AVCodecContext *dec;
419
    AVPicture *picture2;
420
    AVPicture picture_tmp;
421
    uint8_t *buf = 0;
422

    
423
    dec = &ist->st->codec;
424

    
425
    /* deinterlace : must be done before any resize */
426
    if (do_deinterlace || using_vhook) {
427
        int size;
428

    
429
        /* create temporary picture */
430
        size = avpicture_get_size(dec->pix_fmt, dec->width, dec->height);
431
        buf = av_malloc(size);
432
        if (!buf)
433
            return;
434
        
435
        picture2 = &picture_tmp;
436
        avpicture_fill(picture2, buf, dec->pix_fmt, dec->width, dec->height);
437

    
438
        if (do_deinterlace){
439
            if(avpicture_deinterlace(picture2, picture, 
440
                                     dec->pix_fmt, dec->width, dec->height) < 0) {
441
                /* if error, do not deinterlace */
442
                av_free(buf);
443
                buf = NULL;
444
                picture2 = picture;
445
            }
446
        } else {
447
            if (img_convert(picture2, dec->pix_fmt, picture, 
448
                            dec->pix_fmt, dec->width, dec->height) < 0) {
449
                /* if error, do not copy */
450
                av_free(buf);
451
                buf = NULL;
452
                picture2 = picture;
453
            }
454
        }
455
    } else {
456
        picture2 = picture;
457
    }
458

    
459
    frame_hook_process(picture2, dec->pix_fmt, dec->width, dec->height);
460

    
461
    if (picture != picture2)
462
        *picture = *picture2;
463
    *bufp = buf;
464
}
465

    
466
/* we begin to correct av delay at this threshold */
467
#define AV_DELAY_MAX 0.100
468

    
469
static void do_video_out(AVFormatContext *s, 
470
                         AVOutputStream *ost, 
471
                         AVInputStream *ist,
472
                         AVFrame *in_picture,
473
                         int *frame_size, AVOutputStream *audio_sync)
474
{
475
    int nb_frames, i, ret;
476
    AVPicture *final_picture, *formatted_picture;
477
    AVPicture picture_format_temp, picture_crop_temp;
478
    static uint8_t *video_buffer;
479
    uint8_t *buf = NULL, *buf1 = NULL;
480
    AVCodecContext *enc, *dec;
481
    enum PixelFormat target_pixfmt;
482

    
483
#define VIDEO_BUFFER_SIZE (1024*1024)
484

    
485
    enc = &ost->st->codec;
486
    dec = &ist->st->codec;
487

    
488
    /* by default, we output a single frame */
489
    nb_frames = 1;
490

    
491
    *frame_size = 0;
492

    
493
    /* NOTE: the A/V sync is always done by considering the audio is
494
       the master clock. It is suffisant for transcoding or playing,
495
       but not for the general case */
496
    if (audio_sync) {
497
        /* compute the A-V delay and duplicate/remove frames if needed */
498
        double adelta, vdelta, av_delay;
499

    
500
        adelta = audio_sync->sync_ipts - ((double)audio_sync->sync_opts * 
501
            s->pts_num / s->pts_den);
502

    
503
        vdelta = ost->sync_ipts - ((double)ost->sync_opts *
504
            s->pts_num / s->pts_den);
505

    
506
        av_delay = adelta - vdelta;
507
        //            printf("delay=%f\n", av_delay);
508
        if (av_delay < -AV_DELAY_MAX)
509
            nb_frames = 2;
510
        else if (av_delay > AV_DELAY_MAX)
511
            nb_frames = 0;
512
    } else {
513
        double vdelta;
514

    
515
        vdelta = (double)(ost->st->pts.val) * s->pts_num / s->pts_den - (ost->sync_ipts - ost->sync_ipts_offset);
516
        if (vdelta < 100 && vdelta > -100 && ost->sync_ipts_offset) {
517
            if (vdelta < -AV_DELAY_MAX)
518
                nb_frames = 2;
519
            else if (vdelta > AV_DELAY_MAX)
520
                nb_frames = 0;
521
        } else {
522
            ost->sync_ipts_offset -= vdelta;
523
            if (!ost->sync_ipts_offset)
524
                ost->sync_ipts_offset = 0.000001; /* one microsecond */
525
        }
526
    }
527
    
528
#if defined(AVSYNC_DEBUG)
529
    {
530
        static char *action[] = { "drop frame", "copy frame", "dup frame" };
531
        if (audio_sync)
532
            fprintf(stderr, "Input APTS %12.6f, output APTS %12.6f, ",
533
                    (double) audio_sync->sync_ipts, 
534
                    (double) audio_sync->st->pts.val * s->pts_num / s->pts_den);
535
        fprintf(stderr, "Input VPTS %12.6f, output VPTS %12.6f: %s\n",
536
                (double) ost->sync_ipts, 
537
                (double) ost->st->pts.val * s->pts_num / s->pts_den,
538
                action[nb_frames]);
539
    }
540
#endif
541

    
542
    if (nb_frames <= 0) 
543
        return;
544

    
545
    if (!video_buffer)
546
        video_buffer = av_malloc(VIDEO_BUFFER_SIZE);
547
    if (!video_buffer)
548
        return;
549

    
550
    /* convert pixel format if needed */
551
    target_pixfmt = ost->video_resample ? PIX_FMT_YUV420P : enc->pix_fmt;
552
    if (dec->pix_fmt != target_pixfmt) {
553
        int size;
554

    
555
        /* create temporary picture */
556
        size = avpicture_get_size(target_pixfmt, dec->width, dec->height);
557
        buf = av_malloc(size);
558
        if (!buf)
559
            return;
560
        formatted_picture = &picture_format_temp;
561
        avpicture_fill(formatted_picture, buf, target_pixfmt, dec->width, dec->height);
562
        
563
        if (img_convert(formatted_picture, target_pixfmt, 
564
                        (AVPicture *)in_picture, dec->pix_fmt, 
565
                        dec->width, dec->height) < 0) {
566
            fprintf(stderr, "pixel format conversion not handled\n");
567
            goto the_end;
568
        }
569
    } else {
570
        formatted_picture = (AVPicture *)in_picture;
571
    }
572

    
573
    /* XXX: resampling could be done before raw format convertion in
574
       some cases to go faster */
575
    /* XXX: only works for YUV420P */
576
    if (ost->video_resample) {
577
        final_picture = &ost->pict_tmp;
578
        img_resample(ost->img_resample_ctx, final_picture, formatted_picture);
579
        if (enc->pix_fmt != PIX_FMT_YUV420P) {
580
            int size;
581
            
582
            av_free(buf);
583
            /* create temporary picture */
584
            size = avpicture_get_size(enc->pix_fmt, enc->width, enc->height);
585
            buf = av_malloc(size);
586
            if (!buf)
587
                return;
588
            final_picture = &picture_format_temp;
589
            avpicture_fill(final_picture, buf, enc->pix_fmt, enc->width, enc->height);
590
        
591
            if (img_convert(final_picture, enc->pix_fmt, 
592
                            &ost->pict_tmp, PIX_FMT_YUV420P, 
593
                            enc->width, enc->height) < 0) {
594
                fprintf(stderr, "pixel format conversion not handled\n");
595
                goto the_end;
596
            }
597
        }
598
    } else if (ost->video_crop) {
599
        picture_crop_temp.data[0] = formatted_picture->data[0] +
600
                (ost->topBand * formatted_picture->linesize[0]) + ost->leftBand;
601

    
602
        picture_crop_temp.data[1] = formatted_picture->data[1] +
603
                ((ost->topBand >> 1) * formatted_picture->linesize[1]) +
604
                (ost->leftBand >> 1);
605

    
606
        picture_crop_temp.data[2] = formatted_picture->data[2] +
607
                ((ost->topBand >> 1) * formatted_picture->linesize[2]) +
608
                (ost->leftBand >> 1);
609

    
610
        picture_crop_temp.linesize[0] = formatted_picture->linesize[0];
611
        picture_crop_temp.linesize[1] = formatted_picture->linesize[1];
612
        picture_crop_temp.linesize[2] = formatted_picture->linesize[2];
613
        final_picture = &picture_crop_temp;
614
    } else {
615
        final_picture = formatted_picture;
616
    }
617
    /* duplicates frame if needed */
618
    /* XXX: pb because no interleaving */
619
    for(i=0;i<nb_frames;i++) {
620
        if (s->oformat->flags & AVFMT_RAWPICTURE) {
621
            /* raw pictures are written as AVPicture structure to
622
               avoid any copies. We support temorarily the older
623
               method. */
624
            AVFrame* old_frame = enc->coded_frame;
625
            enc->coded_frame = dec->coded_frame;
626
            av_write_frame(s, ost->index, 
627
                           (uint8_t *)final_picture, sizeof(AVPicture));
628
            enc->coded_frame = old_frame;
629
        } else {
630
            AVFrame big_picture;
631
            
632
            memset(&big_picture, 0, sizeof(AVFrame));
633
            *(AVPicture*)&big_picture= *final_picture;
634
            /* better than nothing: use input picture interlaced
635
               settings */
636
            big_picture.interlaced_frame = in_picture->interlaced_frame;
637
            big_picture.top_field_first = in_picture->top_field_first;
638

    
639
            /* handles sameq here. This is not correct because it may
640
               not be a global option */
641
            if (same_quality) {
642
                big_picture.quality = ist->st->quality;
643
            }else
644
                big_picture.quality = ost->st->quality;
645
            
646
            ret = avcodec_encode_video(enc, 
647
                                       video_buffer, VIDEO_BUFFER_SIZE,
648
                                       &big_picture);
649
            //enc->frame_number = enc->real_pict_num;
650
            av_write_frame(s, ost->index, video_buffer, ret);
651
            *frame_size = ret;
652
            //fprintf(stderr,"\nFrame: %3d %3d size: %5d type: %d",
653
            //        enc->frame_number-1, enc->real_pict_num, ret,
654
            //        enc->pict_type);
655
            /* if two pass, output log */
656
            if (ost->logfile && enc->stats_out) {
657
                fprintf(ost->logfile, "%s", enc->stats_out);
658
            }
659
        }
660
        ost->frame_number++;
661
    }
662
 the_end:
663
    av_free(buf);
664
    av_free(buf1);
665
}
666

    
667
static double psnr(double d){
668
    if(d==0) return INFINITY;
669
    return -10.0*log(d)/log(10.0);
670
}
671

    
672
static void do_video_stats(AVFormatContext *os, AVOutputStream *ost, 
673
                           int frame_size)
674
{
675
    static FILE *fvstats=NULL;
676
    static int64_t total_size = 0;
677
    char filename[40];
678
    time_t today2;
679
    struct tm *today;
680
    AVCodecContext *enc;
681
    int frame_number;
682
    int64_t ti;
683
    double ti1, bitrate, avg_bitrate;
684
    
685
    if (!fvstats) {
686
        today2 = time(NULL);
687
        today = localtime(&today2);
688
        sprintf(filename, "vstats_%02d%02d%02d.log", today->tm_hour,
689
                                               today->tm_min,
690
                                               today->tm_sec);
691
        fvstats = fopen(filename,"w");
692
        if (!fvstats) {
693
            perror("fopen");
694
            exit(1);
695
        }
696
    }
697
    
698
    ti = MAXINT64;
699
    enc = &ost->st->codec;
700
    total_size += frame_size;
701
    if (enc->codec_type == CODEC_TYPE_VIDEO) {
702
        frame_number = ost->frame_number;
703
        fprintf(fvstats, "frame= %5d q= %2.1f ", frame_number, enc->coded_frame->quality/(float)FF_QP2LAMBDA);
704
        if (enc->flags&CODEC_FLAG_PSNR)
705
            fprintf(fvstats, "PSNR= %6.2f ", psnr(enc->coded_frame->error[0]/(enc->width*enc->height*255.0*255.0)));
706
        
707
        fprintf(fvstats,"f_size= %6d ", frame_size);
708
        /* compute pts value */
709
        ti1 = (double)ost->st->pts.val * os->pts_num / os->pts_den;
710
        if (ti1 < 0.01)
711
            ti1 = 0.01;
712
    
713
        bitrate = (double)(frame_size * 8) * enc->frame_rate / enc->frame_rate_base / 1000.0;
714
        avg_bitrate = (double)(total_size * 8) / ti1 / 1000.0;
715
        fprintf(fvstats, "s_size= %8.0fkB time= %0.3f br= %7.1fkbits/s avg_br= %7.1fkbits/s ",
716
            (double)total_size / 1024, ti1, bitrate, avg_bitrate);
717
        fprintf(fvstats,"type= %c\n", av_get_pict_type_char(enc->coded_frame->pict_type));        
718
    }
719
}
720

    
721
static void print_report(AVFormatContext **output_files,
722
                         AVOutputStream **ost_table, int nb_ostreams,
723
                         int is_last_report)
724
{
725
    char buf[1024];
726
    AVOutputStream *ost;
727
    AVFormatContext *oc, *os;
728
    int64_t total_size;
729
    AVCodecContext *enc;
730
    int frame_number, vid, i;
731
    double bitrate, ti1, pts;
732
    static int64_t last_time = -1;
733
    
734
    if (!is_last_report) {
735
        int64_t cur_time;
736
        /* display the report every 0.5 seconds */
737
        cur_time = av_gettime();
738
        if (last_time == -1) {
739
            last_time = cur_time;
740
            return;
741
        } 
742
        if ((cur_time - last_time) < 500000)
743
            return;
744
        last_time = cur_time;
745
    }
746

    
747

    
748
    oc = output_files[0];
749

    
750
    total_size = url_ftell(&oc->pb);
751
    
752
    buf[0] = '\0';
753
    ti1 = 1e10;
754
    vid = 0;
755
    for(i=0;i<nb_ostreams;i++) {
756
        ost = ost_table[i];
757
        os = output_files[ost->file_index];
758
        enc = &ost->st->codec;
759
        if (vid && enc->codec_type == CODEC_TYPE_VIDEO) {
760
            sprintf(buf + strlen(buf), "q=%2.1f ",
761
                    enc->coded_frame->quality/(float)FF_QP2LAMBDA);
762
        }
763
        if (!vid && enc->codec_type == CODEC_TYPE_VIDEO) {
764
            frame_number = ost->frame_number;
765
            sprintf(buf + strlen(buf), "frame=%5d q=%2.1f ",
766
                    frame_number, enc->coded_frame ? enc->coded_frame->quality/(float)FF_QP2LAMBDA : 0);
767
            if (enc->flags&CODEC_FLAG_PSNR)
768
                sprintf(buf + strlen(buf), "PSNR= %6.2f ", psnr(enc->coded_frame->error[0]/(enc->width*enc->height*255.0*255.0)));
769
            vid = 1;
770
        }
771
        /* compute min output value */
772
        pts = (double)ost->st->pts.val * os->pts_num / os->pts_den;
773
        if ((pts < ti1) && (pts > 0))
774
            ti1 = pts;
775
    }
776
    if (ti1 < 0.01)
777
        ti1 = 0.01;
778
    
779
    if (verbose || is_last_report) {
780
        bitrate = (double)(total_size * 8) / ti1 / 1000.0;
781
        
782
        sprintf(buf + strlen(buf), 
783
            "size=%8.0fkB time=%0.1f bitrate=%6.1fkbits/s",
784
            (double)total_size / 1024, ti1, bitrate);
785
        
786
        fprintf(stderr, "%s    \r", buf);
787
        fflush(stderr);
788
    }
789
        
790
    if (is_last_report)
791
        fprintf(stderr, "\n");
792
}
793

    
794
/*
795
 * The following code is the main loop of the file converter
796
 */
797
static int av_encode(AVFormatContext **output_files,
798
                     int nb_output_files,
799
                     AVFormatContext **input_files,
800
                     int nb_input_files,
801
                     AVStreamMap *stream_maps, int nb_stream_maps)
802
{
803
    int ret, i, j, k, n, nb_istreams = 0, nb_ostreams = 0;
804
    AVFormatContext *is, *os;
805
    AVCodecContext *codec, *icodec;
806
    AVOutputStream *ost, **ost_table = NULL;
807
    AVInputStream *ist, **ist_table = NULL;
808
    AVInputFile *file_table;
809
    AVFormatContext *stream_no_data;
810
    int key;
811

    
812
    file_table= (AVInputFile*) av_mallocz(nb_input_files * sizeof(AVInputFile));
813
    if (!file_table)
814
        goto fail;
815

    
816
    /* input stream init */
817
    j = 0;
818
    for(i=0;i<nb_input_files;i++) {
819
        is = input_files[i];
820
        file_table[i].ist_index = j;
821
        file_table[i].nb_streams = is->nb_streams;
822
        j += is->nb_streams;
823
    }
824
    nb_istreams = j;
825

    
826
    ist_table = av_mallocz(nb_istreams * sizeof(AVInputStream *));
827
    if (!ist_table)
828
        goto fail;
829
    
830
    for(i=0;i<nb_istreams;i++) {
831
        ist = av_mallocz(sizeof(AVInputStream));
832
        if (!ist)
833
            goto fail;
834
        ist_table[i] = ist;
835
    }
836
    j = 0;
837
    for(i=0;i<nb_input_files;i++) {
838
        is = input_files[i];
839
        for(k=0;k<is->nb_streams;k++) {
840
            ist = ist_table[j++];
841
            ist->st = is->streams[k];
842
            ist->file_index = i;
843
            ist->index = k;
844
            ist->discard = 1; /* the stream is discarded by default
845
                                 (changed later) */
846

    
847
            if (ist->st->codec.rate_emu) {
848
                ist->start = av_gettime();
849
                ist->frame = 0;
850
            }
851
        }
852
    }
853

    
854
    /* output stream init */
855
    nb_ostreams = 0;
856
    for(i=0;i<nb_output_files;i++) {
857
        os = output_files[i];
858
        nb_ostreams += os->nb_streams;
859
    }
860
    if (nb_stream_maps > 0 && nb_stream_maps != nb_ostreams) {
861
        fprintf(stderr, "Number of stream maps must match number of output streams\n");
862
        exit(1);
863
    }
864

    
865
    /* Sanity check the mapping args -- do the input files & streams exist? */
866
    for(i=0;i<nb_stream_maps;i++) {
867
        int fi = stream_maps[i].file_index;
868
        int si = stream_maps[i].stream_index;
869
        
870
        if (fi < 0 || fi > nb_input_files - 1 ||
871
            si < 0 || si > file_table[fi].nb_streams - 1) {
872
            fprintf(stderr,"Could not find input stream #%d.%d\n", fi, si);
873
            exit(1);
874
        }
875
    }
876
    
877
    ost_table = av_mallocz(sizeof(AVOutputStream *) * nb_ostreams);
878
    if (!ost_table)
879
        goto fail;
880
    for(i=0;i<nb_ostreams;i++) {
881
        ost = av_mallocz(sizeof(AVOutputStream));
882
        if (!ost)
883
            goto fail;
884
        ost_table[i] = ost;
885
    }
886
    
887
    n = 0;
888
    for(k=0;k<nb_output_files;k++) {
889
        os = output_files[k];
890
        for(i=0;i<os->nb_streams;i++) {
891
            int found;
892
            ost = ost_table[n++];
893
            ost->file_index = k;
894
            ost->index = i;
895
            ost->st = os->streams[i];
896
            if (nb_stream_maps > 0) {
897
                ost->source_index = file_table[stream_maps[n-1].file_index].ist_index + 
898
                    stream_maps[n-1].stream_index;
899
                    
900
                /* Sanity check that the stream types match */
901
                if (ist_table[ost->source_index]->st->codec.codec_type != ost->st->codec.codec_type) {
902
                    fprintf(stderr, "Codec type mismatch for mapping #%d.%d -> #%d.%d\n",
903
                        stream_maps[n-1].file_index, stream_maps[n-1].stream_index,
904
                        ost->file_index, ost->index);
905
                    exit(1);
906
                }
907
                
908
            } else {
909
                /* get corresponding input stream index : we select the first one with the right type */
910
                found = 0;
911
                for(j=0;j<nb_istreams;j++) {
912
                    ist = ist_table[j];
913
                    if (ist->discard && 
914
                        ist->st->codec.codec_type == ost->st->codec.codec_type) {
915
                        ost->source_index = j;
916
                        found = 1;
917
                    }
918
                }
919
                
920
                if (!found) {
921
                    /* try again and reuse existing stream */
922
                    for(j=0;j<nb_istreams;j++) {
923
                        ist = ist_table[j];
924
                        if (ist->st->codec.codec_type == ost->st->codec.codec_type) {
925
                            ost->source_index = j;
926
                            found = 1;
927
                        }
928
                    }
929
                    if (!found) {
930
                        fprintf(stderr, "Could not find input stream matching output stream #%d.%d\n",
931
                                ost->file_index, ost->index);
932
                        exit(1);
933
                    }
934
                }
935
            }
936
            ist = ist_table[ost->source_index];
937
            ist->discard = 0;
938
        }
939
    }
940

    
941
    /* for each output stream, we compute the right encoding parameters */
942
    for(i=0;i<nb_ostreams;i++) {
943
        ost = ost_table[i];
944
        ist = ist_table[ost->source_index];
945

    
946
        codec = &ost->st->codec;
947
        icodec = &ist->st->codec;
948

    
949
        if (ost->st->stream_copy) {
950
            /* if stream_copy is selected, no need to decode or encode */
951
            codec->codec_id = icodec->codec_id;
952
            codec->codec_type = icodec->codec_type;
953
            codec->codec_tag = icodec->codec_tag;
954
            codec->bit_rate = icodec->bit_rate;
955
            switch(codec->codec_type) {
956
            case CODEC_TYPE_AUDIO:
957
                codec->sample_rate = icodec->sample_rate;
958
                codec->channels = icodec->channels;
959
                break;
960
            case CODEC_TYPE_VIDEO:
961
                codec->frame_rate = icodec->frame_rate;
962
                codec->frame_rate_base = icodec->frame_rate_base;
963
                codec->width = icodec->width;
964
                codec->height = icodec->height;
965
                break;
966
            default:
967
                av_abort();
968
            }
969
        } else {
970
            switch(codec->codec_type) {
971
            case CODEC_TYPE_AUDIO:
972
                if (fifo_init(&ost->fifo, 2 * MAX_AUDIO_PACKET_SIZE))
973
                    goto fail;
974
                
975
                if (codec->channels == icodec->channels &&
976
                    codec->sample_rate == icodec->sample_rate) {
977
                    ost->audio_resample = 0;
978
                } else {
979
                    if (codec->channels != icodec->channels &&
980
                        icodec->codec_id == CODEC_ID_AC3) {
981
                        /* Special case for 5:1 AC3 input */
982
                        /* and mono or stereo output      */
983
                        /* Request specific number of channels */
984
                        icodec->channels = codec->channels;
985
                        if (codec->sample_rate == icodec->sample_rate)
986
                            ost->audio_resample = 0;
987
                        else {
988
                            ost->audio_resample = 1;
989
                            ost->resample = audio_resample_init(codec->channels, icodec->channels,
990
                                                        codec->sample_rate, 
991
                                                        icodec->sample_rate);
992
                            if(!ost->resample)
993
                              {
994
                                printf("Can't resample.  Aborting.\n");
995
                                av_abort();
996
                              }
997
                        }
998
                        /* Request specific number of channels */
999
                        icodec->channels = codec->channels;
1000
                    } else {
1001
                        ost->audio_resample = 1; 
1002
                        ost->resample = audio_resample_init(codec->channels, icodec->channels,
1003
                                                        codec->sample_rate, 
1004
                                                        icodec->sample_rate);
1005
                        if(!ost->resample)
1006
                          {
1007
                            printf("Can't resample.  Aborting.\n");
1008
                            av_abort();
1009
                          }
1010
                    }
1011
                }
1012
                ist->decoding_needed = 1;
1013
                ost->encoding_needed = 1;
1014
                break;
1015
            case CODEC_TYPE_VIDEO:
1016
                if (codec->width == icodec->width &&
1017
                    codec->height == icodec->height &&
1018
                    frame_topBand == 0 &&
1019
                    frame_bottomBand == 0 &&
1020
                    frame_leftBand == 0 &&
1021
                    frame_rightBand == 0)
1022
                {
1023
                    ost->video_resample = 0;
1024
                    ost->video_crop = 0;
1025
                } else if ((codec->width == icodec->width -
1026
                                (frame_leftBand + frame_rightBand)) &&
1027
                        (codec->height == icodec->height -
1028
                                (frame_topBand  + frame_bottomBand)))
1029
                {
1030
                    ost->video_resample = 0;
1031
                    ost->video_crop = 1;
1032
                    ost->topBand = frame_topBand;
1033
                    ost->leftBand = frame_leftBand;
1034
                } else {
1035
                    uint8_t *buf;
1036
                    ost->video_resample = 1;
1037
                    ost->video_crop = 0; // cropping is handled as part of resample
1038
                    buf = av_malloc((codec->width * codec->height * 3) / 2);
1039
                    if (!buf)
1040
                        goto fail;
1041
                    ost->pict_tmp.data[0] = buf;
1042
                    ost->pict_tmp.data[1] = ost->pict_tmp.data[0] + (codec->width * codec->height);
1043
                    ost->pict_tmp.data[2] = ost->pict_tmp.data[1] + (codec->width * codec->height) / 4;
1044
                    ost->pict_tmp.linesize[0] = codec->width;
1045
                    ost->pict_tmp.linesize[1] = codec->width / 2;
1046
                    ost->pict_tmp.linesize[2] = codec->width / 2;
1047

    
1048
                    ost->img_resample_ctx = img_resample_full_init( 
1049
                                      ost->st->codec.width, ost->st->codec.height,
1050
                                      ist->st->codec.width, ist->st->codec.height,
1051
                                      frame_topBand, frame_bottomBand,
1052
                                      frame_leftBand, frame_rightBand);
1053
                }
1054
                ost->encoding_needed = 1;
1055
                ist->decoding_needed = 1;
1056
                break;
1057
            default:
1058
                av_abort();
1059
            }
1060
            /* two pass mode */
1061
            if (ost->encoding_needed && 
1062
                (codec->flags & (CODEC_FLAG_PASS1 | CODEC_FLAG_PASS2))) {
1063
                char logfilename[1024];
1064
                FILE *f;
1065
                int size;
1066
                char *logbuffer;
1067
                
1068
                snprintf(logfilename, sizeof(logfilename), "%s-%d.log", 
1069
                         pass_logfilename ? 
1070
                         pass_logfilename : DEFAULT_PASS_LOGFILENAME, i);
1071
                if (codec->flags & CODEC_FLAG_PASS1) {
1072
                    f = fopen(logfilename, "w");
1073
                    if (!f) {
1074
                        perror(logfilename);
1075
                        exit(1);
1076
                    }
1077
                    ost->logfile = f;
1078
                } else {
1079
                    /* read the log file */
1080
                    f = fopen(logfilename, "r");
1081
                    if (!f) {
1082
                        perror(logfilename);
1083
                        exit(1);
1084
                    }
1085
                    fseek(f, 0, SEEK_END);
1086
                    size = ftell(f);
1087
                    fseek(f, 0, SEEK_SET);
1088
                    logbuffer = av_malloc(size + 1);
1089
                    if (!logbuffer) {
1090
                        fprintf(stderr, "Could not allocate log buffer\n");
1091
                        exit(1);
1092
                    }
1093
                    fread(logbuffer, 1, size, f);
1094
                    fclose(f);
1095
                    logbuffer[size] = '\0';
1096
                    codec->stats_in = logbuffer;
1097
                }
1098
            }
1099
        }
1100
    }
1101

    
1102
    /* dump the file output parameters - cannot be done before in case
1103
       of stream copy */
1104
    for(i=0;i<nb_output_files;i++) {
1105
        dump_format(output_files[i], i, output_files[i]->filename, 1);
1106
    }
1107

    
1108
    /* dump the stream mapping */
1109
    fprintf(stderr, "Stream mapping:\n");
1110
    for(i=0;i<nb_ostreams;i++) {
1111
        ost = ost_table[i];
1112
        fprintf(stderr, "  Stream #%d.%d -> #%d.%d\n",
1113
                ist_table[ost->source_index]->file_index,
1114
                ist_table[ost->source_index]->index,
1115
                ost->file_index, 
1116
                ost->index);
1117
    }
1118

    
1119
    /* open each encoder */
1120
    for(i=0;i<nb_ostreams;i++) {
1121
        ost = ost_table[i];
1122
        if (ost->encoding_needed) {
1123
            AVCodec *codec;
1124
            codec = avcodec_find_encoder(ost->st->codec.codec_id);
1125
            if (!codec) {
1126
                fprintf(stderr, "Unsupported codec for output stream #%d.%d\n", 
1127
                        ost->file_index, ost->index);
1128
                exit(1);
1129
            }
1130
            if (avcodec_open(&ost->st->codec, codec) < 0) {
1131
                fprintf(stderr, "Error while opening codec for stream #%d.%d - maybe incorrect parameters such as bit_rate, rate, width or height\n", 
1132
                        ost->file_index, ost->index);
1133
                exit(1);
1134
            }
1135
        }
1136
    }
1137

    
1138
    /* open each decoder */
1139
    for(i=0;i<nb_istreams;i++) {
1140
        ist = ist_table[i];
1141
        if (ist->decoding_needed) {
1142
            AVCodec *codec;
1143
            codec = avcodec_find_decoder(ist->st->codec.codec_id);
1144
            if (!codec) {
1145
                fprintf(stderr, "Unsupported codec (id=%d) for input stream #%d.%d\n", 
1146
                        ist->st->codec.codec_id, ist->file_index, ist->index);
1147
                exit(1);
1148
            }
1149
            if (avcodec_open(&ist->st->codec, codec) < 0) {
1150
                fprintf(stderr, "Error while opening codec for input stream #%d.%d\n", 
1151
                        ist->file_index, ist->index);
1152
                exit(1);
1153
            }
1154
            //if (ist->st->codec.codec_type == CODEC_TYPE_VIDEO)
1155
            //    ist->st->codec.flags |= CODEC_FLAG_REPEAT_FIELD;
1156
        }
1157
    }
1158

    
1159
    /* init pts */
1160
    for(i=0;i<nb_istreams;i++) {
1161
        ist = ist_table[i];
1162
        is = input_files[ist->file_index];
1163
        ist->pts = 0;
1164
        ist->next_pts = 0;
1165
    }
1166
    
1167
    /* compute buffer size max (should use a complete heuristic) */
1168
    for(i=0;i<nb_input_files;i++) {
1169
        file_table[i].buffer_size_max = 2048;
1170
    }
1171

    
1172
    /* open files and write file headers */
1173
    for(i=0;i<nb_output_files;i++) {
1174
        os = output_files[i];
1175
        if (av_write_header(os) < 0) {
1176
            fprintf(stderr, "Could not write header for output file #%d (incorrect codec paramters ?)\n", i);
1177
            ret = -EINVAL;
1178
            goto fail;
1179
        }
1180
    }
1181

    
1182
#ifndef CONFIG_WIN32
1183
    if ( !using_stdin )
1184
        fprintf(stderr, "Press [q] to stop encoding\n");
1185
#endif
1186
    term_init();
1187

    
1188
    stream_no_data = 0;
1189
    key = -1;
1190

    
1191
    for(; received_sigterm == 0;) {
1192
        int file_index, ist_index;
1193
        AVPacket pkt;
1194
        uint8_t *ptr;
1195
        int len;
1196
        uint8_t *data_buf;
1197
        int data_size, got_picture;
1198
        AVFrame picture;
1199
        short samples[AVCODEC_MAX_AUDIO_FRAME_SIZE / 2];
1200
        void *buffer_to_free;
1201
        double pts_min;
1202
        
1203
    redo:
1204
        /* if 'q' pressed, exits */
1205
        if (!using_stdin) {
1206
            /* read_key() returns 0 on EOF */
1207
            key = read_key();
1208
            if (key == 'q')
1209
                break;
1210
        }
1211

    
1212
        /* select the stream that we must read now by looking at the
1213
           smallest output pts */
1214
        file_index = -1;
1215
        pts_min = 1e10;
1216
        for(i=0;i<nb_ostreams;i++) {
1217
            double pts;
1218
            ost = ost_table[i];
1219
            os = output_files[ost->file_index];
1220
            ist = ist_table[ost->source_index];
1221
            pts = (double)ost->st->pts.val * os->pts_num / os->pts_den;
1222
            if (!file_table[ist->file_index].eof_reached && 
1223
                pts < pts_min) {
1224
                pts_min = pts;
1225
                file_index = ist->file_index;
1226
            }
1227
        }
1228
        /* if none, if is finished */
1229
        if (file_index < 0) {
1230
            break;
1231
        }
1232

    
1233
        /* finish if recording time exhausted */
1234
        if (recording_time > 0 && pts_min >= (recording_time / 1000000.0))
1235
            break;
1236

    
1237
        /* read a frame from it and output it in the fifo */
1238
        is = input_files[file_index];
1239
        if (av_read_frame(is, &pkt) < 0) {
1240
            file_table[file_index].eof_reached = 1;
1241
            continue;
1242
        }
1243
        if (!pkt.size) {
1244
            stream_no_data = is;
1245
        } else {
1246
            stream_no_data = 0;
1247
        }
1248
        if (do_pkt_dump) {
1249
            av_pkt_dump(stdout, &pkt, do_hex_dump);
1250
        }
1251
        /* the following test is needed in case new streams appear
1252
           dynamically in stream : we ignore them */
1253
        if (pkt.stream_index >= file_table[file_index].nb_streams)
1254
            goto discard_packet;
1255
        ist_index = file_table[file_index].ist_index + pkt.stream_index;
1256
        ist = ist_table[ist_index];
1257
        if (ist->discard)
1258
            goto discard_packet;
1259

    
1260
        //fprintf(stderr,"read #%d.%d size=%d\n", ist->file_index, ist->index, pkt.size);
1261
        
1262
        if (pkt.pts != AV_NOPTS_VALUE) {
1263
            ist->pts = pkt.pts;
1264
        } else {
1265
            ist->pts = ist->next_pts;
1266
        }
1267

    
1268
        len = pkt.size;
1269
        ptr = pkt.data;
1270
        while (len > 0) {
1271
            /* decode the packet if needed */
1272
            data_buf = NULL; /* fail safe */
1273
            data_size = 0;
1274
            if (ist->decoding_needed) {
1275
                switch(ist->st->codec.codec_type) {
1276
                case CODEC_TYPE_AUDIO:
1277
                    /* XXX: could avoid copy if PCM 16 bits with same
1278
                       endianness as CPU */
1279
                    ret = avcodec_decode_audio(&ist->st->codec, samples, &data_size,
1280
                                               ptr, len);
1281
                    if (ret < 0)
1282
                        goto fail_decode;
1283
                    ptr += ret;
1284
                    len -= ret;
1285
                    /* Some bug in mpeg audio decoder gives */
1286
                    /* data_size < 0, it seems they are overflows */
1287
                    if (data_size <= 0) {
1288
                        /* no audio frame */
1289
                        continue;
1290
                    }
1291
                    data_buf = (uint8_t *)samples;
1292
                    ist->next_pts += ((int64_t)AV_TIME_BASE * data_size) / 
1293
                        (2 * ist->st->codec.channels);
1294
                    break;
1295
                case CODEC_TYPE_VIDEO:
1296
                    data_size = (ist->st->codec.width * ist->st->codec.height * 3) / 2;
1297
                    /* XXX: allocate picture correctly */
1298
                    memset(&picture, 0, sizeof(picture));
1299
                    ret = avcodec_decode_video(&ist->st->codec, 
1300
                                               &picture, &got_picture, ptr, len);
1301
                    ist->st->quality= picture.quality;
1302
                    if (ret < 0) {
1303
                    fail_decode:
1304
                        fprintf(stderr, "Error while decoding stream #%d.%d\n",
1305
                                ist->file_index, ist->index);
1306
                        av_free_packet(&pkt);
1307
                        goto redo;
1308
                    }
1309
                    if (!got_picture) {
1310
                        /* no picture yet */
1311
                        goto discard_packet;
1312
                    }
1313
                    if (ist->st->codec.frame_rate_base != 0) {
1314
                        ist->next_pts += ((int64_t)AV_TIME_BASE * 
1315
                                          ist->st->codec.frame_rate_base) /
1316
                            ist->st->codec.frame_rate;
1317
                    }
1318
                    len = 0;
1319
                    break;
1320
                default:
1321
                    goto fail_decode;
1322
                }
1323
            } else {
1324
                data_buf = ptr;
1325
                data_size = len;
1326
                ret = len;
1327
                len = 0;
1328
            }
1329

    
1330
            buffer_to_free = NULL;
1331
            if (ist->st->codec.codec_type == CODEC_TYPE_VIDEO) {
1332
                pre_process_video_frame(ist, (AVPicture *)&picture, 
1333
                                        &buffer_to_free);
1334
            }
1335

    
1336
            /* frame rate emulation */
1337
            if (ist->st->codec.rate_emu) {
1338
                int64_t pts = av_rescale((int64_t) ist->frame * ist->st->codec.frame_rate_base, 1000000, ist->st->codec.frame_rate);
1339
                int64_t now = av_gettime() - ist->start;
1340
                if (pts > now)
1341
                    usleep(pts - now);
1342

    
1343
                ist->frame++;
1344
            }
1345

    
1346
#if 0
1347
            /* mpeg PTS deordering : if it is a P or I frame, the PTS
1348
               is the one of the next displayed one */
1349
            /* XXX: add mpeg4 too ? */
1350
            if (ist->st->codec.codec_id == CODEC_ID_MPEG1VIDEO) {
1351
                if (ist->st->codec.pict_type != B_TYPE) {
1352
                    int64_t tmp;
1353
                    tmp = ist->last_ip_pts;
1354
                    ist->last_ip_pts  = ist->frac_pts.val;
1355
                    ist->frac_pts.val = tmp;
1356
                }
1357
            }
1358
#endif
1359
            /* if output time reached then transcode raw format, 
1360
               encode packets and output them */
1361
            if (start_time == 0 || ist->pts >= start_time)
1362
                for(i=0;i<nb_ostreams;i++) {
1363
                    int frame_size;
1364

    
1365
                    ost = ost_table[i];
1366
                    if (ost->source_index == ist_index) {
1367
                        os = output_files[ost->file_index];
1368

    
1369
#if 0
1370
                        printf("%d: got pts=%0.3f %0.3f\n", i, 
1371
                               (double)pkt.pts / AV_TIME_BASE, 
1372
                               ((double)ist->pts / AV_TIME_BASE) - 
1373
                               ((double)ost->st->pts.val * os->pts_num / os->pts_den));
1374
#endif
1375
                        /* set the input output pts pairs */
1376
                        ost->sync_ipts = (double)ist->pts / AV_TIME_BASE;
1377
                        /* XXX: take into account the various fifos,
1378
                           in particular for audio */
1379
                        ost->sync_opts = ost->st->pts.val;
1380
                        //printf("ipts=%lld sync_ipts=%f sync_opts=%lld pts.val=%lld pkt.pts=%lld\n", ist->pts, ost->sync_ipts, ost->sync_opts, ost->st->pts.val, pkt.pts); 
1381

    
1382
                        if (ost->encoding_needed) {
1383
                            switch(ost->st->codec.codec_type) {
1384
                            case CODEC_TYPE_AUDIO:
1385
                                do_audio_out(os, ost, ist, data_buf, data_size);
1386
                                break;
1387
                            case CODEC_TYPE_VIDEO:
1388
                                /* find an audio stream for synchro */
1389
                                {
1390
                                    int i;
1391
                                    AVOutputStream *audio_sync, *ost1;
1392
                                    audio_sync = NULL;
1393
                                    for(i=0;i<nb_ostreams;i++) {
1394
                                        ost1 = ost_table[i];
1395
                                        if (ost1->file_index == ost->file_index &&
1396
                                            ost1->st->codec.codec_type == CODEC_TYPE_AUDIO) {
1397
                                            audio_sync = ost1;
1398
                                            break;
1399
                                        }
1400
                                    }
1401

    
1402
                                    do_video_out(os, ost, ist, &picture, &frame_size, audio_sync);
1403
                                    if (do_vstats && frame_size)
1404
                                        do_video_stats(os, ost, frame_size);
1405
                                }
1406
                                break;
1407
                            default:
1408
                                av_abort();
1409
                            }
1410
                        } else {
1411
                            AVFrame avframe;
1412
                                                
1413
                            /* no reencoding needed : output the packet directly */
1414
                            /* force the input stream PTS */
1415
                        
1416
                            memset(&avframe, 0, sizeof(AVFrame));
1417
                            ost->st->codec.coded_frame= &avframe;
1418
                            avframe.key_frame = pkt.flags & PKT_FLAG_KEY; 
1419
                        
1420
                            av_write_frame(os, ost->index, data_buf, data_size);
1421
                            ost->st->codec.frame_number++;
1422
                            ost->frame_number++;
1423
                        }
1424
                    }
1425
                }
1426
            av_free(buffer_to_free);
1427
        }
1428
    discard_packet:
1429
        av_free_packet(&pkt);
1430
        
1431
        /* dump report by using the output first video and audio streams */
1432
        print_report(output_files, ost_table, nb_ostreams, 0);
1433
    }
1434
    term_exit();
1435

    
1436
    /* dump report by using the first video and audio streams */
1437
    print_report(output_files, ost_table, nb_ostreams, 1);
1438

    
1439
    /* close each encoder */
1440
    for(i=0;i<nb_ostreams;i++) {
1441
        ost = ost_table[i];
1442
        if (ost->encoding_needed) {
1443
            av_freep(&ost->st->codec.stats_in);
1444
            avcodec_close(&ost->st->codec);
1445
        }
1446
    }
1447
    
1448
    /* close each decoder */
1449
    for(i=0;i<nb_istreams;i++) {
1450
        ist = ist_table[i];
1451
        if (ist->decoding_needed) {
1452
            avcodec_close(&ist->st->codec);
1453
        }
1454
    }
1455
    
1456

    
1457
    /* write the trailer if needed and close file */
1458
    for(i=0;i<nb_output_files;i++) {
1459
        os = output_files[i];
1460
        av_write_trailer(os);
1461
    }
1462
    /* finished ! */
1463
    
1464
    ret = 0;
1465
 fail1:
1466
    av_free(file_table);
1467

    
1468
    if (ist_table) {
1469
        for(i=0;i<nb_istreams;i++) {
1470
            ist = ist_table[i];
1471
            av_free(ist);
1472
        }
1473
        av_free(ist_table);
1474
    }
1475
    if (ost_table) {
1476
        for(i=0;i<nb_ostreams;i++) {
1477
            ost = ost_table[i];
1478
            if (ost) {
1479
                if (ost->logfile) {
1480
                    fclose(ost->logfile);
1481
                    ost->logfile = NULL;
1482
                }
1483
                fifo_free(&ost->fifo); /* works even if fifo is not
1484
                                          initialized but set to zero */
1485
                av_free(ost->pict_tmp.data[0]);
1486
                if (ost->video_resample)
1487
                    img_resample_close(ost->img_resample_ctx);
1488
                if (ost->audio_resample)
1489
                    audio_resample_close(ost->resample);
1490
                av_free(ost);
1491
            }
1492
        }
1493
        av_free(ost_table);
1494
    }
1495
    return ret;
1496
 fail:
1497
    ret = -ENOMEM;
1498
    goto fail1;
1499
}
1500

    
1501
#if 0
1502
int file_read(const char *filename)
1503
{
1504
    URLContext *h;
1505
    unsigned char buffer[1024];
1506
    int len, i;
1507

1508
    if (url_open(&h, filename, O_RDONLY) < 0) {
1509
        printf("could not open '%s'\n", filename);
1510
        return -1;
1511
    }
1512
    for(;;) {
1513
        len = url_read(h, buffer, sizeof(buffer));
1514
        if (len <= 0)
1515
            break;
1516
        for(i=0;i<len;i++) putchar(buffer[i]);
1517
    }
1518
    url_close(h);
1519
    return 0;
1520
}
1521
#endif
1522

    
1523
static void opt_image_format(const char *arg)
1524
{
1525
    AVImageFormat *f;
1526
    
1527
    for(f = first_image_format; f != NULL; f = f->next) {
1528
        if (!strcmp(arg, f->name))
1529
            break;
1530
    }
1531
    if (!f) {
1532
        fprintf(stderr, "Unknown image format: '%s'\n", arg);
1533
        exit(1);
1534
    }
1535
    image_format = f;
1536
}
1537

    
1538
static void opt_format(const char *arg)
1539
{
1540
    /* compatibility stuff for pgmyuv */
1541
    if (!strcmp(arg, "pgmyuv")) {
1542
        opt_image_format(arg);
1543
        arg = "image";
1544
    }
1545

    
1546
    file_iformat = av_find_input_format(arg);
1547
    file_oformat = guess_format(arg, NULL, NULL);
1548
    if (!file_iformat && !file_oformat) {
1549
        fprintf(stderr, "Unknown input or output format: %s\n", arg);
1550
        exit(1);
1551
    }
1552
}
1553

    
1554
static void opt_video_bitrate(const char *arg)
1555
{
1556
    video_bit_rate = atoi(arg) * 1000;
1557
}
1558

    
1559
static void opt_video_bitrate_tolerance(const char *arg)
1560
{
1561
    video_bit_rate_tolerance = atoi(arg) * 1000;
1562
}
1563

    
1564
static void opt_video_bitrate_max(const char *arg)
1565
{
1566
    video_rc_max_rate = atoi(arg) * 1000;
1567
}
1568

    
1569
static void opt_video_bitrate_min(const char *arg)
1570
{
1571
    video_rc_min_rate = atoi(arg) * 1000;
1572
}
1573

    
1574
static void opt_video_buffer_size(const char *arg)
1575
{
1576
    video_rc_buffer_size = atoi(arg) * 1024;
1577
}
1578

    
1579
static void opt_video_rc_eq(char *arg)
1580
{
1581
    video_rc_eq = arg;
1582
}
1583

    
1584
static void opt_video_rc_override_string(char *arg)
1585
{
1586
    video_rc_override_string = arg;
1587
}
1588

    
1589

    
1590
static void opt_workaround_bugs(const char *arg)
1591
{
1592
    workaround_bugs = atoi(arg);
1593
}
1594

    
1595
static void opt_dct_algo(const char *arg)
1596
{
1597
    dct_algo = atoi(arg);
1598
}
1599

    
1600
static void opt_idct_algo(const char *arg)
1601
{
1602
    idct_algo = atoi(arg);
1603
}
1604

    
1605

    
1606
static void opt_error_resilience(const char *arg)
1607
{
1608
    error_resilience = atoi(arg);
1609
}
1610

    
1611
static void opt_error_concealment(const char *arg)
1612
{
1613
    error_concealment = atoi(arg);
1614
}
1615

    
1616
static void opt_debug(const char *arg)
1617
{
1618
    debug = atoi(arg);
1619
}
1620

    
1621
static void opt_verbose(const char *arg)
1622
{
1623
    verbose = atoi(arg);
1624
}
1625

    
1626
static void opt_frame_rate(const char *arg)
1627
{
1628
    if (parse_frame_rate(&frame_rate, &frame_rate_base, arg) < 0) {
1629
        fprintf(stderr, "Incorrect frame rate\n");
1630
        exit(1);
1631
    }
1632
}
1633

    
1634
static void opt_frame_crop_top(const char *arg)
1635
{
1636
    frame_topBand = atoi(arg); 
1637
    if (frame_topBand < 0) {
1638
        fprintf(stderr, "Incorrect top crop size\n");
1639
        exit(1);
1640
    }
1641
    if ((frame_topBand % 2) != 0) {
1642
        fprintf(stderr, "Top crop size must be a multiple of 2\n");
1643
        exit(1);
1644
    }
1645
    if ((frame_topBand) >= frame_height){
1646
            fprintf(stderr, "Vertical crop dimensions are outside the range of the original image.\nRemember to crop first and scale second.\n");
1647
        exit(1);
1648
    }
1649
    frame_height -= frame_topBand;
1650
}
1651

    
1652
static void opt_frame_crop_bottom(const char *arg)
1653
{
1654
    frame_bottomBand = atoi(arg);
1655
    if (frame_bottomBand < 0) {
1656
        fprintf(stderr, "Incorrect bottom crop size\n");
1657
        exit(1);
1658
    }
1659
    if ((frame_bottomBand % 2) != 0) {
1660
        fprintf(stderr, "Bottom crop size must be a multiple of 2\n");
1661
        exit(1);        
1662
    }
1663
    if ((frame_bottomBand) >= frame_height){
1664
            fprintf(stderr, "Vertical crop dimensions are outside the range of the original image.\nRemember to crop first and scale second.\n");
1665
        exit(1);
1666
    }
1667
    frame_height -= frame_bottomBand;
1668
}
1669

    
1670
static void opt_frame_crop_left(const char *arg)
1671
{
1672
    frame_leftBand = atoi(arg);
1673
    if (frame_leftBand < 0) {
1674
        fprintf(stderr, "Incorrect left crop size\n");
1675
        exit(1);
1676
    }
1677
    if ((frame_leftBand % 2) != 0) {
1678
        fprintf(stderr, "Left crop size must be a multiple of 2\n");
1679
        exit(1);
1680
    }
1681
    if ((frame_leftBand) >= frame_width){
1682
            fprintf(stderr, "Horizontal crop dimensions are outside the range of the original image.\nRemember to crop first and scale second.\n");
1683
        exit(1);
1684
    }
1685
    frame_width -= frame_leftBand;
1686
}
1687

    
1688
static void opt_frame_crop_right(const char *arg)
1689
{
1690
    frame_rightBand = atoi(arg);
1691
    if (frame_rightBand < 0) {
1692
        fprintf(stderr, "Incorrect right crop size\n");
1693
        exit(1);
1694
    }
1695
    if ((frame_rightBand % 2) != 0) {
1696
        fprintf(stderr, "Right crop size must be a multiple of 2\n");
1697
        exit(1);        
1698
    }
1699
    if ((frame_rightBand) >= frame_width){
1700
            fprintf(stderr, "Horizontal crop dimensions are outside the range of the original image.\nRemember to crop first and scale second.\n");
1701
        exit(1);
1702
    }
1703
    frame_width -= frame_rightBand;
1704
}
1705

    
1706
static void opt_frame_size(const char *arg)
1707
{
1708
    if (parse_image_size(&frame_width, &frame_height, arg) < 0) {
1709
        fprintf(stderr, "Incorrect frame size\n");
1710
        exit(1);
1711
    }
1712
    if ((frame_width % 2) != 0 || (frame_height % 2) != 0) {
1713
        fprintf(stderr, "Frame size must be a multiple of 2\n");
1714
        exit(1);
1715
    }
1716
}
1717

    
1718
static void opt_frame_pix_fmt(const char *arg)
1719
{
1720
    frame_pix_fmt = avcodec_get_pix_fmt(arg);
1721
}
1722

    
1723
static void opt_frame_aspect_ratio(const char *arg)
1724
{
1725
    int x = 0, y = 0;
1726
    double ar = 0;
1727
    const char *p;
1728
    
1729
    p = strchr(arg, ':');
1730
    if (p) {
1731
        x = strtol(arg, (char **)&arg, 10);
1732
        if (arg == p)
1733
            y = strtol(arg+1, (char **)&arg, 10);
1734
        if (x > 0 && y > 0)
1735
            ar = (double)x / (double)y;
1736
    } else
1737
        ar = strtod(arg, (char **)&arg);
1738

    
1739
    if (!ar) {
1740
        fprintf(stderr, "Incorrect aspect ratio specification.\n");
1741
        exit(1);
1742
    }
1743
    frame_aspect_ratio = ar;
1744
}
1745

    
1746
static void opt_gop_size(const char *arg)
1747
{
1748
    gop_size = atoi(arg);
1749
}
1750

    
1751
static void opt_b_frames(const char *arg)
1752
{
1753
    b_frames = atoi(arg);
1754
    if (b_frames > FF_MAX_B_FRAMES) {
1755
        fprintf(stderr, "\nCannot have more than %d B frames, increase FF_MAX_B_FRAMES.\n", FF_MAX_B_FRAMES);
1756
        exit(1);
1757
    } else if (b_frames < 1) {
1758
        fprintf(stderr, "\nNumber of B frames must be higher than 0\n");
1759
        exit(1);
1760
    }
1761
}
1762

    
1763
static void opt_mb_decision(const char *arg)
1764
{
1765
    mb_decision = atoi(arg);
1766
}
1767

    
1768
static void opt_mb_cmp(const char *arg)
1769
{
1770
    mb_cmp = atoi(arg);
1771
}
1772

    
1773
static void opt_sub_cmp(const char *arg)
1774
{
1775
    sub_cmp = atoi(arg);
1776
}
1777

    
1778
static void opt_cmp(const char *arg)
1779
{
1780
    cmp = atoi(arg);
1781
}
1782

    
1783
static void opt_qscale(const char *arg)
1784
{
1785
    video_qscale = atof(arg);
1786
    if (video_qscale < 0.01 ||
1787
        video_qscale > 255) {
1788
        fprintf(stderr, "qscale must be >= 0.01 and <= 255\n");
1789
        exit(1);
1790
    }
1791
}
1792

    
1793
static void opt_qmin(const char *arg)
1794
{
1795
    video_qmin = atoi(arg);
1796
    if (video_qmin < 0 ||
1797
        video_qmin > 31) {
1798
        fprintf(stderr, "qmin must be >= 1 and <= 31\n");
1799
        exit(1);
1800
    }
1801
}
1802

    
1803
static void opt_qmax(const char *arg)
1804
{
1805
    video_qmax = atoi(arg);
1806
    if (video_qmax < 0 ||
1807
        video_qmax > 31) {
1808
        fprintf(stderr, "qmax must be >= 1 and <= 31\n");
1809
        exit(1);
1810
    }
1811
}
1812

    
1813
static void opt_mb_qmin(const char *arg)
1814
{
1815
    video_mb_qmin = atoi(arg);
1816
    if (video_mb_qmin < 0 ||
1817
        video_mb_qmin > 31) {
1818
        fprintf(stderr, "qmin must be >= 1 and <= 31\n");
1819
        exit(1);
1820
    }
1821
}
1822

    
1823
static void opt_mb_qmax(const char *arg)
1824
{
1825
    video_mb_qmax = atoi(arg);
1826
    if (video_mb_qmax < 0 ||
1827
        video_mb_qmax > 31) {
1828
        fprintf(stderr, "qmax must be >= 1 and <= 31\n");
1829
        exit(1);
1830
    }
1831
}
1832

    
1833
static void opt_qdiff(const char *arg)
1834
{
1835
    video_qdiff = atoi(arg);
1836
    if (video_qdiff < 0 ||
1837
        video_qdiff > 31) {
1838
        fprintf(stderr, "qdiff must be >= 1 and <= 31\n");
1839
        exit(1);
1840
    }
1841
}
1842

    
1843
static void opt_qblur(const char *arg)
1844
{
1845
    video_qblur = atof(arg);
1846
}
1847

    
1848
static void opt_qcomp(const char *arg)
1849
{
1850
    video_qcomp = atof(arg);
1851
}
1852

    
1853
static void opt_rc_initial_cplx(const char *arg)
1854
{
1855
    video_rc_initial_cplx = atof(arg);
1856
}
1857
static void opt_b_qfactor(const char *arg)
1858
{
1859
    video_b_qfactor = atof(arg);
1860
}
1861
static void opt_i_qfactor(const char *arg)
1862
{
1863
    video_i_qfactor = atof(arg);
1864
}
1865
static void opt_b_qoffset(const char *arg)
1866
{
1867
    video_b_qoffset = atof(arg);
1868
}
1869
static void opt_i_qoffset(const char *arg)
1870
{
1871
    video_i_qoffset = atof(arg);
1872
}
1873

    
1874
static void opt_packet_size(const char *arg)
1875
{
1876
    packet_size= atoi(arg);
1877
}
1878

    
1879
static void opt_error_rate(const char *arg)
1880
{
1881
    error_rate= atoi(arg);
1882
}
1883

    
1884
static void opt_strict(const char *arg)
1885
{
1886
    strict= atoi(arg);
1887
}
1888

    
1889
static void opt_audio_bitrate(const char *arg)
1890
{
1891
    audio_bit_rate = atoi(arg) * 1000;
1892
}
1893

    
1894
static void opt_audio_rate(const char *arg)
1895
{
1896
    audio_sample_rate = atoi(arg);
1897
}
1898

    
1899
static void opt_audio_channels(const char *arg)
1900
{
1901
    audio_channels = atoi(arg);
1902
}
1903

    
1904
static void opt_video_device(const char *arg)
1905
{
1906
    video_device = av_strdup(arg);
1907
}
1908

    
1909
static void opt_video_channel(const char *arg)
1910
{
1911
    video_channel = strtol(arg, NULL, 0);
1912
}
1913

    
1914
static void opt_video_standard(const char *arg)
1915
{
1916
    video_standard = av_strdup(arg);
1917
}
1918

    
1919
static void opt_audio_device(const char *arg)
1920
{
1921
    audio_device = av_strdup(arg);
1922
}
1923

    
1924
static void opt_dv1394(const char *arg)
1925
{
1926
    video_grab_format = "dv1394";
1927
    audio_grab_format = NULL;
1928
}
1929

    
1930
static void opt_audio_codec(const char *arg)
1931
{
1932
    AVCodec *p;
1933

    
1934
    if (!strcmp(arg, "copy")) {
1935
        audio_stream_copy = 1;
1936
    } else {
1937
        p = first_avcodec;
1938
        while (p) {
1939
            if (!strcmp(p->name, arg) && p->type == CODEC_TYPE_AUDIO)
1940
                break;
1941
            p = p->next;
1942
        }
1943
        if (p == NULL) {
1944
            fprintf(stderr, "Unknown audio codec '%s'\n", arg);
1945
            exit(1);
1946
        } else {
1947
            audio_codec_id = p->id;
1948
        }
1949
    }
1950
}
1951

    
1952
static void add_frame_hooker(const char *arg)
1953
{
1954
    int argc = 0;
1955
    char *argv[64];
1956
    int i;
1957
    char *args = av_strdup(arg);
1958

    
1959
    using_vhook = 1;
1960

    
1961
    argv[0] = strtok(args, " ");
1962
    while (argc < 62 && (argv[++argc] = strtok(NULL, " "))) {
1963
    }
1964

    
1965
    i = frame_hook_add(argc, argv);
1966

    
1967
    if (i != 0) {
1968
        fprintf(stderr, "Failed to add video hook function: %s\n", arg);
1969
        exit(1);
1970
    }
1971
}
1972

    
1973
const char *motion_str[] = {
1974
    "zero",
1975
    "full",
1976
    "log",
1977
    "phods",
1978
    "epzs",
1979
    "x1",
1980
    NULL,
1981
};
1982

    
1983
static void opt_motion_estimation(const char *arg)
1984
{
1985
    const char **p;
1986
    p = motion_str;
1987
    for(;;) {
1988
        if (!*p) {
1989
            fprintf(stderr, "Unknown motion estimation method '%s'\n", arg);
1990
            exit(1);
1991
        }
1992
        if (!strcmp(*p, arg))
1993
            break;
1994
        p++;
1995
    }
1996
    me_method = (p - motion_str) + 1;
1997
}
1998

    
1999
static void opt_video_codec(const char *arg)
2000
{
2001
    AVCodec *p;
2002

    
2003
    if (!strcmp(arg, "copy")) {
2004
        video_stream_copy = 1;
2005
    } else {
2006
        p = first_avcodec;
2007
        while (p) {
2008
            if (!strcmp(p->name, arg) && p->type == CODEC_TYPE_VIDEO)
2009
                break;
2010
            p = p->next;
2011
        }
2012
        if (p == NULL) {
2013
            fprintf(stderr, "Unknown video codec '%s'\n", arg);
2014
            exit(1);
2015
        } else {
2016
            video_codec_id = p->id;
2017
        }
2018
    }
2019
}
2020

    
2021
static void opt_map(const char *arg)
2022
{
2023
    AVStreamMap *m;
2024
    const char *p;
2025

    
2026
    p = arg;
2027
    m = &stream_maps[nb_stream_maps++];
2028

    
2029
    m->file_index = strtol(arg, (char **)&p, 0);
2030
    if (*p)
2031
        p++;
2032

    
2033
    m->stream_index = strtol(p, (char **)&p, 0);
2034
}
2035

    
2036
static void opt_recording_time(const char *arg)
2037
{
2038
    recording_time = parse_date(arg, 1);
2039
}
2040

    
2041
static void opt_start_time(const char *arg)
2042
{
2043
    start_time = parse_date(arg, 1);
2044
}
2045

    
2046
static void opt_input_file(const char *filename)
2047
{
2048
    AVFormatContext *ic;
2049
    AVFormatParameters params, *ap = &params;
2050
    int err, i, ret, rfps, rfps_base;
2051

    
2052
    if (!strcmp(filename, "-"))
2053
        filename = "pipe:";
2054

    
2055
    using_stdin |= !strcmp(filename, "pipe:" ) || 
2056
                   !strcmp( filename, "/dev/stdin" );
2057

    
2058
    /* get default parameters from command line */
2059
    memset(ap, 0, sizeof(*ap));
2060
    ap->sample_rate = audio_sample_rate;
2061
    ap->channels = audio_channels;
2062
    ap->frame_rate = frame_rate;
2063
    ap->frame_rate_base = frame_rate_base;
2064
    ap->width = frame_width;
2065
    ap->height = frame_height;
2066
    ap->image_format = image_format;
2067
    ap->pix_fmt = frame_pix_fmt;
2068

    
2069
    /* open the input file with generic libav function */
2070
    err = av_open_input_file(&ic, filename, file_iformat, 0, ap);
2071
    if (err < 0) {
2072
        print_error(filename, err);
2073
        exit(1);
2074
    }
2075
    
2076
    /* If not enough info to get the stream parameters, we decode the
2077
       first frames to get it. (used in mpeg case for example) */
2078
    ret = av_find_stream_info(ic);
2079
    if (ret < 0) {
2080
        fprintf(stderr, "%s: could not find codec parameters\n", filename);
2081
        exit(1);
2082
    }
2083

    
2084
    /* if seeking requested, we execute it */
2085
    if (start_time != 0) {
2086
        int64_t timestamp;
2087

    
2088
        timestamp = start_time;
2089
        /* add the stream start time */
2090
        if (ic->start_time != AV_NOPTS_VALUE)
2091
            timestamp += ic->start_time;
2092
        ret = av_seek_frame(ic, -1, timestamp);
2093
        if (ret < 0) {
2094
            fprintf(stderr, "%s: could not seek to position %0.3f\n", 
2095
                    filename, (double)timestamp / AV_TIME_BASE);
2096
        }
2097
        /* reset seek info */
2098
        start_time = 0;
2099
    }
2100

    
2101
    /* update the current parameters so that they match the one of the input stream */
2102
    for(i=0;i<ic->nb_streams;i++) {
2103
        AVCodecContext *enc = &ic->streams[i]->codec;
2104
        switch(enc->codec_type) {
2105
        case CODEC_TYPE_AUDIO:
2106
            //fprintf(stderr, "\nInput Audio channels: %d", enc->channels);
2107
            audio_channels = enc->channels;
2108
            audio_sample_rate = enc->sample_rate;
2109
            break;
2110
        case CODEC_TYPE_VIDEO:
2111
            frame_height = enc->height;
2112
            frame_width = enc->width;
2113
            frame_aspect_ratio = av_q2d(enc->sample_aspect_ratio) * enc->width / enc->height;
2114
            frame_pix_fmt = enc->pix_fmt;
2115
            rfps      = ic->streams[i]->r_frame_rate;
2116
            rfps_base = ic->streams[i]->r_frame_rate_base;
2117
            enc->workaround_bugs = workaround_bugs;
2118
            enc->error_resilience = error_resilience; 
2119
            enc->error_concealment = error_concealment; 
2120
            enc->idct_algo= idct_algo;
2121
            enc->debug= debug;
2122
            if(bitexact)
2123
                enc->flags|= CODEC_FLAG_BITEXACT;
2124

    
2125
            assert(enc->frame_rate_base == rfps_base); // should be true for now
2126
            if (enc->frame_rate != rfps) { 
2127
                fprintf(stderr,"\nSeems that stream %d comes from film source: %2.2f->%2.2f\n",
2128
                    i, (float)enc->frame_rate / enc->frame_rate_base,
2129
                    (float)rfps / rfps_base);
2130
            }
2131
            /* update the current frame rate to match the stream frame rate */
2132
            frame_rate      = rfps;
2133
            frame_rate_base = rfps_base;
2134

    
2135
            enc->rate_emu = rate_emu;
2136
            break;
2137
        case CODEC_TYPE_DATA:
2138
            break;
2139
        default:
2140
            av_abort();
2141
        }
2142
    }
2143
    
2144
    input_files[nb_input_files] = ic;
2145
    /* dump the file content */
2146
    dump_format(ic, nb_input_files, filename, 0);
2147
    nb_input_files++;
2148
    file_iformat = NULL;
2149
    file_oformat = NULL;
2150
    image_format = NULL;
2151

    
2152
    rate_emu = 0;
2153
}
2154

    
2155
static void check_audio_video_inputs(int *has_video_ptr, int *has_audio_ptr)
2156
{
2157
    int has_video, has_audio, i, j;
2158
    AVFormatContext *ic;
2159

    
2160
    has_video = 0;
2161
    has_audio = 0;
2162
    for(j=0;j<nb_input_files;j++) {
2163
        ic = input_files[j];
2164
        for(i=0;i<ic->nb_streams;i++) {
2165
            AVCodecContext *enc = &ic->streams[i]->codec;
2166
            switch(enc->codec_type) {
2167
            case CODEC_TYPE_AUDIO:
2168
                has_audio = 1;
2169
                break;
2170
            case CODEC_TYPE_VIDEO:
2171
                has_video = 1;
2172
                break;
2173
            default:
2174
                av_abort();
2175
            }
2176
        }
2177
    }
2178
    *has_video_ptr = has_video;
2179
    *has_audio_ptr = has_audio;
2180
}
2181

    
2182
static void opt_output_file(const char *filename)
2183
{
2184
    AVStream *st;
2185
    AVFormatContext *oc;
2186
    int use_video, use_audio, nb_streams, input_has_video, input_has_audio;
2187
    int codec_id;
2188
    AVFormatParameters params, *ap = &params;
2189

    
2190
    if (!strcmp(filename, "-"))
2191
        filename = "pipe:";
2192

    
2193
    oc = av_mallocz(sizeof(AVFormatContext));
2194

    
2195
    if (!file_oformat) {
2196
        file_oformat = guess_format(NULL, filename, NULL);
2197
        if (!file_oformat) {
2198
            fprintf(stderr, "Unable for find a suitable output format for '%s'\n",
2199
                    filename);
2200
            exit(1);
2201
        }
2202
    }
2203
    
2204
    oc->oformat = file_oformat;
2205

    
2206
    if (!strcmp(file_oformat->name, "ffm") && 
2207
        strstart(filename, "http:", NULL)) {
2208
        /* special case for files sent to ffserver: we get the stream
2209
           parameters from ffserver */
2210
        if (read_ffserver_streams(oc, filename) < 0) {
2211
            fprintf(stderr, "Could not read stream parameters from '%s'\n", filename);
2212
            exit(1);
2213
        }
2214
    } else {
2215
        use_video = file_oformat->video_codec != CODEC_ID_NONE;
2216
        use_audio = file_oformat->audio_codec != CODEC_ID_NONE;
2217

    
2218
        /* disable if no corresponding type found and at least one
2219
           input file */
2220
        if (nb_input_files > 0) {
2221
            check_audio_video_inputs(&input_has_video, &input_has_audio);
2222
            if (!input_has_video)
2223
                use_video = 0;
2224
            if (!input_has_audio)
2225
                use_audio = 0;
2226
        }
2227

    
2228
        /* manual disable */
2229
        if (audio_disable) {
2230
            use_audio = 0;
2231
        }
2232
        if (video_disable) {
2233
            use_video = 0;
2234
        }
2235
        
2236
        nb_streams = 0;
2237
        if (use_video) {
2238
            AVCodecContext *video_enc;
2239
            
2240
            st = av_mallocz(sizeof(AVStream));
2241
            if (!st) {
2242
                fprintf(stderr, "Could not alloc stream\n");
2243
                exit(1);
2244
            }
2245
            avcodec_get_context_defaults(&st->codec);
2246

    
2247
            video_enc = &st->codec;
2248
            
2249
            if(!strcmp(file_oformat->name, "mp4") || !strcmp(file_oformat->name, "mov") || !strcmp(file_oformat->name, "3gp"))
2250
                video_enc->flags |= CODEC_FLAG_GLOBAL_HEADER;
2251
            if (video_stream_copy) {
2252
                st->stream_copy = 1;
2253
                video_enc->codec_type = CODEC_TYPE_VIDEO;
2254
            } else {
2255
                char *p;
2256
                int i;
2257
            
2258
                codec_id = file_oformat->video_codec;
2259
                if (video_codec_id != CODEC_ID_NONE)
2260
                    codec_id = video_codec_id;
2261
                
2262
                video_enc->codec_id = codec_id;
2263
                
2264
                video_enc->bit_rate = video_bit_rate;
2265
                video_enc->bit_rate_tolerance = video_bit_rate_tolerance;
2266
                video_enc->frame_rate = frame_rate; 
2267
                video_enc->frame_rate_base = frame_rate_base; 
2268
                
2269
                video_enc->width = frame_width;
2270
                video_enc->height = frame_height;
2271
                video_enc->sample_aspect_ratio = av_d2q(frame_aspect_ratio*frame_height/frame_width, 255);
2272
                video_enc->pix_fmt = frame_pix_fmt;
2273

    
2274
                if (!intra_only)
2275
                    video_enc->gop_size = gop_size;
2276
                else
2277
                    video_enc->gop_size = 0;
2278
                if (video_qscale || same_quality) {
2279
                    video_enc->flags |= CODEC_FLAG_QSCALE;
2280
                    st->quality = FF_QP2LAMBDA * video_qscale;
2281
                }
2282

    
2283
                if(intra_matrix)
2284
                    video_enc->intra_matrix = intra_matrix;
2285
                if(inter_matrix)
2286
                    video_enc->inter_matrix = inter_matrix;
2287

    
2288
                if(bitexact)
2289
                    video_enc->flags |= CODEC_FLAG_BITEXACT;
2290

    
2291
                video_enc->mb_decision = mb_decision;
2292
                video_enc->mb_cmp = mb_cmp;
2293
                video_enc->me_sub_cmp = sub_cmp;
2294
                video_enc->me_cmp = cmp;
2295
                
2296
                if (use_umv) {
2297
                    video_enc->flags |= CODEC_FLAG_H263P_UMV;
2298
                }
2299
                   if (use_aic) {
2300
                    video_enc->flags |= CODEC_FLAG_H263P_AIC;
2301
                }
2302
                   if (use_aiv) {
2303
                    video_enc->flags |= CODEC_FLAG_H263P_AIV;
2304
                }
2305
                if (use_4mv) {
2306
                    video_enc->flags |= CODEC_FLAG_4MV;
2307
                }
2308
                if (use_obmc) {
2309
                    video_enc->flags |= CODEC_FLAG_OBMC;
2310
                }
2311
            
2312
                if(use_part) {
2313
                    video_enc->flags |= CODEC_FLAG_PART;
2314
                }
2315
                if (b_frames) {
2316
                    video_enc->max_b_frames = b_frames;
2317
                    video_enc->b_frame_strategy = 0;
2318
                    video_enc->b_quant_factor = 2.0;
2319
                }
2320
                if (do_interlace) {
2321
                    video_enc->flags |= CODEC_FLAG_INTERLACED_DCT;
2322
                }
2323
                video_enc->qmin = video_qmin;
2324
                video_enc->qmax = video_qmax;
2325
                video_enc->mb_qmin = video_mb_qmin;
2326
                video_enc->mb_qmax = video_mb_qmax;
2327
                video_enc->max_qdiff = video_qdiff;
2328
                video_enc->qblur = video_qblur;
2329
                video_enc->qcompress = video_qcomp;
2330
                video_enc->rc_eq = video_rc_eq;
2331
                video_enc->debug= debug;
2332
                
2333
                p= video_rc_override_string;
2334
                for(i=0; p; i++){
2335
                    int start, end, q;
2336
                    int e=sscanf(p, "%d,%d,%d", &start, &end, &q);
2337
                    if(e!=3){
2338
                        fprintf(stderr, "error parsing rc_override\n");
2339
                        exit(1);
2340
                    }
2341
                    video_enc->rc_override= 
2342
                        av_realloc(video_enc->rc_override, 
2343
                                   sizeof(RcOverride)*(i+1));
2344
                    video_enc->rc_override[i].start_frame= start;
2345
                    video_enc->rc_override[i].end_frame  = end;
2346
                    if(q>0){
2347
                        video_enc->rc_override[i].qscale= q;
2348
                        video_enc->rc_override[i].quality_factor= 1.0;
2349
                    }
2350
                    else{
2351
                        video_enc->rc_override[i].qscale= 0;
2352
                        video_enc->rc_override[i].quality_factor= -q/100.0;
2353
                    }
2354
                    p= strchr(p, '/');
2355
                    if(p) p++;
2356
                }
2357
                video_enc->rc_override_count=i;
2358

    
2359
                video_enc->rc_max_rate = video_rc_max_rate;
2360
                video_enc->rc_min_rate = video_rc_min_rate;
2361
                video_enc->rc_buffer_size = video_rc_buffer_size;
2362
                video_enc->rc_buffer_aggressivity= video_rc_buffer_aggressivity;
2363
                video_enc->rc_initial_cplx= video_rc_initial_cplx;
2364
                video_enc->i_quant_factor = video_i_qfactor;
2365
                video_enc->b_quant_factor = video_b_qfactor;
2366
                video_enc->i_quant_offset = video_i_qoffset;
2367
                video_enc->b_quant_offset = video_b_qoffset;
2368
                video_enc->dct_algo = dct_algo;
2369
                video_enc->idct_algo = idct_algo;
2370
                video_enc->strict_std_compliance = strict;
2371
                video_enc->error_rate = error_rate;
2372
                if(packet_size){
2373
                    video_enc->rtp_mode= 1;
2374
                    video_enc->rtp_payload_size= packet_size;
2375
                }
2376
            
2377
                if (do_psnr)
2378
                    video_enc->flags|= CODEC_FLAG_PSNR;
2379
            
2380
                video_enc->me_method = me_method;
2381

    
2382
                /* two pass mode */
2383
                if (do_pass) {
2384
                    if (do_pass == 1) {
2385
                        video_enc->flags |= CODEC_FLAG_PASS1;
2386
                    } else {
2387
                        video_enc->flags |= CODEC_FLAG_PASS2;
2388
                    }
2389
                }
2390
            }
2391
            oc->streams[nb_streams] = st;
2392
            nb_streams++;
2393
        }
2394
    
2395
        if (use_audio) {
2396
            AVCodecContext *audio_enc;
2397

    
2398
            st = av_mallocz(sizeof(AVStream));
2399
            if (!st) {
2400
                fprintf(stderr, "Could not alloc stream\n");
2401
                exit(1);
2402
            }
2403
            avcodec_get_context_defaults(&st->codec);
2404

    
2405
            audio_enc = &st->codec;
2406
            audio_enc->codec_type = CODEC_TYPE_AUDIO;
2407

    
2408
            if(!strcmp(file_oformat->name, "mp4") || !strcmp(file_oformat->name, "mov") || !strcmp(file_oformat->name, "3gp"))
2409
                audio_enc->flags |= CODEC_FLAG_GLOBAL_HEADER;
2410
            if (audio_stream_copy) {
2411
                st->stream_copy = 1;
2412
            } else {
2413
                codec_id = file_oformat->audio_codec;
2414
                if (audio_codec_id != CODEC_ID_NONE)
2415
                    codec_id = audio_codec_id;
2416
                audio_enc->codec_id = codec_id;
2417
                
2418
                audio_enc->bit_rate = audio_bit_rate;
2419
                audio_enc->sample_rate = audio_sample_rate;
2420
                /* For audio codecs other than AC3 we limit */
2421
                /* the number of coded channels to stereo   */
2422
                if (audio_channels > 2 && codec_id != CODEC_ID_AC3) {
2423
                    audio_enc->channels = 2;
2424
                } else
2425
                    audio_enc->channels = audio_channels;
2426
            }
2427
            oc->streams[nb_streams] = st;
2428
            nb_streams++;
2429
        }
2430

    
2431
        oc->nb_streams = nb_streams;
2432

    
2433
        if (!nb_streams) {
2434
            fprintf(stderr, "No audio or video streams available\n");
2435
            exit(1);
2436
        }
2437

    
2438
        if (str_title)
2439
            pstrcpy(oc->title, sizeof(oc->title), str_title);
2440
        if (str_author)
2441
            pstrcpy(oc->author, sizeof(oc->author), str_author);
2442
        if (str_copyright)
2443
            pstrcpy(oc->copyright, sizeof(oc->copyright), str_copyright);
2444
        if (str_comment)
2445
            pstrcpy(oc->comment, sizeof(oc->comment), str_comment);
2446
    }
2447

    
2448
    output_files[nb_output_files++] = oc;
2449

    
2450
    strcpy(oc->filename, filename);
2451

    
2452
    /* check filename in case of an image number is expected */
2453
    if (oc->oformat->flags & AVFMT_NEEDNUMBER) {
2454
        if (filename_number_test(oc->filename) < 0) {
2455
            print_error(oc->filename, AVERROR_NUMEXPECTED);
2456
            exit(1);
2457
        }
2458
    }
2459

    
2460
    if (!(oc->oformat->flags & AVFMT_NOFILE)) {
2461
        /* test if it already exists to avoid loosing precious files */
2462
        if (!file_overwrite && 
2463
            (strchr(filename, ':') == NULL ||
2464
             strstart(filename, "file:", NULL))) {
2465
            if (url_exist(filename)) {
2466
                int c;
2467
                
2468
                if ( !using_stdin ) {
2469
                    fprintf(stderr,"File '%s' already exists. Overwrite ? [y/N] ", filename);
2470
                    fflush(stderr);
2471
                    c = getchar();
2472
                    if (toupper(c) != 'Y') {
2473
                        fprintf(stderr, "Not overwriting - exiting\n");
2474
                        exit(1);
2475
                    }
2476
                                }
2477
                                else {
2478
                    fprintf(stderr,"File '%s' already exists. Exiting.\n", filename);
2479
                    exit(1);
2480
                                }
2481
            }
2482
        }
2483
        
2484
        /* open the file */
2485
        if (url_fopen(&oc->pb, filename, URL_WRONLY) < 0) {
2486
            fprintf(stderr, "Could not open '%s'\n", filename);
2487
            exit(1);
2488
        }
2489
    }
2490

    
2491
    memset(ap, 0, sizeof(*ap));
2492
    ap->image_format = image_format;
2493
    if (av_set_parameters(oc, ap) < 0) {
2494
        fprintf(stderr, "%s: Invalid encoding parameters\n",
2495
                oc->filename);
2496
        exit(1);
2497
    }
2498

    
2499
    /* reset some options */
2500
    file_oformat = NULL;
2501
    file_iformat = NULL;
2502
    image_format = NULL;
2503
    audio_disable = 0;
2504
    video_disable = 0;
2505
    audio_codec_id = CODEC_ID_NONE;
2506
    video_codec_id = CODEC_ID_NONE;
2507
    audio_stream_copy = 0;
2508
    video_stream_copy = 0;
2509
}
2510

    
2511
/* prepare dummy protocols for grab */
2512
static void prepare_grab(void)
2513
{
2514
    int has_video, has_audio, i, j;
2515
    AVFormatContext *oc;
2516
    AVFormatContext *ic;
2517
    AVFormatParameters vp1, *vp = &vp1;
2518
    AVFormatParameters ap1, *ap = &ap1;
2519
    
2520
    /* see if audio/video inputs are needed */
2521
    has_video = 0;
2522
    has_audio = 0;
2523
    memset(ap, 0, sizeof(*ap));
2524
    memset(vp, 0, sizeof(*vp));
2525
    for(j=0;j<nb_output_files;j++) {
2526
        oc = output_files[j];
2527
        for(i=0;i<oc->nb_streams;i++) {
2528
            AVCodecContext *enc = &oc->streams[i]->codec;
2529
            switch(enc->codec_type) {
2530
            case CODEC_TYPE_AUDIO:
2531
                if (enc->sample_rate > ap->sample_rate)
2532
                    ap->sample_rate = enc->sample_rate;
2533
                if (enc->channels > ap->channels)
2534
                    ap->channels = enc->channels;
2535
                has_audio = 1;
2536
                break;
2537
            case CODEC_TYPE_VIDEO:
2538
                if (enc->width > vp->width)
2539
                    vp->width = enc->width;
2540
                if (enc->height > vp->height)
2541
                    vp->height = enc->height;
2542
                
2543
                assert(enc->frame_rate_base == DEFAULT_FRAME_RATE_BASE);
2544
                if (enc->frame_rate > vp->frame_rate){
2545
                    vp->frame_rate      = enc->frame_rate;
2546
                    vp->frame_rate_base = enc->frame_rate_base;
2547
                }
2548
                has_video = 1;
2549
                break;
2550
            default:
2551
                av_abort();
2552
            }
2553
        }
2554
    }
2555
    
2556
    if (has_video == 0 && has_audio == 0) {
2557
        fprintf(stderr, "Output file must have at least one audio or video stream\n");
2558
        exit(1);
2559
    }
2560
    
2561
    if (has_video) {
2562
        AVInputFormat *fmt1;
2563
        fmt1 = av_find_input_format(video_grab_format);
2564
        vp->device  = video_device;
2565
        vp->channel = video_channel;
2566
        vp->standard = video_standard;
2567
        if (av_open_input_file(&ic, "", fmt1, 0, vp) < 0) {
2568
            fprintf(stderr, "Could not find video grab device\n");
2569
            exit(1);
2570
        }
2571
        /* If not enough info to get the stream parameters, we decode the
2572
           first frames to get it. */
2573
        if ((ic->ctx_flags & AVFMTCTX_NOHEADER) && av_find_stream_info(ic) < 0) {
2574
            fprintf(stderr, "Could not find video grab parameters\n");
2575
            exit(1);
2576
        }
2577
        /* by now video grab has one stream */
2578
        ic->streams[0]->r_frame_rate      = vp->frame_rate;
2579
        ic->streams[0]->r_frame_rate_base = vp->frame_rate_base;
2580
        input_files[nb_input_files] = ic;
2581
        dump_format(ic, nb_input_files, "", 0);
2582
        nb_input_files++;
2583
    }
2584
    if (has_audio && audio_grab_format) {
2585
        AVInputFormat *fmt1;
2586
        fmt1 = av_find_input_format(audio_grab_format);
2587
        ap->device = audio_device;
2588
        if (av_open_input_file(&ic, "", fmt1, 0, ap) < 0) {
2589
            fprintf(stderr, "Could not find audio grab device\n");
2590
            exit(1);
2591
        }
2592
        input_files[nb_input_files] = ic;
2593
        dump_format(ic, nb_input_files, "", 0);
2594
        nb_input_files++;
2595
    }
2596
}
2597

    
2598
/* same option as mencoder */
2599
static void opt_pass(const char *pass_str)
2600
{
2601
    int pass;
2602
    pass = atoi(pass_str);
2603
    if (pass != 1 && pass != 2) {
2604
        fprintf(stderr, "pass number can be only 1 or 2\n");
2605
        exit(1);
2606
    }
2607
    do_pass = pass;
2608
}
2609

    
2610
#if defined(CONFIG_WIN32) || defined(CONFIG_OS2)
2611
static int64_t getutime(void)
2612
{
2613
  return av_gettime();
2614
}
2615
#else
2616
static int64_t getutime(void)
2617
{
2618
    struct rusage rusage;
2619

    
2620
    getrusage(RUSAGE_SELF, &rusage);
2621
    return (rusage.ru_utime.tv_sec * 1000000LL) + rusage.ru_utime.tv_usec;
2622
}
2623
#endif
2624

    
2625
extern int ffm_nopts;
2626

    
2627
static void opt_bitexact(void)
2628
{
2629
    bitexact=1;
2630
    /* disable generate of real time pts in ffm (need to be supressed anyway) */
2631
    ffm_nopts = 1;
2632
}
2633

    
2634
static void show_formats(void)
2635
{
2636
    AVInputFormat *ifmt;
2637
    AVOutputFormat *ofmt;
2638
    AVImageFormat *image_fmt;
2639
    URLProtocol *up;
2640
    AVCodec *p;
2641
    const char **pp;
2642

    
2643
    printf("Output audio/video file formats:");
2644
    for(ofmt = first_oformat; ofmt != NULL; ofmt = ofmt->next) {
2645
        printf(" %s", ofmt->name);
2646
    }
2647
    printf("\n");
2648

    
2649
    printf("Input audio/video file formats:");
2650
    for(ifmt = first_iformat; ifmt != NULL; ifmt = ifmt->next) {
2651
        printf(" %s", ifmt->name);
2652
    }
2653
    printf("\n");
2654

    
2655
    printf("Output image formats:");
2656
    for(image_fmt = first_image_format; image_fmt != NULL; 
2657
        image_fmt = image_fmt->next) {
2658
        if (image_fmt->img_write)
2659
            printf(" %s", image_fmt->name);
2660
    }
2661
    printf("\n");
2662

    
2663
    printf("Input image formats:");
2664
    for(image_fmt = first_image_format; image_fmt != NULL; 
2665
        image_fmt = image_fmt->next) {
2666
        if (image_fmt->img_read)
2667
            printf(" %s", image_fmt->name);
2668
    }
2669
    printf("\n");
2670

    
2671
    printf("Codecs:\n");
2672
    printf("  Encoders:");
2673
    for(p = first_avcodec; p != NULL; p = p->next) {
2674
        if (p->encode)
2675
            printf(" %s", p->name);
2676
    }
2677
    printf("\n");
2678

    
2679
    printf("  Decoders:");
2680
    for(p = first_avcodec; p != NULL; p = p->next) {
2681
        if (p->decode)
2682
            printf(" %s", p->name);
2683
    }
2684
    printf("\n");
2685

    
2686
    printf("Supported file protocols:");
2687
    for(up = first_protocol; up != NULL; up = up->next)
2688
        printf(" %s:", up->name);
2689
    printf("\n");
2690
    
2691
    printf("Frame size, frame rate abbreviations: ntsc pal qntsc qpal sntsc spal film ntsc-film sqcif qcif cif 4cif\n");
2692
    printf("Motion estimation methods:");
2693
    pp = motion_str;
2694
    while (*pp) {
2695
        printf(" %s", *pp);
2696
        if ((pp - motion_str + 1) == ME_ZERO) 
2697
            printf("(fastest)");
2698
        else if ((pp - motion_str + 1) == ME_FULL) 
2699
            printf("(slowest)");
2700
        else if ((pp - motion_str + 1) == ME_EPZS) 
2701
            printf("(default)");
2702
        pp++;
2703
    }
2704
    printf("\n");
2705
    exit(1);
2706
}
2707

    
2708
void parse_matrix_coeffs(uint16_t *dest, const char *str)
2709
{
2710
    int i;
2711
    const char *p = str;
2712
    for(i = 0;; i++) {
2713
        dest[i] = atoi(p);
2714
        if(i == 63)
2715
            break;
2716
        p = strchr(p, ',');
2717
        if(!p) {
2718
            fprintf(stderr, "Syntax error in matrix \"%s\" at coeff %d\n", str, i);
2719
            exit(1);
2720
        }
2721
        p++;
2722
    }
2723
}
2724

    
2725
void opt_inter_matrix(const char *arg)
2726
{
2727
    inter_matrix = av_mallocz(sizeof(uint16_t) * 64);
2728
    parse_matrix_coeffs(inter_matrix, arg);
2729
}
2730

    
2731
void opt_intra_matrix(const char *arg)
2732
{
2733
    intra_matrix = av_mallocz(sizeof(uint16_t) * 64);
2734
    parse_matrix_coeffs(intra_matrix, arg);
2735
}
2736

    
2737
static void opt_target(const char *arg)
2738
{
2739
    int norm = -1;
2740

    
2741
    if(!strncmp(arg, "pal-", 4)) {
2742
        norm = 0;
2743
        arg += 4;
2744
    } else if(!strncmp(arg, "ntsc-", 5)) {
2745
        norm = 1;
2746
        arg += 5;
2747
    } else {
2748
        int fr;
2749
        /* Calculate FR via float to avoid int overflow */
2750
        fr = (int)(frame_rate * 1000.0 / frame_rate_base);
2751
        if(fr == 25000) {
2752
            norm = 0;
2753
        } else if((fr == 29970) || (fr == 23976)) {
2754
            norm = 1;
2755
        } else {
2756
            /* Try to determine PAL/NTSC by peeking in the input files */
2757
            if(nb_input_files) {
2758
                int i, j;
2759
                for(j = 0; j < nb_input_files; j++) {
2760
                    for(i = 0; i < input_files[j]->nb_streams; i++) {
2761
                        AVCodecContext *c = &input_files[j]->streams[i]->codec;
2762
                        if(c->codec_type != CODEC_TYPE_VIDEO)
2763
                            continue;
2764
                        fr = c->frame_rate * 1000 / c->frame_rate_base;
2765
                        if(fr == 25000) {
2766
                            norm = 0;
2767
                            break;
2768
                        } else if((fr == 29970) || (fr == 23976)) {
2769
                            norm = 1;
2770
                            break;
2771
                        }
2772
                    }
2773
                    if(norm >= 0)
2774
                        break;
2775
                }
2776
            }
2777
        }
2778
        if(verbose && norm >= 0)
2779
            printf("Assuming %s for target.\n", norm ? "NTSC" : "PAL");
2780
    }
2781

    
2782
    if(norm < 0) {
2783
        fprintf(stderr, "Could not determine norm (PAL/NTSC) for target.\n");
2784
        fprintf(stderr, "Please prefix target with \"pal-\" or \"ntsc-\",\n");
2785
        fprintf(stderr, "or set a framerate with \"-r xxx\".\n");
2786
        exit(1);
2787
    }
2788

    
2789
    if(!strcmp(arg, "vcd")) {
2790

    
2791
        opt_video_codec("mpeg1video");
2792
        opt_audio_codec("mp2");
2793
        opt_format("vcd");
2794

    
2795
        opt_frame_size(norm ? "352x240" : "352x288");
2796

    
2797
        video_bit_rate = 1150000;
2798
        video_rc_max_rate = 1150000;
2799
        video_rc_min_rate = 1150000;
2800
        video_rc_buffer_size = 40*1024*8;
2801

    
2802
        audio_bit_rate = 224000;
2803
        audio_sample_rate = 44100;
2804

    
2805
    } else if(!strcmp(arg, "svcd")) {
2806

    
2807
        opt_video_codec("mpeg2video");
2808
        opt_audio_codec("mp2");
2809
        opt_format("vcd");
2810

    
2811
        opt_frame_size(norm ? "480x480" : "480x576");
2812
        opt_gop_size(norm ? "18" : "15");
2813

    
2814
        video_bit_rate = 2040000;
2815
        video_rc_max_rate = 2516000;
2816
        video_rc_min_rate = 1145000;
2817
        video_rc_buffer_size = 224*1024*8;
2818

    
2819
        audio_bit_rate = 224000;
2820
        audio_sample_rate = 44100;
2821

    
2822
    } else if(!strcmp(arg, "dvd")) {
2823

    
2824
        opt_video_codec("mpeg2video");
2825
        opt_audio_codec("ac3");
2826
        opt_format("vob");
2827

    
2828
        opt_frame_size(norm ? "720x480" : "720x576");
2829
        opt_gop_size(norm ? "18" : "15");
2830

    
2831
        video_bit_rate = 6000000;
2832
        video_rc_max_rate = 9000000;
2833
        video_rc_min_rate = 1500000;
2834
        video_rc_buffer_size = 224*1024*8;
2835

    
2836
        audio_bit_rate = 448000;
2837
        audio_sample_rate = 48000;
2838

    
2839
    } else {
2840
        fprintf(stderr, "Unknown target: %s\n", arg);
2841
        exit(1);
2842
    }
2843
}
2844

    
2845
const OptionDef options[] = {
2846
    /* main options */
2847
    { "L", 0, {(void*)show_license}, "show license" },
2848
    { "h", 0, {(void*)show_help}, "show help" },
2849
    { "formats", 0, {(void*)show_formats}, "show available formats, codecs, protocols, ..." },
2850
    { "f", HAS_ARG, {(void*)opt_format}, "force format", "fmt" },
2851
    { "img", HAS_ARG, {(void*)opt_image_format}, "force image format", "img_fmt" },
2852
    { "i", HAS_ARG, {(void*)opt_input_file}, "input file name", "filename" },
2853
    { "y", OPT_BOOL, {(void*)&file_overwrite}, "overwrite output files" },
2854
    { "map", HAS_ARG | OPT_EXPERT, {(void*)opt_map}, "set input stream mapping", "file:stream" },
2855
    { "t", HAS_ARG, {(void*)opt_recording_time}, "set the recording time", "duration" },
2856
    { "ss", HAS_ARG, {(void*)opt_start_time}, "set the start time offset", "time_off" },
2857
    { "title", HAS_ARG | OPT_STRING, {(void*)&str_title}, "set the title", "string" },
2858
    { "author", HAS_ARG | OPT_STRING, {(void*)&str_author}, "set the author", "string" },
2859
    { "copyright", HAS_ARG | OPT_STRING, {(void*)&str_copyright}, "set the copyright", "string" },
2860
    { "comment", HAS_ARG | OPT_STRING, {(void*)&str_comment}, "set the comment", "string" },
2861
    { "debug", HAS_ARG | OPT_EXPERT, {(void*)opt_debug}, "print specific debug info", "" },
2862
    { "benchmark", OPT_BOOL | OPT_EXPERT, {(void*)&do_benchmark}, 
2863
      "add timings for benchmarking" },
2864
    { "dump", OPT_BOOL | OPT_EXPERT, {(void*)&do_pkt_dump}, 
2865
      "dump each input packet" },
2866
    { "hex", OPT_BOOL | OPT_EXPERT, {(void*)&do_hex_dump}, 
2867
      "when dumping packets, also dump the payload" },
2868
    { "bitexact", OPT_EXPERT, {(void*)opt_bitexact}, "only use bit exact algorithms (for codec testing)" }, 
2869
    { "re", OPT_BOOL | OPT_EXPERT, {(void*)&rate_emu}, "read input at native frame rate", "" },
2870
    { "loop", OPT_BOOL | OPT_EXPERT, {(void*)&loop_input}, "loop (current only works with images)" },
2871
    { "v", HAS_ARG, {(void*)opt_verbose}, "control amount of logging", "verbose" },
2872
    { "target", HAS_ARG, {(void*)opt_target}, "specify target file type (\"vcd\", \"svcd\" or \"dvd\")", "type" },
2873

    
2874
    /* video options */
2875
    { "b", HAS_ARG | OPT_VIDEO, {(void*)opt_video_bitrate}, "set video bitrate (in kbit/s)", "bitrate" },
2876
    { "r", HAS_ARG | OPT_VIDEO, {(void*)opt_frame_rate}, "set frame rate (Hz value, fraction or abbreviation)", "rate" },
2877
    { "s", HAS_ARG | OPT_VIDEO, {(void*)opt_frame_size}, "set frame size (WxH or abbreviation)", "size" },
2878
    { "aspect", HAS_ARG | OPT_VIDEO, {(void*)opt_frame_aspect_ratio}, "set aspect ratio (4:3, 16:9 or 1.3333, 1.7777)", "aspect" },
2879
    { "pix_fmt", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_frame_pix_fmt}, "set pixel format", "format" },
2880
    { "croptop", HAS_ARG | OPT_VIDEO, {(void*)opt_frame_crop_top}, "set top crop band size (in pixels)", "size" },
2881
    { "cropbottom", HAS_ARG | OPT_VIDEO, {(void*)opt_frame_crop_bottom}, "set bottom crop band size (in pixels)", "size" },
2882
    { "cropleft", HAS_ARG | OPT_VIDEO, {(void*)opt_frame_crop_left}, "set left crop band size (in pixels)", "size" },
2883
    { "cropright", HAS_ARG | OPT_VIDEO, {(void*)opt_frame_crop_right}, "set right crop band size (in pixels)", "size" },
2884
    { "g", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_gop_size}, "set the group of picture size", "gop_size" },
2885
    { "intra", OPT_BOOL | OPT_EXPERT | OPT_VIDEO, {(void*)&intra_only}, "use only intra frames"},
2886
    { "vn", OPT_BOOL | OPT_VIDEO, {(void*)&video_disable}, "disable video" },
2887
    { "qscale", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_qscale}, "use fixed video quantiser scale (VBR)", "q" },
2888
    { "qmin", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_qmin}, "min video quantiser scale (VBR)", "q" },
2889
    { "qmax", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_qmax}, "max video quantiser scale (VBR)", "q" },
2890
    { "mbqmin", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_mb_qmin}, "min macroblock quantiser scale (VBR)", "q" },
2891
    { "mbqmax", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_mb_qmax}, "max macroblock quantiser scale (VBR)", "q" },
2892
    { "qdiff", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_qdiff}, "max difference between the quantiser scale (VBR)", "q" },
2893
    { "qblur", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_qblur}, "video quantiser scale blur (VBR)", "blur" },
2894
    { "qcomp", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_qcomp}, "video quantiser scale compression (VBR)", "compression" },
2895
    { "rc_init_cplx", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_rc_initial_cplx}, "initial complexity for 1-pass encoding", "complexity" },
2896
    { "b_qfactor", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_b_qfactor}, "qp factor between p and b frames", "factor" },
2897
    { "i_qfactor", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_i_qfactor}, "qp factor between p and i frames", "factor" },
2898
    { "b_qoffset", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_b_qoffset}, "qp offset between p and b frames", "offset" },
2899
    { "i_qoffset", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_i_qoffset}, "qp offset between p and i frames", "offset" },
2900
//    { "b_strategy", HAS_ARG | OPT_EXPERT, {(void*)opt_b_strategy}, "dynamic b frame selection strategy", "strategy" },
2901
    { "rc_eq", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_video_rc_eq}, "set rate control equation", "equation" },
2902
    { "rc_override", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_video_rc_override_string}, "rate control override for specific intervals", "override" },
2903
    { "bt", HAS_ARG | OPT_VIDEO, {(void*)opt_video_bitrate_tolerance}, "set video bitrate tolerance (in kbit/s)", "tolerance" },
2904
    { "maxrate", HAS_ARG | OPT_VIDEO, {(void*)opt_video_bitrate_max}, "set max video bitrate tolerance (in kbit/s)", "bitrate" },
2905
    { "minrate", HAS_ARG | OPT_VIDEO, {(void*)opt_video_bitrate_min}, "set min video bitrate tolerance (in kbit/s)", "bitrate" },
2906
    { "bufsize", HAS_ARG | OPT_VIDEO, {(void*)opt_video_buffer_size}, "set ratecontrol buffere size (in kbit)", "size" },
2907
    { "vcodec", HAS_ARG | OPT_VIDEO, {(void*)opt_video_codec}, "force video codec ('copy' to copy stream)", "codec" },
2908
    { "me", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_motion_estimation}, "set motion estimation method", 
2909
      "method" },
2910
    { "dct_algo", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_dct_algo}, "set dct algo",  "algo" },
2911
    { "idct_algo", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_idct_algo}, "set idct algo",  "algo" },
2912
    { "er", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_error_resilience}, "set error resilience",  "n" },
2913
    { "ec", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_error_concealment}, "set error concealment",  "bit_mask" },
2914
    { "bf", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_b_frames}, "use 'frames' B frames", "frames" },
2915
    { "hq", OPT_BOOL, {(void*)&mb_decision}, "activate high quality settings" },
2916
    { "mbd", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_mb_decision}, "macroblock decision", "mode" },
2917
    { "mbcmp", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_mb_cmp}, "macroblock compare function", "cmp function" },
2918
    { "subcmp", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_sub_cmp}, "subpel compare function", "cmp function" },
2919
    { "cmp", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_cmp}, "fullpel compare function", "cmp function" },
2920
    { "4mv", OPT_BOOL | OPT_EXPERT | OPT_VIDEO, {(void*)&use_4mv}, "use four motion vector by macroblock (MPEG4)" },
2921
    { "obmc", OPT_BOOL | OPT_EXPERT | OPT_VIDEO, {(void*)&use_obmc}, "use overlapped block motion compensation (h263+)" },
2922
    { "part", OPT_BOOL | OPT_EXPERT | OPT_VIDEO, {(void*)&use_part}, "use data partitioning (MPEG4)" },
2923
    { "bug", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_workaround_bugs}, "workaround not auto detected encoder bugs", "param" },
2924
    { "ps", HAS_ARG | OPT_EXPERT, {(void*)opt_packet_size}, "set packet size in bits", "size" },
2925
    { "error", HAS_ARG | OPT_EXPERT, {(void*)opt_error_rate}, "error rate", "rate" },
2926
    { "strict", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_strict}, "how strictly to follow the standarts", "strictness" },
2927
    { "sameq", OPT_BOOL | OPT_VIDEO, {(void*)&same_quality}, 
2928
      "use same video quality as source (implies VBR)" },
2929
    { "pass", HAS_ARG | OPT_VIDEO, {(void*)&opt_pass}, "select the pass number (1 or 2)", "n" },
2930
    { "passlogfile", HAS_ARG | OPT_STRING | OPT_VIDEO, {(void*)&pass_logfilename}, "select two pass log file name", "file" },
2931
    { "deinterlace", OPT_BOOL | OPT_EXPERT | OPT_VIDEO, {(void*)&do_deinterlace}, 
2932
      "deinterlace pictures" },
2933
    { "interlace", OPT_BOOL | OPT_EXPERT | OPT_VIDEO, {(void*)&do_interlace}, 
2934
      "force interlacing support in encoder (MPEG2/MPEG4)" },
2935
    { "psnr", OPT_BOOL | OPT_EXPERT | OPT_VIDEO, {(void*)&do_psnr}, "calculate PSNR of compressed frames" },
2936
    { "vstats", OPT_BOOL | OPT_EXPERT | OPT_VIDEO, {(void*)&do_vstats}, "dump video coding statistics to file" }, 
2937
    { "vhook", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)add_frame_hooker}, "insert video processing module", "module" },
2938
    { "aic", OPT_BOOL | OPT_EXPERT | OPT_VIDEO, {(void*)&use_aic}, "enable Advanced intra coding (h263+)" },
2939
    { "aiv", OPT_BOOL | OPT_EXPERT | OPT_VIDEO, {(void*)&use_aiv}, "enable Alternative inter vlc (h263+)" },
2940
    { "umv", OPT_BOOL | OPT_EXPERT | OPT_VIDEO, {(void*)&use_umv}, "enable Unlimited Motion Vector (h263+)" },
2941
    { "intra_matrix", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_intra_matrix}, "specify intra matrix coeffs", "matrix" },
2942
    { "inter_matrix", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_inter_matrix}, "specify inter matrix coeffs", "matrix" },
2943

    
2944
    /* audio options */
2945
    { "ab", HAS_ARG | OPT_AUDIO, {(void*)opt_audio_bitrate}, "set audio bitrate (in kbit/s)", "bitrate", },
2946
    { "ar", HAS_ARG | OPT_AUDIO, {(void*)opt_audio_rate}, "set audio sampling rate (in Hz)", "rate" },
2947
    { "ac", HAS_ARG | OPT_AUDIO, {(void*)opt_audio_channels}, "set number of audio channels", "channels" },
2948
    { "an", OPT_BOOL | OPT_AUDIO, {(void*)&audio_disable}, "disable audio" },
2949
    { "acodec", HAS_ARG | OPT_AUDIO, {(void*)opt_audio_codec}, "force audio codec ('copy' to copy stream)", "codec" },
2950

    
2951
    /* grab options */
2952
    { "vd", HAS_ARG | OPT_EXPERT | OPT_VIDEO | OPT_GRAB, {(void*)opt_video_device}, "set video grab device", "device" },
2953
    { "vc", HAS_ARG | OPT_EXPERT | OPT_VIDEO | OPT_GRAB, {(void*)opt_video_channel}, "set video grab channel (DV1394 only)", "channel" },
2954
    { "tvstd", HAS_ARG | OPT_EXPERT | OPT_VIDEO | OPT_GRAB, {(void*)opt_video_standard}, "set television standard (NTSC, PAL (SECAM))", "standard" },
2955
    { "dv1394", OPT_EXPERT | OPT_GRAB, {(void*)opt_dv1394}, "set DV1394 grab", "" },
2956
    { "ad", HAS_ARG | OPT_EXPERT | OPT_AUDIO | OPT_GRAB, {(void*)opt_audio_device}, "set audio device", "device" },
2957
    { NULL, },
2958
};
2959

    
2960
static void show_banner(void)
2961
{
2962
    printf("ffmpeg version " FFMPEG_VERSION ", Copyright (c) 2000-2003 Fabrice Bellard\n");
2963
}
2964

    
2965
static void show_license(void)
2966
{
2967
    show_banner();
2968
    printf(
2969
    "This library is free software; you can redistribute it and/or\n"
2970
    "modify it under the terms of the GNU Lesser General Public\n"
2971
    "License as published by the Free Software Foundation; either\n"
2972
    "version 2 of the License, or (at your option) any later version.\n"
2973
    "\n"
2974
    "This library is distributed in the hope that it will be useful,\n"
2975
    "but WITHOUT ANY WARRANTY; without even the implied warranty of\n"
2976
    "MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n"
2977
    "Lesser General Public License for more details.\n"
2978
    "\n"
2979
    "You should have received a copy of the GNU Lesser General Public\n"
2980
    "License along with this library; if not, write to the Free Software\n"
2981
    "Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA\n"
2982
    );
2983
    exit(1);
2984
}
2985

    
2986
static void show_help(void)
2987
{
2988
    show_banner();
2989
    printf("usage: ffmpeg [[options] -i input_file]... {[options] outfile}...\n"
2990
           "Hyper fast Audio and Video encoder\n");
2991
    printf("\n");
2992
    show_help_options(options, "Main options:\n",
2993
                      OPT_EXPERT | OPT_AUDIO | OPT_VIDEO, 0);
2994
    show_help_options(options, "\nVideo options:\n",
2995
                      OPT_EXPERT | OPT_AUDIO | OPT_VIDEO | OPT_GRAB, 
2996
                      OPT_VIDEO);
2997
    show_help_options(options, "\nAdvanced Video options:\n",
2998
                      OPT_EXPERT | OPT_AUDIO | OPT_VIDEO | OPT_GRAB, 
2999
                      OPT_VIDEO | OPT_EXPERT);
3000
    show_help_options(options, "\nAudio options:\n",
3001
                      OPT_EXPERT | OPT_AUDIO | OPT_VIDEO | OPT_GRAB, 
3002
                      OPT_AUDIO);
3003
    show_help_options(options, "\nAdvanced Audio options:\n",
3004
                      OPT_EXPERT | OPT_AUDIO | OPT_VIDEO | OPT_GRAB, 
3005
                      OPT_AUDIO | OPT_EXPERT);
3006
    show_help_options(options, "\nAudio/Video grab options:\n",
3007
                      OPT_GRAB, 
3008
                      OPT_GRAB);
3009
    show_help_options(options, "\nAdvanced options:\n",
3010
                      OPT_EXPERT | OPT_AUDIO | OPT_VIDEO | OPT_GRAB, 
3011
                      OPT_EXPERT);
3012
    exit(1);
3013
}
3014

    
3015
void parse_arg_file(const char *filename)
3016
{
3017
    opt_output_file(filename);
3018
}
3019

    
3020
int main(int argc, char **argv)
3021
{
3022
    int i;
3023
    int64_t ti;
3024

    
3025
    av_register_all();
3026

    
3027
    if (argc <= 1)
3028
        show_help();
3029
    
3030
    /* parse options */
3031
    parse_options(argc, argv, options);
3032

    
3033
    /* file converter / grab */
3034
    if (nb_output_files <= 0) {
3035
        fprintf(stderr, "Must supply at least one output file\n");
3036
        exit(1);
3037
    }
3038
    
3039
    if (nb_input_files == 0) {
3040
        prepare_grab();
3041
    }
3042

    
3043
    ti = getutime();
3044
    av_encode(output_files, nb_output_files, input_files, nb_input_files, 
3045
              stream_maps, nb_stream_maps);
3046
    ti = getutime() - ti;
3047
    if (do_benchmark) {
3048
        printf("bench: utime=%0.3fs\n", ti / 1000000.0);
3049
    }
3050

    
3051
    /* close files */
3052
    for(i=0;i<nb_output_files;i++) {
3053
        /* maybe av_close_output_file ??? */
3054
        AVFormatContext *s = output_files[i];
3055
        int j;
3056
        if (!(s->oformat->flags & AVFMT_NOFILE))
3057
            url_fclose(&s->pb);
3058
        for(j=0;j<s->nb_streams;j++)
3059
            av_free(s->streams[j]);
3060
        av_free(s);
3061
    }
3062
    for(i=0;i<nb_input_files;i++)
3063
        av_close_input_file(input_files[i]);
3064

    
3065
    av_free_static();
3066

    
3067
    if(intra_matrix)
3068
        av_free(intra_matrix);
3069
    if(inter_matrix)
3070
        av_free(inter_matrix);
3071
    
3072
#ifdef POWERPC_PERFORMANCE_REPORT
3073
    extern void powerpc_display_perf_report(void);
3074
    powerpc_display_perf_report();
3075
#endif /* POWERPC_PERFORMANCE_REPORT */
3076

    
3077
#ifndef CONFIG_WIN32
3078
    if (received_sigterm) {
3079
        fprintf(stderr,
3080
            "Received signal %d: terminating.\n",
3081
            (int) received_sigterm);
3082
        exit (255);
3083
    }
3084
#endif
3085
    exit(0); /* not all OS-es handle main() return value */
3086
    return 0;
3087
}