Statistics
| Branch: | Revision:

ffmpeg / ffmpeg.c @ 9ce2f2b1

History | View | Annotate | Download (81.8 KB)

1
/*
2
 * FFmpeg main 
3
 * Copyright (c) 2000, 2001, 2002 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

    
22
#ifndef CONFIG_WIN32
23
#include <unistd.h>
24
#include <fcntl.h>
25
#include <sys/ioctl.h>
26
#include <sys/time.h>
27
#include <termios.h>
28
#include <sys/resource.h>
29
#endif
30
#include <time.h>
31
#include <ctype.h>
32

    
33

    
34
#define MAXINT64 INT64_C(0x7fffffffffffffff)
35

    
36
typedef struct {
37
    const char *name;
38
    int flags;
39
#define HAS_ARG    0x0001
40
#define OPT_BOOL   0x0002
41
#define OPT_EXPERT 0x0004
42
#define OPT_STRING 0x0008
43
    union {
44
        void (*func_arg)();
45
        int *int_arg;
46
        char **str_arg;
47
    } u;
48
    const char *help;
49
    const char *argname;
50
} OptionDef;
51

    
52
/* select an input stream for an output stream */
53
typedef struct AVStreamMap {
54
    int file_index;
55
    int stream_index;
56
} AVStreamMap;
57

    
58
extern const OptionDef options[];
59

    
60
void show_help(void);
61

    
62
#define MAX_FILES 20
63

    
64
static AVFormatContext *input_files[MAX_FILES];
65
static int nb_input_files = 0;
66

    
67
static AVFormatContext *output_files[MAX_FILES];
68
static int nb_output_files = 0;
69

    
70
static AVStreamMap stream_maps[MAX_FILES];
71
static int nb_stream_maps;
72

    
73
static AVInputFormat *file_iformat;
74
static AVOutputFormat *file_oformat;
75
static int frame_width  = 160;
76
static int frame_height = 128;
77
static int frame_topBand  = 0;
78
static int frame_bottomBand = 0;
79
static int frame_leftBand  = 0;
80
static int frame_rightBand = 0;
81
static int frame_rate = 25 * FRAME_RATE_BASE;
82
static int video_bit_rate = 200*1000;
83
static int video_bit_rate_tolerance = 4000*1000;
84
static int video_qscale = 0;
85
static int video_qmin = 2;
86
static int video_qmax = 31;
87
static int video_qdiff = 3;
88
static float video_qblur = 0.5;
89
static float video_qcomp = 0.5;
90
#if 0 //experimental, (can be removed)
91
static float video_rc_qsquish=1.0;
92
static float video_rc_qmod_amp=0;
93
static int video_rc_qmod_freq=0;
94
#endif
95
static char *video_rc_override_string=NULL;
96
static char *video_rc_eq="tex^qComp";
97
static int video_rc_buffer_size=0;
98
static float video_rc_buffer_aggressivity=1.0;
99
static int video_rc_max_rate=0;
100
static int video_rc_min_rate=0;
101
static float video_rc_initial_cplx=0;
102
static float video_b_qfactor = 1.25;
103
static float video_b_qoffset = 1.25;
104
static float video_i_qfactor = -0.8;
105
static float video_i_qoffset = 0.0;
106
static int me_method = 0;
107
static int video_disable = 0;
108
static int video_codec_id = CODEC_ID_NONE;
109
static int same_quality = 0;
110
static int b_frames = 0;
111
static int use_hq = 0;
112
static int use_4mv = 0;
113
static int do_deinterlace = 0;
114
static int workaround_bugs = FF_BUG_AUTODETECT;
115
static int error_resilience = 2;
116
static int error_concealment = 3;
117
static int dct_algo = 0;
118
static int idct_algo = 0;
119
static int use_part = 0;
120
static int packet_size = 0;
121

    
122
static int gop_size = 12;
123
static int intra_only = 0;
124
static int audio_sample_rate = 44100;
125
static int audio_bit_rate = 64000;
126
static int audio_disable = 0;
127
static int audio_channels = 1;
128
static int audio_codec_id = CODEC_ID_NONE;
129

    
130
static INT64 recording_time = 0;
131
static int file_overwrite = 0;
132
static char *str_title = NULL;
133
static char *str_author = NULL;
134
static char *str_copyright = NULL;
135
static char *str_comment = NULL;
136
static int do_benchmark = 0;
137
static int do_hex_dump = 0;
138
static int do_play = 0;
139
static int do_psnr = 0;
140
static int do_vstats = 0;
141
static int do_pass = 0;
142
static char *pass_logfilename = NULL;
143
static int audio_stream_copy = 0;
144
static int video_stream_copy = 0;
145

    
146
#define DEFAULT_PASS_LOGFILENAME "ffmpeg2pass"
147

    
148
#if !defined(CONFIG_AUDIO_OSS) && !defined(CONFIG_AUDIO_BEOS)
149
const char *audio_device = "none";
150
#endif
151
#ifndef CONFIG_VIDEO4LINUX
152
const char *v4l_device = "none";
153
#endif
154

    
155
typedef struct AVOutputStream {
156
    int file_index;          /* file index */
157
    int index;               /* stream index in the output file */
158
    int source_index;        /* AVInputStream index */
159
    AVStream *st;            /* stream in the output file */
160
    int encoding_needed;     /* true if encoding needed for this stream */
161
    int frame_number;
162
    /* input pts and corresponding output pts
163
       for A/V sync */
164
    double sync_ipts;
165
    INT64 sync_opts;
166
    /* video only */
167
    AVPicture pict_tmp;         /* temporary image for resizing */
168
    int video_resample;
169
    ImgReSampleContext *img_resample_ctx; /* for image resampling */
170
    
171
    /* audio only */
172
    int audio_resample;
173
    ReSampleContext *resample; /* for audio resampling */
174
    FifoBuffer fifo;     /* for compression: one audio fifo per codec */
175
    FILE *logfile;
176
} AVOutputStream;
177

    
178
typedef struct AVInputStream {
179
    int file_index;
180
    int index;
181
    AVStream *st;
182
    int discard;             /* true if stream data should be discarded */
183
    int decoding_needed;     /* true if the packets must be decoded in 'raw_fifo' */
184
    INT64 sample_index;      /* current sample */
185
    int frame_decoded;       /* true if a video or audio frame has been decoded */
186
} AVInputStream;
187

    
188
typedef struct AVInputFile {
189
    int eof_reached;      /* true if eof reached */
190
    int ist_index;        /* index of first stream in ist_table */
191
    int buffer_size;      /* current total buffer size */
192
    int buffer_size_max;  /* buffer size at which we consider we can stop
193
                             buffering */
194
    int nb_streams;       /* nb streams we are aware of */
195
} AVInputFile;
196

    
197
#ifndef CONFIG_WIN32
198

    
199
/* init terminal so that we can grab keys */
200
static struct termios oldtty;
201

    
202
static void term_exit(void)
203
{
204
    tcsetattr (0, TCSANOW, &oldtty);
205
}
206

    
207
static void term_init(void)
208
{
209
    struct termios tty;
210

    
211
    tcgetattr (0, &tty);
212
    oldtty = tty;
213

    
214
    tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
215
                          |INLCR|IGNCR|ICRNL|IXON);
216
    tty.c_oflag |= OPOST;
217
    tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
218
    tty.c_cflag &= ~(CSIZE|PARENB);
219
    tty.c_cflag |= CS8;
220
    tty.c_cc[VMIN] = 1;
221
    tty.c_cc[VTIME] = 0;
222
    
223
    tcsetattr (0, TCSANOW, &tty);
224

    
225
    atexit(term_exit);
226
#ifdef CONFIG_BEOS_NETSERVER
227
    fcntl(0, F_SETFL, fcntl(0, F_GETFL) | O_NONBLOCK);
228
#endif
229
}
230

    
231
/* read a key without blocking */
232
static int read_key(void)
233
{
234
    int n = 1;
235
    unsigned char ch;
236
#ifndef CONFIG_BEOS_NETSERVER
237
    struct timeval tv;
238
    fd_set rfds;
239

    
240
    FD_ZERO(&rfds);
241
    FD_SET(0, &rfds);
242
    tv.tv_sec = 0;
243
    tv.tv_usec = 0;
244
    n = select(1, &rfds, NULL, NULL, &tv);
245
#endif
246
    if (n > 0) {
247
        n = read(0, &ch, 1);
248
        if (n == 1)
249
            return ch;
250

    
251
        return n;
252
    }
253
    return -1;
254
}
255

    
256
#else
257

    
258
/* no interactive support */
259
static void term_exit(void)
260
{
261
}
262

    
263
static void term_init(void)
264
{
265
}
266

    
267
static int read_key(void)
268
{
269
    return 0;
270
}
271

    
272
#endif
273

    
274
int read_ffserver_streams(AVFormatContext *s, const char *filename)
275
{
276
    int i, err;
277
    AVFormatContext *ic;
278

    
279
    err = av_open_input_file(&ic, filename, NULL, FFM_PACKET_SIZE, NULL);
280
    if (err < 0)
281
        return err;
282
    /* copy stream format */
283
    s->nb_streams = ic->nb_streams;
284
    for(i=0;i<ic->nb_streams;i++) {
285
        AVStream *st;
286
        st = av_mallocz(sizeof(AVFormatContext));
287
        memcpy(st, ic->streams[i], sizeof(AVStream));
288
        s->streams[i] = st;
289
    }
290

    
291
    av_close_input_file(ic);
292
    return 0;
293
}
294

    
295
#define MAX_AUDIO_PACKET_SIZE 16384
296

    
297
static void do_audio_out(AVFormatContext *s, 
298
                         AVOutputStream *ost, 
299
                         AVInputStream *ist,
300
                         unsigned char *buf, int size)
301
{
302
    UINT8 *buftmp;
303
    UINT8 audio_buf[2*MAX_AUDIO_PACKET_SIZE]; /* XXX: allocate it */
304
    UINT8 audio_out[4*MAX_AUDIO_PACKET_SIZE]; /* XXX: allocate it - yep really WMA */
305
    int size_out, frame_bytes, ret;
306
    AVCodecContext *enc;
307

    
308
    enc = &ost->st->codec;
309

    
310
    if (ost->audio_resample) {
311
        buftmp = audio_buf;
312
        size_out = audio_resample(ost->resample, 
313
                                  (short *)buftmp, (short *)buf,
314
                                  size / (ist->st->codec.channels * 2));
315
        size_out = size_out * enc->channels * 2;
316
    } else {
317
        buftmp = buf;
318
        size_out = size;
319
    }
320

    
321
    /* now encode as many frames as possible */
322
    if (enc->frame_size > 1) {
323
        /* output resampled raw samples */
324
        fifo_write(&ost->fifo, buftmp, size_out, 
325
                   &ost->fifo.wptr);
326

    
327
        frame_bytes = enc->frame_size * 2 * enc->channels;
328
        
329
        while (fifo_read(&ost->fifo, audio_buf, frame_bytes, 
330
                     &ost->fifo.rptr) == 0) {
331
            ret = avcodec_encode_audio(enc, audio_out, sizeof(audio_out), 
332
                                       (short *)audio_buf);
333
            av_write_frame(s, ost->index, audio_out, ret);
334
        }
335
    } else {
336
        /* output a pcm frame */
337
        /* XXX: change encoding codec API to avoid this ? */
338
        switch(enc->codec->id) {
339
        case CODEC_ID_PCM_S16LE:
340
        case CODEC_ID_PCM_S16BE:
341
        case CODEC_ID_PCM_U16LE:
342
        case CODEC_ID_PCM_U16BE:
343
            break;
344
        default:
345
            size_out = size_out >> 1;
346
            break;
347
        }
348
        ret = avcodec_encode_audio(enc, audio_out, size_out, 
349
                                   (short *)buftmp);
350
        av_write_frame(s, ost->index, audio_out, ret);
351
    }
352
}
353

    
354
/* write a picture to a raw mux */
355
static void write_picture(AVFormatContext *s, int index, AVPicture *picture, 
356
                          int pix_fmt, int w, int h)
