Statistics
| Branch: | Revision:

ffmpeg / ffmpeg.c @ 9ddd71fc

History | View | Annotate | Download (81.3 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
#ifndef CONFIG_AUDIO_OSS
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[MAX_AUDIO_PACKET_SIZE]; /* XXX: allocate it */
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
                    }
1296
                }
1297
            }
1298
            ipts = AV_NOPTS_VALUE;
1299
        }
1300
    discard_packet:
1301
        av_free_packet(&pkt);
1302
        
1303
        /* dump report by using the output first video and audio streams */
1304
        print_report(output_files, ost_table, nb_ostreams, 0);
1305
    }
1306
    term_exit();
1307

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1462

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

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

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

    
1478

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

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

    
1489

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

    
1495

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1840
    /* update the current parameters so that they match the one of the input stream */
1841
    for(i=0;i<ic->nb_streams;i++) {
1842
        AVCodecContext *enc = &ic->streams[i]->codec;
1843
        switch(enc->codec_type) {
1844
        case CODEC_TYPE_AUDIO:
1845
            //fprintf(stderr, "\nInput Audio channels: %d", enc->channels);
1846
            audio_channels = enc->channels;
1847
            audio_sample_rate = enc->sample_rate;
1848
            break;
1849
        case CODEC_TYPE_VIDEO:
1850
            frame_height = enc->height;
1851
            frame_width = enc->width;
1852
            rfps = ic->streams[i]->r_frame_rate;
1853
            enc->workaround_bugs = workaround_bugs;
1854
            enc->error_resilience = error_resilience; 
1855
            enc->error_concealment = error_concealment; 
1856
            enc->idct_algo= idct_algo;
1857
            if (enc->frame_rate != rfps) {
1858
                fprintf(stderr,"\nSeems that stream %d comes from film source: %2.2f->%2.2f\n",
1859
                    i, (float)enc->frame_rate / FRAME_RATE_BASE,
1860
                    (float)rfps / FRAME_RATE_BASE);
1861
            }
1862
            /* update the current frame rate to match the stream frame rate */
1863
            frame_rate = rfps;
1864
            break;
1865
        default:
1866
            av_abort();
1867
        }
1868
    }
1869
    
1870
    input_files[nb_input_files] = ic;
1871
    /* dump the file content */
1872
    dump_format(ic, nb_input_files, filename, 0);
1873
    nb_input_files++;
1874
    file_iformat = NULL;
1875
    file_oformat = NULL;
