Statistics
| Branch: | Revision:

ffmpeg / ffmpeg.c @ 8bb27bdf

History | View | Annotate | Download (101 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 use_4mv = 0;
115
static int use_obmc = 0;
116
static int use_aic = 0;
117
static int use_aiv = 0;
118
static int use_umv = 0;
119
static int do_deinterlace = 0;
120
static int do_interlace = 0;
121
static int workaround_bugs = FF_BUG_AUTODETECT;
122
static int error_resilience = 2;
123
static int error_concealment = 3;
124
static int dct_algo = 0;
125
static int idct_algo = 0;
126
static int use_part = 0;
127
static int packet_size = 0;
128
static int error_rate = 0;
129
static int strict = 0;
130
static int debug = 0;
131
extern int loop_input; /* currently a hack */
132

    
133
static int gop_size = 12;
134
static int intra_only = 0;
135
static int audio_sample_rate = 44100;
136
static int audio_bit_rate = 64000;
137
static int audio_disable = 0;
138
static int audio_channels = 1;
139
static int audio_codec_id = CODEC_ID_NONE;
140

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

    
159
static int rate_emu = 0;
160

    
161
static char *video_grab_format = "video4linux";
162
static char *video_device = NULL;
163
static int  video_channel = 0;
164
static char *video_standard = "ntsc";
165

    
166
static char *audio_grab_format = "audio_device";
167
static char *audio_device = NULL;
168

    
169
static int using_stdin = 0;
170
static int using_vhook = 0;
171
static int verbose = 1;
172

    
173
#define DEFAULT_PASS_LOGFILENAME "ffmpeg2pass"
174

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

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

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

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

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

    
227
#ifndef CONFIG_WIN32
228

    
229
/* init terminal so that we can grab keys */
230
static struct termios oldtty;
231

    
232
static void term_exit(void)
233
{
234
    tcsetattr (0, TCSANOW, &oldtty);
235
}
236

    
237
static volatile sig_atomic_t received_sigterm = 0;
238

    
239
static void
240
sigterm_handler(int sig)
241
{
242
    received_sigterm = sig;
243
    term_exit();
244
}
245

    
246
static void term_init(void)
247
{
248
    struct termios tty;
249

    
250
    tcgetattr (0, &tty);
251
    oldtty = tty;
252

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

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

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

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

    
296
        return n;
297
    }
298
    return -1;
299
}
300

    
301
#else
302

    
303
static volatile int received_sigterm = 0;
304

    
305
/* no interactive support */
306
static void term_exit(void)
307
{
308
}
309

    
310
static void term_init(void)
311
{
312
}
313

    
314
static int read_key(void)
315
{
316
    return 0;
317
}
318

    
319
#endif
320

    
321
static int read_ffserver_streams(AVFormatContext *s, const char *filename)
322
{
323
    int i, err;
324
    AVFormatContext *ic;
325

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

    
334
        st = av_mallocz(sizeof(AVStream));
335
        memcpy(st, ic->streams[i], sizeof(AVStream));
336
        s->streams[i] = st;
337
    }
338

    
339
    av_close_input_file(ic);
340
    return 0;
341
}
342

    
343
#define MAX_AUDIO_PACKET_SIZE (128 * 1024)
344

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

    
355
    int size_out, frame_bytes, ret;
356
    AVCodecContext *enc;
357

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

    
366
    
367
    enc = &ost->st->codec;
368

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

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

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

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

    
420
    dec = &ist->st->codec;
421

    
422
    /* deinterlace : must be done before any resize */
423
    if (do_deinterlace || using_vhook) {
424
        int size;
425

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

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

    
456
    frame_hook_process(picture2, dec->pix_fmt, dec->width, dec->height);
457

    
458
    if (picture != picture2)
459
        *picture = *picture2;
460
    *bufp = buf;
461
}
462

    
463
/* we begin to correct av delay at this threshold */
464
#define AV_DELAY_MAX 0.100
465

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

    
480
#define VIDEO_BUFFER_SIZE (1024*1024)
481

    
482
    enc = &ost->st->codec;
483
    dec = &ist->st->codec;
484

    
485
    /* by default, we output a single frame */
486
    nb_frames = 1;
487

    
488
    *frame_size = 0;
489

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

    
497
        adelta = audio_sync->sync_ipts - ((double)audio_sync->sync_opts * 
498
            s->pts_num / s->pts_den);
499

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

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

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

    
539
    if (nb_frames <= 0) 
540
        return;
541

    
542
    if (!video_buffer)
543
        video_buffer = av_malloc(VIDEO_BUFFER_SIZE);
544
    if (!video_buffer)
545
        return;
546

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

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

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

    
599
        picture_crop_temp.data[1] = formatted_picture->data[1] +
600
                ((ost->topBand >> 1) * formatted_picture->linesize[1]) +
601
                (ost->leftBand >> 1);
602

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

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

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

    
664
static double psnr(double d){
665
    if(d==0) return INFINITY;
666
    return -10.0*log(d)/log(10.0);
667
}
668

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

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

    
744

    
745
    oc = output_files[0];
746

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

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

    
809
    file_table= (AVInputFile*) av_mallocz(nb_input_files * sizeof(AVInputFile));
810
    if (!file_table)
811
        goto fail;
812

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

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

    
844
            if (ist->st->codec.rate_emu) {
845
                ist->start = av_gettime();
846
                ist->frame = 0;
847
            }
848
        }
849
    }
850

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

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

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

    
943
        codec = &ost->st->codec;
944
        icodec = &ist->st->codec;
945

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

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

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

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

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

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

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

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

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

    
1185
    stream_no_data = 0;
1186
    key = -1;
1187

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

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

    
1230
        /* finish if recording time exhausted */
1231
        if (recording_time > 0 && pts_min >= (recording_time / 1000000.0))
1232
            break;
1233

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

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

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

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

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

    
1340
                ist->frame++;
1341
            }
1342

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

    
1362
                    ost = ost_table[i];