357
{
358
    UINT8 *buf, *src, *dest;
359
    int size, j, i;
360

    
361
    /* XXX: not efficient, should add test if we can take
362
       directly the AVPicture */
363
    switch(pix_fmt) {
364
    case PIX_FMT_YUV420P:
365
        size = avpicture_get_size(pix_fmt, w, h);
366
        buf = av_malloc(size);
367
        if (!buf)
368
            return;
369
        dest = buf;
370
        for(i=0;i<3;i++) {
371
            if (i == 1) {
372
                w >>= 1;
373
                h >>= 1;
374
            }
375
            src = picture->data[i];
376
            for(j=0;j<h;j++) {
377
                memcpy(dest, src, w);
378
                dest += w;
379
                src += picture->linesize[i];
380
            }
381
        }
382
        break;
383
    case PIX_FMT_YUV422P:
384
        size = (w * h) * 2; 
385
        buf = av_malloc(size);
386
        if (!buf)
387
            return;
388
        dest = buf;
389
        for(i=0;i<3;i++) {
390
            if (i == 1) {
391
                w >>= 1;
392
            }
393
            src = picture->data[i];
394
            for(j=0;j<h;j++) {
395
                memcpy(dest, src, w);
396
                dest += w;
397
                src += picture->linesize[i];
398
            }
399
        }
400
        break;
401
    case PIX_FMT_YUV444P:
402
        size = (w * h) * 3; 
403
        buf = av_malloc(size);
404
        if (!buf)
405
            return;
406
        dest = buf;
407
        for(i=0;i<3;i++) {
408
            src = picture->data[i];
409
            for(j=0;j<h;j++) {
410
                memcpy(dest, src, w);
411
                dest += w;
412
                src += picture->linesize[i];
413
            }
414
        }
415
        break;
416
    case PIX_FMT_YUV422:
417
        size = (w * h) * 2; 
418
        buf = av_malloc(size);
419
        if (!buf)
420
            return;
421
        dest = buf;
422
        src = picture->data[0];
423
        for(j=0;j<h;j++) {
424
            memcpy(dest, src, w * 2);
425
            dest += w * 2;
426
            src += picture->linesize[0];
427
        }
428
        break;
429
    case PIX_FMT_RGB24:
430
    case PIX_FMT_BGR24:
431
        size = (w * h) * 3; 
432
        buf = av_malloc(size);
433
        if (!buf)
434
            return;
435
        dest = buf;
436
        src = picture->data[0];
437
        for(j=0;j<h;j++) {
438
            memcpy(dest, src, w * 3);
439
            dest += w * 3;
440
            src += picture->linesize[0];
441
        }
442
        break;
443
    default:
444
        return;
445
    }
446
    av_write_frame(s, index, buf, size);
447
    av_free(buf);
448
}
449

    
450
/* we begin to correct av delay at this threshold */
451
#define AV_DELAY_MAX 0.100
452

    
453
static void do_video_out(AVFormatContext *s, 
454
                         AVOutputStream *ost, 
455
                         AVInputStream *ist,
456
                         AVPicture *picture1,
457
                         int *frame_size, AVOutputStream *audio_sync)
458
{
459
    int nb_frames, i, ret;
460
    AVPicture *picture, *picture2, *pict;
461
    AVPicture picture_tmp1, picture_tmp2;
462
    static UINT8 *video_buffer;
463
    UINT8 *buf = NULL, *buf1 = NULL;
464
    AVCodecContext *enc, *dec;
465

    
466
#define VIDEO_BUFFER_SIZE (1024*1024)
467

    
468
    enc = &ost->st->codec;
469
    dec = &ist->st->codec;
470

    
471
    /* by default, we output a single frame */
472
    nb_frames = 1;
473

    
474
    /* NOTE: the A/V sync is always done by considering the audio is
475
       the master clock. It is suffisant for transcoding or playing,
476
       but not for the general case */
477
    if (audio_sync) {
478
        /* compute the A-V delay and duplicate/remove frames if needed */
479
        double adelta, vdelta, apts, vpts, av_delay;
480
        
481
        if (audio_sync->sync_ipts != AV_NOPTS_VALUE &&
482
            ost->sync_ipts != AV_NOPTS_VALUE) {
483
            
484
            adelta = (double)(ost->st->pts.val - audio_sync->sync_opts) * 
485
                s->pts_num / s->pts_den;
486
            apts = audio_sync->sync_ipts + adelta; 
487
            
488
            vdelta = (double)(ost->st->pts.val - ost->sync_opts) *
489
                s->pts_num / s->pts_den;
490
            vpts = ost->sync_ipts + vdelta;
491
            
492
            av_delay = apts - vpts;
493
            //            printf("delay=%f\n", av_delay);
494
            if (av_delay < -AV_DELAY_MAX)
495
                nb_frames = 2;
496
            else if (av_delay > AV_DELAY_MAX)
497
                nb_frames = 0;
498
        }
499
    }
500
    /* XXX: also handle frame rate conversion */
501
    if (nb_frames <= 0) 
502
        return;
503

    
504
    if (!video_buffer)
505
        video_buffer = av_malloc(VIDEO_BUFFER_SIZE);
506
    if (!video_buffer)
507
        return;
508

    
509
    /* deinterlace : must be done before any resize */
510
    if (do_deinterlace) {
511
        int size;
512

    
513
        /* create temporary picture */
514
        size = avpicture_get_size(dec->pix_fmt, dec->width, dec->height);
515
        buf1 = av_malloc(size);
516
        if (!buf1)
517
            return;
518
        
519
        picture2 = &picture_tmp2;
520
        avpicture_fill(picture2, buf1, dec->pix_fmt, dec->width, dec->height);
521

    
522
        if (avpicture_deinterlace(picture2, picture1, 
523
                                  dec->pix_fmt, dec->width, dec->height) < 0) {
524
            /* if error, do not deinterlace */
525
            av_free(buf1);
526
            buf1 = NULL;
527
            picture2 = picture1;
528
        }
529
    } else {
530
        picture2 = picture1;
531
    }
532

    
533
    /* convert pixel format if needed */
534
    if (enc->pix_fmt != dec->pix_fmt) {
535
        int size;
536

    
537
        /* create temporary picture */
538
        size = avpicture_get_size(enc->pix_fmt, dec->width, dec->height);
539
        buf = av_malloc(size);
540
        if (!buf)
541
            return;
542
        pict = &picture_tmp1;
543
        avpicture_fill(pict, buf, enc->pix_fmt, dec->width, dec->height);
544
        
545
        if (img_convert(pict, enc->pix_fmt, 
546
                        picture2, dec->pix_fmt, 
547
                        dec->width, dec->height) < 0) {
548
            fprintf(stderr, "pixel format conversion not handled\n");
549
            goto the_end;
550
        }
551
    } else {
552
        pict = picture2;
553
    }
554

    
555
    /* XXX: resampling could be done before raw format convertion in
556
       some cases to go faster */
557
    /* XXX: only works for YUV420P */
558
    if (ost->video_resample) {
559
        picture = &ost->pict_tmp;
560
        img_resample(ost->img_resample_ctx, picture, pict);
561
    } else {
562
        picture = pict;
563
    }
564
    /* duplicates frame if needed */
565
    /* XXX: pb because no interleaving */
566
    for(i=0;i<nb_frames;i++) {
567
        if (enc->codec_id != CODEC_ID_RAWVIDEO) {
568
            /* handles sameq here. This is not correct because it may
569
               not be a global option */
570
            if (same_quality) {
571
                enc->quality = dec->quality;
572
            }
573
            
574
            ret = avcodec_encode_video(enc, 
575
                                       video_buffer, VIDEO_BUFFER_SIZE,
576
                                       picture);
577
            //enc->frame_number = enc->real_pict_num;
578
            av_write_frame(s, ost->index, video_buffer, ret);
579
            *frame_size = ret;
580
            //fprintf(stderr,"\nFrame: %3d %3d size: %5d type: %d",
581
            //        enc->frame_number-1, enc->real_pict_num, ret,
582
            //        enc->pict_type);
583
            /* if two pass, output log */
584
            if (ost->logfile && enc->stats_out) {
585
                fprintf(ost->logfile, "%s", enc->stats_out);
586
            }
587
        } else {
588
            if (s->oformat->flags & AVFMT_RAWPICTURE) {
589
                /* raw pictures are written as AVPicture structure to
590
                   avoid any copies. We support temorarily the older
591
                   method. */
592
                av_write_frame(s, ost->index, 
593
                               (UINT8 *)picture, sizeof(AVPicture));
594
            } else {
595
                write_picture(s, ost->index, picture, enc->pix_fmt, 
596
                              enc->width, enc->height);
597
            }
598
        }
599
        ost->frame_number++;
600
    }
601
 the_end:
602
    av_free(buf);
603
    av_free(buf1);
604
}
605

    
606
static void do_video_stats(AVFormatContext *os, AVOutputStream *ost, 
607
                           int frame_size)
608
{
609
    static FILE *fvstats=NULL;
610
    static INT64 total_size = 0;
611
    char filename[40];
612
    time_t today2;
613
    struct tm *today;
614
    AVCodecContext *enc;
615
    int frame_number;
616
    INT64 ti;
617
    double ti1, bitrate, avg_bitrate;
618
    
619
    if (!fvstats) {
620
        today2 = time(NULL);
621
        today = localtime(&today2);
622
        sprintf(filename, "vstats_%02d%02d%02d.log", today->tm_hour,
623
                                               today->tm_min,
624
                                               today->tm_sec);
625
        fvstats = fopen(filename,"w");
626
        if (!fvstats) {
627
            perror("fopen");
628
            exit(1);
629
        }
630
    }
631
    
632
    ti = MAXINT64;
633
    enc = &ost->st->codec;
634
    total_size += frame_size;
635
    if (enc->codec_type == CODEC_TYPE_VIDEO) {
636
        frame_number = ost->frame_number;
637
        fprintf(fvstats, "frame= %5d q= %2d ", frame_number, enc->quality);
638
        if (do_psnr)
639
            fprintf(fvstats, "PSNR= %6.2f ", enc->psnr_y);
640
        
641
        fprintf(fvstats,"f_size= %6d ", frame_size);
642
        /* compute pts value */
643
        ti1 = (double)ost->st->pts.val * os->pts_num / os->pts_den;
644
        if (ti1 < 0.01)
645
            ti1 = 0.01;
646
    
647
        bitrate = (double)(frame_size * 8) * enc->frame_rate / FRAME_RATE_BASE / 1000.0;
648
        avg_bitrate = (double)(total_size * 8) / ti1 / 1000.0;
649
        fprintf(fvstats, "s_size= %8.0fkB time= %0.3f br= %7.1fkbits/s avg_br= %7.1fkbits/s ",
650
            (double)total_size / 1024, ti1, bitrate, avg_bitrate);
651
        fprintf(fvstats,"type= %s\n", enc->key_frame == 1 ? "I" : "P");        
652
    }
653
}
654

    
655
void print_report(AVFormatContext **output_files, 
656
                  AVOutputStream **ost_table, int nb_ostreams,
657
                  int is_last_report)
658
{
659
    char buf[1024];
660
    AVOutputStream *ost;
661
    AVFormatContext *oc, *os;
662
    INT64 total_size;
663
    AVCodecContext *enc;
664
    int frame_number, vid, i;
665
    double bitrate, ti1, pts;
666
    static INT64 last_time = -1;
667
    
668
    if (!is_last_report) {
669
        INT64 cur_time;
670
        /* display the report every 0.5 seconds */
671
        cur_time = av_gettime();
672
        if (last_time == -1) {
673
            last_time = cur_time;
674
            return;
675
        } 
676
        if ((cur_time - last_time) < 500000)
677
            return;
678
        last_time = cur_time;
679
    }
680

    
681

    
682
    oc = output_files[0];
683

    
684
    total_size = url_ftell(&oc->pb);
685
    
686
    buf[0] = '\0';
687
    ti1 = 1e10;
688
    vid = 0;
689
    for(i=0;i<nb_ostreams;i++) {
690
        ost = ost_table[i];
691
        os = output_files[ost->file_index];
692
        enc = &ost->st->codec;
693
        if (!vid && enc->codec_type == CODEC_TYPE_VIDEO) {
694
            frame_number = ost->frame_number;
695
            sprintf(buf + strlen(buf), "frame=%5d q=%2d ",
696
                    frame_number, enc->quality);
697
            if (do_psnr)
698
                sprintf(buf + strlen(buf), "PSNR=%6.2f ", enc->psnr_y);
699
            vid = 1;
700
        }
701
        /* compute min output value */
702
        pts = (double)ost->st->pts.val * os->pts_num / os->pts_den;
703
        if ((pts < ti1) && (pts > 0))
704
            ti1 = pts;
705
    }
706
    if (ti1 < 0.01)
707
        ti1 = 0.01;
708
    bitrate = (double)(total_size * 8) / ti1 / 1000.0;
709
    
710
    sprintf(buf + strlen(buf), 
711
            "size=%8.0fkB time=%0.1f bitrate=%6.1fkbits/s",
712
            (double)total_size / 1024, ti1, bitrate);
713
    
714
    fprintf(stderr, "%s   ", buf);
715
    
716
    if (is_last_report) {
717
        fprintf(stderr, "\n");
718
    } else {
719
        fprintf(stderr, "\r");
720
        fflush(stderr);
721
    }
722
}
723

    
724
/*
725
 * The following code is the main loop of the file converter
726
 */