1876
}
1877

    
1878
void check_audio_video_inputs(int *has_video_ptr, int *has_audio_ptr)
1879
{
1880
    int has_video, has_audio, i, j;
1881
    AVFormatContext *ic;
1882

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

    
1905
void opt_output_file(const char *filename)
1906
{
1907
    AVStream *st;
1908
    AVFormatContext *oc;
1909
    int use_video, use_audio, nb_streams, input_has_video, input_has_audio;
1910
    int codec_id;
1911

    
1912
    if (!strcmp(filename, "-"))
1913
        filename = "pipe:";
1914

    
1915
    oc = av_mallocz(sizeof(AVFormatContext));
1916

    
1917
    if (!file_oformat) {
1918
        file_oformat = guess_format(NULL, filename, NULL);
1919
        if (!file_oformat) {
1920
            fprintf(stderr, "Unable for find a suitable output format for '%s'\n",
1921
                    filename);
1922
            exit(1);
1923
        }
1924
    }
1925
    
1926
    oc->oformat = file_oformat;
1927

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

    
1940
        /* disable if no corresponding type found and at least one
1941
           input file */
1942
        if (nb_input_files > 0) {
1943
            check_audio_video_inputs(&input_has_video, &input_has_audio);
1944
            if (!input_has_video)
1945
                use_video = 0;
1946
            if (!input_has_audio)
1947
                use_audio = 0;
1948
        }
1949

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

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

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

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

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

    
2097
            st = av_mallocz(sizeof(AVStream));
2098
            if (!st) {
2099
                fprintf(stderr, "Could not alloc stream\n");
2100
                exit(1);
2101
            }
2102

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

    
2126
        oc->nb_streams = nb_streams;
2127

    
2128
        if (!nb_streams) {
2129
            fprintf(stderr, "No audio or video streams available\n");
2130
            exit(1);
2131
        }
2132

    
2133
        if (str_title)
2134
            pstrcpy(oc->title, sizeof(oc->title), str_title);
2135
        if (str_author)
2136
            pstrcpy(oc->author, sizeof(oc->author), str_author);
2137
        if (str_copyright)
2138
            pstrcpy(oc->copyright, sizeof(oc->copyright), str_copyright);
2139
        if (str_comment)
2140
            pstrcpy(oc->comment, sizeof(oc->comment), str_comment);
2141
    }
2142

    
2143
    output_files[nb_output_files++] = oc;
2144

    
2145
    strcpy(oc->filename, filename);
2146

    
2147
    /* check filename in case of an image number is expected */
2148
    if (oc->oformat->flags & AVFMT_NEEDNUMBER) {
2149
        if (filename_number_test(oc->filename) < 0) {
2150
            print_error(oc->filename, AVERROR_NUMEXPECTED);
2151
            exit(1);
2152
        }
2153
    }
2154

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

    
2180
    /* reset some options */
2181
    file_oformat = NULL;
2182
    file_iformat = NULL;
2183
    audio_disable = 0;
2184
    video_disable = 0;
2185
    audio_codec_id = CODEC_ID_NONE;
2186
    video_codec_id = CODEC_ID_NONE;
2187
    audio_stream_copy = 0;
2188
    video_stream_copy = 0;
2189
}
2190

    
2191
/* prepare dummy protocols for grab */
2192
void prepare_grab(void)
2193
{
2194
    int has_video, has_audio, i, j;
2195
    AVFormatContext *oc;
2196
    AVFormatContext *ic;
2197
    AVFormatParameters ap1, *ap = &ap1;
2198

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

    
2261
/* open the necessary output devices for playing */
2262
void prepare_play(void)
2263
{
2264
    file_iformat = NULL;
2265
    file_oformat = guess_format("audio_device", NULL, NULL);
2266
    if (!file_oformat) {
2267
        fprintf(stderr, "Could not find audio device\n");
2268
        exit(1);
2269
    }
2270
    
2271
    opt_output_file(audio_device);
2272
}
2273

    
2274
/* same option as mencoder */
2275
void opt_pass(const char *pass_str)
2276
{
2277
    int pass;
2278
    pass = atoi(pass_str);
2279
    if (pass != 1 && pass != 2) {
2280
        fprintf(stderr, "pass number can be only 1 or 2\n");
2281
        exit(1);
2282
    }
2283
    do_pass = pass;
2284
}
2285

    
2286
#ifndef CONFIG_WIN32
2287
INT64 getutime(void)
2288
{
2289
    struct rusage rusage;
2290

    
2291
    getrusage(RUSAGE_SELF, &rusage);
2292
    return (rusage.ru_utime.tv_sec * 1000000LL) + rusage.ru_utime.tv_usec;
2293
}
2294
#else
2295
INT64 getutime(void)
2296
{
2297
  return av_gettime();
2298
}
2299
#endif
2300

    
2301
extern int ffm_nopts;
2302

    
2303
void opt_bitexact(void)
2304
{
2305
    avcodec_set_bit_exact();
2306
    /* disable generate of real time pts in ffm (need to be supressed anyway) */
2307
    ffm_nopts = 1;
2308
}
2309

    
2310
void show_formats(void)
2311
{
2312
    AVInputFormat *ifmt;
2313
    AVOutputFormat *ofmt;
2314
    URLProtocol *up;
2315
    AVCodec *p;
2316
    const char **pp;
2317

    
2318
    printf("File formats:\n");
2319
    printf("  Encoding:");
2320
    for(ofmt = first_oformat; ofmt != NULL; ofmt = ofmt->next) {
2321
        printf(" %s", ofmt->name);
2322
    }
2323
    printf("\n");
2324
    printf("  Decoding:");
2325
    for(ifmt = first_iformat; ifmt != NULL; ifmt = ifmt->next) {
2326
        printf(" %s", ifmt->name);
2327
    }
2328
    printf("\n");
2329

    
2330
    printf("Codecs:\n");
2331
    printf("  Encoders:");
2332
    for(p = first_avcodec; p != NULL; p = p->next) {
2333
        if (p->encode)
2334
            printf(" %s", p->name);
2335
    }
2336
    printf("\n");
2337

    
2338
    printf("  Decoders:");
2339
    for(p = first_avcodec; p != NULL; p = p->next) {
2340
        if (p->decode)
2341
            printf(" %s", p->name);
2342
    }
2343
    printf("\n");
2344

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

    
2367
void show_help(void)
2368
{
2369
    const char *prog;
2370
    const OptionDef *po;
2371
    int i, expert;
2372
    
2373
    prog = do_play ? "ffplay" : "ffmpeg";
2374

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

    
2405
    exit(1);
2406
}
2407

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

    
2486
int main(int argc, char **argv)
2487
{
2488
    int optindex, i;
2489
    const char *opt, *arg;
2490
    const OptionDef *po;
2491
    INT64 ti;
2492
    
2493
    av_register_all();
2494

    
2495
    /* detect if invoked as player */
2496
    i = strlen(argv[0]);
2497
    if (i >= 6 && !strcmp(argv[0] + i - 6, "ffplay"))
2498
        do_play = 1;
2499

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

    
2540

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

    
2560
    ti = getutime();
2561
    av_encode(output_files, nb_output_files, input_files, nb_input_files, 
2562
              stream_maps, nb_stream_maps);
2563
    ti = getutime() - ti;
2564
    if (do_benchmark) {
2565
        printf("bench: utime=%0.3fs\n", ti / 1000000.0);
2566
    }
2567

    
2568
    /* close files */
2569
    for(i=0;i<nb_output_files;i++) {
2570
        if (!(output_files[i]->oformat->flags & AVFMT_NOFILE)) 
2571
            url_fclose(&output_files[i]->pb);
2572
    }
2573
    for(i=0;i<nb_input_files;i++)
2574
        av_close_input_file(input_files[i]);
2575

    
2576
    return 0;
2577
}