1363
                    if (ost->source_index == ist_index) {
1364
                        os = output_files[ost->file_index];
1365

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

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

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

    
1433
    /* dump report by using the first video and audio streams */
1434
    print_report(output_files, ost_table, nb_ostreams, 1);
1435

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

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

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

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

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

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

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

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

    
1551
static void opt_video_bitrate(const char *arg)
1552
{
1553
    video_bit_rate = atoi(arg) * 1000;
1554
}
1555

    
1556
static void opt_video_bitrate_tolerance(const char *arg)
1557
{
1558
    video_bit_rate_tolerance = atoi(arg) * 1000;
1559
}
1560

    
1561
static void opt_video_bitrate_max(const char *arg)
1562
{
1563
    video_rc_max_rate = atoi(arg) * 1000;
1564
}
1565

    
1566
static void opt_video_bitrate_min(const char *arg)
1567
{
1568
    video_rc_min_rate = atoi(arg) * 1000;
1569
}
1570

    
1571
static void opt_video_buffer_size(const char *arg)
1572
{
1573
    video_rc_buffer_size = atoi(arg) * 1024;
1574
}
1575

    
1576
static void opt_video_rc_eq(char *arg)
1577
{
1578
    video_rc_eq = arg;
1579
}
1580

    
1581
static void opt_video_rc_override_string(char *arg)
1582
{
1583
    video_rc_override_string = arg;
1584
}
1585

    
1586

    
1587
static void opt_workaround_bugs(const char *arg)
1588
{
1589
    workaround_bugs = atoi(arg);
1590
}
1591

    
1592
static void opt_dct_algo(const char *arg)
1593
{
1594
    dct_algo = atoi(arg);
1595
}
1596

    
1597
static void opt_idct_algo(const char *arg)
1598
{
1599
    idct_algo = atoi(arg);
1600
}
1601

    
1602

    
1603
static void opt_error_resilience(const char *arg)
1604
{
1605
    error_resilience = atoi(arg);
1606
}
1607

    
1608
static void opt_error_concealment(const char *arg)
1609
{
1610
    error_concealment = atoi(arg);
1611
}
1612

    
1613
static void opt_debug(const char *arg)
1614
{
1615
    debug = atoi(arg);
1616
}
1617

    
1618
static void opt_verbose(const char *arg)
1619
{
1620
    verbose = atoi(arg);
1621
}
1622

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

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

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

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

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

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

    
1715
static void opt_frame_pix_fmt(const char *arg)
1716
{
1717
    frame_pix_fmt = avcodec_get_pix_fmt(arg);
1718
}
1719

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

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

    
1743
static void opt_gop_size(const char *arg)
1744
{
1745
    gop_size = atoi(arg);
1746
}
1747

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

    
1760
static void opt_mb_decision(const char *arg)
1761
{
1762
    mb_decision = atoi(arg);
1763
}
1764

    
1765
static void opt_qscale(const char *arg)
1766
{
1767
    video_qscale = atof(arg);
1768
    if (video_qscale < 0.01 ||
1769
        video_qscale > 255) {
1770
        fprintf(stderr, "qscale must be >= 0.01 and <= 255\n");
1771
        exit(1);
1772
    }
1773
}
1774

    
1775
static void opt_qmin(const char *arg)
1776
{
1777
    video_qmin = atoi(arg);
1778
    if (video_qmin < 0 ||
1779
        video_qmin > 31) {
1780
        fprintf(stderr, "qmin must be >= 1 and <= 31\n");
1781
        exit(1);
1782
    }
1783
}
1784

    
1785
static void opt_qmax(const char *arg)
1786
{
1787
    video_qmax = atoi(arg);
1788
    if (video_qmax < 0 ||
1789
        video_qmax > 31) {
1790
        fprintf(stderr, "qmax must be >= 1 and <= 31\n");
1791
        exit(1);
1792
    }
1793
}
1794

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

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

    
1815
static void opt_qdiff(const char *arg)
1816
{
1817
    video_qdiff = atoi(arg);
1818
    if (video_qdiff < 0 ||
1819
        video_qdiff > 31) {
1820
        fprintf(stderr, "qdiff must be >= 1 and <= 31\n");
1821
        exit(1);
1822
    }
1823
}
1824

    
1825
static void opt_qblur(const char *arg)
1826
{
1827
    video_qblur = atof(arg);
1828
}
1829

    
1830
static void opt_qcomp(const char *arg)
1831
{
1832
    video_qcomp = atof(arg);
1833
}
1834

    
1835
static void opt_rc_initial_cplx(const char *arg)
1836
{
1837
    video_rc_initial_cplx = atof(arg);
1838
}
1839
static void opt_b_qfactor(const char *arg)
1840
{
1841
    video_b_qfactor = atof(arg);
1842
}
1843
static void opt_i_qfactor(const char *arg)
1844
{
1845
    video_i_qfactor = atof(arg);
1846
}
1847
static void opt_b_qoffset(const char *arg)
1848
{
1849
    video_b_qoffset = atof(arg);
1850
}
1851
static void opt_i_qoffset(const char *arg)
1852
{
1853
    video_i_qoffset = atof(arg);
1854
}
1855

    
1856
static void opt_packet_size(const char *arg)
1857
{
1858
    packet_size= atoi(arg);
1859
}
1860

    
1861
static void opt_error_rate(const char *arg)
1862
{
1863
    error_rate= atoi(arg);
1864
}
1865

    
1866
static void opt_strict(const char *arg)
1867
{
1868
    strict= atoi(arg);
1869
}
1870

    
1871
static void opt_audio_bitrate(const char *arg)
1872
{
1873
    audio_bit_rate = atoi(arg) * 1000;
1874
}
1875

    
1876
static void opt_audio_rate(const char *arg)
1877
{
1878
    audio_sample_rate = atoi(arg);
1879
}
1880

    
1881
static void opt_audio_channels(const char *arg)
1882
{
1883
    audio_channels = atoi(arg);
1884
}
1885

    
1886
static void opt_video_device(const char *arg)
1887
{
1888
    video_device = av_strdup(arg);
1889
}
1890

    
1891
static void opt_video_channel(const char *arg)
1892
{
1893
    video_channel = strtol(arg, NULL, 0);
1894
}
1895

    
1896
static void opt_video_standard(const char *arg)
1897
{
1898
    video_standard = av_strdup(arg);
1899
}
1900

    
1901
static void opt_audio_device(const char *arg)
1902
{
1903
    audio_device = av_strdup(arg);
1904
}
1905

    
1906
static void opt_dv1394(const char *arg)
1907
{
1908
    video_grab_format = "dv1394";
1909
    audio_grab_format = NULL;
1910
}
1911

    
1912
static void opt_audio_codec(const char *arg)
1913
{
1914
    AVCodec *p;
1915

    
1916
    if (!strcmp(arg, "copy")) {
1917
        audio_stream_copy = 1;
1918
    } else {
1919
        p = first_avcodec;
1920
        while (p) {
1921
            if (!strcmp(p->name, arg) && p->type == CODEC_TYPE_AUDIO)
1922
                break;
1923
            p = p->next;
1924
        }
1925
        if (p == NULL) {
1926
            fprintf(stderr, "Unknown audio codec '%s'\n", arg);
1927
            exit(1);
1928
        } else {
1929
            audio_codec_id = p->id;
1930
        }
1931
    }
1932
}
1933

    
1934
static void add_frame_hooker(const char *arg)
1935
{
1936
    int argc = 0;
1937
    char *argv[64];
1938
    int i;
1939
    char *args = av_strdup(arg);
1940

    
1941
    using_vhook = 1;
1942

    
1943
    argv[0] = strtok(args, " ");
1944
    while (argc < 62 && (argv[++argc] = strtok(NULL, " "))) {
1945
    }
1946

    
1947
    i = frame_hook_add(argc, argv);
1948

    
1949
    if (i != 0) {
1950
        fprintf(stderr, "Failed to add video hook function: %s\n", arg);
1951
        exit(1);
1952
    }
1953
}
1954

    
1955
const char *motion_str[] = {
1956
    "zero",
1957
    "full",
1958
    "log",
1959
    "phods",
1960
    "epzs",
1961
    "x1",
1962
    NULL,
1963
};
1964

    
1965
static void opt_motion_estimation(const char *arg)
1966
{
1967
    const char **p;
1968
    p = motion_str;
1969
    for(;;) {
1970
        if (!*p) {
1971
            fprintf(stderr, "Unknown motion estimation method '%s'\n", arg);
1972
            exit(1);
1973
        }
1974
        if (!strcmp(*p, arg))
1975
            break;
1976
        p++;
1977
    }
1978
    me_method = (p - motion_str) + 1;
1979
}
1980

    
1981
static void opt_video_codec(const char *arg)
1982
{
1983
    AVCodec *p;
1984

    
1985
    if (!strcmp(arg, "copy")) {
1986
        video_stream_copy = 1;
1987
    } else {
1988
        p = first_avcodec;
1989
        while (p) {
1990
            if (!strcmp(p->name, arg) && p->type == CODEC_TYPE_VIDEO)
1991
                break;
1992
            p = p->next;
1993
        }
1994
        if (p == NULL) {
1995
            fprintf(stderr, "Unknown video codec '%s'\n", arg);
1996
            exit(1);
1997
        } else {
1998
            video_codec_id = p->id;
1999
        }
2000
    }
2001
}
2002

    
2003
static void opt_map(const char *arg)
2004
{
2005
    AVStreamMap *m;
2006
    const char *p;
2007

    
2008
    p = arg;
2009
    m = &stream_maps[nb_stream_maps++];
2010

    
2011
    m->file_index = strtol(arg, (char **)&p, 0);
2012
    if (*p)
2013
        p++;
2014

    
2015
    m->stream_index = strtol(p, (char **)&p, 0);
2016
}
2017

    
2018
static void opt_recording_time(const char *arg)
2019
{
2020
    recording_time = parse_date(arg, 1);
2021
}
2022

    
2023
static void opt_start_time(const char *arg)
2024
{
2025
    start_time = parse_date(arg, 1);
2026
}
2027

    
2028
static void opt_input_file(const char *filename)
2029
{
2030
    AVFormatContext *ic;
2031
    AVFormatParameters params, *ap = &params;
2032
    int err, i, ret, rfps, rfps_base;
2033

    
2034
    if (!strcmp(filename, "-"))
2035
        filename = "pipe:";
2036

    
2037
    using_stdin |= !strcmp(filename, "pipe:" ) || 
2038
                   !strcmp( filename, "/dev/stdin" );
2039

    
2040
    /* get default parameters from command line */
2041
    memset(ap, 0, sizeof(*ap));
2042
    ap->sample_rate = audio_sample_rate;
2043
    ap->channels = audio_channels;
2044
    ap->frame_rate = frame_rate;
2045
    ap->frame_rate_base = frame_rate_base;
2046
    ap->width = frame_width;
2047
    ap->height = frame_height;
2048
    ap->image_format = image_format;
2049
    ap->pix_fmt = frame_pix_fmt;
2050

    
2051
    /* open the input file with generic libav function */
2052
    err = av_open_input_file(&ic, filename, file_iformat, 0, ap);
2053
    if (err < 0) {
2054
        print_error(filename, err);
2055
        exit(1);
2056
    }
2057
    
2058
    /* If not enough info to get the stream parameters, we decode the
2059
       first frames to get it. (used in mpeg case for example) */
2060
    ret = av_find_stream_info(ic);
2061
    if (ret < 0) {
2062
        fprintf(stderr, "%s: could not find codec parameters\n", filename);
2063
        exit(1);
2064
    }
2065

    
2066
    /* if seeking requested, we execute it */
2067
    if (start_time != 0) {
2068
        int64_t timestamp;
2069

    
2070
        timestamp = start_time;
2071
        /* add the stream start time */
2072
        if (ic->start_time != AV_NOPTS_VALUE)
2073
            timestamp += ic->start_time;
2074
        ret = av_seek_frame(ic, -1, timestamp);
2075
        if (ret < 0) {
2076
            fprintf(stderr, "%s: could not seek to position %0.3f\n", 
2077
                    filename, (double)timestamp / AV_TIME_BASE);
2078
        }
2079
        /* reset seek info */
2080
        start_time = 0;
2081
    }
2082

    
2083
    /* update the current parameters so that they match the one of the input stream */
2084
    for(i=0;i<ic->nb_streams;i++) {
2085
        AVCodecContext *enc = &ic->streams[i]->codec;
2086
        switch(enc->codec_type) {
2087
        case CODEC_TYPE_AUDIO:
2088
            //fprintf(stderr, "\nInput Audio channels: %d", enc->channels);
2089
            audio_channels = enc->channels;
2090
            audio_sample_rate = enc->sample_rate;
2091
            break;
2092
        case CODEC_TYPE_VIDEO:
2093
            frame_height = enc->height;
2094
            frame_width = enc->width;
2095
            frame_aspect_ratio = av_q2d(enc->sample_aspect_ratio) * enc->width / enc->height;
2096
            frame_pix_fmt = enc->pix_fmt;
2097
            rfps      = ic->streams[i]->r_frame_rate;
2098
            rfps_base = ic->streams[i]->r_frame_rate_base;
2099
            enc->workaround_bugs = workaround_bugs;
2100
            enc->error_resilience = error_resilience; 
2101
            enc->error_concealment = error_concealment; 
2102
            enc->idct_algo= idct_algo;
2103
            enc->debug= debug;
2104
            if(bitexact)
2105
                enc->flags|= CODEC_FLAG_BITEXACT;
2106

    
2107
            assert(enc->frame_rate_base == rfps_base); // should be true for now
2108
            if (enc->frame_rate != rfps) { 
2109
                fprintf(stderr,"\nSeems that stream %d comes from film source: %2.2f->%2.2f\n",
2110
                    i, (float)enc->frame_rate / enc->frame_rate_base,
2111
                    (float)rfps / rfps_base);
2112
            }
2113
            /* update the current frame rate to match the stream frame rate */
2114
            frame_rate      = rfps;
2115
            frame_rate_base = rfps_base;
2116

    
2117
            enc->rate_emu = rate_emu;
2118
            break;
2119
        case CODEC_TYPE_DATA:
2120
            break;
2121
        default:
2122
            av_abort();
2123
        }
2124
    }
2125
    
2126
    input_files[nb_input_files] = ic;
2127
    /* dump the file content */
2128
    dump_format(ic, nb_input_files, filename, 0);
2129
    nb_input_files++;
2130
    file_iformat = NULL;
2131
    file_oformat = NULL;
2132
    image_format = NULL;
2133

    
2134
    rate_emu = 0;
2135
}
2136

    
2137
static void check_audio_video_inputs(int *has_video_ptr, int *has_audio_ptr)
2138
{
2139
    int has_video, has_audio, i, j;
2140
    AVFormatContext *ic;
2141

    
2142
    has_video = 0;
2143
    has_audio = 0;
2144
    for(j=0;j<nb_input_files;j++) {
2145
        ic = input_files[j];
2146
        for(i=0;i<ic->nb_streams;i++) {
2147
            AVCodecContext *enc = &ic->streams[i]->codec;
2148
            switch(enc->codec_type) {
2149
            case CODEC_TYPE_AUDIO:
2150
                has_audio = 1;
2151
                break;
2152
            case CODEC_TYPE_VIDEO:
2153
                has_video = 1;
2154
                break;
2155
            default:
2156
                av_abort();
2157
            }
2158
        }
2159
    }
2160
    *has_video_ptr = has_video;
2161
    *has_audio_ptr = has_audio;
2162
}
2163

    
2164
static void opt_output_file(const char *filename)
2165
{
2166
    AVStream *st;
2167
    AVFormatContext *oc;
2168
    int use_video, use_audio, nb_streams, input_has_video, input_has_audio;
2169
    int codec_id;
2170
    AVFormatParameters params, *ap = &params;
2171

    
2172
    if (!strcmp(filename, "-"))
2173
        filename = "pipe:";
2174

    
2175
    oc = av_mallocz(sizeof(AVFormatContext));
2176

    
2177
    if (!file_oformat) {
2178
        file_oformat = guess_format(NULL, filename, NULL);
2179
        if (!file_oformat) {
2180
            fprintf(stderr, "Unable for find a suitable output format for '%s'\n",
2181
                    filename);
2182
            exit(1);
2183
        }
2184
    }
2185
    
2186
    oc->oformat = file_oformat;
2187

    
2188
    if (!strcmp(file_oformat->name, "ffm") && 
2189
        strstart(filename, "http:", NULL)) {
2190
        /* special case for files sent to ffserver: we get the stream
2191
           parameters from ffserver */
2192
        if (read_ffserver_streams(oc, filename) < 0) {
2193
            fprintf(stderr, "Could not read stream parameters from '%s'\n", filename);
2194
            exit(1);
2195
        }
2196
    } else {
2197
        use_video = file_oformat->video_codec != CODEC_ID_NONE;
2198
        use_audio = file_oformat->audio_codec != CODEC_ID_NONE;
2199

    
2200
        /* disable if no corresponding type found and at least one
2201
           input file */
2202
        if (nb_input_files > 0) {
2203
            check_audio_video_inputs(&input_has_video, &input_has_audio);
2204
            if (!input_has_video)
2205
                use_video = 0;
2206
            if (!input_has_audio)
2207
                use_audio = 0;
2208
        }
2209

    
2210
        /* manual disable */
2211
        if (audio_disable) {
2212
            use_audio = 0;
2213
        }
2214
        if (video_disable) {
2215
            use_video = 0;
2216
        }
2217
        
2218
        nb_streams = 0;
2219
        if (use_video) {
2220
            AVCodecContext *video_enc;
2221
            
2222
            st = av_mallocz(sizeof(AVStream));
2223
            if (!st) {
2224
                fprintf(stderr, "Could not alloc stream\n");
2225
                exit(1);
2226
            }
2227
            avcodec_get_context_defaults(&st->codec);
2228

    
2229
            video_enc = &st->codec;
2230
            
2231
            if(!strcmp(file_oformat->name, "mp4") || !strcmp(file_oformat->name, "mov") || !strcmp(file_oformat->name, "3gp"))
2232
                video_enc->flags |= CODEC_FLAG_GLOBAL_HEADER;
2233
            if (video_stream_copy) {
2234
                st->stream_copy = 1;
2235
                video_enc->codec_type = CODEC_TYPE_VIDEO;
2236
            } else {
2237
                char *p;
2238
                int i;
2239
            
2240
                codec_id = file_oformat->video_codec;
2241
                if (video_codec_id != CODEC_ID_NONE)
2242
                    codec_id = video_codec_id;
2243
                
2244
                video_enc->codec_id = codec_id;
2245
                
2246
                video_enc->bit_rate = video_bit_rate;
2247
                video_enc->bit_rate_tolerance = video_bit_rate_tolerance;
2248
                video_enc->frame_rate = frame_rate; 
2249
                video_enc->frame_rate_base = frame_rate_base; 
2250
                
2251
                video_enc->width = frame_width;
2252
                video_enc->height = frame_height;
2253
                video_enc->sample_aspect_ratio = av_d2q(frame_aspect_ratio*frame_height/frame_width, 255);
2254
                video_enc->pix_fmt = frame_pix_fmt;
2255

    
2256
                if (!intra_only)
2257
                    video_enc->gop_size = gop_size;
2258
                else
2259
                    video_enc->gop_size = 0;
2260
                if (video_qscale || same_quality) {
2261
                    video_enc->flags |= CODEC_FLAG_QSCALE;
2262
                    st->quality = FF_QP2LAMBDA * video_qscale;
2263
                }
2264

    
2265
                if(intra_matrix)
2266
                    video_enc->intra_matrix = intra_matrix;
2267
                if(inter_matrix)
2268
                    video_enc->inter_matrix = inter_matrix;
2269

    
2270
                if(bitexact)
2271
                    video_enc->flags |= CODEC_FLAG_BITEXACT;
2272

    
2273
                video_enc->mb_decision = mb_decision;
2274
                
2275
                if (use_umv) {
2276
                    video_enc->flags |= CODEC_FLAG_H263P_UMV;
2277
                }
2278
                   if (use_aic) {
2279
                    video_enc->flags |= CODEC_FLAG_H263P_AIC;
2280
                }
2281
                   if (use_aiv) {
2282
                    video_enc->flags |= CODEC_FLAG_H263P_AIV;
2283
                }
2284
                if (use_4mv) {
2285
                    video_enc->flags |= CODEC_FLAG_4MV;
2286
                }
2287
                if (use_obmc) {
2288
                    video_enc->flags |= CODEC_FLAG_OBMC;
2289
                }
2290
            
2291
                if(use_part) {
2292
                    video_enc->flags |= CODEC_FLAG_PART;
2293
                }
2294
                if (b_frames) {
2295
                    video_enc->max_b_frames = b_frames;
2296
                    video_enc->b_frame_strategy = 0;
2297
                    video_enc->b_quant_factor = 2.0;
2298
                }
2299
                if (do_interlace) {
2300
                    video_enc->flags |= CODEC_FLAG_INTERLACED_DCT;
2301
                }
2302
                video_enc->qmin = video_qmin;
2303
                video_enc->qmax = video_qmax;
2304
                video_enc->mb_qmin = video_mb_qmin;
2305
                video_enc->mb_qmax = video_mb_qmax;
2306
                video_enc->max_qdiff = video_qdiff;
2307
                video_enc->qblur = video_qblur;
2308
                video_enc->qcompress = video_qcomp;
2309
                video_enc->rc_eq = video_rc_eq;
2310
                video_enc->debug= debug;
2311
                
2312
                p= video_rc_override_string;
2313
                for(i=0; p; i++){
2314
                    int start, end, q;
2315
                    int e=sscanf(p, "%d,%d,%d", &start, &end, &q);
2316
                    if(e!=3){
2317
                        fprintf(stderr, "error parsing rc_override\n");
2318
                        exit(1);
2319
                    }
2320
                    video_enc->rc_override= 
2321
                        av_realloc(video_enc->rc_override, 
2322
                                   sizeof(RcOverride)*(i+1));
2323
                    video_enc->rc_override[i].start_frame= start;
2324
                    video_enc->rc_override[i].end_frame  = end;
2325
                    if(q>0){
2326
                        video_enc->rc_override[i].qscale= q;
2327
                        video_enc->rc_override[i].quality_factor= 1.0;
2328
                    }
2329
                    else{
2330
                        video_enc->rc_override[i].qscale= 0;
2331
                        video_enc->rc_override[i].quality_factor= -q/100.0;
2332
                    }
2333
                    p= strchr(p, '/');
2334
                    if(p) p++;
2335
                }
2336
                video_enc->rc_override_count=i;
2337

    
2338
                video_enc->rc_max_rate = video_rc_max_rate;
2339
                video_enc->rc_min_rate = video_rc_min_rate;
2340
                video_enc->rc_buffer_size = video_rc_buffer_size;
2341
                video_enc->rc_buffer_aggressivity= video_rc_buffer_aggressivity;
2342
                video_enc->rc_initial_cplx= video_rc_initial_cplx;
2343
                video_enc->i_quant_factor = video_i_qfactor;
2344
                video_enc->b_quant_factor = video_b_qfactor;
2345
                video_enc->i_quant_offset = video_i_qoffset;
2346
                video_enc->b_quant_offset = video_b_qoffset;
2347
                video_enc->dct_algo = dct_algo;
2348
                video_enc->idct_algo = idct_algo;
2349
                video_enc->strict_std_compliance = strict;
2350
                video_enc->error_rate = error_rate;
2351
                if(packet_size){
2352
                    video_enc->rtp_mode= 1;
2353
                    video_enc->rtp_payload_size= packet_size;
2354
                }
2355
            
2356
                if (do_psnr)
2357
                    video_enc->flags|= CODEC_FLAG_PSNR;
2358
            
2359
                video_enc->me_method = me_method;
2360

    
2361
                /* two pass mode */
2362
                if (do_pass) {
2363
                    if (do_pass == 1) {
2364
                        video_enc->flags |= CODEC_FLAG_PASS1;
2365
                    } else {
2366
                        video_enc->flags |= CODEC_FLAG_PASS2;
2367
                    }
2368
                }
2369
            }
2370
            oc->streams[nb_streams] = st;
2371
            nb_streams++;
2372
        }
2373
    
2374
        if (use_audio) {
2375
            AVCodecContext *audio_enc;
2376

    
2377
            st = av_mallocz(sizeof(AVStream));
2378
            if (!st) {
2379
                fprintf(stderr, "Could not alloc stream\n");
2380
                exit(1);
2381
            }
2382
            avcodec_get_context_defaults(&st->codec);
2383

    
2384
            audio_enc = &st->codec;
2385
            audio_enc->codec_type = CODEC_TYPE_AUDIO;
2386

    
2387
            if(!strcmp(file_oformat->name, "mp4") || !strcmp(file_oformat->name, "mov") || !strcmp(file_oformat->name, "3gp"))
2388
                audio_enc->flags |= CODEC_FLAG_GLOBAL_HEADER;
2389
            if (audio_stream_copy) {
2390
                st->stream_copy = 1;
2391
            } else {
2392
                codec_id = file_oformat->audio_codec;
2393
                if (audio_codec_id != CODEC_ID_NONE)
2394
                    codec_id = audio_codec_id;
2395
                audio_enc->codec_id = codec_id;
2396
                
2397
                audio_enc->bit_rate = audio_bit_rate;
2398
                audio_enc->sample_rate = audio_sample_rate;
2399
                /* For audio codecs other than AC3 we limit */
2400
                /* the number of coded channels to stereo   */
2401
                if (audio_channels > 2 && codec_id != CODEC_ID_AC3) {
2402
                    audio_enc->channels = 2;
2403
                } else
2404
                    audio_enc->channels = audio_channels;
2405
            }
2406
            oc->streams[nb_streams] = st;
2407
            nb_streams++;
2408
        }
2409

    
2410
        oc->nb_streams = nb_streams;
2411

    
2412
        if (!nb_streams) {
2413
            fprintf(stderr, "No audio or video streams available\n");
2414
            exit(1);
2415
        }
2416

    
2417
        if (str_title)
2418
            pstrcpy(oc->title, sizeof(oc->title), str_title);
2419
        if (str_author)
2420
            pstrcpy(oc->author, sizeof(oc->author), str_author);
2421
        if (str_copyright)
2422
            pstrcpy(oc->copyright, sizeof(oc->copyright), str_copyright);
2423
        if (str_comment)
2424
            pstrcpy(oc->comment, sizeof(oc->comment), str_comment);
2425
    }
2426

    
2427
    output_files[nb_output_files++] = oc;
2428

    
2429
    strcpy(oc->filename, filename);
2430

    
2431
    /* check filename in case of an image number is expected */
2432
    if (oc->oformat->flags & AVFMT_NEEDNUMBER) {
2433
        if (filename_number_test(oc->filename) < 0) {
2434
            print_error(oc->filename, AVERROR_NUMEXPECTED);
2435
            exit(1);
2436
        }
2437
    }
2438

    
2439
    if (!(oc->oformat->flags & AVFMT_NOFILE)) {
2440
        /* test if it already exists to avoid loosing precious files */
2441
        if (!file_overwrite && 
2442
            (strchr(filename, ':') == NULL ||
2443
             strstart(filename, "file:", NULL))) {
2444
            if (url_exist(filename)) {
2445
                int c;
2446
                
2447
                if ( !using_stdin ) {
2448
                    fprintf(stderr,"File '%s' already exists. Overwrite ? [y/N] ", filename);
2449
                    fflush(stderr);
2450
                    c = getchar();
2451
                    if (toupper(c) != 'Y') {
2452
                        fprintf(stderr, "Not overwriting - exiting\n");
2453
                        exit(1);
2454
                    }
2455
                                }
2456
                                else {
2457
                    fprintf(stderr,"File '%s' already exists. Exiting.\n", filename);
2458
                    exit(1);
2459
                                }
2460
            }
2461
        }
2462
        
2463
        /* open the file */
2464
        if (url_fopen(&oc->pb, filename, URL_WRONLY) < 0) {
2465
            fprintf(stderr, "Could not open '%s'\n", filename);
2466
            exit(1);
2467
        }
2468
    }
2469

    
2470
    memset(ap, 0, sizeof(*ap));
2471
    ap->image_format = image_format;
2472
    if (av_set_parameters(oc, ap) < 0) {
2473
        fprintf(stderr, "%s: Invalid encoding parameters\n",
2474
                oc->filename);
2475
        exit(1);
2476
    }
2477

    
2478
    /* reset some options */
2479
    file_oformat = NULL;
2480
    file_iformat = NULL;
2481
    image_format = NULL;
2482
    audio_disable = 0;
2483
    video_disable = 0;
2484
    audio_codec_id = CODEC_ID_NONE;
2485
    video_codec_id = CODEC_ID_NONE;
2486
    audio_stream_copy = 0;
2487
    video_stream_copy = 0;
2488
}
2489

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

    
2577
/* same option as mencoder */
2578
static void opt_pass(const char *pass_str)
2579
{
2580
    int pass;
2581
    pass = atoi(pass_str);
2582
    if (pass != 1 && pass != 2) {
2583
        fprintf(stderr, "pass number can be only 1 or 2\n");
2584
        exit(1);
2585
    }
2586
    do_pass = pass;
2587
}
2588

    
2589
#if defined(CONFIG_WIN32) || defined(CONFIG_OS2)
2590
static int64_t getutime(void)
2591
{
2592
  return av_gettime();
2593
}
2594
#else
2595
static int64_t getutime(void)
2596
{
2597
    struct rusage rusage;
2598

    
2599
    getrusage(RUSAGE_SELF, &rusage);
2600
    return (rusage.ru_utime.tv_sec * 1000000LL) + rusage.ru_utime.tv_usec;
2601
}
2602
#endif
2603

    
2604
extern int ffm_nopts;
2605

    
2606
static void opt_bitexact(void)
2607
{
2608
    bitexact=1;
2609
    /* disable generate of real time pts in ffm (need to be supressed anyway) */
2610
    ffm_nopts = 1;
2611
}
2612

    
2613
static void show_formats(void)
2614
{
2615
    AVInputFormat *ifmt;
2616
    AVOutputFormat *ofmt;
2617
    AVImageFormat *image_fmt;
2618
    URLProtocol *up;
2619
    AVCodec *p;
2620
    const char **pp;
2621

    
2622
    printf("Output audio/video file formats:");
2623
    for(ofmt = first_oformat; ofmt != NULL; ofmt = ofmt->next) {
2624
        printf(" %s", ofmt->name);
2625
    }
2626
    printf("\n");
2627

    
2628
    printf("Input audio/video file formats:");
2629
    for(ifmt = first_iformat; ifmt != NULL; ifmt = ifmt->next) {
2630
        printf(" %s", ifmt->name);
2631
    }
2632
    printf("\n");
2633

    
2634
    printf("Output image formats:");
2635
    for(image_fmt = first_image_format; image_fmt != NULL; 
2636
        image_fmt = image_fmt->next) {
2637
        if (image_fmt->img_write)
2638
            printf(" %s", image_fmt->name);
2639
    }
2640
    printf("\n");
2641

    
2642
    printf("Input image formats:");
2643
    for(image_fmt = first_image_format; image_fmt != NULL; 
2644
        image_fmt = image_fmt->next) {
2645
        if (image_fmt->img_read)
2646
            printf(" %s", image_fmt->name);
2647
    }
2648
    printf("\n");
2649

    
2650
    printf("Codecs:\n");
2651
    printf("  Encoders:");
2652
    for(p = first_avcodec; p != NULL; p = p->next) {
2653
        if (p->encode)
2654
            printf(" %s", p->name);
2655
    }
2656
    printf("\n");
2657

    
2658
    printf("  Decoders:");
2659
    for(p = first_avcodec; p != NULL; p = p->next) {
2660
        if (p->decode)
2661
            printf(" %s", p->name);
2662
    }
2663
    printf("\n");
2664

    
2665
    printf("Supported file protocols:");
2666
    for(up = first_protocol; up != NULL; up = up->next)
2667
        printf(" %s:", up->name);
2668
    printf("\n");
2669
    
2670
    printf("Frame size, frame rate abbreviations: ntsc pal qntsc qpal sntsc spal film ntsc-film sqcif qcif cif 4cif\n");
2671
    printf("Motion estimation methods:");
2672
    pp = motion_str;
2673
    while (*pp) {
2674
        printf(" %s", *pp);
2675
        if ((pp - motion_str + 1) == ME_ZERO) 
2676
            printf("(fastest)");
2677
        else if ((pp - motion_str + 1) == ME_FULL) 
2678
            printf("(slowest)");
2679
        else if ((pp - motion_str + 1) == ME_EPZS) 
2680
            printf("(default)");
2681
        pp++;
2682
    }
2683
    printf("\n");
2684
    exit(1);
2685
}
2686

    
2687
void parse_matrix_coeffs(uint16_t *dest, const char *str)
2688
{
2689
    int i;
2690
    const char *p = str;
2691
    for(i = 0;; i++) {
2692
        dest[i] = atoi(p);
2693
        if(i == 63)
2694
            break;
2695
        p = strchr(p, ',');
2696
        if(!p) {
2697
            fprintf(stderr, "Syntax error in matrix \"%s\" at coeff %d\n", str, i);
2698
            exit(1);
2699
        }
2700
        p++;
2701
    }
2702
}
2703

    
2704
void opt_inter_matrix(const char *arg)
2705
{
2706
    inter_matrix = av_mallocz(sizeof(uint16_t) * 64);
2707
    parse_matrix_coeffs(inter_matrix, arg);
2708
}
2709

    
2710
void opt_intra_matrix(const char *arg)
2711
{
2712
    intra_matrix = av_mallocz(sizeof(uint16_t) * 64);
2713
    parse_matrix_coeffs(intra_matrix, arg);
2714
}
2715

    
2716
static void opt_target(const char *arg)
2717
{
2718
    int norm = -1;
2719

    
2720
    if(!strncmp(arg, "pal-", 4)) {
2721
        norm = 0;
2722
        arg += 4;
2723
    } else if(!strncmp(arg, "ntsc-", 5)) {
2724
        norm = 1;
2725
        arg += 5;
2726
    } else {
2727
        int fr;
2728
        /* Calculate FR via float to avoid int overflow */
2729
        fr = (int)(frame_rate * 1000.0 / frame_rate_base);
2730
        if(fr == 25000) {
2731
            norm = 0;
2732
        } else if((fr == 29970) || (fr == 23976)) {
2733
            norm = 1;
2734
        } else {
2735
            /* Try to determine PAL/NTSC by peeking in the input files */
2736
            if(nb_input_files) {
2737
                int i, j;
2738
                for(j = 0; j < nb_input_files; j++) {
2739
                    for(i = 0; i < input_files[j]->nb_streams; i++) {
2740
                        AVCodecContext *c = &input_files[j]->streams[i]->codec;
2741
                        if(c->codec_type != CODEC_TYPE_VIDEO)
2742
                            continue;
2743
                        fr = c->frame_rate * 1000 / c->frame_rate_base;
2744
                        if(fr == 25000) {
2745
                            norm = 0;
2746
                            break;
2747
                        } else if((fr == 29970) || (fr == 23976)) {
2748
                            norm = 1;
2749
                            break;
2750
                        }
2751
                    }
2752
                    if(norm >= 0)
2753
                        break;
2754
                }
2755
            }
2756
        }
2757
        if(verbose && norm >= 0)
2758
            printf("Assuming %s for target.\n", norm ? "NTSC" : "PAL");
2759
    }
2760

    
2761
    if(norm < 0) {
2762
        fprintf(stderr, "Could not determine norm (PAL/NTSC) for target.\n");
2763
        fprintf(stderr, "Please prefix target with \"pal-\" or \"ntsc-\",\n");
2764
        fprintf(stderr, "or set a framerate with \"-r xxx\".\n");
2765
        exit(1);
2766
    }
2767

    
2768
    if(!strcmp(arg, "vcd")) {
2769

    
2770
        opt_video_codec("mpeg1video");
2771
        opt_audio_codec("mp2");
2772
        opt_format("vcd");
2773

    
2774
        opt_frame_size(norm ? "352x240" : "352x288");
2775

    
2776
        video_bit_rate = 1150000;
2777
        video_rc_max_rate = 1150000;
2778
        video_rc_min_rate = 1150000;
2779
        video_rc_buffer_size = 40*1024*8;
2780

    
2781
        audio_bit_rate = 224000;
2782
        audio_sample_rate = 44100;
2783

    
2784
    } else if(!strcmp(arg, "svcd")) {
2785

    
2786
        opt_video_codec("mpeg2video");
2787
        opt_audio_codec("mp2");
2788
        opt_format("vcd");
2789

    
2790
        opt_frame_size(norm ? "480x480" : "480x576");
2791
        opt_gop_size(norm ? "18" : "15");
2792

    
2793
        video_bit_rate = 2040000;
2794
        video_rc_max_rate = 2516000;
2795
        video_rc_min_rate = 1145000;
2796
        video_rc_buffer_size = 224*1024*8;
2797

    
2798
        audio_bit_rate = 224000;
2799
        audio_sample_rate = 44100;
2800

    
2801
    } else if(!strcmp(arg, "dvd")) {
2802

    
2803
        opt_video_codec("mpeg2video");
2804
        opt_audio_codec("ac3");
2805
        opt_format("vob");
2806

    
2807
        opt_frame_size(norm ? "720x480" : "720x576");
2808
        opt_gop_size(norm ? "18" : "15");
2809

    
2810
        video_bit_rate = 6000000;
2811
        video_rc_max_rate = 9000000;
2812
        video_rc_min_rate = 1500000;
2813
        video_rc_buffer_size = 224*1024*8;
2814

    
2815
        audio_bit_rate = 448000;
2816
        audio_sample_rate = 48000;
2817

    
2818
    } else {
2819
        fprintf(stderr, "Unknown target: %s\n", arg);
2820
        exit(1);
2821
    }
2822
}
2823

    
2824
const OptionDef options[] = {
2825
    /* main options */
2826
    { "L", 0, {(void*)show_license}, "show license" },
2827
    { "h", 0, {(void*)show_help}, "show help" },
2828
    { "formats", 0, {(void*)show_formats}, "show available formats, codecs, protocols, ..." },
2829
    { "f", HAS_ARG, {(void*)opt_format}, "force format", "fmt" },
2830
    { "img", HAS_ARG, {(void*)opt_image_format}, "force image format", "img_fmt" },
2831
    { "i", HAS_ARG, {(void*)opt_input_file}, "input file name", "filename" },
2832
    { "y", OPT_BOOL, {(void*)&file_overwrite}, "overwrite output files" },
2833
    { "map", HAS_ARG | OPT_EXPERT, {(void*)opt_map}, "set input stream mapping", "file:stream" },
2834
    { "t", HAS_ARG, {(void*)opt_recording_time}, "set the recording time", "duration" },
2835
    { "ss", HAS_ARG, {(void*)opt_start_time}, "set the start time offset", "time_off" },
2836
    { "title", HAS_ARG | OPT_STRING, {(void*)&str_title}, "set the title", "string" },
2837
    { "author", HAS_ARG | OPT_STRING, {(void*)&str_author}, "set the author", "string" },
2838
    { "copyright", HAS_ARG | OPT_STRING, {(void*)&str_copyright}, "set the copyright", "string" },
2839
    { "comment", HAS_ARG | OPT_STRING, {(void*)&str_comment}, "set the comment", "string" },
2840
    { "debug", HAS_ARG | OPT_EXPERT, {(void*)opt_debug}, "print specific debug info", "" },
2841
    { "benchmark", OPT_BOOL | OPT_EXPERT, {(void*)&do_benchmark}, 
2842
      "add timings for benchmarking" },
2843
    { "dump", OPT_BOOL | OPT_EXPERT, {(void*)&do_pkt_dump}, 
2844
      "dump each input packet" },
2845
    { "hex", OPT_BOOL | OPT_EXPERT, {(void*)&do_hex_dump}, 
2846
      "when dumping packets, also dump the payload" },
2847
    { "bitexact", OPT_EXPERT, {(void*)opt_bitexact}, "only use bit exact algorithms (for codec testing)" }, 
2848
    { "re", OPT_BOOL | OPT_EXPERT, {(void*)&rate_emu}, "read input at native frame rate", "" },
2849
    { "loop", OPT_BOOL | OPT_EXPERT, {(void*)&loop_input}, "loop (current only works with images)" },
2850
    { "v", HAS_ARG, {(void*)opt_verbose}, "control amount of logging", "verbose" },
2851
    { "target", HAS_ARG, {(void*)opt_target}, "specify target file type (\"vcd\", \"svcd\" or \"dvd\")", "type" },
2852

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

    
2920
    /* audio options */
2921
    { "ab", HAS_ARG | OPT_AUDIO, {(void*)opt_audio_bitrate}, "set audio bitrate (in kbit/s)", "bitrate", },
2922
    { "ar", HAS_ARG | OPT_AUDIO, {(void*)opt_audio_rate}, "set audio sampling rate (in Hz)", "rate" },
2923
    { "ac", HAS_ARG | OPT_AUDIO, {(void*)opt_audio_channels}, "set number of audio channels", "channels" },
2924
    { "an", OPT_BOOL | OPT_AUDIO, {(void*)&audio_disable}, "disable audio" },
2925
    { "acodec", HAS_ARG | OPT_AUDIO, {(void*)opt_audio_codec}, "force audio codec ('copy' to copy stream)", "codec" },
2926

    
2927
    /* grab options */
2928
    { "vd", HAS_ARG | OPT_EXPERT | OPT_VIDEO | OPT_GRAB, {(void*)opt_video_device}, "set video grab device", "device" },
2929
    { "vc", HAS_ARG | OPT_EXPERT | OPT_VIDEO | OPT_GRAB, {(void*)opt_video_channel}, "set video grab channel (DV1394 only)", "channel" },
2930
    { "tvstd", HAS_ARG | OPT_EXPERT | OPT_VIDEO | OPT_GRAB, {(void*)opt_video_standard}, "set television standard (NTSC, PAL (SECAM))", "standard" },
2931
    { "dv1394", OPT_EXPERT | OPT_GRAB, {(void*)opt_dv1394}, "set DV1394 grab", "" },
2932
    { "ad", HAS_ARG | OPT_EXPERT | OPT_AUDIO | OPT_GRAB, {(void*)opt_audio_device}, "set audio device", "device" },
2933
    { NULL, },
2934
};
2935

    
2936
static void show_banner(void)
2937
{
2938
    printf("ffmpeg version " FFMPEG_VERSION ", Copyright (c) 2000-2003 Fabrice Bellard\n");
2939
}
2940

    
2941
static void show_license(void)
2942
{
2943
    show_banner();
2944
    printf(
2945
    "This library is free software; you can redistribute it and/or\n"
2946
    "modify it under the terms of the GNU Lesser General Public\n"
2947
    "License as published by the Free Software Foundation; either\n"
2948
    "version 2 of the License, or (at your option) any later version.\n"
2949
    "\n"
2950
    "This library is distributed in the hope that it will be useful,\n"
2951
    "but WITHOUT ANY WARRANTY; without even the implied warranty of\n"
2952
    "MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n"
2953
    "Lesser General Public License for more details.\n"
2954
    "\n"
2955
    "You should have received a copy of the GNU Lesser General Public\n"
2956
    "License along with this library; if not, write to the Free Software\n"
2957
    "Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA\n"
2958
    );
2959
    exit(1);
2960
}
2961

    
2962
static void show_help(void)
2963
{
2964
    show_banner();
2965
    printf("usage: ffmpeg [[options] -i input_file]... {[options] outfile}...\n"
2966
           "Hyper fast Audio and Video encoder\n");
2967
    printf("\n");
2968
    show_help_options(options, "Main options:\n",
2969
                      OPT_EXPERT | OPT_AUDIO | OPT_VIDEO, 0);
2970
    show_help_options(options, "\nVideo options:\n",
2971
                      OPT_EXPERT | OPT_AUDIO | OPT_VIDEO | OPT_GRAB, 
2972
                      OPT_VIDEO);
2973
    show_help_options(options, "\nAdvanced Video options:\n",
2974
                      OPT_EXPERT | OPT_AUDIO | OPT_VIDEO | OPT_GRAB, 
2975
                      OPT_VIDEO | OPT_EXPERT);
2976
    show_help_options(options, "\nAudio options:\n",
2977
                      OPT_EXPERT | OPT_AUDIO | OPT_VIDEO | OPT_GRAB, 
2978
                      OPT_AUDIO);
2979
    show_help_options(options, "\nAdvanced Audio options:\n",
2980
                      OPT_EXPERT | OPT_AUDIO | OPT_VIDEO | OPT_GRAB, 
2981
                      OPT_AUDIO | OPT_EXPERT);
2982
    show_help_options(options, "\nAudio/Video grab options:\n",
2983
                      OPT_GRAB, 
2984
                      OPT_GRAB);
2985
    show_help_options(options, "\nAdvanced options:\n",
2986
                      OPT_EXPERT | OPT_AUDIO | OPT_VIDEO | OPT_GRAB, 
2987
                      OPT_EXPERT);
2988
    exit(1);
2989
}
2990

    
2991
void parse_arg_file(const char *filename)
2992
{
2993
    opt_output_file(filename);
2994
}
2995

    
2996
int main(int argc, char **argv)
2997
{
2998
    int i;
2999
    int64_t ti;
3000

    
3001
    av_register_all();
3002

    
3003
    if (argc <= 1)
3004
        show_help();
3005
    
3006
    /* parse options */
3007
    parse_options(argc, argv, options);
3008

    
3009
    /* file converter / grab */
3010
    if (nb_output_files <= 0) {
3011
        fprintf(stderr, "Must supply at least one output file\n");
3012
        exit(1);
3013
    }
3014
    
3015
    if (nb_input_files == 0) {
3016
        prepare_grab();
3017
    }
3018

    
3019
    ti = getutime();
3020
    av_encode(output_files, nb_output_files, input_files, nb_input_files, 
3021
              stream_maps, nb_stream_maps);
3022
    ti = getutime() - ti;
3023
    if (do_benchmark) {
3024
        printf("bench: utime=%0.3fs\n", ti / 1000000.0);
3025
    }
3026

    
3027
    /* close files */
3028
    for(i=0;i<nb_output_files;i++) {
3029
        /* maybe av_close_output_file ??? */
3030
        AVFormatContext *s = output_files[i];
3031
        int j;
3032
        if (!(s->oformat->flags & AVFMT_NOFILE))
3033
            url_fclose(&s->pb);
3034
        for(j=0;j<s->nb_streams;j++)
3035
            av_free(s->streams[j]);
3036
        av_free(s);
3037
    }
3038
    for(i=0;i<nb_input_files;i++)
3039
        av_close_input_file(input_files[i]);
3040

    
3041
    av_free_static();
3042

    
3043
    if(intra_matrix)
3044
        av_free(intra_matrix);
3045
    if(inter_matrix)
3046
        av_free(inter_matrix);
3047
    
3048
#ifdef POWERPC_PERFORMANCE_REPORT
3049
    extern void powerpc_display_perf_report(void);
3050
    powerpc_display_perf_report();
3051
#endif /* POWERPC_PERFORMANCE_REPORT */
3052

    
3053
#ifndef CONFIG_WIN32
3054
    if (received_sigterm) {
3055
        fprintf(stderr,
3056
            "Received signal %d: terminating.\n",
3057
            (int) received_sigterm);
3058
        exit (255);
3059
    }
3060
#endif
3061
    exit(0); /* not all OS-es handle main() return value */
3062
    return 0;
3063
}