727
static int av_encode(AVFormatContext **output_files,
728
                     int nb_output_files,
729
                     AVFormatContext **input_files,
730
                     int nb_input_files,
731
                     AVStreamMap *stream_maps, int nb_stream_maps)
732
{
733
    int ret, i, j, k, n, nb_istreams = 0, nb_ostreams = 0, pts_set;
734
    AVFormatContext *is, *os;
735
    AVCodecContext *codec, *icodec;
736
    AVOutputStream *ost, **ost_table = NULL;
737
    AVInputStream *ist, **ist_table = NULL;
738
    AVInputFile *file_table;
739
    AVFormatContext *stream_no_data;
740
    int key;
741

    
742
    file_table= (AVInputFile*) av_mallocz(nb_input_files * sizeof(AVInputFile));
743
    if (!file_table)
744
        goto fail;
745

    
746
    /* input stream init */
747
    j = 0;
748
    for(i=0;i<nb_input_files;i++) {
749
        is = input_files[i];
750
        file_table[i].ist_index = j;
751
        file_table[i].nb_streams = is->nb_streams;
752
        j += is->nb_streams;
753
    }
754
    nb_istreams = j;
755

    
756
    ist_table = av_mallocz(nb_istreams * sizeof(AVInputStream *));
757
    if (!ist_table)
758
        goto fail;
759
    
760
    for(i=0;i<nb_istreams;i++) {
761
        ist = av_mallocz(sizeof(AVInputStream));
762
        if (!ist)
763
            goto fail;
764
        ist_table[i] = ist;
765
    }
766
    j = 0;
767
    for(i=0;i<nb_input_files;i++) {
768
        is = input_files[i];
769
        for(k=0;k<is->nb_streams;k++) {
770
            ist = ist_table[j++];
771
            ist->st = is->streams[k];
772
            ist->file_index = i;
773
            ist->index = k;
774
            ist->discard = 1; /* the stream is discarded by default
775
                                 (changed later) */
776
        }
777
    }
778

    
779
    /* output stream init */
780
    nb_ostreams = 0;
781
    for(i=0;i<nb_output_files;i++) {
782
        os = output_files[i];
783
        nb_ostreams += os->nb_streams;
784
    }
785
    if (nb_stream_maps > 0 && nb_stream_maps != nb_ostreams) {
786
        fprintf(stderr, "Number of stream maps must match number of output streams\n");
787
        exit(1);
788
    }
789

    
790
    ost_table = av_mallocz(sizeof(AVOutputStream *) * nb_ostreams);
791
    if (!ost_table)
792
        goto fail;
793
    for(i=0;i<nb_ostreams;i++) {
794
        ost = av_mallocz(sizeof(AVOutputStream));
795
        if (!ost)
796
            goto fail;
797
        ost_table[i] = ost;
798
    }
799
    
800
    n = 0;
801
    for(k=0;k<nb_output_files;k++) {
802
        os = output_files[k];
803
        for(i=0;i<os->nb_streams;i++) {
804
            int found;
805
            ost = ost_table[n++];
806
            ost->file_index = k;
807
            ost->index = i;
808
            ost->st = os->streams[i];
809
            if (nb_stream_maps > 0) {
810
                ost->source_index = file_table[stream_maps[n-1].file_index].ist_index + 
811
                    stream_maps[n-1].stream_index;
812
            } else {
813
                /* get corresponding input stream index : we select the first one with the right type */
814
                found = 0;
815
                for(j=0;j<nb_istreams;j++) {
816
                    ist = ist_table[j];
817
                    if (ist->discard && 
818
                        ist->st->codec.codec_type == ost->st->codec.codec_type) {
819
                        ost->source_index = j;
820
                        found = 1;
821
                    }
822
                }
823
                
824
                if (!found) {
825
                    /* try again and reuse existing stream */
826
                    for(j=0;j<nb_istreams;j++) {
827
                        ist = ist_table[j];
828
                        if (ist->st->codec.codec_type == ost->st->codec.codec_type) {
829
                            ost->source_index = j;
830
                            found = 1;
831
                        }
832
                    }
833
                    if (!found) {
834
                        fprintf(stderr, "Could not find input stream matching output stream #%d.%d\n",
835
                                ost->file_index, ost->index);
836
                        exit(1);
837
                    }
838
                }
839
            }
840
            ist = ist_table[ost->source_index];
841
            ist->discard = 0;
842
        }
843
    }
844

    
845
    /* for each output stream, we compute the right encoding parameters */
846
    for(i=0;i<nb_ostreams;i++) {
847
        ost = ost_table[i];
848
        ist = ist_table[ost->source_index];
849

    
850
        codec = &ost->st->codec;
851
        icodec = &ist->st->codec;
852

    
853
        if (ost->st->stream_copy) {
854
            /* if stream_copy is selected, no need to decode or encode */
855
            codec->codec_id = icodec->codec_id;
856
            codec->codec_type = icodec->codec_type;
857
            codec->codec_tag = icodec->codec_tag;
858
            codec->bit_rate = icodec->bit_rate;
859
            switch(codec->codec_type) {
860
            case CODEC_TYPE_AUDIO:
861
                codec->sample_rate = icodec->sample_rate;
862
                codec->channels = icodec->channels;
863
                break;
864
            case CODEC_TYPE_VIDEO:
865
                codec->frame_rate = icodec->frame_rate;
866
                codec->width = icodec->width;
867
                codec->height = icodec->height;
868
                break;
869
            default:
870
                av_abort();
871
            }
872
        } else {
873
            switch(codec->codec_type) {
874
            case CODEC_TYPE_AUDIO:
875
                if (fifo_init(&ost->fifo, 2 * MAX_AUDIO_PACKET_SIZE))
876
                    goto fail;
877
                
878
                if (codec->channels == icodec->channels &&
879
                    codec->sample_rate == icodec->sample_rate) {
880
                    ost->audio_resample = 0;
881
                } else {
882
                    if (codec->channels != icodec->channels &&
883
                        icodec->codec_id == CODEC_ID_AC3) {
884
                        /* Special case for 5:1 AC3 input */
885
                        /* and mono or stereo output      */
886
                        /* Request specific number of channels */
887
                        icodec->channels = codec->channels;
888
                        if (codec->sample_rate == icodec->sample_rate)
889
                            ost->audio_resample = 0;
890
                        else {
891
                            ost->audio_resample = 1;
892
                            ost->resample = audio_resample_init(codec->channels, icodec->channels,
893
                                                        codec->sample_rate, 
894
                                                        icodec->sample_rate);
895
                        }
896
                        /* Request specific number of channels */
897
                        icodec->channels = codec->channels;
898
                    } else {
899
                        ost->audio_resample = 1; 
900
                        ost->resample = audio_resample_init(codec->channels, icodec->channels,
901
                                                        codec->sample_rate, 
902
                                                        icodec->sample_rate);
903
                    }
904
                }
905
                ist->decoding_needed = 1;
906
                ost->encoding_needed = 1;
907
                break;
908
            case CODEC_TYPE_VIDEO:
909
                if (codec->width == icodec->width &&
910
                    codec->height == icodec->height) {
911
                    ost->video_resample = 0;
912
                } else {
913
                    UINT8 *buf;
914
                    ost->video_resample = 1;
915
                    buf = av_malloc((codec->width * codec->height * 3) / 2);
916
                    if (!buf)
917
                        goto fail;
918
                    ost->pict_tmp.data[0] = buf;
919
                    ost->pict_tmp.data[1] = ost->pict_tmp.data[0] + (codec->width * codec->height);
920
                    ost->pict_tmp.data[2] = ost->pict_tmp.data[1] + (codec->width * codec->height) / 4;
921
                    ost->pict_tmp.linesize[0] = codec->width;
922
                    ost->pict_tmp.linesize[1] = codec->width / 2;
923
                    ost->pict_tmp.linesize[2] = codec->width / 2;
924

    
925
                    ost->img_resample_ctx = img_resample_full_init( 
926
                                      ost->st->codec.width, ost->st->codec.height,
927
                                      ist->st->codec.width, ist->st->codec.height,
928
                                      frame_topBand, frame_bottomBand,
929
                                      frame_leftBand, frame_rightBand);
930
                }
931
                ost->encoding_needed = 1;
932
                ist->decoding_needed = 1;
933
                break;
934
            default:
935
                av_abort();
936
            }
937
            /* two pass mode */
938
            if (ost->encoding_needed && 
939
                (codec->flags & (CODEC_FLAG_PASS1 | CODEC_FLAG_PASS2))) {
940
                char logfilename[1024];
941
                FILE *f;
942
                int size;
943
                char *logbuffer;
944
                
945
                snprintf(logfilename, sizeof(logfilename), "%s-%d.log", 
946
                         pass_logfilename ? 
947
                         pass_logfilename : DEFAULT_PASS_LOGFILENAME, i);
948
                if (codec->flags & CODEC_FLAG_PASS1) {
949
                    f = fopen(logfilename, "w");
950
                    if (!f) {
951
                        perror(logfilename);
952
                        exit(1);
953
                    }
954
                    ost->logfile = f;
955
                } else {
956
                    /* read the log file */
957
                    f = fopen(logfilename, "r");
958
                    if (!f) {
959
                        perror(logfilename);
960
                        exit(1);
961
                    }
962
                    fseek(f, 0, SEEK_END);
963
                    size = ftell(f);
964
                    fseek(f, 0, SEEK_SET);
965
                    logbuffer = av_malloc(size + 1);
966
                    if (!logbuffer) {
967
                        fprintf(stderr, "Could not allocate log buffer\n");
968
                        exit(1);
969
                    }
970
                    fread(logbuffer, 1, size, f);
971
                    fclose(f);
972
                    logbuffer[size] = '\0';
973
                    codec->stats_in = logbuffer;
974
                }
975
            }
976
        }
977
    }
978

    
979
    /* dump the file output parameters - cannot be done before in case
980
       of stream copy */
981
    for(i=0;i<nb_output_files;i++) {
982
        dump_format(output_files[i], i, output_files[i]->filename, 1);
983
    }
984

    
985
    /* dump the stream mapping */
986
    fprintf(stderr, "Stream mapping:\n");
987
    for(i=0;i<nb_ostreams;i++) {
988
        ost = ost_table[i];
989
        fprintf(stderr, "  Stream #%d.%d -> #%d.%d\n",
990
                ist_table[ost->source_index]->file_index,
991
                ist_table[ost->source_index]->index,
992
                ost->file_index, 
993
                ost->index);
994
    }
995

    
996
    /* open each encoder */
997
    for(i=0;i<nb_ostreams;i++) {
998
        ost = ost_table[i];
999
        if (ost->encoding_needed) {
1000
            AVCodec *codec;
1001
            codec = avcodec_find_encoder(ost->st->codec.codec_id);
1002
            if (!codec) {
1003
                fprintf(stderr, "Unsupported codec for output stream #%d.%d\n", 
1004
                        ost->file_index, ost->index);
1005
                exit(1);
1006
            }
1007
            if (avcodec_open(&ost->st->codec, codec) < 0) {
1008
                fprintf(stderr, "Error while opening codec for stream #%d.%d - maybe incorrect parameters such as bit_rate, rate, width or height\n", 
1009
                        ost->file_index, ost->index);
1010
                exit(1);
1011
            }
1012
        }
1013
    }
1014

    
1015
    /* open each decoder */
1016
    for(i=0;i<nb_istreams;i++) {
1017
        ist = ist_table[i];
1018
        if (ist->decoding_needed) {
1019
            AVCodec *codec;
1020
            codec = avcodec_find_decoder(ist->st->codec.codec_id);
1021
            if (!codec) {
1022
                fprintf(stderr, "Unsupported codec for input stream #%d.%d\n", 
1023
                        ist->file_index, ist->index);
1024
                exit(1);
1025
            }
1026
            if (avcodec_open(&ist->st->codec, codec) < 0) {
1027
                fprintf(stderr, "Error while opening codec for input stream #%d.%d\n", 
1028
                        ist->file_index, ist->index);
1029
                exit(1);
1030
            }
1031
            //if (ist->st->codec.codec_type == CODEC_TYPE_VIDEO)
1032
            //    ist->st->codec.flags |= CODEC_FLAG_REPEAT_FIELD;
1033
            ist->frame_decoded = 1;
1034
        }
1035
    }
1036

    
1037
    /* init pts */
1038
    for(i=0;i<nb_istreams;i++) {
1039
        ist = ist_table[i];
1040
    }
1041
    
1042
    /* compute buffer size max (should use a complete heuristic) */
1043
    for(i=0;i<nb_input_files;i++) {
1044
        file_table[i].buffer_size_max = 2048;
1045
    }
1046

    
1047
    /* open files and write file headers */
1048
    for(i=0;i<nb_output_files;i++) {
1049
        os = output_files[i];
1050
        if (av_write_header(os) < 0) {
1051
            fprintf(stderr, "Could not write header for output file #%d (incorrect codec paramters ?)\n", i);
1052
            ret = -EINVAL;
1053
            goto fail;
1054
        }
1055
    }
1056

    
1057
#ifndef CONFIG_WIN32
1058
    if (!do_play) {
1059
        fprintf(stderr, "Press [q] to stop encoding\n");
1060
    } else {
1061
        fprintf(stderr, "Press [q] to stop playing\n");
1062
    }
1063
#endif
1064
    term_init();
1065

    
1066
    stream_no_data = 0;
1067
    key = -1;
1068

    
1069
    for(;;) {
1070
        int file_index, ist_index;
1071
        AVPacket pkt;
1072
        UINT8 *ptr;
1073
        int len;
1074
        UINT8 *data_buf;
1075
        int data_size, got_picture;
1076
        AVPicture picture;
1077
        short samples[AVCODEC_MAX_AUDIO_FRAME_SIZE / 2];
1078
        double pts_min;
1079
        
1080
    redo:
1081
        /* if 'q' pressed, exits */
1082
        if (key) {
1083
            /* read_key() returns 0 on EOF */
1084
            key = read_key();
1085
            if (key == 'q')
1086
                break;
1087
        }
1088

    
1089
        /* select the stream that we must read now by looking at the
1090
           smallest output pts */
1091
        file_index = -1;
1092
        pts_min = 1e10;
1093
        for(i=0;i<nb_ostreams;i++) {
1094
            double pts;
1095
            ost = ost_table[i];
1096
            os = output_files[ost->file_index];
1097
            ist = ist_table[ost->source_index];
1098
            pts = (double)ost->st->pts.val * os->pts_num / os->pts_den;
1099
            if (!file_table[ist->file_index].eof_reached && 
1100
                pts < pts_min) {
1101
                pts_min = pts;
1102
                file_index = ist->file_index;
1103
            }
1104
        }
1105
        /* if none, if is finished */
1106
        if (file_index < 0) {
1107
            break;
1108
        }
1109

    
1110
        /* finish if recording time exhausted */
1111
        if (recording_time > 0 && pts_min >= (recording_time / 1000000.0))
1112
            break;
1113

    
1114
        /* read a packet from it and output it in the fifo */
1115
        is = input_files[file_index];
1116
        if (av_read_packet(is, &pkt) < 0) {
1117
            file_table[file_index].eof_reached = 1;
1118
            continue;
1119
        }
1120
        if (!pkt.size) {
1121
            stream_no_data = is;
1122
        } else {
1123
            stream_no_data = 0;
1124
        }
1125
        /* the following test is needed in case new streams appear
1126
           dynamically in stream : we ignore them */
1127
        if (pkt.stream_index >= file_table[file_index].nb_streams)
1128
            goto discard_packet;
1129
        ist_index = file_table[file_index].ist_index + pkt.stream_index;
1130
        ist = ist_table[ist_index];
1131
        if (ist->discard)
1132
            goto discard_packet;
1133

    
1134
        if (do_hex_dump) {
1135
            printf("stream #%d, size=%d:\n", pkt.stream_index, pkt.size);
1136
            av_hex_dump(pkt.data, pkt.size);
1137
        }
1138

    
1139
        //        printf("read #%d.%d size=%d\n", ist->file_index, ist->index, pkt.size);
1140

    
1141
        len = pkt.size;
1142
        ptr = pkt.data;
1143
        pts_set = 0;
1144
        while (len > 0) {
1145
            INT64 ipts;
1146

    
1147
            ipts = AV_NOPTS_VALUE;
1148

    
1149
            /* decode the packet if needed */
1150
            data_buf = NULL; /* fail safe */
1151
            data_size = 0;
1152
            if (ist->decoding_needed) {
1153
                /* NOTE1: we only take into account the PTS if a new
1154
                   frame has begun (MPEG semantics) */
1155
                /* NOTE2: even if the fraction is not initialized,
1156
                   av_frac_set can be used to set the integer part */
1157
                if (ist->frame_decoded && 
1158
                    pkt.pts != AV_NOPTS_VALUE && 
1159
                    !pts_set) {
1160
                    ipts = pkt.pts;
1161
                    ist->frame_decoded = 0;
1162
                    pts_set = 1;
1163
                }
1164

    
1165
                switch(ist->st->codec.codec_type) {
1166
                case CODEC_TYPE_AUDIO:
1167
                    /* XXX: could avoid copy if PCM 16 bits with same
1168
                       endianness as CPU */
1169
                    ret = avcodec_decode_audio(&ist->st->codec, samples, &data_size,
1170
                                               ptr, len);
1171
                    if (ret < 0)
1172
                        goto fail_decode;
1173
                    /* Some bug in mpeg audio decoder gives */
1174
                    /* data_size < 0, it seems they are overflows */
1175
                    if (data_size <= 0) {
1176
                        /* no audio frame */
1177
                        ptr += ret;
1178
                        len -= ret;
1179
                        continue;
1180
                    }
1181
                    data_buf = (UINT8 *)samples;
1182
                    break;
1183
                case CODEC_TYPE_VIDEO:
1184
                    if (ist->st->codec.codec_id == CODEC_ID_RAWVIDEO) {
1185
                        int size;
1186

    
1187
                        size = (ist->st->codec.width * ist->st->codec.height);
1188
                        avpicture_fill(&picture, ptr, 
1189
                                     ist->st->codec.pix_fmt,
1190
                                     ist->st->codec.width,
1191
                                     ist->st->codec.height);
1192
                        ret = len;
1193
                    } else {
1194
                        data_size = (ist->st->codec.width * ist->st->codec.height * 3) / 2;
1195
                        ret = avcodec_decode_video(&ist->st->codec, 
1196
                                                   &picture, &got_picture, ptr, len);
1197
                        if (ret < 0) {
1198
                        fail_decode:
1199
                            fprintf(stderr, "Error while decoding stream #%d.%d\n",
1200
                                    ist->file_index, ist->index);
1201
                            av_free_packet(&pkt);
1202
                            goto redo;
1203
                        }
1204
                        if (!got_picture) {
1205
                            /* no picture yet */
1206
                            ptr += ret;
1207
                            len -= ret;
1208
                            continue;
1209
                        }
1210
                                  
1211
                    }
1212
                    break;
1213
                default:
1214
                    goto fail_decode;
1215
                }
1216
            } else {
1217
                data_buf = ptr;
1218
                data_size = len;
1219
                ret = len;
1220
            }
1221
            ptr += ret;
1222
            len -= ret;
1223

    
1224
            ist->frame_decoded = 1;
1225

    
1226
#if 0
1227
            /* mpeg PTS deordering : if it is a P or I frame, the PTS
1228
               is the one of the next displayed one */
1229
            /* XXX: add mpeg4 too ? */
1230
            if (ist->st->codec.codec_id == CODEC_ID_MPEG1VIDEO) {
1231
                if (ist->st->codec.pict_type != B_TYPE) {
1232
                    INT64 tmp;
1233
                    tmp = ist->last_ip_pts;
1234
                    ist->last_ip_pts  = ist->frac_pts.val;
1235
                    ist->frac_pts.val = tmp;
1236
                }
1237
            }
1238
#endif
1239
            /* transcode raw format, encode packets and output them */
1240

    
1241
            for(i=0;i<nb_ostreams;i++) {
1242
                int frame_size;
1243

    
1244
                ost = ost_table[i];
1245
                if (ost->source_index == ist_index) {
1246
                    os = output_files[ost->file_index];
1247

    
1248
                    if (ipts != AV_NOPTS_VALUE) {
1249
#if 0
1250
                        printf("%d: got pts=%f %f\n", 
1251
                               i, pkt.pts / 90000.0, 
1252
                               (ipts - ost->st->pts.val) / 90000.0);
1253
#endif
1254
                        /* set the input output pts pairs */
1255
                        ost->sync_ipts = (double)ipts * is->pts_num / 
1256
                            is->pts_den;
1257
                        /* XXX: take into account the various fifos,
1258
                           in particular for audio */
1259
                        ost->sync_opts = ost->st->pts.val;
1260
                    }
1261

    
1262
                    if (ost->encoding_needed) {
1263
                        switch(ost->st->codec.codec_type) {
1264
                        case CODEC_TYPE_AUDIO:
1265
                            do_audio_out(os, ost, ist, data_buf, data_size);
1266
                            break;
1267
                        case CODEC_TYPE_VIDEO:
1268
                            /* find an audio stream for synchro */
1269
                            {
1270
                                int i;
1271
                                AVOutputStream *audio_sync, *ost1;
1272
                                audio_sync = NULL;
1273
                                for(i=0;i<nb_ostreams;i++) {
1274
                                    ost1 = ost_table[i];
1275
                                    if (ost1->file_index == ost->file_index &&
1276
                                        ost1->st->codec.codec_type == CODEC_TYPE_AUDIO) {
1277
                                        audio_sync = ost1;
1278
                                        break;
1279
                                    }
1280
                                }
1281

    
1282
                                do_video_out(os, ost, ist, &picture, &frame_size, audio_sync);
1283
                                if (do_vstats)
1284
                                    do_video_stats(os, ost, frame_size);
1285
                            }
1286
                            break;
1287
                        default:
1288
                            av_abort();
1289
                        }
1290
                    } else {
1291
                        /* no reencoding needed : output the packet directly */
1292
                        /* force the input stream PTS */
1293
                        av_write_frame(os, ost->index, data_buf, data_size);
1294
                        ost->st->codec.frame_number++;
1295
                        ost->frame_number++;
1296
                    }
1297
                }
1298
            }
1299
            ipts = AV_NOPTS_VALUE;
1300
        }
1301
    discard_packet:
1302
        av_free_packet(&pkt);
1303
        
1304
        /* dump report by using the output first video and audio streams */
1305
        print_report(output_files, ost_table, nb_ostreams, 0);
1306
    }
1307
    term_exit();
1308

    
1309
    /* dump report by using the first video and audio streams */
1310
    print_report(output_files, ost_table, nb_ostreams, 1);
1311

    
1312
    /* close each encoder */
1313
    for(i=0;i<nb_ostreams;i++) {
1314
        ost = ost_table[i];
1315
        if (ost->encoding_needed) {
1316
            av_freep(&ost->st->codec.stats_in);
1317
            avcodec_close(&ost->st->codec);
1318
        }
1319
    }
1320
    
1321
    /* close each decoder */
1322
    for(i=0;i<nb_istreams;i++) {
1323
        ist = ist_table[i];
1324
        if (ist->decoding_needed) {
1325
            avcodec_close(&ist->st->codec);
1326
        }
1327
    }
1328
    
1329

    
1330
    /* write the trailer if needed and close file */
1331
    for(i=0;i<nb_output_files;i++) {
1332
        os = output_files[i];
1333
        av_write_trailer(os);
1334
    }
1335
    /* finished ! */
1336
    
1337
    ret = 0;
1338
 fail1:
1339
    av_free(file_table);
1340

    
1341
    if (ist_table) {
1342
        for(i=0;i<nb_istreams;i++) {
1343
            ist = ist_table[i];
1344
            av_free(ist);
1345
        }
1346
        av_free(ist_table);
1347
    }
1348
    if (ost_table) {
1349
        for(i=0;i<nb_ostreams;i++) {
1350
            ost = ost_table[i];
1351
            if (ost) {
1352
                if (ost->logfile) {
1353
                    fclose(ost->logfile);
1354
                    ost->logfile = NULL;
1355
                }
1356
                fifo_free(&ost->fifo); /* works even if fifo is not
1357
                                          initialized but set to zero */
1358
                av_free(ost->pict_tmp.data[0]);
1359
                if (ost->video_resample)
1360
                    img_resample_close(ost->img_resample_ctx);
1361
                if (ost->audio_resample)
1362
                    audio_resample_close(ost->resample);
1363
                av_free(ost);
1364
            }
1365
        }
1366
        av_free(ost_table);
1367
    }
1368
    return ret;
1369
 fail:
1370
    ret = -ENOMEM;
1371
    goto fail1;
1372
}
1373

    
1374
#if 0
1375
int file_read(const char *filename)
1376
{
1377
    URLContext *h;
1378
    unsigned char buffer[1024];
1379
    int len, i;
1380

1381
    if (url_open(&h, filename, O_RDONLY) < 0) {
1382
        printf("could not open '%s'\n", filename);
1383
        return -1;
1384
    }
1385
    for(;;) {
1386
        len = url_read(h, buffer, sizeof(buffer));
1387
        if (len <= 0)
1388
            break;
1389
        for(i=0;i<len;i++) putchar(buffer[i]);
1390
    }
1391
    url_close(h);
1392
    return 0;
1393
}
1394
#endif
1395

    
1396
void show_licence(void)
1397
{
1398
    printf(
1399
    "ffmpeg version " FFMPEG_VERSION "\n"
1400
    "Copyright (c) 2000, 2001, 2002 Fabrice Bellard\n"
1401
    "This library is free software; you can redistribute it and/or\n"
1402
    "modify it under the terms of the GNU Lesser General Public\n"
1403
    "License as published by the Free Software Foundation; either\n"
1404
    "version 2 of the License, or (at your option) any later version.\n"
1405
    "\n"
1406
    "This library is distributed in the hope that it will be useful,\n"
1407
    "but WITHOUT ANY WARRANTY; without even the implied warranty of\n"
1408
    "MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n"
1409
    "Lesser General Public License for more details.\n"
1410
    "\n"
1411
    "You should have received a copy of the GNU Lesser General Public\n"
1412
    "License along with this library; if not, write to the Free Software\n"
1413
    "Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA\n"
1414
    );
1415
    exit(1);
1416
}
1417

    
1418
void opt_format(const char *arg)
1419
{
1420
    file_iformat = av_find_input_format(arg);
1421
    file_oformat = guess_format(arg, NULL, NULL);
1422
    if (!file_iformat && !file_oformat) {
1423
        fprintf(stderr, "Unknown input or output format: %s\n", arg);
1424
        exit(1);
1425
    }
1426
}
1427

    
1428
void opt_video_bitrate(const char *arg)
1429
{
1430
    video_bit_rate = atoi(arg) * 1000;
1431
}
1432

    
1433
void opt_video_bitrate_tolerance(const char *arg)
1434
{
1435
    video_bit_rate_tolerance = atoi(arg) * 1000;
1436
}
1437

    
1438
void opt_video_bitrate_max(const char *arg)
1439
{
1440
    video_rc_max_rate = atoi(arg) * 1000;
1441
}
1442

    
1443
void opt_video_bitrate_min(const char *arg)
1444
{
1445
    video_rc_min_rate = atoi(arg) * 1000;
1446
}
1447

    
1448
void opt_video_buffer_size(const char *arg)
1449
{
1450
    video_rc_buffer_size = atoi(arg) * 1000;
1451
}
1452

    
1453
void opt_video_rc_eq(char *arg)
1454
{
1455
    video_rc_eq = arg;
1456
}
1457

    
1458
void opt_video_rc_override_string(char *arg)
1459
{
1460
    video_rc_override_string = arg;
1461
}
1462

    
1463

    
1464
void opt_workaround_bugs(const char *arg)
1465
{
1466
    workaround_bugs = atoi(arg);
1467
}
1468

    
1469
void opt_dct_algo(const char *arg)
1470
{
1471
    dct_algo = atoi(arg);
1472
}
1473

    
1474
void opt_idct_algo(const char *arg)
1475
{
1476
    idct_algo = atoi(arg);
1477
}
1478

    
1479

    
1480
void opt_error_resilience(const char *arg)
1481
{
1482
    error_resilience = atoi(arg);
1483
}
1484

    
1485
void opt_error_concealment(const char *arg)
1486
{
1487
    error_concealment = atoi(arg);
1488
}
1489

    
1490

    
1491
void opt_frame_rate(const char *arg)
1492
{
1493
    frame_rate = (int)(strtod(arg, 0) * FRAME_RATE_BASE);
1494
}
1495

    
1496

    
1497
void opt_frame_crop_top(const char *arg)
1498
{
1499
    frame_topBand = atoi(arg); 
1500
    if (frame_topBand < 0) {
1501
        fprintf(stderr, "Incorrect top crop size\n");
1502
        exit(1);
1503
    }
1504
    if ((frame_topBand % 2) != 0) {
1505
        fprintf(stderr, "Top crop size must be a multiple of 2\n");
1506
        exit(1);
1507
    }
1508
    if ((frame_topBand) >= frame_height){
1509
            fprintf(stderr, "Vertical crop dimensions are outside the range of the original image.\nRemember to crop first and scale second.\n");
1510
        exit(1);
1511
    }
1512
    frame_height -= frame_topBand;
1513
}
1514

    
1515
void opt_frame_crop_bottom(const char *arg)
1516
{
1517
    frame_bottomBand = atoi(arg);
1518
    if (frame_bottomBand < 0) {
1519
        fprintf(stderr, "Incorrect bottom crop size\n");
1520
        exit(1);
1521
    }
1522
    if ((frame_bottomBand % 2) != 0) {
1523
        fprintf(stderr, "Bottom crop size must be a multiple of 2\n");
1524
        exit(1);        
1525
    }
1526
    if ((frame_bottomBand) >= frame_height){
1527
            fprintf(stderr, "Vertical crop dimensions are outside the range of the original image.\nRemember to crop first and scale second.\n");
1528
        exit(1);
1529
    }
1530
    frame_height -= frame_bottomBand;
1531
}
1532

    
1533
void opt_frame_crop_left(const char *arg)
1534
{
1535
    frame_leftBand = atoi(arg);
1536
    if (frame_leftBand < 0) {
1537
        fprintf(stderr, "Incorrect left crop size\n");
1538
        exit(1);
1539
    }
1540
    if ((frame_leftBand % 2) != 0) {
1541
        fprintf(stderr, "Left crop size must be a multiple of 2\n");
1542
        exit(1);
1543
    }
1544
    if ((frame_leftBand) >= frame_width){
1545
            fprintf(stderr, "Horizontal crop dimensions are outside the range of the original image.\nRemember to crop first and scale second.\n");
1546
        exit(1);
1547
    }
1548
    frame_width -= frame_leftBand;
1549
}
1550

    
1551
void opt_frame_crop_right(const char *arg)
1552
{
1553
    frame_rightBand = atoi(arg);
1554
    if (frame_rightBand < 0) {
1555
        fprintf(stderr, "Incorrect right crop size\n");
1556
        exit(1);
1557
    }
1558
    if ((frame_rightBand % 2) != 0) {
1559
        fprintf(stderr, "Right crop size must be a multiple of 2\n");
1560
        exit(1);        
1561
    }
1562
    if ((frame_rightBand) >= frame_width){
1563
            fprintf(stderr, "Horizontal crop dimensions are outside the range of the original image.\nRemember to crop first and scale second.\n");
1564
        exit(1);
1565
    }
1566
    frame_width -= frame_rightBand;
1567
}
1568

    
1569
void opt_frame_size(const char *arg)
1570
{
1571
    parse_image_size(&frame_width, &frame_height, arg);
1572
    if (frame_width <= 0 || frame_height <= 0) {
1573
        fprintf(stderr, "Incorrect frame size\n");
1574
        exit(1);
1575
    }
1576
    if ((frame_width % 2) != 0 || (frame_height % 2) != 0) {
1577
        fprintf(stderr, "Frame size must be a multiple of 2\n");
1578
        exit(1);
1579
    }
1580
}
1581

    
1582
void opt_gop_size(const char *arg)
1583
{
1584
    gop_size = atoi(arg);
1585
}
1586

    
1587
void opt_b_frames(const char *arg)
1588
{
1589
    b_frames = atoi(arg);
1590
    if (b_frames > FF_MAX_B_FRAMES) {
1591
        fprintf(stderr, "\nCannot have more than %d B frames, increase FF_MAX_B_FRAMES.\n", FF_MAX_B_FRAMES);
1592
        exit(1);
1593
    } else if (b_frames < 1) {
1594
        fprintf(stderr, "\nNumber of B frames must be higher than 0\n");
1595
        exit(1);
1596
    }
1597
}
1598

    
1599
void opt_qscale(const char *arg)
1600
{
1601
    video_qscale = atoi(arg);
1602
    if (video_qscale < 0 ||
1603
        video_qscale > 31) {
1604
        fprintf(stderr, "qscale must be >= 1 and <= 31\n");
1605
        exit(1);
1606
    }
1607
}
1608

    
1609
void opt_qmin(const char *arg)
1610
{
1611
    video_qmin = atoi(arg);
1612
    if (video_qmin < 0 ||
1613
        video_qmin > 31) {
1614
        fprintf(stderr, "qmin must be >= 1 and <= 31\n");
1615
        exit(1);
1616
    }
1617
}
1618

    
1619
void opt_qmax(const char *arg)
1620
{
1621
    video_qmax = atoi(arg);
1622
    if (video_qmax < 0 ||
1623
        video_qmax > 31) {
1624
        fprintf(stderr, "qmax must be >= 1 and <= 31\n");
1625
        exit(1);
1626
    }
1627
}
1628

    
1629
void opt_qdiff(const char *arg)
1630
{
1631
    video_qdiff = atoi(arg);
1632
    if (video_qdiff < 0 ||
1633
        video_qdiff > 31) {
1634
        fprintf(stderr, "qdiff must be >= 1 and <= 31\n");
1635
        exit(1);
1636
    }
1637
}
1638

    
1639
void opt_qblur(const char *arg)
1640
{
1641
    video_qblur = atof(arg);
1642
}
1643

    
1644
void opt_qcomp(const char *arg)
1645
{
1646
    video_qcomp = atof(arg);
1647
}
1648

    
1649
void opt_rc_initial_cplx(const char *arg)
1650
{
1651
    video_rc_initial_cplx = atof(arg);
1652
}
1653
void opt_b_qfactor(const char *arg)
1654
{
1655
    video_b_qfactor = atof(arg);
1656
}
1657
void opt_i_qfactor(const char *arg)
1658
{
1659
    video_i_qfactor = atof(arg);
1660
}
1661
void opt_b_qoffset(const char *arg)
1662
{
1663
    video_b_qoffset = atof(arg);
1664
}
1665
void opt_i_qoffset(const char *arg)
1666
{
1667
    video_i_qoffset = atof(arg);
1668
}
1669

    
1670
void opt_packet_size(const char *arg)
1671
{
1672
    packet_size= atoi(arg);
1673
}
1674

    
1675
void opt_audio_bitrate(const char *arg)
1676
{
1677
    audio_bit_rate = atoi(arg) * 1000;
1678
}
1679

    
1680
void opt_audio_rate(const char *arg)
1681
{
1682
    audio_sample_rate = atoi(arg);
1683
}
1684

    
1685
void opt_audio_channels(const char *arg)
1686
{
1687
    audio_channels = atoi(arg);
1688
}
1689

    
1690
void opt_video_device(const char *arg)
1691
{
1692
    v4l_device = strdup(arg);
1693
}
1694

    
1695
void opt_audio_device(const char *arg)
1696
{
1697
    audio_device = strdup(arg);
1698
}
1699

    
1700
void opt_audio_codec(const char *arg)
1701
{
1702
    AVCodec *p;
1703

    
1704
    if (!strcmp(arg, "copy")) {
1705
        audio_stream_copy = 1;
1706
    } else {
1707
        p = first_avcodec;
1708
        while (p) {
1709
            if (!strcmp(p->name, arg) && p->type == CODEC_TYPE_AUDIO)
1710
                break;
1711
            p = p->next;
1712
        }
1713
        if (p == NULL) {
1714
            fprintf(stderr, "Unknown audio codec '%s'\n", arg);
1715
            exit(1);
1716
        } else {
1717
            audio_codec_id = p->id;
1718
        }
1719
    }
1720
}
1721

    
1722
const char *motion_str[] = {
1723
    "zero",
1724
    "full",
1725
    "log",
1726
    "phods",
1727
    "epzs",
1728
    "x1",
1729
    NULL,
1730
};
1731

    
1732
void opt_motion_estimation(const char *arg)
1733
{
1734
    const char **p;
1735
    p = motion_str;
1736
    for(;;) {
1737
        if (!*p) {
1738
            fprintf(stderr, "Unknown motion estimation method '%s'\n", arg);
1739
            exit(1);
1740
        }
1741
        if (!strcmp(*p, arg))
1742
            break;
1743
        p++;
1744
    }
1745
    me_method = (p - motion_str) + 1;
1746
}
1747

    
1748
void opt_video_codec(const char *arg)
1749
{
1750
    AVCodec *p;
1751

    
1752
    if (!strcmp(arg, "copy")) {
1753
        video_stream_copy = 1;
1754
    } else {
1755
        p = first_avcodec;
1756
        while (p) {
1757
            if (!strcmp(p->name, arg) && p->type == CODEC_TYPE_VIDEO)
1758
                break;
1759
            p = p->next;
1760
        }
1761
        if (p == NULL) {
1762
            fprintf(stderr, "Unknown video codec '%s'\n", arg);
1763
            exit(1);
1764
        } else {
1765
            video_codec_id = p->id;
1766
        }
1767
    }
1768
}
1769

    
1770
void opt_map(const char *arg)
1771
{
1772
    AVStreamMap *m;
1773
    const char *p;
1774

    
1775
    p = arg;
1776
    m = &stream_maps[nb_stream_maps++];
1777

    
1778
    m->file_index = strtol(arg, (char **)&p, 0);
1779
    if (*p)
1780
        p++;
1781

    
1782
    m->stream_index = strtol(p, (char **)&p, 0);
1783
}
1784

    
1785
void opt_recording_time(const char *arg)
1786
{
1787
    recording_time = parse_date(arg, 1);
1788
}
1789

    
1790
void print_error(const char *filename, int err)
1791
{
1792
    switch(err) {
1793
    case AVERROR_NUMEXPECTED:
1794
        fprintf(stderr, "%s: Incorrect image filename syntax.\n"
1795
                "Use '%%d' to specify the image number:\n"
1796
                "  for img1.jpg, img2.jpg, ..., use 'img%%d.jpg';\n"
1797
                "  for img001.jpg, img002.jpg, ..., use 'img%%03d.jpg'.\n", 
1798
                filename);
1799
        break;
1800
    case AVERROR_INVALIDDATA:
1801
        fprintf(stderr, "%s: Error while parsing header\n", filename);
1802
        break;
1803
    case AVERROR_NOFMT:
1804
        fprintf(stderr, "%s: Unknown format\n", filename);
1805
        break;
1806
    default:
1807
        fprintf(stderr, "%s: Error while opening file\n", filename);
1808
        break;
1809
    }
1810
}
1811

    
1812
void opt_input_file(const char *filename)
1813
{
1814
    AVFormatContext *ic;
1815
    AVFormatParameters params, *ap = &params;
1816
    int err, i, ret, rfps;
1817

    
1818
    /* get default parameters from command line */
1819
    memset(ap, 0, sizeof(*ap));
1820
    ap->sample_rate = audio_sample_rate;
1821
    ap->channels = audio_channels;
1822
    ap->frame_rate = frame_rate;
1823
    ap->width = frame_width;
1824
    ap->height = frame_height;
1825

    
1826
    /* open the input file with generic libav function */
1827
    err = av_open_input_file(&ic, filename, file_iformat, 0, ap);
1828
    if (err < 0) {
1829
        print_error(filename, err);
1830
        exit(1);
1831
    }
1832
    
1833
    /* If not enough info to get the stream parameters, we decode the
1834
       first frames to get it. (used in mpeg case for example) */
1835
    ret = av_find_stream_info(ic);
1836
    if (ret < 0) {
1837
        fprintf(stderr, "%s: could not find codec parameters\n", filename);
1838
        exit(1);
1839
    }
1840

    
1841
    /* update the current parameters so that they match the one of the input stream */
1842
    for(i=0;i<ic->nb_streams;i++) {
1843
        AVCodecContext *enc = &ic->streams[i]->codec;
1844
        switch(enc->codec_type) {
1845
        case CODEC_TYPE_AUDIO:
1846
            //fprintf(stderr, "\nInput Audio channels: %d", enc->channels);
1847
            audio_channels = enc->channels;
1848
            audio_sample_rate = enc->sample_rate;
1849
            break;
1850
        case CODEC_TYPE_VIDEO:
1851
            frame_height = enc->height;
1852
            frame_width = enc->width;
1853
            rfps = ic->streams[i]->r_frame_rate;
1854
            enc->workaround_bugs = workaround_bugs;
1855
            enc->error_resilience = error_resilience; 
1856
            enc->error_concealment = error_concealment; 
1857
            enc->idct_algo= idct_algo;
1858
/*            if(enc->codec->capabilities & CODEC_CAP_TRUNCATED)
1859
                enc->flags|= CODEC_FLAG_TRUNCATED; */
1860
            if(/*enc->codec_id==CODEC_ID_MPEG4 || */enc->codec_id==CODEC_ID_MPEG1VIDEO)
1861
                enc->flags|= CODEC_FLAG_TRUNCATED;
1862

    
1863
            if (enc->frame_rate != rfps) {
1864
                fprintf(stderr,"\nSeems that stream %d comes from film source: %2.2f->%2.2f\n",
1865
                    i, (float)enc->frame_rate / FRAME_RATE_BASE,
1866
                    (float)rfps / FRAME_RATE_BASE);
1867
            }
1868
            /* update the current frame rate to match the stream frame rate */
1869
            frame_rate = rfps;
1870
            break;
1871
        default:
1872
            av_abort();
1873
        }
1874
    }
1875
    
1876
    input_files[nb_input_files] = ic;
1877
    /* dump the file content */
1878
    dump_format(ic, nb_input_files, filename, 0);
1879
    nb_input_files++;
1880
    file_iformat = NULL;
1881
    file_oformat = NULL;
1882
}
1883

    
1884
void check_audio_video_inputs(int *has_video_ptr, int *has_audio_ptr)
1885
{
1886
    int has_video, has_audio, i, j;
1887
    AVFormatContext *ic;
1888

    
1889
    has_video = 0;
1890
    has_audio = 0;
1891
    for(j=0;j<nb_input_files;j++) {
1892
        ic = input_files[j];
1893
        for(i=0;i<ic->nb_streams;i++) {
1894
            AVCodecContext *enc = &ic->streams[i]->codec;
1895
            switch(enc->codec_type) {
1896
            case CODEC_TYPE_AUDIO:
1897
                has_audio = 1;
1898
                break;
1899
            case CODEC_TYPE_VIDEO:
1900
                has_video = 1;
1901
                break;
1902
            default:
1903
                av_abort();
1904
            }
1905
        }
1906
    }
1907
    *has_video_ptr = has_video;
1908
    *has_audio_ptr = has_audio;
1909
}
1910

    
1911
void opt_output_file(const char *filename)
1912
{
1913
    AVStream *st;
1914
    AVFormatContext *oc;
1915
    int use_video, use_audio, nb_streams, input_has_video, input_has_audio;
1916
    int codec_id;
1917

    
1918
    if (!strcmp(filename, "-"))
1919
        filename = "pipe:";
1920

    
1921
    oc = av_mallocz(sizeof(AVFormatContext));
1922

    
1923
    if (!file_oformat) {
1924
        file_oformat = guess_format(NULL, filename, NULL);
1925
        if (!file_oformat) {
1926
            fprintf(stderr, "Unable for find a suitable output format for '%s'\n",
1927
                    filename);
1928
            exit(1);
1929
        }
1930
    }
1931
    
1932
    oc->oformat = file_oformat;
1933

    
1934
    if (!strcmp(file_oformat->name, "ffm") && 
1935
        strstart(filename, "http:", NULL)) {
1936
        /* special case for files sent to ffserver: we get the stream
1937
           parameters from ffserver */
1938
        if (read_ffserver_streams(oc, filename) < 0) {
1939
            fprintf(stderr, "Could not read stream parameters from '%s'\n", filename);
1940
            exit(1);
1941
        }
1942
    } else {
1943
        use_video = file_oformat->video_codec != CODEC_ID_NONE;
1944
        use_audio = file_oformat->audio_codec != CODEC_ID_NONE;
1945

    
1946
        /* disable if no corresponding type found and at least one
1947
           input file */
1948
        if (nb_input_files > 0) {
1949
            check_audio_video_inputs(&input_has_video, &input_has_audio);
1950
            if (!input_has_video)
1951
                use_video = 0;
1952
            if (!input_has_audio)
1953
                use_audio = 0;
1954
        }
1955

    
1956
        /* manual disable */
1957
        if (audio_disable) {
1958
            use_audio = 0;
1959
        }
1960
        if (video_disable) {
1961
            use_video = 0;
1962
        }
1963
        
1964
        nb_streams = 0;
1965
        if (use_video) {
1966
            AVCodecContext *video_enc;
1967
            
1968
            st = av_mallocz(sizeof(AVStream));
1969
            if (!st) {
1970
                fprintf(stderr, "Could not alloc stream\n");
1971
                exit(1);
1972
            }
1973

    
1974
            video_enc = &st->codec;
1975
            if (video_stream_copy) {
1976
                st->stream_copy = 1;
1977
                video_enc->codec_type = CODEC_TYPE_VIDEO;
1978
            } else {
1979
                char *p;
1980
                int i;
1981
            
1982
                codec_id = file_oformat->video_codec;
1983
                if (video_codec_id != CODEC_ID_NONE)
1984
                    codec_id = video_codec_id;
1985
                
1986
                video_enc->codec_id = codec_id;
1987
                
1988
                video_enc->bit_rate = video_bit_rate;
1989
                video_enc->bit_rate_tolerance = video_bit_rate_tolerance;
1990
                video_enc->frame_rate = frame_rate; 
1991
                
1992
                video_enc->width = frame_width;
1993
                video_enc->height = frame_height;
1994

    
1995
                if (!intra_only)
1996
                    video_enc->gop_size = gop_size;
1997
                else
1998
                    video_enc->gop_size = 0;
1999
                if (video_qscale || same_quality) {
2000
                    video_enc->flags |= CODEC_FLAG_QSCALE;
2001
                    video_enc->quality = video_qscale;
2002
                }
2003
            
2004
                if (use_hq) {
2005
                    video_enc->flags |= CODEC_FLAG_HQ;
2006
                }
2007
            
2008
                if (use_4mv) {
2009
                    video_enc->flags |= CODEC_FLAG_HQ;
2010
                    video_enc->flags |= CODEC_FLAG_4MV;
2011
                }
2012
            
2013
                if(use_part)
2014
                    video_enc->flags |= CODEC_FLAG_PART;
2015
               
2016
            
2017
                if (b_frames) {
2018
                    if (codec_id != CODEC_ID_MPEG4) {
2019
                        fprintf(stderr, "\nB frames encoding only supported by MPEG-4.\n");
2020
                        exit(1);
2021
                    }
2022
                    video_enc->max_b_frames = b_frames;
2023
                    video_enc->b_frame_strategy = 0;
2024
                    video_enc->b_quant_factor = 2.0;
2025
                }
2026
            
2027
                video_enc->qmin = video_qmin;
2028
                video_enc->qmax = video_qmax;
2029
                video_enc->max_qdiff = video_qdiff;
2030
                video_enc->qblur = video_qblur;
2031
                video_enc->qcompress = video_qcomp;
2032
                video_enc->rc_eq = video_rc_eq;
2033
                
2034
                p= video_rc_override_string;
2035
                for(i=0; p; i++){
2036
                    int start, end, q;
2037
                    int e=sscanf(p, "%d,%d,%d", &start, &end, &q);
2038
                    if(e!=3){
2039
                        fprintf(stderr, "error parsing rc_override\n");
2040
                        exit(1);
2041
                    }
2042
                    video_enc->rc_override= 
2043
                        realloc(video_enc->rc_override, sizeof(RcOverride)*(i+1));
2044
                    video_enc->rc_override[i].start_frame= start;
2045
                    video_enc->rc_override[i].end_frame  = end;
2046
                    if(q>0){
2047
                        video_enc->rc_override[i].qscale= q;
2048
                        video_enc->rc_override[i].quality_factor= 1.0;
2049
                    }
2050
                    else{
2051
                        video_enc->rc_override[i].qscale= 0;
2052
                        video_enc->rc_override[i].quality_factor= -q/100.0;
2053
                    }
2054
                    p= strchr(p, '/');
2055
                    if(p) p++;
2056
                }
2057
                video_enc->rc_override_count=i;
2058

    
2059
                video_enc->rc_max_rate = video_rc_max_rate;
2060
                video_enc->rc_min_rate = video_rc_min_rate;
2061
                video_enc->rc_buffer_size = video_rc_buffer_size;
2062
                video_enc->rc_buffer_aggressivity= video_rc_buffer_aggressivity;
2063
                video_enc->rc_initial_cplx= video_rc_initial_cplx;
2064
                video_enc->i_quant_factor = video_i_qfactor;
2065
                video_enc->b_quant_factor = video_b_qfactor;
2066
                video_enc->i_quant_offset = video_i_qoffset;
2067
                video_enc->b_quant_offset = video_b_qoffset;
2068
                video_enc->dct_algo = dct_algo;
2069
                video_enc->idct_algo = idct_algo;
2070
                if(packet_size){
2071
                    video_enc->rtp_mode= 1;
2072
                    video_enc->rtp_payload_size= packet_size;
2073
                }
2074
            
2075
                if (do_psnr)
2076
                    video_enc->get_psnr = 1;
2077
                else
2078
                    video_enc->get_psnr = 0;
2079
            
2080
                video_enc->me_method = me_method;
2081

    
2082
                /* two pass mode */
2083
                if (do_pass) {
2084
                    if (do_pass == 1) {
2085
                        video_enc->flags |= CODEC_FLAG_PASS1;
2086
                    } else {
2087
                        video_enc->flags |= CODEC_FLAG_PASS2;
2088
                    }
2089
                }
2090
            
2091
                /* XXX: need to find a way to set codec parameters */
2092
                if (oc->oformat->flags & AVFMT_RGB24) {
2093
                    video_enc->pix_fmt = PIX_FMT_RGB24;
2094
                }
2095
            }
2096
            oc->streams[nb_streams] = st;
2097
            nb_streams++;
2098
        }
2099
    
2100
        if (use_audio) {
2101
            AVCodecContext *audio_enc;
2102

    
2103
            st = av_mallocz(sizeof(AVStream));
2104
            if (!st) {
2105
                fprintf(stderr, "Could not alloc stream\n");
2106
                exit(1);
2107
            }
2108

    
2109
            audio_enc = &st->codec;
2110
            audio_enc->codec_type = CODEC_TYPE_AUDIO;
2111
            if (audio_stream_copy) {
2112
                st->stream_copy = 1;
2113
            } else {
2114
                codec_id = file_oformat->audio_codec;
2115
                if (audio_codec_id != CODEC_ID_NONE)
2116
                    codec_id = audio_codec_id;
2117
                audio_enc->codec_id = codec_id;
2118
                
2119
                audio_enc->bit_rate = audio_bit_rate;
2120
                audio_enc->sample_rate = audio_sample_rate;
2121
                /* For audio codecs other than AC3 we limit */
2122
                /* the number of coded channels to stereo   */
2123
                if (audio_channels > 2 && codec_id != CODEC_ID_AC3) {
2124
                    audio_enc->channels = 2;
2125
                } else
2126
                    audio_enc->channels = audio_channels;
2127
            }
2128
            oc->streams[nb_streams] = st;
2129
            nb_streams++;
2130
        }
2131

    
2132
        oc->nb_streams = nb_streams;
2133

    
2134
        if (!nb_streams) {
2135
            fprintf(stderr, "No audio or video streams available\n");
2136
            exit(1);
2137
        }
2138

    
2139
        if (str_title)
2140
            pstrcpy(oc->title, sizeof(oc->title), str_title);
2141
        if (str_author)
2142
            pstrcpy(oc->author, sizeof(oc->author), str_author);
2143
        if (str_copyright)
2144
            pstrcpy(oc->copyright, sizeof(oc->copyright), str_copyright);
2145
        if (str_comment)
2146
            pstrcpy(oc->comment, sizeof(oc->comment), str_comment);
2147
    }
2148

    
2149
    output_files[nb_output_files++] = oc;
2150

    
2151
    strcpy(oc->filename, filename);
2152

    
2153
    /* check filename in case of an image number is expected */
2154
    if (oc->oformat->flags & AVFMT_NEEDNUMBER) {
2155
        if (filename_number_test(oc->filename) < 0) {
2156
            print_error(oc->filename, AVERROR_NUMEXPECTED);
2157
            exit(1);
2158
        }
2159
    }
2160

    
2161
    if (!(oc->oformat->flags & AVFMT_NOFILE)) {
2162
        /* test if it already exists to avoid loosing precious files */
2163
        if (!file_overwrite && 
2164
            (strchr(filename, ':') == NULL ||
2165
             strstart(filename, "file:", NULL))) {
2166
            if (url_exist(filename)) {
2167
                int c;
2168
                
2169
                printf("File '%s' already exists. Overwrite ? [y/N] ", filename);
2170
                fflush(stdout);
2171
                c = getchar();
2172
                if (toupper(c) != 'Y') {
2173
                    fprintf(stderr, "Not overwriting - exiting\n");
2174
                    exit(1);
2175
                }
2176
            }
2177
        }
2178
        
2179
        /* open the file */
2180
        if (url_fopen(&oc->pb, filename, URL_WRONLY) < 0) {
2181
            fprintf(stderr, "Could not open '%s'\n", filename);
2182
            exit(1);
2183
        }
2184
    }
2185

    
2186
    /* reset some options */
2187
    file_oformat = NULL;
2188
    file_iformat = NULL;
2189
    audio_disable = 0;
2190
    video_disable = 0;
2191
    audio_codec_id = CODEC_ID_NONE;
2192
    video_codec_id = CODEC_ID_NONE;
2193
    audio_stream_copy = 0;
2194
    video_stream_copy = 0;
2195
}
2196

    
2197
/* prepare dummy protocols for grab */
2198
void prepare_grab(void)
2199
{
2200
    int has_video, has_audio, i, j;
2201
    AVFormatContext *oc;
2202
    AVFormatContext *ic;
2203
    AVFormatParameters ap1, *ap = &ap1;
2204

    
2205
    /* see if audio/video inputs are needed */
2206
    has_video = 0;
2207
    has_audio = 0;
2208
    memset(ap, 0, sizeof(*ap));
2209
    for(j=0;j<nb_output_files;j++) {
2210
        oc = output_files[j];
2211
        for(i=0;i<oc->nb_streams;i++) {
2212
            AVCodecContext *enc = &oc->streams[i]->codec;
2213
            switch(enc->codec_type) {
2214
            case CODEC_TYPE_AUDIO:
2215
                if (enc->sample_rate > ap->sample_rate)
2216
                    ap->sample_rate = enc->sample_rate;
2217
                if (enc->channels > ap->channels)
2218
                    ap->channels = enc->channels;
2219
                has_audio = 1;
2220
                break;
2221
            case CODEC_TYPE_VIDEO:
2222
                if (enc->width > ap->width)
2223
                    ap->width = enc->width;
2224
                if (enc->height > ap->height)
2225
                    ap->height = enc->height;
2226
                if (enc->frame_rate > ap->frame_rate)
2227
                    ap->frame_rate = enc->frame_rate;
2228
                has_video = 1;
2229
                break;
2230
            default:
2231
                av_abort();
2232
            }
2233
        }
2234
    }
2235
    
2236
    if (has_video == 0 && has_audio == 0) {
2237
        fprintf(stderr, "Output file must have at least one audio or video stream\n");
2238
        exit(1);
2239
    }
2240
    
2241
    if (has_video) {
2242
        AVInputFormat *fmt1;
2243
        fmt1 = av_find_input_format("video_grab_device");
2244
        if (av_open_input_file(&ic, "", fmt1, 0, ap) < 0) {
2245
            fprintf(stderr, "Could not find video grab device\n");
2246
            exit(1);
2247
        }
2248
        /* by now video grab has one stream */
2249
        ic->streams[0]->r_frame_rate = ap->frame_rate;
2250
        input_files[nb_input_files] = ic;
2251
        dump_format(ic, nb_input_files, v4l_device, 0);
2252
        nb_input_files++;
2253
    }
2254
    if (has_audio) {
2255
        AVInputFormat *fmt1;
2256
        fmt1 = av_find_input_format("audio_device");
2257
        if (av_open_input_file(&ic, "", fmt1, 0, ap) < 0) {
2258
            fprintf(stderr, "Could not find audio grab device\n");
2259
            exit(1);
2260
        }
2261
        input_files[nb_input_files] = ic;
2262
        dump_format(ic, nb_input_files, audio_device, 0);
2263
        nb_input_files++;
2264
    }
2265
}
2266

    
2267
/* open the necessary output devices for playing */
2268
void prepare_play(void)
2269
{
2270
    file_iformat = NULL;
2271
    file_oformat = guess_format("audio_device", NULL, NULL);
2272
    if (!file_oformat) {
2273
        fprintf(stderr, "Could not find audio device\n");
2274
        exit(1);
2275
    }
2276
    
2277
    opt_output_file(audio_device);
2278
}
2279

    
2280
/* same option as mencoder */
2281
void opt_pass(const char *pass_str)
2282
{
2283
    int pass;
2284
    pass = atoi(pass_str);
2285
    if (pass != 1 && pass != 2) {
2286
        fprintf(stderr, "pass number can be only 1 or 2\n");
2287
        exit(1);
2288
    }
2289
    do_pass = pass;
2290
}
2291

    
2292
#ifndef CONFIG_WIN32
2293
INT64 getutime(void)
2294
{
2295
    struct rusage rusage;
2296

    
2297
    getrusage(RUSAGE_SELF, &rusage);
2298
    return (rusage.ru_utime.tv_sec * 1000000LL) + rusage.ru_utime.tv_usec;
2299
}
2300
#else
2301
INT64 getutime(void)
2302
{
2303
  return av_gettime();
2304
}
2305
#endif
2306

    
2307
extern int ffm_nopts;
2308

    
2309
void opt_bitexact(void)
2310
{
2311
    avcodec_set_bit_exact();
2312
    /* disable generate of real time pts in ffm (need to be supressed anyway) */
2313
    ffm_nopts = 1;
2314
}
2315

    
2316
void show_formats(void)
2317
{
2318
    AVInputFormat *ifmt;
2319
    AVOutputFormat *ofmt;
2320
    URLProtocol *up;
2321
    AVCodec *p;
2322
    const char **pp;
2323

    
2324
    printf("File formats:\n");
2325
    printf("  Encoding:");
2326
    for(ofmt = first_oformat; ofmt != NULL; ofmt = ofmt->next) {
2327
        printf(" %s", ofmt->name);
2328
    }
2329
    printf("\n");
2330
    printf("  Decoding:");
2331
    for(ifmt = first_iformat; ifmt != NULL; ifmt = ifmt->next) {
2332
        printf(" %s", ifmt->name);
2333
    }
2334
    printf("\n");
2335

    
2336
    printf("Codecs:\n");
2337
    printf("  Encoders:");
2338
    for(p = first_avcodec; p != NULL; p = p->next) {
2339
        if (p->encode)
2340
            printf(" %s", p->name);
2341
    }
2342
    printf("\n");
2343

    
2344
    printf("  Decoders:");
2345
    for(p = first_avcodec; p != NULL; p = p->next) {
2346
        if (p->decode)
2347
            printf(" %s", p->name);
2348
    }
2349
    printf("\n");
2350

    
2351
    printf("Supported file protocols:");
2352
    for(up = first_protocol; up != NULL; up = up->next)
2353
        printf(" %s:", up->name);
2354
    printf("\n");
2355
    
2356
    printf("Frame size abbreviations: sqcif qcif cif 4cif\n");
2357
    printf("Motion estimation methods:");
2358
    pp = motion_str;
2359
    while (*pp) {
2360
        printf(" %s", *pp);
2361
        if ((pp - motion_str + 1) == ME_ZERO) 
2362
            printf("(fastest)");
2363
        else if ((pp - motion_str + 1) == ME_FULL) 
2364
            printf("(slowest)");
2365
        else if ((pp - motion_str + 1) == ME_EPZS) 
2366
            printf("(default)");
2367
        pp++;
2368
    }
2369
    printf("\n");
2370
    exit(1);
2371
}
2372

    
2373
void show_help(void)
2374
{
2375
    const char *prog;
2376
    const OptionDef *po;
2377
    int i, expert;
2378
    
2379
    prog = do_play ? "ffplay" : "ffmpeg";
2380

    
2381
    printf("%s version " FFMPEG_VERSION ", Copyright (c) 2000, 2001, 2002 Fabrice Bellard\n",
2382
           prog);
2383
    
2384
    if (!do_play) {
2385
        printf("usage: ffmpeg [[options] -i input_file]... {[options] outfile}...\n"
2386
               "Hyper fast MPEG1/MPEG4/H263/RV and AC3/MPEG audio encoder\n");
2387
    } else {
2388
        printf("usage: ffplay [options] input_file...\n"
2389
               "Simple audio player\n");
2390
    }
2391
           
2392
    printf("\n"
2393
           "Main options are:\n");
2394
    for(i=0;i<2;i++) {
2395
        if (i == 1)
2396
            printf("\nAdvanced options are:\n");
2397
        for(po = options; po->name != NULL; po++) {
2398
            char buf[64];
2399
            expert = (po->flags & OPT_EXPERT) != 0;
2400
            if (expert == i) {
2401
                strcpy(buf, po->name);
2402
                if (po->flags & HAS_ARG) {
2403
                    strcat(buf, " ");
2404
                    strcat(buf, po->argname);
2405
                }
2406
                printf("-%-17s  %s\n", buf, po->help);
2407
            }
2408
        }
2409
    }
2410

    
2411
    exit(1);
2412
}
2413

    
2414
const OptionDef options[] = {
2415
    { "L", 0, {(void*)show_licence}, "show license" },
2416
    { "h", 0, {(void*)show_help}, "show help" },
2417
    { "formats", 0, {(void*)show_formats}, "show available formats, codecs, protocols, ..." },
2418
    { "f", HAS_ARG, {(void*)opt_format}, "force format", "fmt" },
2419
    { "i", HAS_ARG, {(void*)opt_input_file}, "input file name", "filename" },
2420
    { "y", OPT_BOOL, {(void*)&file_overwrite}, "overwrite output files" },
2421
    { "map", HAS_ARG | OPT_EXPERT, {(void*)opt_map}, "set input stream mapping", "file:stream" },
2422
    { "t", HAS_ARG, {(void*)opt_recording_time}, "set the recording time", "duration" },
2423
    { "title", HAS_ARG | OPT_STRING, {(void*)&str_title}, "set the title", "string" },
2424
    { "author", HAS_ARG | OPT_STRING, {(void*)&str_author}, "set the author", "string" },
2425
    { "copyright", HAS_ARG | OPT_STRING, {(void*)&str_copyright}, "set the copyright", "string" },
2426
    { "comment", HAS_ARG | OPT_STRING, {(void*)&str_comment}, "set the comment", "string" },
2427
    { "pass", HAS_ARG, {(void*)&opt_pass}, "select the pass number (1 or 2)", "n" },
2428
    { "passlogfile", HAS_ARG | OPT_STRING, {(void*)&pass_logfilename}, "select two pass log file name", "file" },
2429
    /* video options */
2430
    { "b", HAS_ARG, {(void*)opt_video_bitrate}, "set video bitrate (in kbit/s)", "bitrate" },
2431
    { "r", HAS_ARG, {(void*)opt_frame_rate}, "set frame rate (in Hz)", "rate" },
2432
    { "s", HAS_ARG, {(void*)opt_frame_size}, "set frame size (WxH or abbreviation)", "size" },
2433
    { "croptop", HAS_ARG, {(void*)opt_frame_crop_top}, "set top crop band size (in pixels)", "size" },
2434
    { "cropbottom", HAS_ARG, {(void*)opt_frame_crop_bottom}, "set bottom crop band size (in pixels)", "size" },
2435
    { "cropleft", HAS_ARG, {(void*)opt_frame_crop_left}, "set left crop band size (in pixels)", "size" },
2436
    { "cropright", HAS_ARG, {(void*)opt_frame_crop_right}, "set right crop band size (in pixels)", "size" },
2437
    { "g", HAS_ARG | OPT_EXPERT, {(void*)opt_gop_size}, "set the group of picture size", "gop_size" },
2438
    { "intra", OPT_BOOL | OPT_EXPERT, {(void*)&intra_only}, "use only intra frames"},
2439
    { "vn", OPT_BOOL, {(void*)&video_disable}, "disable video" },
2440
    { "qscale", HAS_ARG | OPT_EXPERT, {(void*)opt_qscale}, "use fixed video quantiser scale (VBR)", "q" },
2441
    { "qmin", HAS_ARG | OPT_EXPERT, {(void*)opt_qmin}, "min video quantiser scale (VBR)", "q" },
2442
    { "qmax", HAS_ARG | OPT_EXPERT, {(void*)opt_qmax}, "max video quantiser scale (VBR)", "q" },
2443
    { "qdiff", HAS_ARG | OPT_EXPERT, {(void*)opt_qdiff}, "max difference between the quantiser scale (VBR)", "q" },
2444
    { "qblur", HAS_ARG | OPT_EXPERT, {(void*)opt_qblur}, "video quantiser scale blur (VBR)", "blur" },
2445
    { "qcomp", HAS_ARG | OPT_EXPERT, {(void*)opt_qcomp}, "video quantiser scale compression (VBR)", "compression" },
2446
    { "rc_init_cplx", HAS_ARG | OPT_EXPERT, {(void*)opt_rc_initial_cplx}, "initial complexity for 1-pass encoding", "complexity" },
2447
    { "b_qfactor", HAS_ARG | OPT_EXPERT, {(void*)opt_b_qfactor}, "qp factor between p and b frames", "factor" },
2448
    { "i_qfactor", HAS_ARG | OPT_EXPERT, {(void*)opt_i_qfactor}, "qp factor between p and i frames", "factor" },
2449
    { "b_qoffset", HAS_ARG | OPT_EXPERT, {(void*)opt_b_qoffset}, "qp offset between p and b frames", "offset" },
2450
    { "i_qoffset", HAS_ARG | OPT_EXPERT, {(void*)opt_i_qoffset}, "qp offset between p and i frames", "offset" },
2451
    { "rc_eq", HAS_ARG | OPT_EXPERT, {(void*)opt_video_rc_eq}, "", "equation" },
2452
    { "rc_override", HAS_ARG | OPT_EXPERT, {(void*)opt_video_rc_override_string}, "Rate control override", "qualities for specific intervals" },
2453
    { "bt", HAS_ARG, {(void*)opt_video_bitrate_tolerance}, "set video bitrate tolerance (in kbit/s)", "tolerance" },
2454
    { "maxrate", HAS_ARG, {(void*)opt_video_bitrate_max}, "set max video bitrate tolerance (in kbit/s)", "bitrate" },
2455
    { "minrate", HAS_ARG, {(void*)opt_video_bitrate_min}, "set min video bitrate tolerance (in kbit/s)", "bitrate" },
2456
    { "bufsize", HAS_ARG, {(void*)opt_video_buffer_size}, "set ratecontrol buffere size (in kbit)", "size" },
2457
    { "vd", HAS_ARG | OPT_EXPERT, {(void*)opt_video_device}, "set video grab device", "device" },
2458
    { "vcodec", HAS_ARG | OPT_EXPERT, {(void*)opt_video_codec}, "force video codec ('copy' to copy stream)", "codec" },
2459
    { "me", HAS_ARG | OPT_EXPERT, {(void*)opt_motion_estimation}, "set motion estimation method", 
2460
      "method" },
2461
    { "dct_algo", HAS_ARG | OPT_EXPERT, {(void*)opt_dct_algo}, "set dct algo",  "algo" },
2462
    { "idct_algo", HAS_ARG | OPT_EXPERT, {(void*)opt_idct_algo}, "set idct algo",  "algo" },
2463
    { "er", HAS_ARG | OPT_EXPERT, {(void*)opt_error_resilience}, "set error resilience",  "" },
2464
    { "ec", HAS_ARG | OPT_EXPERT, {(void*)opt_error_resilience}, "set error concealment",  "" },
2465
    { "bf", HAS_ARG | OPT_EXPERT, {(void*)opt_b_frames}, "use 'frames' B frames (only MPEG-4)", "frames" },
2466
    { "hq", OPT_BOOL | OPT_EXPERT, {(void*)&use_hq}, "activate high quality settings" },
2467
    { "4mv", OPT_BOOL | OPT_EXPERT, {(void*)&use_4mv}, "use four motion vector by macroblock (only MPEG-4)" },
2468
    { "part", OPT_BOOL | OPT_EXPERT, {(void*)&use_part}, "use data partitioning (only MPEG-4)" },
2469
    { "bug", HAS_ARG | OPT_EXPERT, {(void*)opt_workaround_bugs}, "workaround not auto detected encoder bugs", "param" },
2470
    { "ps", HAS_ARG | OPT_EXPERT, {(void*)opt_packet_size}, "packet size", "size in bits" },
2471
    { "sameq", OPT_BOOL, {(void*)&same_quality}, 
2472
      "use same video quality as source (implies VBR)" },
2473
    /* audio options */
2474
    { "ab", HAS_ARG, {(void*)opt_audio_bitrate}, "set audio bitrate (in kbit/s)", "bitrate", },
2475
    { "ar", HAS_ARG, {(void*)opt_audio_rate}, "set audio sampling rate (in Hz)", "rate" },
2476
    { "ac", HAS_ARG, {(void*)opt_audio_channels}, "set number of audio channels", "channels" },
2477
    { "an", OPT_BOOL, {(void*)&audio_disable}, "disable audio" },
2478
    { "ad", HAS_ARG | OPT_EXPERT, {(void*)opt_audio_device}, "set audio device", "device" },
2479
    { "acodec", HAS_ARG | OPT_EXPERT, {(void*)opt_audio_codec}, "force audio codec ('copy' to copy stream)", "codec" },
2480
    { "deinterlace", OPT_BOOL | OPT_EXPERT, {(void*)&do_deinterlace}, 
2481
      "deinterlace pictures" },
2482
    { "benchmark", OPT_BOOL | OPT_EXPERT, {(void*)&do_benchmark}, 
2483
      "add timings for benchmarking" },
2484
    { "hex", OPT_BOOL | OPT_EXPERT, {(void*)&do_hex_dump}, 
2485
      "dump each input packet" },
2486
    { "psnr", OPT_BOOL | OPT_EXPERT, {(void*)&do_psnr}, "calculate PSNR of compressed frames" },
2487
    { "vstats", OPT_BOOL | OPT_EXPERT, {(void*)&do_vstats}, "dump video coding statistics to file" }, 
2488
    { "bitexact", OPT_EXPERT, {(void*)opt_bitexact}, "only use bit exact algorithms (for codec testing)" }, 
2489
    { NULL, },
2490
};
2491

    
2492
int main(int argc, char **argv)
2493
{
2494
    int optindex, i;
2495
    const char *opt, *arg;
2496
    const OptionDef *po;
2497
    INT64 ti;
2498
    
2499
    av_register_all();
2500

    
2501
    /* detect if invoked as player */
2502
    i = strlen(argv[0]);
2503
    if (i >= 6 && !strcmp(argv[0] + i - 6, "ffplay"))
2504
        do_play = 1;
2505

    
2506
    if (argc <= 1)
2507
        show_help();
2508
    
2509
    /* parse options */
2510
    optindex = 1;
2511
    while (optindex < argc) {
2512
        opt = argv[optindex++];
2513
        
2514
        if (opt[0] == '-' && opt[1] != '\0') {
2515
            po = options;
2516
            while (po->name != NULL) {
2517
                if (!strcmp(opt + 1, po->name))
2518
                    break;
2519
                po++;
2520
            }
2521
            if (!po->name) {
2522
                fprintf(stderr, "%s: unrecognized option '%s'\n", argv[0], opt);
2523
                exit(1);
2524
            }
2525
            arg = NULL;
2526
            if (po->flags & HAS_ARG)
2527
                arg = argv[optindex++];
2528
            if (po->flags & OPT_STRING) {
2529
                char *str;
2530
                str = strdup(arg);
2531
                *po->u.str_arg = str;
2532
            } else if (po->flags & OPT_BOOL) {
2533
                *po->u.int_arg = 1;
2534
            } else {
2535
                po->u.func_arg(arg);
2536
            }
2537
        } else {
2538
            if (!do_play) {
2539
                opt_output_file(opt);
2540
            } else {
2541
                opt_input_file(opt);
2542
            }
2543
        }
2544
    }
2545

    
2546

    
2547
    if (!do_play) {
2548
        /* file converter / grab */
2549
        if (nb_output_files <= 0) {
2550
            fprintf(stderr, "Must supply at least one output file\n");
2551
            exit(1);
2552
        }
2553
        
2554
        if (nb_input_files == 0) {
2555
            prepare_grab();
2556
        }
2557
    } else {
2558
        /* player */
2559
        if (nb_input_files <= 0) {
2560
            fprintf(stderr, "Must supply at least one input file\n");
2561
            exit(1);
2562
        }
2563
        prepare_play();
2564
    }
2565

    
2566
    ti = getutime();
2567
    av_encode(output_files, nb_output_files, input_files, nb_input_files, 
2568
              stream_maps, nb_stream_maps);
2569
    ti = getutime() - ti;
2570
    if (do_benchmark) {
2571
        printf("bench: utime=%0.3fs\n", ti / 1000000.0);
2572
    }
2573

    
2574
    /* close files */
2575
    for(i=0;i<nb_output_files;i++) {
2576
        /* maybe av_close_output_file ??? */
2577
        AVFormatContext *s = output_files[i];
2578
        int j;
2579
        if (!(s->oformat->flags & AVFMT_NOFILE))
2580
            url_fclose(&s->pb);
2581
        for(j=0;j<s->nb_streams;j++)
2582
            av_free(s->streams[j]);
2583
        av_free(s);
2584
    }
2585
    for(i=0;i<nb_input_files;i++)
2586
        av_close_input_file(input_files[i]);
2587

    
2588
    return 0;
2589
}