Statistics
| Branch: | Revision:

ffmpeg / ffmpeg.c @ 90da4d76

History | View | Annotate | Download (75.6 KB)

1
/*
2
 * FFmpeg main 
3
 * Copyright (c) 2000,2001 Gerard Lantau
4
 *
5
 * This program is free software; you can redistribute it and/or modify
6
 * it under the terms of the GNU General Public License as published by
7
 * the Free Software Foundation; either version 2 of the License, or
8
 * (at your option) any later version.
9
 *
10
 * This program 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
13
 * GNU General Public License for more details.
14
 *
15
 * You should have received a copy of the GNU General Public License
16
 * along with this program; if not, write to the Free Software
17
 * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
18
 */
19
#define HAVE_AV_CONFIG_H
20
#include "avformat.h"
21
#include "tick.h"
22

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

    
34

    
35
#define MAXINT64 INT64_C(0x7fffffffffffffff)
36

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

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

    
59
extern const OptionDef options[];
60

    
61
void show_help(void);
62

    
63
#define MAX_FILES 20
64

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

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

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

    
74
static AVFormat *file_format;
75
static int frame_width  = 160;
76
static int frame_height = 128;
77
static int frame_rate = 25 * FRAME_RATE_BASE;
78
static int video_bit_rate = 200000;
79
static int video_bit_rate_tolerance = 200000;
80
static int video_qscale = 0;
81
static int video_qmin = 3;
82
static int video_qmax = 15;
83
static int video_qdiff = 3;
84
static float video_qblur = 0.5;
85
static float video_qcomp = 0.5;
86
static int me_method = 0;
87
static int video_disable = 0;
88
static int video_codec_id = CODEC_ID_NONE;
89
static int same_quality = 0;
90
static int b_frames = 0;
91
static int use_hq = 0;
92
static int use_4mv = 0;
93
static int do_deinterlace = 0;
94

    
95
static int gop_size = 12;
96
static int intra_only = 0;
97
static int audio_sample_rate = 44100;
98
static int audio_bit_rate = 64000;
99
static int audio_disable = 0;
100
static int audio_channels = 1;
101
static int audio_codec_id = CODEC_ID_NONE;
102

    
103
static INT64 recording_time = 0;
104
static int file_overwrite = 0;
105
static char *str_title = NULL;
106
static char *str_author = NULL;
107
static char *str_copyright = NULL;
108
static char *str_comment = NULL;
109
static int do_benchmark = 0;
110
static int do_hex_dump = 0;
111
static int do_play = 0;
112
static int do_psnr = 0;
113
static int do_vstats = 0;
114
static int mpeg_vcd = 0;
115

    
116
typedef struct AVOutputStream {
117
    int file_index;          /* file index */
118
    int index;               /* stream index in the output file */
119
    int source_index;        /* AVInputStream index */
120
    AVStream *st;            /* stream in the output file */
121
    int encoding_needed;   /* true if encoding needed for this stream */
122

    
123
    int fifo_packet_rptr;    /* read index in the corresponding
124
                                avinputstream packet fifo */
125
    /* video only */
126
    AVPicture pict_tmp;         /* temporary image for resizing */
127
    int video_resample;
128
    ImgReSampleContext *img_resample_ctx; /* for image resampling */
129
    
130
    /* audio only */
131
    int audio_resample;
132
    ReSampleContext *resample; /* for audio resampling */
133
    FifoBuffer fifo;     /* for compression: one audio fifo per codec */
134
} AVOutputStream;
135

    
136
typedef struct AVInputStream {
137
    int file_index;
138
    int index;
139
    AVStream *st;
140
    int discard;             /* true if stream data should be discarded */
141
    int decoding_needed;     /* true if the packets must be decoded in 'raw_fifo' */
142
    Ticker pts_ticker;       /* Ticker for PTS calculation */
143
    int ticker_inited;       /* to signal if the ticker was initialized */
144
    INT64 pts;               /* current pts */
145
    int   pts_increment;     /* expected pts increment for next packet */
146
    int frame_number;        /* current frame */
147
    INT64 sample_index;      /* current sample */
148
} AVInputStream;
149

    
150
typedef struct AVInputFile {
151
    int eof_reached;      /* true if eof reached */
152
    int ist_index;        /* index of first stream in ist_table */
153
    int buffer_size;      /* current total buffer size */
154
    int buffer_size_max;  /* buffer size at which we consider we can stop
155
                             buffering */
156
} AVInputFile;
157

    
158
#ifndef CONFIG_WIN32
159

    
160
/* init terminal so that we can grab keys */
161
static struct termios oldtty;
162

    
163
static void term_exit(void)
164
{
165
    tcsetattr (0, TCSANOW, &oldtty);
166
}
167

    
168
static void term_init(void)
169
{
170
    struct termios tty;
171

    
172
    tcgetattr (0, &tty);
173
    oldtty = tty;
174

    
175
    tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
176
                          |INLCR|IGNCR|ICRNL|IXON);
177
    tty.c_oflag |= OPOST;
178
    tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
179
    tty.c_cflag &= ~(CSIZE|PARENB);
180
    tty.c_cflag |= CS8;
181
    tty.c_cc[VMIN] = 1;
182
    tty.c_cc[VTIME] = 0;
183
    
184
    tcsetattr (0, TCSANOW, &tty);
185

    
186
    atexit(term_exit);
187
}
188

    
189
/* read a key without blocking */
190
static int read_key(void)
191
{
192
    struct timeval tv;
193
    int n;
194
    unsigned char ch;
195
    fd_set rfds;
196

    
197
    FD_ZERO(&rfds);
198
    FD_SET(0, &rfds);
199
    tv.tv_sec = 0;
200
    tv.tv_usec = 0;
201
    n = select(1, &rfds, NULL, NULL, &tv);
202
    if (n > 0) {
203
        if (read(0, &ch, 1) == 1)
204
            return ch;
205
    }
206
    return -1;
207
}
208

    
209
#else
210

    
211
/* no interactive support */
212
static void term_exit(void)
213
{
214
}
215

    
216
static void term_init(void)
217
{
218
}
219

    
220
static int read_key(void)
221
{
222
    return -1;
223
}
224

    
225
#endif
226

    
227
int read_ffserver_streams(AVFormatContext *s, const char *filename)
228
{
229
    int i;
230
    AVFormatContext *ic;
231

    
232
    ic = av_open_input_file(filename, NULL, FFM_PACKET_SIZE, NULL);
233
    if (!ic)
234
        return -EIO;
235
    /* copy stream format */
236
    s->nb_streams = ic->nb_streams;
237
    for(i=0;i<ic->nb_streams;i++) {
238
        AVStream *st;
239
        st = av_mallocz(sizeof(AVFormatContext));
240
        memcpy(st, ic->streams[i], sizeof(AVStream));
241
        s->streams[i] = st;
242
    }
243

    
244
    av_close_input_file(ic);
245
    return 0;
246
}
247

    
248
#define MAX_AUDIO_PACKET_SIZE 16384
249

    
250
static void do_audio_out(AVFormatContext *s, 
251
                         AVOutputStream *ost, 
252
                         AVInputStream *ist,
253
                         unsigned char *buf, int size)
254
{
255
    UINT8 *buftmp;
256
    UINT8 audio_buf[2*MAX_AUDIO_PACKET_SIZE]; /* XXX: allocate it */
257
    UINT8 audio_out[MAX_AUDIO_PACKET_SIZE]; /* XXX: allocate it */
258
    int size_out, frame_bytes, ret;
259
    AVCodecContext *enc;
260

    
261
    enc = &ost->st->codec;
262

    
263
    if (ost->audio_resample) {
264
        buftmp = audio_buf;
265
        size_out = audio_resample(ost->resample, 
266
                                  (short *)buftmp, (short *)buf,
267
                                  size / (ist->st->codec.channels * 2));
268
        size_out = size_out * enc->channels * 2;
269
    } else {
270
        buftmp = buf;
271
        size_out = size;
272
    }
273

    
274
    /* now encode as many frames as possible */
275
    if (enc->frame_size > 1) {
276
        /* output resampled raw samples */
277
        fifo_write(&ost->fifo, buftmp, size_out, 
278
                   &ost->fifo.wptr);
279

    
280
        frame_bytes = enc->frame_size * 2 * enc->channels;
281
        
282
        while (fifo_read(&ost->fifo, audio_buf, frame_bytes, 
283
                     &ost->fifo.rptr) == 0) {
284
            ret = avcodec_encode_audio(enc, audio_out, sizeof(audio_out), 
285
                                       (short *)audio_buf);
286
            s->format->write_packet(s, ost->index, audio_out, ret, 0);
287
        }
288
    } else {
289
        /* output a pcm frame */
290
        /* XXX: change encoding codec API to avoid this ? */
291
        switch(enc->codec->id) {
292
        case CODEC_ID_PCM_S16LE:
293
        case CODEC_ID_PCM_S16BE:
294
        case CODEC_ID_PCM_U16LE:
295
        case CODEC_ID_PCM_U16BE:
296
            break;
297
        default:
298
            size_out = size_out >> 1;
299
            break;
300
        }
301
        ret = avcodec_encode_audio(enc, audio_out, size_out, 
302
                                   (short *)buftmp);
303
        s->format->write_packet(s, ost->index, audio_out, ret, 0);
304
    }
305
}
306

    
307
/* write a picture to a raw mux */
308
static void write_picture(AVFormatContext *s, int index, AVPicture *picture, 
309
                          int pix_fmt, int w, int h)
310
{
311
    UINT8 *buf, *src, *dest;
312
    int size, j, i;
313

    
314
    /* XXX: not efficient, should add test if we can take
315
       directly the AVPicture */
316
    switch(pix_fmt) {
317
    case PIX_FMT_YUV420P:
318
        size = avpicture_get_size(pix_fmt, w, h);
319
        buf = malloc(size);
320
        if (!buf)
321
            return;
322
        dest = buf;
323
        for(i=0;i<3;i++) {
324
            if (i == 1) {
325
                w >>= 1;
326
                h >>= 1;
327
            }
328
            src = picture->data[i];
329
            for(j=0;j<h;j++) {
330
                memcpy(dest, src, w);
331
                dest += w;
332
                src += picture->linesize[i];
333
            }
334
        }
335
        break;
336
    case PIX_FMT_YUV422P:
337
        size = (w * h) * 2; 
338
        buf = malloc(size);
339
        if (!buf)
340
            return;
341
        dest = buf;
342
        for(i=0;i<3;i++) {
343
            if (i == 1) {
344
                w >>= 1;
345
            }
346
            src = picture->data[i];
347
            for(j=0;j<h;j++) {
348
                memcpy(dest, src, w);
349
                dest += w;
350
                src += picture->linesize[i];
351
            }
352
        }
353
        break;
354
    case PIX_FMT_YUV444P:
355
        size = (w * h) * 3; 
356
        buf = malloc(size);
357
        if (!buf)
358
            return;
359
        dest = buf;
360
        for(i=0;i<3;i++) {
361
            src = picture->data[i];
362
            for(j=0;j<h;j++) {
363
                memcpy(dest, src, w);
364
                dest += w;
365
                src += picture->linesize[i];
366
            }
367
        }
368
        break;
369
    case PIX_FMT_YUV422:
370
        size = (w * h) * 2; 
371
        buf = malloc(size);
372
        if (!buf)
373
            return;
374
        dest = buf;
375
        src = picture->data[0];
376
        for(j=0;j<h;j++) {
377
            memcpy(dest, src, w * 2);
378
            dest += w * 2;
379
            src += picture->linesize[0];
380
        }
381
        break;
382
    case PIX_FMT_RGB24:
383
    case PIX_FMT_BGR24:
384
        size = (w * h) * 3; 
385
        buf = malloc(size);
386
        if (!buf)
387
            return;
388
        dest = buf;
389
        src = picture->data[0];
390
        for(j=0;j<h;j++) {
391
            memcpy(dest, src, w * 3);
392
            dest += w * 3;
393
            src += picture->linesize[0];
394
        }
395
        break;
396
    default:
397
        return;
398
    }
399
    s->format->write_packet(s, index, buf, size, 0);
400
    free(buf);
401
}
402

    
403

    
404
static void do_video_out(AVFormatContext *s, 
405
                         AVOutputStream *ost, 
406
                         AVInputStream *ist,
407
                         AVPicture *picture1,
408
                         int *frame_size)
409
{
410
    int n1, n2, nb, i, ret, frame_number, dec_frame_rate;
411
    AVPicture *picture, *picture2, *pict;
412
    AVPicture picture_tmp1, picture_tmp2;
413
    UINT8 video_buffer[1024*1024];
414
    UINT8 *buf = NULL, *buf1 = NULL;
415
    AVCodecContext *enc, *dec;
416

    
417
    enc = &ost->st->codec;
418
    dec = &ist->st->codec;
419

    
420
    frame_number = ist->frame_number;
421
    dec_frame_rate = ist->st->r_frame_rate;
422
    //fprintf(stderr, "\n%d", dec_frame_rate);
423
    /* first drop frame if needed */
424
    n1 = ((INT64)frame_number * enc->frame_rate) / dec_frame_rate;
425
    n2 = (((INT64)frame_number + 1) * enc->frame_rate) / dec_frame_rate;
426
    nb = n2 - n1;
427
    if (nb <= 0) 
428
        return;
429

    
430
    /* deinterlace : must be done before any resize */
431
    if (do_deinterlace) {
432
        int size;
433

    
434
        /* create temporary picture */
435
        size = avpicture_get_size(dec->pix_fmt, dec->width, dec->height);
436
        buf1 = malloc(size);
437
        if (!buf1)
438
            return;
439
        
440
        picture2 = &picture_tmp2;
441
        avpicture_fill(picture2, buf1, dec->pix_fmt, dec->width, dec->height);
442

    
443
        if (avpicture_deinterlace(picture2, picture1, 
444
                                  dec->pix_fmt, dec->width, dec->height) < 0) {
445
            /* if error, do not deinterlace */
446
            free(buf1);
447
            buf1 = NULL;
448
            picture2 = picture1;
449
        }
450
    } else {
451
        picture2 = picture1;
452
    }
453

    
454
    /* convert pixel format if needed */
455
    if (enc->pix_fmt != dec->pix_fmt) {
456
        int size;
457

    
458
        /* create temporary picture */
459
        size = avpicture_get_size(enc->pix_fmt, dec->width, dec->height);
460
        buf = malloc(size);
461
        if (!buf)
462
            return;
463
        pict = &picture_tmp1;
464
        avpicture_fill(pict, buf, enc->pix_fmt, dec->width, dec->height);
465
        
466
        if (img_convert(pict, enc->pix_fmt, 
467
                        picture2, dec->pix_fmt, 
468
                        dec->width, dec->height) < 0) {
469
            fprintf(stderr, "pixel format conversion not handled\n");
470
            goto the_end;
471
        }
472
    } else {
473
        pict = picture2;
474
    }
475

    
476
    /* XXX: resampling could be done before raw format convertion in
477
       some cases to go faster */
478
    /* XXX: only works for YUV420P */
479
    if (ost->video_resample) {
480
        picture = &ost->pict_tmp;
481
        img_resample(ost->img_resample_ctx, picture, pict);
482
    } else {
483
        picture = pict;
484
    }
485
    nb=1;
486
    /* duplicates frame if needed */
487
    /* XXX: pb because no interleaving */
488
    for(i=0;i<nb;i++) {
489
        if (enc->codec_id != CODEC_ID_RAWVIDEO) {
490
            /* handles sameq here. This is not correct because it may
491
               not be a global option */
492
            if (same_quality) {
493
                enc->quality = dec->quality;
494
            }
495
            
496
            ret = avcodec_encode_video(enc, 
497
                                       video_buffer, sizeof(video_buffer), 
498
                                       picture);
499
            //enc->frame_number = enc->real_pict_num;
500
            s->format->write_packet(s, ost->index, video_buffer, ret, 0);
501
            *frame_size = ret;
502
            //fprintf(stderr,"\nFrame: %3d %3d size: %5d type: %d",
503
            //        enc->frame_number-1, enc->real_pict_num, ret,
504
            //        enc->pict_type);
505
        } else {
506
            write_picture(s, ost->index, picture, enc->pix_fmt, enc->width, enc->height);
507
        }
508
    }
509
    the_end:
510
    if (buf)
511
        free(buf);
512
    if (buf1)
513
        free(buf1);
514
}
515

    
516
static void do_video_stats(AVOutputStream *ost, 
517
                         AVInputStream *ist,
518
                         int frame_size)
519
{
520
    static FILE *fvstats=NULL;
521
    static INT64 total_size = 0;
522
    struct tm *today;
523
    time_t today2;
524
    char filename[40];
525
    AVCodecContext *enc;
526
    int frame_number;
527
    INT64 ti;
528
    double ti1, bitrate, avg_bitrate;
529
    
530
    if (!fvstats) {
531
        today2 = time(NULL);
532
        today = localtime(&today2);
533
        sprintf(filename, "vstats_%02d%02d%02d.log", today->tm_hour,
534
                                               today->tm_min,
535
                                               today->tm_sec);
536
        fvstats = fopen(filename,"w");
537
        if (!fvstats) {
538
            perror("fopen");
539
            exit(1);
540
        }
541
    }
542
    
543
    ti = MAXINT64;
544
    enc = &ost->st->codec;
545
    total_size += frame_size;
546
    if (enc->codec_type == CODEC_TYPE_VIDEO) {
547
        frame_number = ist->frame_number;
548
        fprintf(fvstats, "frame= %5d q= %2d ", frame_number, enc->quality);
549
        if (do_psnr)
550
            fprintf(fvstats, "PSNR= %6.2f ", enc->psnr_y);
551
        
552
        fprintf(fvstats,"f_size= %6d ", frame_size);
553
        /* compute min pts value */
554
        if (!ist->discard && ist->pts < ti) {
555
            ti = ist->pts;
556
        }
557
        ti1 = (double)ti / 1000000.0;
558
        if (ti1 < 0.01)
559
            ti1 = 0.01;
560
    
561
        bitrate = (double)(frame_size * 8) * enc->frame_rate / FRAME_RATE_BASE / 1000.0;
562
        avg_bitrate = (double)(total_size * 8) / ti1 / 1000.0;
563
        fprintf(fvstats, "s_size= %8.0fkB time= %0.3f br= %7.1fkbits/s avg_br= %7.1fkbits/s ",
564
            (double)total_size / 1024, ti1, bitrate, avg_bitrate);
565
        fprintf(fvstats,"type= %s\n", enc->key_frame == 1 ? "I" : "P");        
566
    }
567

    
568
    
569
    
570
}
571

    
572
static void hex_dump(UINT8 *buf, int size)
573
{
574
    int len, i, j, c;
575

    
576
    for(i=0;i<size;i+=16) {
577
        len = size - i;
578
        if (len > 16)
579
            len = 16;
580
        printf("%08x ", i);
581
        for(j=0;j<16;j++) {
582
            if (j < len)
583
                printf(" %02x", buf[i+j]);
584
            else
585
                printf("   ");
586
        }
587
        printf(" ");
588
        for(j=0;j<len;j++) {
589
            c = buf[i+j];
590
            if (c < ' ' || c > '~')
591
                c = '.';
592
            printf("%c", c);
593
        }
594
        printf("\n");
595
    }
596
}
597

    
598
/*
599
 * The following code is the main loop of the file converter
600
 */
601
static int av_encode(AVFormatContext **output_files,
602
                     int nb_output_files,
603
                     AVFormatContext **input_files,
604
                     int nb_input_files,
605
                     AVStreamMap *stream_maps, int nb_stream_maps)
606
{
607
    int ret, i, j, k, n, nb_istreams = 0, nb_ostreams = 0;
608
    AVFormatContext *is, *os;
609
    AVCodecContext *codec, *icodec;
610
    AVOutputStream *ost, **ost_table = NULL;
611
    AVInputStream *ist, **ist_table = NULL;
612
    INT64 min_pts, start_time;
613
    AVInputFile *file_table;
614
    AVFormatContext *stream_no_data;
615

    
616
    file_table= (AVInputFile*) av_mallocz(nb_input_files * sizeof(AVInputFile));
617
    if (!file_table)
618
        goto fail;
619

    
620
    /* input stream init */
621
    j = 0;
622
    for(i=0;i<nb_input_files;i++) {
623
        is = input_files[i];
624
        file_table[i].ist_index = j;
625
        j += is->nb_streams;
626
    }
627
    nb_istreams = j;
628

    
629
    ist_table = av_mallocz(nb_istreams * sizeof(AVInputStream *));
630
    if (!ist_table)
631
        goto fail;
632
    
633
    for(i=0;i<nb_istreams;i++) {
634
        ist = av_mallocz(sizeof(AVInputStream));
635
        if (!ist)
636
            goto fail;
637
        ist_table[i] = ist;
638
    }
639
    j = 0;
640
    for(i=0;i<nb_input_files;i++) {
641
        is = input_files[i];
642
        for(k=0;k<is->nb_streams;k++) {
643
            ist = ist_table[j++];
644
            ist->st = is->streams[k];
645
            ist->file_index = i;
646
            ist->index = k;
647
            ist->discard = 1; /* the stream is discarded by default
648
                                 (changed later) */
649
        }
650
    }
651

    
652
    /* output stream init */
653
    nb_ostreams = 0;
654
    for(i=0;i<nb_output_files;i++) {
655
        os = output_files[i];
656
        nb_ostreams += os->nb_streams;
657
        if (mpeg_vcd)
658
            os->flags |= AVF_FLAG_VCD;
659
    }
660
    if (nb_stream_maps > 0 && nb_stream_maps != nb_ostreams) {
661
        fprintf(stderr, "Number of stream maps must match number of output streams\n");
662
        exit(1);
663
    }
664

    
665
    ost_table = av_mallocz(sizeof(AVOutputStream *) * nb_ostreams);
666
    if (!ost_table)
667
        goto fail;
668
    for(i=0;i<nb_ostreams;i++) {
669
        ost = av_mallocz(sizeof(AVOutputStream));
670
        if (!ost)
671
            goto fail;
672
        ost_table[i] = ost;
673
    }
674
    
675
    n = 0;
676
    for(k=0;k<nb_output_files;k++) {
677
        os = output_files[k];
678
        for(i=0;i<os->nb_streams;i++) {
679
            int found;
680
            ost = ost_table[n++];
681
            ost->file_index = k;
682
            ost->index = i;
683
            ost->st = os->streams[i];
684
            if (nb_stream_maps > 0) {
685
                ost->source_index = file_table[stream_maps[n-1].file_index].ist_index + 
686
                    stream_maps[n-1].stream_index;
687
            } else {
688
                /* get corresponding input stream index : we select the first one with the right type */
689
                found = 0;
690
                for(j=0;j<nb_istreams;j++) {
691
                    ist = ist_table[j];
692
                    if (ist->discard && 
693
                        ist->st->codec.codec_type == ost->st->codec.codec_type) {
694
                        ost->source_index = j;
695
                        found = 1;
696
                    }
697
                }
698
                
699
                if (!found) {
700
                    /* try again and reuse existing stream */
701
                    for(j=0;j<nb_istreams;j++) {
702
                        ist = ist_table[j];
703
                        if (ist->st->codec.codec_type == ost->st->codec.codec_type) {
704
                            ost->source_index = j;
705
                            found = 1;
706
                        }
707
                    }
708
                    if (!found) {
709
                        fprintf(stderr, "Could not find input stream matching output stream #%d.%d\n",
710
                                ost->file_index, ost->index);
711
                        exit(1);
712
                    }
713
                }
714
            }
715
            ist = ist_table[ost->source_index];
716
            ist->discard = 0;
717
        }
718
    }
719

    
720
    /* dump the stream mapping */
721
    fprintf(stderr, "Stream mapping:\n");
722
    for(i=0;i<nb_ostreams;i++) {
723
        ost = ost_table[i];
724
        fprintf(stderr, "  Stream #%d.%d -> #%d.%d\n",
725
                ist_table[ost->source_index]->file_index,
726
                ist_table[ost->source_index]->index,
727
                ost->file_index, 
728
                ost->index);
729
    }
730

    
731
    /* for each output stream, we compute the right encoding parameters */
732
    for(i=0;i<nb_ostreams;i++) {
733
        ost = ost_table[i];
734
        ist = ist_table[ost->source_index];
735

    
736
        codec = &ost->st->codec;
737
        icodec = &ist->st->codec;
738

    
739
        switch(codec->codec_type) {
740
        case CODEC_TYPE_AUDIO:
741
            /* check if same codec with same parameters. If so, no
742
               reencoding is needed */
743
            if (codec->codec_id == icodec->codec_id &&
744
                codec->bit_rate == icodec->bit_rate &&
745
                codec->sample_rate == icodec->sample_rate &&
746
                codec->channels == icodec->channels) {
747
                /* no reencoding */
748
                /* use the same frame size */
749
                codec->frame_size = icodec->frame_size;
750
                //codec->frame_size = 8*icodec->sample_rate*icodec->frame_size/
751
                //                    icodec->bit_rate;
752
                //fprintf(stderr,"\nFrame size: %d", codec->frame_size);
753
            } else {
754
                if (fifo_init(&ost->fifo, 2 * MAX_AUDIO_PACKET_SIZE))
755
                    goto fail;
756

    
757
                if (codec->channels == icodec->channels &&
758
                    codec->sample_rate == icodec->sample_rate) {
759
                    ost->audio_resample = 0;
760
                } else {
761
                    if (codec->channels != icodec->channels &&
762
                        icodec->codec_id == CODEC_ID_AC3) {
763
                        /* Special case for 5:1 AC3 input */
764
                        /* and mono or stereo output      */
765
                        /* Request specific number of channels */
766
                        icodec->channels = codec->channels;
767
                        if (codec->sample_rate == icodec->sample_rate)
768
                            ost->audio_resample = 0;
769
                        else {
770
                            ost->audio_resample = 1;
771
                            ost->resample = audio_resample_init(codec->channels, icodec->channels,
772
                                                        codec->sample_rate, 
773
                                                        icodec->sample_rate);
774
                        }
775
                        /* Request specific number of channels */
776
                        icodec->channels = codec->channels;
777
                    } else {
778
                        ost->audio_resample = 1; 
779
                        ost->resample = audio_resample_init(codec->channels, icodec->channels,
780
                                                        codec->sample_rate, 
781
                                                        icodec->sample_rate);
782
                    }
783
                }
784
                ist->decoding_needed = 1;
785
                ost->encoding_needed = 1;
786
            }
787
            break;
788
        case CODEC_TYPE_VIDEO:
789
            /* check if same codec with same parameters. If so, no
790
               reencoding is needed */
791
            if (codec->codec_id == icodec->codec_id &&
792
                codec->bit_rate == icodec->bit_rate &&
793
                codec->frame_rate == icodec->frame_rate &&
794
                codec->width == icodec->width &&
795
                codec->height == icodec->height) {
796
                /* no reencoding */
797
            } else {
798
                if (codec->width == icodec->width &&
799
                    codec->height == icodec->height) {
800
                    ost->video_resample = 0;
801
                } else {
802
                    UINT8 *buf;
803
                    ost->video_resample = 1;
804
                    buf = malloc((codec->width * codec->height * 3) / 2);
805
                    if (!buf)
806
                        goto fail;
807
                    ost->pict_tmp.data[0] = buf;
808
                    ost->pict_tmp.data[1] = ost->pict_tmp.data[0] + (codec->width * codec->height);
809
                    ost->pict_tmp.data[2] = ost->pict_tmp.data[1] + (codec->width * codec->height) / 4;
810
                    ost->pict_tmp.linesize[0] = codec->width;
811
                    ost->pict_tmp.linesize[1] = codec->width / 2;
812
                    ost->pict_tmp.linesize[2] = codec->width / 2;
813

    
814
                    ost->img_resample_ctx = img_resample_init( 
815
                                      ost->st->codec.width, ost->st->codec.height,
816
                                      ist->st->codec.width, ist->st->codec.height);
817
                }
818
                ost->encoding_needed = 1;
819
                ist->decoding_needed = 1;
820
            }
821
            break;
822
        default:
823
            abort();
824
        }
825
    }
826

    
827
    /* open each encoder */
828
    for(i=0;i<nb_ostreams;i++) {
829
        ost = ost_table[i];
830
        if (ost->encoding_needed) {
831
            AVCodec *codec;
832
            codec = avcodec_find_encoder(ost->st->codec.codec_id);
833
            if (!codec) {
834
                fprintf(stderr, "Unsupported codec for output stream #%d.%d\n", 
835
                        ost->file_index, ost->index);
836
                exit(1);
837
            }
838
            if (avcodec_open(&ost->st->codec, codec) < 0) {
839
                fprintf(stderr, "Error while opening codec for stream #%d.%d - maybe incorrect parameters such as bit_rate, rate, width or height\n", 
840
                        ost->file_index, ost->index);
841
                exit(1);
842
            }
843
        }
844
    }
845

    
846
    /* open each decoder */
847
    for(i=0;i<nb_istreams;i++) {
848
        ist = ist_table[i];
849
        if (ist->decoding_needed) {
850
            AVCodec *codec;
851
            codec = avcodec_find_decoder(ist->st->codec.codec_id);
852
            if (!codec) {
853
                fprintf(stderr, "Unsupported codec for input stream #%d.%d\n", 
854
                        ist->file_index, ist->index);
855
                exit(1);
856
            }
857
            if (avcodec_open(&ist->st->codec, codec) < 0) {
858
                fprintf(stderr, "Error while opening codec for input stream #%d.%d\n", 
859
                        ist->file_index, ist->index);
860
                exit(1);
861
            }
862
            //if (ist->st->codec.codec_type == CODEC_TYPE_VIDEO)
863
            //    ist->st->codec.flags |= CODEC_FLAG_REPEAT_FIELD;
864
        }
865
    }
866

    
867
    /* init pts */
868
    for(i=0;i<nb_istreams;i++) {
869
        ist = ist_table[i];
870
        ist->pts = 0;
871
        ist->frame_number = 0;
872
    }
873
    
874
    /* compute buffer size max (should use a complete heuristic) */
875
    for(i=0;i<nb_input_files;i++) {
876
        file_table[i].buffer_size_max = 2048;
877
    }
878

    
879
    /* open files and write file headers */
880
    for(i=0;i<nb_output_files;i++) {
881
        os = output_files[i];
882
        if (os->format->write_header(os) < 0) {
883
            fprintf(stderr, "Could not write header for output file #%d (incorrect codec paramters ?)\n", i);
884
            ret = -EINVAL;
885
            goto fail;
886
        }
887
    }
888

    
889
#ifndef CONFIG_WIN32
890
    if (!do_play) {
891
        fprintf(stderr, "Press [q] to stop encoding\n");
892
    } else {
893
        fprintf(stderr, "Press [q] to stop playing\n");
894
    }
895
#endif
896
    term_init();
897

    
898
    start_time = gettime();
899
    min_pts = 0;
900
    stream_no_data = 0;
901

    
902
    for(;;) {
903
        int file_index, ist_index;
904
        AVPacket pkt;
905
        UINT8 *ptr;
906
        int len;
907
        UINT8 *data_buf;
908
        int data_size, got_picture;
909
        AVPicture picture;
910
        short samples[AVCODEC_MAX_AUDIO_FRAME_SIZE / 2];
911

    
912
    redo:
913
        /* if 'q' pressed, exits */
914
        if (read_key() == 'q')
915
            break;
916

    
917
        /* select the input file with the smallest pts */
918
        file_index = -1;
919
        min_pts = MAXINT64;
920
        for(i=0;i<nb_istreams;i++) {
921
            ist = ist_table[i];
922
            /* For some reason, the pts_increment code breaks q estimation?!? */
923
            if (!ist->discard && !file_table[ist->file_index].eof_reached && 
924
                ist->pts /* + ist->pts_increment */ < min_pts && input_files[ist->file_index] != stream_no_data) {
925
                min_pts = ist->pts /* + ist->pts_increment */;
926
                file_index = ist->file_index;
927
            }
928
        }
929
        /* if none, if is finished */
930
        if (file_index < 0) {
931
            if (stream_no_data) {
932
                struct timespec ts;
933

    
934
                ts.tv_sec = 0;
935
                ts.tv_nsec = 1000 * 1000 * 10;
936
                nanosleep(&ts, 0);
937
                stream_no_data = 0;
938
                continue;
939
            }
940
            break;
941
        }    
942
        /* finish if recording time exhausted */
943
        if (recording_time > 0 && min_pts >= recording_time)
944
            break;
945
        /* read a packet from it and output it in the fifo */
946
        is = input_files[file_index];
947
        if (av_read_packet(is, &pkt) < 0) {
948
            file_table[file_index].eof_reached = 1;
949
            continue;
950
        }
951
        if (!pkt.size) {
952
            stream_no_data = is;
953
        } else {
954
            stream_no_data = 0;
955
        }
956
        ist_index = file_table[file_index].ist_index + pkt.stream_index;
957
        ist = ist_table[ist_index];
958
        if (ist->discard) {
959
            continue;
960
        }
961

    
962
        if (pkt.flags & PKT_FLAG_DROPPED_FRAME)
963
            ist->frame_number++;
964

    
965
        if (do_hex_dump) {
966
            printf("stream #%d, size=%d:\n", pkt.stream_index, pkt.size);
967
            hex_dump(pkt.data, pkt.size);
968
        }
969

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

    
972
        len = pkt.size;
973
        ptr = pkt.data;
974
        while (len > 0) {
975

    
976
            /* decode the packet if needed */
977
            data_buf = NULL; /* fail safe */
978
            data_size = 0;
979
            if (ist->decoding_needed) {
980
                switch(ist->st->codec.codec_type) {
981
                case CODEC_TYPE_AUDIO:
982
                    /* XXX: could avoid copy if PCM 16 bits with same
983
                       endianness as CPU */
984
                    ret = avcodec_decode_audio(&ist->st->codec, samples, &data_size,
985
                                               ptr, len);
986
                    if (ret < 0)
987
                        goto fail_decode;
988
                    /* Some bug in mpeg audio decoder gives */
989
                    /* data_size < 0, it seems they are overflows */
990
                    if (data_size <= 0) {
991
                        /* no audio frame */
992
                        ptr += ret;
993
                        len -= ret;
994
                        continue;
995
                    }
996
                    data_buf = (UINT8 *)samples;
997
                    break;
998
                case CODEC_TYPE_VIDEO:
999
                    if (ist->st->codec.codec_id == CODEC_ID_RAWVIDEO) {
1000
                        int size;
1001
                        size = (ist->st->codec.width * ist->st->codec.height);
1002
                        avpicture_fill(&picture, ptr, 
1003
                                     ist->st->codec.pix_fmt,
1004
                                     ist->st->codec.width,
1005
                                     ist->st->codec.height);
1006
                        ret = len;
1007
                    } else {
1008
                        data_size = (ist->st->codec.width * ist->st->codec.height * 3) / 2;
1009
                        ret = avcodec_decode_video(&ist->st->codec, 
1010
                                                   &picture, &got_picture, ptr, len);
1011
                        if (ret < 0) {
1012
                        fail_decode:
1013
                            fprintf(stderr, "Error while decoding stream #%d.%d\n",
1014
                                    ist->file_index, ist->index);
1015
                            av_free_packet(&pkt);
1016
                            goto redo;
1017
                        }
1018
                        if (!got_picture) {
1019
                            /* no picture yet */
1020
                            ptr += ret;
1021
                            len -= ret;
1022
                            continue;
1023
                        }
1024
                                  
1025
                    }
1026
                    break;
1027
                default:
1028
                    goto fail_decode;
1029
                }
1030
            } else {
1031
                data_buf = ptr;
1032
                data_size = len;
1033
                ret = len;
1034
            }
1035
            /* init tickers */
1036
            if (!ist->ticker_inited) {
1037
                switch (ist->st->codec.codec_type) {
1038
                case CODEC_TYPE_AUDIO:
1039
                    ticker_init(&ist->pts_ticker,
1040
                            (INT64)ist->st->codec.sample_rate,
1041
                            (INT64)(1000000));
1042
                    ist->ticker_inited = 1;
1043
                    break;
1044
                case CODEC_TYPE_VIDEO:
1045
                    ticker_init(&ist->pts_ticker,
1046
                            (INT64)ist->st->r_frame_rate,
1047
                            ((INT64)1000000 * FRAME_RATE_BASE));
1048
                    ist->ticker_inited = 1;
1049
                    break;
1050
                default:
1051
                    abort();
1052
                }
1053
            }
1054
            /* update pts */
1055
            switch(ist->st->codec.codec_type) {
1056
            case CODEC_TYPE_AUDIO:
1057
                //ist->pts = (INT64)1000000 * ist->sample_index / ist->st->codec.sample_rate;
1058
                ist->pts = ticker_tick(&ist->pts_ticker, ist->sample_index);
1059
                ist->sample_index += data_size / (2 * ist->st->codec.channels);
1060
                ist->pts_increment = (INT64) (data_size / (2 * ist->st->codec.channels)) * 1000000 / ist->st->codec.sample_rate;
1061
                break;
1062
            case CODEC_TYPE_VIDEO:
1063
                ist->frame_number++;
1064
                //ist->pts = ((INT64)ist->frame_number * 1000000 * FRAME_RATE_BASE) / 
1065
                //    ist->st->codec.frame_rate;
1066
                ist->pts = ticker_tick(&ist->pts_ticker, ist->frame_number);
1067
                ist->pts_increment = ((INT64) 1000000 * FRAME_RATE_BASE) / 
1068
                    ist->st->codec.frame_rate;
1069
                break;
1070
            default:
1071
                abort();
1072
            }
1073
            ptr += ret;
1074
            len -= ret;
1075

    
1076
            /* transcode raw format, encode packets and output them */
1077
            
1078
            for(i=0;i<nb_ostreams;i++) {
1079
                int frame_size;
1080
                ost = ost_table[i];
1081
                if (ost->source_index == ist_index) {
1082
                    os = output_files[ost->file_index];
1083

    
1084
                    if (ost->encoding_needed) {
1085
                        switch(ost->st->codec.codec_type) {
1086
                        case CODEC_TYPE_AUDIO:
1087
                            do_audio_out(os, ost, ist, data_buf, data_size);
1088
                            break;
1089
                        case CODEC_TYPE_VIDEO:
1090
                            do_video_out(os, ost, ist, &picture, &frame_size);
1091
                            if (do_vstats)
1092
                                do_video_stats(ost, ist, frame_size);
1093
                            break;
1094
                        default:
1095
                            abort();
1096
                        }
1097
                    } else {
1098
                        /* no reencoding needed : output the packet directly */
1099
                        /* force the input stream PTS */
1100
                        os->format->write_packet(os, ost->index, data_buf, data_size, pkt.pts);
1101
                    }
1102
                }
1103
            }
1104
        }
1105
        av_free_packet(&pkt);
1106
        
1107
        /* dump report by using the first video and audio streams */
1108
        {
1109
            char buf[1024];
1110
            AVFormatContext *oc;
1111
            INT64 total_size, ti;
1112
            AVCodecContext *enc;
1113
            int frame_number, vid;
1114
            double bitrate, ti1;
1115
            static INT64 last_time;
1116

    
1117
            if ((min_pts - last_time) >= 500000) {
1118
                last_time = min_pts;
1119
                
1120
                oc = output_files[0];
1121
                
1122
                total_size = url_ftell(&oc->pb);
1123
                
1124
                buf[0] = '\0';
1125
                ti = MAXINT64;
1126
                vid = 0;
1127
                for(i=0;i<nb_ostreams;i++) {
1128
                    ost = ost_table[i];
1129
                    enc = &ost->st->codec;
1130
                    ist = ist_table[ost->source_index];
1131
                    if (!vid && enc->codec_type == CODEC_TYPE_VIDEO) {
1132
                        frame_number = ist->frame_number;
1133
                        sprintf(buf + strlen(buf), "frame=%5d q=%2d ",
1134
                                frame_number, enc->quality);
1135
                        if (do_psnr)
1136
                            sprintf(buf + strlen(buf), "PSNR=%6.2f ", enc->psnr_y);
1137
                        vid = 1;
1138
                    }
1139
                    /* compute min pts value */
1140
                    if (!ist->discard && ist->pts < ti) {
1141
                        ti = ist->pts;
1142
                    }
1143
                }
1144

    
1145
                ti1 = (double)ti / 1000000.0;
1146
                if (ti1 < 0.01)
1147
                    ti1 = 0.01;
1148
                bitrate = (double)(total_size * 8) / ti1 / 1000.0;
1149

    
1150
                sprintf(buf + strlen(buf), 
1151
                        "size=%8.0fkB time=%0.1f bitrate=%6.1fkbits/s",
1152
                        (double)total_size / 1024, ti1, bitrate);
1153
                
1154
                fprintf(stderr, "%s   \r", buf);
1155
                fflush(stderr);
1156
            }
1157
        }
1158
    }
1159
    term_exit();
1160

    
1161
    /* dump report by using the first video and audio streams */
1162
    {
1163
        char buf[1024];
1164
        AVFormatContext *oc;
1165
        INT64 total_size, ti;
1166
        AVCodecContext *enc;
1167
        int frame_number, vid;
1168
        double bitrate, ti1;
1169

    
1170
        oc = output_files[0];
1171
        
1172
        total_size = url_ftell(&oc->pb);
1173
        
1174
        buf[0] = '\0';
1175
        ti = MAXINT64;
1176
        vid = 0;
1177
        for(i=0;i<nb_ostreams;i++) {
1178
            ost = ost_table[i];
1179
            enc = &ost->st->codec;
1180
            ist = ist_table[ost->source_index];
1181
            if (!vid && enc->codec_type == CODEC_TYPE_VIDEO) {
1182
                frame_number = ist->frame_number;
1183
                sprintf(buf + strlen(buf), "frame=%5d q=%2d ",
1184
                        frame_number, enc->quality);
1185
                if (do_psnr)
1186
                    sprintf(buf + strlen(buf), "PSNR=%6.2f ", enc->psnr_y);
1187
                vid = 1;
1188
            }
1189
            /* compute min pts value */
1190
            if (!ist->discard && ist->pts < ti) {
1191
                ti = ist->pts;
1192
            }
1193
        }
1194
        
1195
        ti1 = ti / 1000000.0;
1196
        if (ti1 < 0.01)
1197
            ti1 = 0.01;
1198
        bitrate = (double)(total_size * 8) / ti1 / 1000.0;
1199
        
1200
        sprintf(buf + strlen(buf), 
1201
                "size=%8.0fkB time=%0.1f bitrate=%6.1fkbits/s",
1202
                (double)total_size / 1024, ti1, bitrate);
1203
        
1204
        fprintf(stderr, "%s   \n", buf);
1205
    }
1206
    /* close each encoder */
1207
    for(i=0;i<nb_ostreams;i++) {
1208
        ost = ost_table[i];
1209
        if (ost->encoding_needed) {
1210
            avcodec_close(&ost->st->codec);
1211
        }
1212
    }
1213
    
1214
    /* close each decoder */
1215
    for(i=0;i<nb_istreams;i++) {
1216
        ist = ist_table[i];
1217
        if (ist->decoding_needed) {
1218
            avcodec_close(&ist->st->codec);
1219
        }
1220
    }
1221
    
1222

    
1223
    /* write the trailer if needed and close file */
1224
    for(i=0;i<nb_output_files;i++) {
1225
        os = output_files[i];
1226
        os->format->write_trailer(os);
1227
    }
1228
    /* finished ! */
1229
    
1230
    ret = 0;
1231
 fail1:
1232
    free(file_table);
1233

    
1234
    if (ist_table) {
1235
        for(i=0;i<nb_istreams;i++) {
1236
            ist = ist_table[i];
1237
            if (ist) {
1238
                free(ist);
1239
            }
1240
        }
1241
        free(ist_table);
1242
    }
1243
    if (ost_table) {
1244
        for(i=0;i<nb_ostreams;i++) {
1245
            ost = ost_table[i];
1246
            if (ost) {
1247
                if (ost->pict_tmp.data[0])
1248
                    free(ost->pict_tmp.data[0]);
1249
                if (ost->video_resample)
1250
                    img_resample_close(ost->img_resample_ctx);
1251
                if (ost->audio_resample)
1252
                    audio_resample_close(ost->resample);
1253
                free(ost);
1254
            }
1255
        }
1256
        free(ost_table);
1257
    }
1258
    return ret;
1259
 fail:
1260
    ret = -ENOMEM;
1261
    goto fail1;
1262
}
1263

    
1264
#if 0
1265
int file_read(const char *filename)
1266
{
1267
    URLContext *h;
1268
    unsigned char buffer[1024];
1269
    int len, i;
1270

1271
    if (url_open(&h, filename, O_RDONLY) < 0) {
1272
        printf("could not open '%s'\n", filename);
1273
        return -1;
1274
    }
1275
    for(;;) {
1276
        len = url_read(h, buffer, sizeof(buffer));
1277
        if (len <= 0)
1278
            break;
1279
        for(i=0;i<len;i++) putchar(buffer[i]);
1280
    }
1281
    url_close(h);
1282
    return 0;
1283
}
1284
#endif
1285

    
1286
void show_licence(void)
1287
{
1288
    printf(
1289
    "ffmpeg version " FFMPEG_VERSION "\n"
1290
    "Copyright (c) 2000,2001 Gerard Lantau\n"
1291
    "This program is free software; you can redistribute it and/or modify\n"
1292
    "it under the terms of the GNU General Public License as published by\n"
1293
    "the Free Software Foundation; either version 2 of the License, or\n"
1294
    "(at your option) any later version.\n"
1295
    "\n"
1296
    "This program is distributed in the hope that it will be useful,\n"
1297
    "but WITHOUT ANY WARRANTY; without even the implied warranty of\n"
1298
    "MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n"
1299
    "GNU General Public License for more details.\n"
1300
    "\n"
1301
    "You should have received a copy of the GNU General Public License\n"
1302
    "along with this program; if not, write to the Free Software\n"
1303
    "Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.\n"
1304
    );
1305
    exit(1);
1306
}
1307

    
1308
void opt_format(const char *arg)
1309
{
1310
    AVFormat *f;
1311
    f = first_format;
1312
    while (f != NULL && strcmp(f->name, arg) != 0) f = f->next;
1313
    if (f == NULL) {
1314
        fprintf(stderr, "Invalid format: %s\n", arg);
1315
        exit(1);
1316
    }
1317
    file_format = f;
1318
}
1319

    
1320
void opt_video_bitrate(const char *arg)
1321
{
1322
    video_bit_rate = atoi(arg) * 1000;
1323
}
1324

    
1325
void opt_video_bitrate_tolerance(const char *arg)
1326
{
1327
    video_bit_rate_tolerance = atoi(arg) * 1000;
1328
}
1329

    
1330
void opt_frame_rate(const char *arg)
1331
{
1332
    frame_rate = (int)(strtod(arg, 0) * FRAME_RATE_BASE);
1333
}
1334

    
1335
void opt_frame_size(const char *arg)
1336
{
1337
    parse_image_size(&frame_width, &frame_height, arg);
1338
    if (frame_width <= 0 || frame_height <= 0) {
1339
        fprintf(stderr, "Incorrect frame size\n");
1340
        exit(1);
1341
    }
1342
    if ((frame_width % 2) != 0 || (frame_height % 2) != 0) {
1343
        fprintf(stderr, "Frame size must be a multiple of 2\n");
1344
        exit(1);
1345
    }
1346
}
1347

    
1348
void opt_gop_size(const char *arg)
1349
{
1350
    gop_size = atoi(arg);
1351
}
1352

    
1353
void opt_b_frames(const char *arg)
1354
{
1355
    b_frames = atoi(arg);
1356
    if (b_frames > FF_MAX_B_FRAMES) {
1357
        fprintf(stderr, "\nCannot have more than %d B frames, increase FF_MAX_B_FRAMES.\n", FF_MAX_B_FRAMES);
1358
        exit(1);
1359
    } else if (b_frames < 1) {
1360
        fprintf(stderr, "\nNumber of B frames must be higher than 0\n");
1361
        exit(1);
1362
    }
1363
}
1364

    
1365
void opt_qscale(const char *arg)
1366
{
1367
    video_qscale = atoi(arg);
1368
    if (video_qscale < 0 ||
1369
        video_qscale > 31) {
1370
        fprintf(stderr, "qscale must be >= 1 and <= 31\n");
1371
        exit(1);
1372
    }
1373
}
1374

    
1375
void opt_qmin(const char *arg)
1376
{
1377
    video_qmin = atoi(arg);
1378
    if (video_qmin < 0 ||
1379
        video_qmin > 31) {
1380
        fprintf(stderr, "qmin must be >= 1 and <= 31\n");
1381
        exit(1);
1382
    }
1383
}
1384

    
1385
void opt_qmax(const char *arg)
1386
{
1387
    video_qmax = atoi(arg);
1388
    if (video_qmax < 0 ||
1389
        video_qmax > 31) {
1390
        fprintf(stderr, "qmax must be >= 1 and <= 31\n");
1391
        exit(1);
1392
    }
1393
}
1394

    
1395
void opt_qdiff(const char *arg)
1396
{
1397
    video_qdiff = atoi(arg);
1398
    if (video_qdiff < 0 ||
1399
        video_qdiff > 31) {
1400
        fprintf(stderr, "qdiff must be >= 1 and <= 31\n");
1401
        exit(1);
1402
    }
1403
}
1404

    
1405
void opt_qblur(const char *arg)
1406
{
1407
    video_qblur = atof(arg);
1408
}
1409

    
1410
void opt_qcomp(const char *arg)
1411
{
1412
    video_qcomp = atof(arg);
1413
}
1414

    
1415
void opt_audio_bitrate(const char *arg)
1416
{
1417
    audio_bit_rate = atoi(arg) * 1000;
1418
}
1419

    
1420
void opt_audio_rate(const char *arg)
1421
{
1422
    audio_sample_rate = atoi(arg);
1423
}
1424

    
1425
void opt_audio_channels(const char *arg)
1426
{
1427
    audio_channels = atoi(arg);
1428
}
1429

    
1430
#ifdef CONFIG_GRAB
1431
void opt_video_device(const char *arg)
1432
{
1433
    v4l_device = strdup(arg);
1434
}
1435

    
1436
void opt_audio_device(const char *arg)
1437
{
1438
    audio_device = strdup(arg);
1439
}
1440
#endif
1441

    
1442
void opt_audio_codec(const char *arg)
1443
{
1444
    AVCodec *p;
1445

    
1446
    p = first_avcodec;
1447
    while (p) {
1448
        if (!strcmp(p->name, arg) && p->type == CODEC_TYPE_AUDIO)
1449
            break;
1450
        p = p->next;
1451
    }
1452
    if (p == NULL) {
1453
        fprintf(stderr, "Unknown audio codec '%s'\n", arg);
1454
        exit(1);
1455
    } else {
1456
        audio_codec_id = p->id;
1457
    }
1458
}
1459

    
1460
const char *motion_str[] = {
1461
    "zero",
1462
    "full",
1463
    "log",
1464
    "phods",
1465
    "epzs",
1466
    "x1",
1467
    NULL,
1468
};
1469

    
1470
void opt_motion_estimation(const char *arg)
1471
{
1472
    const char **p;
1473
    p = motion_str;
1474
    for(;;) {
1475
        if (!*p) {
1476
            fprintf(stderr, "Unknown motion estimation method '%s'\n", arg);
1477
            exit(1);
1478
        }
1479
        if (!strcmp(*p, arg))
1480
            break;
1481
        p++;
1482
    }
1483
    me_method = (p - motion_str) + 1;
1484
}
1485

    
1486
void opt_video_codec(const char *arg)
1487
{
1488
    AVCodec *p;
1489

    
1490
    p = first_avcodec;
1491
    while (p) {
1492
        if (!strcmp(p->name, arg) && p->type == CODEC_TYPE_VIDEO)
1493
            break;
1494
        p = p->next;
1495
    }
1496
    if (p == NULL) {
1497
        fprintf(stderr, "Unknown video codec '%s'\n", arg);
1498
        exit(1);
1499
    } else {
1500
        video_codec_id = p->id;
1501
    }
1502
}
1503

    
1504
void opt_map(const char *arg)
1505
{
1506
    AVStreamMap *m;
1507
    const char *p;
1508

    
1509
    p = arg;
1510
    m = &stream_maps[nb_stream_maps++];
1511

    
1512
    m->file_index = strtol(arg, (char **)&p, 0);
1513
    if (*p)
1514
        p++;
1515

    
1516
    m->stream_index = strtol(p, (char **)&p, 0);
1517
}
1518

    
1519
void opt_recording_time(const char *arg)
1520
{
1521
    recording_time = parse_date(arg, 1);
1522
}
1523

    
1524
/* return the number of packet read to find the codec parameters */
1525
int find_codec_parameters(AVFormatContext *ic)
1526
{
1527
    int val, i, count, ret, got_picture, size;
1528
    AVCodec *codec;
1529
    AVCodecContext *enc;
1530
    AVStream *st;
1531
    AVPacket *pkt;
1532
    AVPicture picture;
1533
    AVPacketList *pktl=NULL, **ppktl;
1534
    short samples[AVCODEC_MAX_AUDIO_FRAME_SIZE / 2];
1535
    UINT8 *ptr;
1536

    
1537
    count = 0;
1538
    ppktl = &ic->packet_buffer;
1539
    for(;;) {
1540
        for(i=0;i<ic->nb_streams;i++) {
1541
            enc = &ic->streams[i]->codec;
1542
            
1543
            switch(enc->codec_type) {
1544
            case CODEC_TYPE_AUDIO:
1545
                val = enc->sample_rate;
1546
                break;
1547
            case CODEC_TYPE_VIDEO:
1548
                val = enc->width;
1549
                break;
1550
            default:
1551
                val = 1;
1552
                break;
1553
            }
1554
            /* if no parameters supplied, then we should read it from
1555
               the stream */
1556
            if (val == 0)
1557
                break;
1558
        }
1559
        if (i == ic->nb_streams) {
1560
            ret = count;
1561
            break;
1562
        }
1563

    
1564
        if (count == 0) {
1565
            /* open each codec */
1566
            for(i=0;i<ic->nb_streams;i++) {
1567
                st = ic->streams[i];
1568
                codec = avcodec_find_decoder(st->codec.codec_id);
1569
                if (codec == NULL) {
1570
                    ret = -1;
1571
                    goto the_end;
1572
                }
1573
                ret = avcodec_open(&st->codec, codec);
1574
                if (ret < 0)
1575
                    goto the_end;
1576
            }
1577
        }
1578
        pktl = av_mallocz(sizeof(AVPacketList));
1579
        if (!pktl) {
1580
            ret = -1;
1581
            break;
1582
        }
1583

    
1584
        /* add the packet in the buffered packet list */
1585
        *ppktl = pktl;
1586
        ppktl = &pktl->next;
1587

    
1588
        pkt = &pktl->pkt;
1589
        if (ic->format->read_packet(ic, pkt) < 0) {
1590
            ret = -1;
1591
            break;
1592
        }
1593
        st = ic->streams[pkt->stream_index];
1594
       
1595
        /* decode the data and update codec parameters */
1596
        ptr = pkt->data;
1597
        size = pkt->size;
1598
        while (size > 0) {
1599
            switch(st->codec.codec_type) {
1600
            case CODEC_TYPE_VIDEO:
1601
                ret = avcodec_decode_video(&st->codec, &picture, &got_picture, ptr, size);
1602
                if (st->codec.codec_id == CODEC_ID_MPEG1VIDEO) {
1603
                    //mpegvid = pkt->stream_index;
1604
                    //fps = st->codec.frame_rate;
1605
                }
1606
                break;
1607
            case CODEC_TYPE_AUDIO:
1608
                ret = avcodec_decode_audio(&st->codec, samples, &got_picture, ptr, size);
1609
                break;
1610
            default:
1611
                ret = -1;
1612
                break;
1613
            }
1614
            if (ret < 0) {
1615
                ret = -1;
1616
                goto the_end;
1617
            }
1618
            if (got_picture)
1619
                break;
1620
            ptr += ret;
1621
            size -= ret;
1622
        }
1623

    
1624
        count++;
1625
    }
1626
 the_end:
1627
    if (count > 0) {     
1628
        /* close each codec */
1629
        for(i=0;i<ic->nb_streams;i++) {
1630
            st = ic->streams[i];
1631
            avcodec_close(&st->codec);
1632
        }
1633
    }
1634
    return ret;
1635
}
1636

    
1637
/* Returns the real frame rate of telecine streams */
1638
int get_real_fps(AVFormatContext *ic, AVFormat *fmt, AVFormatParameters *ap, int stream_id)
1639
{
1640
    int frame_num, r_frames, fps, rfps;
1641
    int ret, got_picture, size;
1642
    UINT8 *ptr;
1643
    AVStream *st;
1644
    AVPacket *pkt;
1645
    AVPicture picture;
1646
    AVPacketList *pktl=NULL, **ppktl=NULL;
1647
    AVCodec *codec;
1648
    AVFormatContext *fc;
1649
            
1650
    frame_num = 0;
1651
    r_frames = 0;
1652
    fps = rfps = -1;
1653
    if (stream_id < 0 || stream_id >= ic->nb_streams)
1654
        return -1;
1655

    
1656
    /* We must use another AVFormatContext, and open the
1657
       file again, since we do not have good seeking */        
1658
    fc = av_mallocz(sizeof(AVFormatContext));
1659
    if (!fc)
1660
        goto the_end;
1661
    
1662
    strcpy(fc->filename, ic->filename);
1663
    
1664
    /* open file */
1665
    if (!(fmt->flags & AVFMT_NOFILE)) {
1666
        if (url_fopen(&fc->pb, fc->filename, URL_RDONLY) < 0) {
1667
            fprintf(stderr, "Could not open '%s'\n", fc->filename);
1668
            exit(1);
1669
        }
1670
    }
1671
    
1672
    /* check format */
1673
    if (!fmt) {
1674
        goto the_end;
1675
    }
1676
    fc->format = fmt;
1677
    
1678
    /* Read header */
1679
    ret = fc->format->read_header(fc, ap);
1680
    if (ret < 0) {
1681
        fprintf(stderr, "%s: Error while parsing header\n", fc->filename);
1682
        goto the_end;
1683
    }
1684

    
1685
    /* Find and open codec */    
1686
    st = fc->streams[stream_id];
1687
    codec = avcodec_find_decoder(st->codec.codec_id);
1688
    if (codec == NULL) {
1689
        goto the_end;
1690
    }
1691
    ret = avcodec_open(&st->codec, codec);
1692
    if (ret < 0)
1693
        goto the_end;
1694
        
1695
    ppktl = &fc->packet_buffer;    
1696
    if (stream_id > -1) {
1697
        /* check telecine MPEG video streams, we */
1698
        /* decode 40 frames to get the real fps  */
1699
        while(1) {
1700
            
1701
            pktl = av_mallocz(sizeof(AVPacketList));
1702
            if (!pktl) {
1703
                goto the_end;
1704
                break;
1705
            }
1706
            /* add the packet in the buffered packet list */
1707
            *ppktl = pktl;
1708
            ppktl = &pktl->next;
1709

    
1710
            pkt = &pktl->pkt;
1711
            if (fc->format->read_packet(fc, pkt) < 0) {
1712
                goto the_end;
1713
                break;
1714
            }
1715
            st = fc->streams[pkt->stream_index];
1716

    
1717
            /* decode the video */
1718
            ptr = pkt->data;
1719
            size = pkt->size;
1720
            while (size > 0) {
1721
                if (pkt->stream_index == stream_id) {
1722
                    ret = avcodec_decode_video(&st->codec, &picture, &got_picture, ptr, size);
1723
                    fps = st->codec.frame_rate;                    
1724
                    if (ret < 0) {
1725
                        goto the_end;
1726
                    }
1727
                    if (got_picture) {
1728
                        frame_num++;
1729
                        r_frames += st->codec.repeat_pict;
1730
                    }
1731
                }
1732
                ptr += ret;
1733
                size -= ret;
1734
             }
1735
             if (frame_num > 39)
1736
                 break;
1737
        }
1738
        rfps = (fps * frame_num) / (frame_num + (r_frames >> 1)); 
1739
        /* close codec */
1740
        avcodec_close(&st->codec);
1741
    }
1742
the_end:
1743
    /* FIXME: leak in packet_buffer */
1744
    if (fc)
1745
        free(fc);
1746
    return rfps;
1747
}
1748

    
1749
int filename_number_test(const char *filename)
1750
{
1751
    char buf[1024];
1752

    
1753
    if (get_frame_filename(buf, sizeof(buf), filename, 1) < 0) {
1754
        fprintf(stderr, "%s: Incorrect image filename syntax.\n"
1755
                "Use '%%d' to specify the image number:\n"
1756
                "  for img1.jpg, img2.jpg, ..., use 'img%%d.jpg';\n"
1757
                "  for img001.jpg, img002.jpg, ..., use 'img%%03d.jpg'.\n", 
1758
                filename);
1759
        return -1;
1760
    } else {
1761
        return 0;
1762
    }
1763
}
1764

    
1765
void opt_input_file(const char *filename)
1766
{
1767
    AVFormatContext *ic;
1768
    AVFormatParameters params, *ap = &params;
1769
    URLFormat url_format;
1770
    AVFormat *fmt;
1771
    int err, i, ret, rfps;
1772

    
1773
    ic = av_mallocz(sizeof(AVFormatContext));
1774
    strcpy(ic->filename, filename);
1775
    /* first format guess to know if we must open file */
1776
    fmt = file_format;
1777
    if (!fmt) 
1778
        fmt = guess_format(NULL, filename, NULL);
1779
    
1780
    if (fmt == NULL || !(fmt->flags & AVFMT_NOFILE)) {
1781
        /* open file */
1782
        if (url_fopen(&ic->pb, filename, URL_RDONLY) < 0) {
1783
            fprintf(stderr, "Could not open '%s'\n", filename);
1784
            exit(1);
1785
        }
1786
    
1787
        /* find format and set default parameters */
1788
        fmt = file_format;
1789
        err = url_getformat(url_fileno(&ic->pb), &url_format);
1790
        if (err >= 0) {
1791
            if (!fmt)
1792
                fmt = guess_format(url_format.format_name, NULL, NULL);
1793
            ap->sample_rate = url_format.sample_rate;
1794
            ap->frame_rate = url_format.frame_rate;
1795
            ap->channels = url_format.channels;
1796
            ap->width = url_format.width;
1797
            ap->height = url_format.height;
1798
            ap->pix_fmt = url_format.pix_fmt;
1799
        } else {
1800
            if (!fmt)
1801
                fmt = guess_format(NULL, filename, NULL);
1802
            memset(ap, 0, sizeof(*ap));
1803
        }
1804
    } else {
1805
        memset(ap, 0, sizeof(*ap));
1806
    }
1807

    
1808
    if (!fmt || !fmt->read_header) {
1809
        fprintf(stderr, "%s: Unknown file format\n", filename);
1810
        exit(1);
1811
    }
1812
    ic->format = fmt;
1813

    
1814
    /* get default parameters from command line */
1815
    if (!ap->sample_rate)
1816
        ap->sample_rate = audio_sample_rate;
1817
    if (!ap->channels)
1818
        ap->channels = audio_channels;
1819

    
1820
    if (!ap->frame_rate)
1821
        ap->frame_rate = frame_rate;
1822
    if (!ap->width)
1823
        ap->width = frame_width;
1824
    if (!ap->height)
1825
        ap->height = frame_height;
1826

    
1827
    /* check filename in case of an image number is expected */
1828
    if (ic->format->flags & AVFMT_NEEDNUMBER) {
1829
        if (filename_number_test(ic->filename) < 0)
1830
            exit(1);
1831
    }
1832
    
1833
    err = ic->format->read_header(ic, ap);
1834
    if (err < 0) {
1835
        fprintf(stderr, "%s: Error while parsing header\n", filename);
1836
        exit(1);
1837
    }
1838
    
1839
    /* If not enough info for the codecs, we decode the first frames
1840
       to get it. (used in mpeg case for example) */
1841
    ret = find_codec_parameters(ic);
1842
    if (ret < 0) {
1843
        fprintf(stderr, "%s: could not find codec parameters\n", filename);
1844
        exit(1);
1845
    }
1846

    
1847
    /* update the current parameters so that they match the one of the input stream */
1848
    for(i=0;i<ic->nb_streams;i++) {
1849
        AVCodecContext *enc = &ic->streams[i]->codec;
1850
        switch(enc->codec_type) {
1851
        case CODEC_TYPE_AUDIO:
1852
            //fprintf(stderr, "\nInput Audio channels: %d", enc->channels);
1853
            audio_channels = enc->channels;
1854
            audio_sample_rate = enc->sample_rate;
1855
            break;
1856
        case CODEC_TYPE_VIDEO:
1857
            frame_height = enc->height;
1858
            frame_width = enc->width;
1859
            rfps = enc->frame_rate;
1860
            if (enc->codec_id == CODEC_ID_MPEG1VIDEO) {
1861
                rfps = get_real_fps(ic, fmt, ap, i);
1862
            }
1863
            if (rfps > 0 && rfps != enc->frame_rate) {
1864
                frame_rate = rfps;
1865
                fprintf(stderr,"\nSeems that stream %d comes from film source: %2.2f->%2.2f\n",
1866
                    i, (float)enc->frame_rate / FRAME_RATE_BASE,
1867
                    (float)rfps / FRAME_RATE_BASE);
1868
            } else                   
1869
                frame_rate = enc->frame_rate;
1870
            ic->streams[i]->r_frame_rate = rfps;
1871
            break;
1872
        default:
1873
            abort();
1874
        }
1875
    }
1876
    
1877
    input_files[nb_input_files] = ic;
1878
    /* dump the file content */
1879
    dump_format(ic, nb_input_files, filename, 0);
1880
    nb_input_files++;
1881
    file_format = NULL;
1882
}
1883

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

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

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

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

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

    
1923
    if (!file_format) {
1924
        file_format = guess_format(NULL, filename, NULL);
1925
        if (!file_format)
1926
            file_format = &mpeg_mux_format;
1927
    }
1928
    
1929
    oc->format = file_format;
1930

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

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

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

    
1972
            codec_id = file_format->video_codec;
1973
            if (video_codec_id != CODEC_ID_NONE)
1974
                codec_id = video_codec_id;
1975

    
1976
            video_enc->codec_id = codec_id;
1977
            video_enc->codec_type = CODEC_TYPE_VIDEO;
1978
            
1979
            video_enc->bit_rate = video_bit_rate;
1980
            video_enc->bit_rate_tolerance = video_bit_rate_tolerance;
1981
            video_enc->frame_rate = frame_rate; 
1982
            
1983
            video_enc->width = frame_width;
1984
            video_enc->height = frame_height;
1985
            if (!intra_only)
1986
                video_enc->gop_size = gop_size;
1987
            else
1988
                video_enc->gop_size = 0;
1989
            if (video_qscale || same_quality) {
1990
                video_enc->flags |= CODEC_FLAG_QSCALE;
1991
                video_enc->quality = video_qscale;
1992
            }
1993
            
1994
            if (use_hq) {
1995
                video_enc->flags |= CODEC_FLAG_HQ;
1996
            }
1997
            
1998
            if (use_4mv) {
1999
                video_enc->flags |= CODEC_FLAG_HQ;
2000
                video_enc->flags |= CODEC_FLAG_4MV;
2001
            }
2002
            
2003
            if (b_frames) {
2004
                if (codec_id != CODEC_ID_MPEG4) {
2005
                    fprintf(stderr, "\nB frames encoding only supported by MPEG-4.\n");
2006
                    exit(1);
2007
                }
2008
                video_enc->max_b_frames = b_frames;
2009
                video_enc->b_frame_strategy = 0;
2010
                video_enc->b_quant_factor = 2.0;
2011
            }
2012
            
2013
            video_enc->qmin = video_qmin;
2014
            video_enc->qmax = video_qmax;
2015
            video_enc->max_qdiff = video_qdiff;
2016
            video_enc->qblur = video_qblur;
2017
            video_enc->qcompress = video_qcomp;
2018
            
2019
            if (do_psnr)
2020
                video_enc->get_psnr = 1;
2021
            else
2022
                video_enc->get_psnr = 0;
2023
            
2024
            video_enc->me_method = me_method;
2025
            
2026
            /* XXX: need to find a way to set codec parameters */
2027
            if (oc->format == &ppm_format ||
2028
                oc->format == &ppmpipe_format) {
2029
                video_enc->pix_fmt = PIX_FMT_RGB24;
2030
            }
2031

    
2032
            oc->streams[nb_streams] = st;
2033
            nb_streams++;
2034
        }
2035
    
2036
        if (use_audio) {
2037
            AVCodecContext *audio_enc;
2038

    
2039
            st = av_mallocz(sizeof(AVStream));
2040
            if (!st) {
2041
                fprintf(stderr, "Could not alloc stream\n");
2042
                exit(1);
2043
            }
2044
            audio_enc = &st->codec;
2045
            codec_id = file_format->audio_codec;
2046
            if (audio_codec_id != CODEC_ID_NONE)
2047
                codec_id = audio_codec_id;
2048
            audio_enc->codec_id = codec_id;
2049
            audio_enc->codec_type = CODEC_TYPE_AUDIO;
2050
            
2051
            audio_enc->bit_rate = audio_bit_rate;
2052
            audio_enc->sample_rate = audio_sample_rate;
2053
            /* For audio codecs other than AC3 we limit */
2054
            /* the number of coded channels to stereo   */
2055
            if (audio_channels > 2 && codec_id != CODEC_ID_AC3) {
2056
                audio_enc->channels = 2;
2057
            } else
2058
                audio_enc->channels = audio_channels;
2059
            oc->streams[nb_streams] = st;
2060
            nb_streams++;
2061
        }
2062

    
2063
        oc->nb_streams = nb_streams;
2064

    
2065
        if (!nb_streams) {
2066
            fprintf(stderr, "No audio or video streams available\n");
2067
            exit(1);
2068
        }
2069

    
2070
        if (str_title)
2071
            nstrcpy(oc->title, sizeof(oc->title), str_title);
2072
        if (str_author)
2073
            nstrcpy(oc->author, sizeof(oc->author), str_author);
2074
        if (str_copyright)
2075
            nstrcpy(oc->copyright, sizeof(oc->copyright), str_copyright);
2076
        if (str_comment)
2077
            nstrcpy(oc->comment, sizeof(oc->comment), str_comment);
2078
    }
2079

    
2080
    output_files[nb_output_files] = oc;
2081
    /* dump the file content */
2082
    dump_format(oc, nb_output_files, filename, 1);
2083
    nb_output_files++;
2084

    
2085
    strcpy(oc->filename, filename);
2086

    
2087
    /* check filename in case of an image number is expected */
2088
    if (oc->format->flags & AVFMT_NEEDNUMBER) {
2089
        if (filename_number_test(oc->filename) < 0)
2090
            exit(1);
2091
    }
2092

    
2093
    if (!(oc->format->flags & AVFMT_NOFILE)) {
2094
        /* test if it already exists to avoid loosing precious files */
2095
        if (!file_overwrite && 
2096
            (strchr(filename, ':') == NULL ||
2097
             strstart(filename, "file:", NULL))) {
2098
            if (url_exist(filename)) {
2099
                int c;
2100
                
2101
                printf("File '%s' already exists. Overwrite ? [y/N] ", filename);
2102
                fflush(stdout);
2103
                c = getchar();
2104
                if (toupper(c) != 'Y') {
2105
                    fprintf(stderr, "Not overwriting - exiting\n");
2106
                    exit(1);
2107
                }
2108
            }
2109
        }
2110
        
2111
        /* open the file */
2112
        if (url_fopen(&oc->pb, filename, URL_WRONLY) < 0) {
2113
            fprintf(stderr, "Could not open '%s'\n", filename);
2114
            exit(1);
2115
        }
2116
    }
2117

    
2118
    /* reset some options */
2119
    file_format = NULL;
2120
    audio_disable = 0;
2121
    video_disable = 0;
2122
    audio_codec_id = CODEC_ID_NONE;
2123
    video_codec_id = CODEC_ID_NONE;
2124
}
2125

    
2126
#ifdef CONFIG_GRAB
2127

    
2128
/* prepare dummy protocols for grab */
2129
void prepare_grab(void)
2130
{
2131
    int has_video, has_audio, i, j;
2132
    AVFormatContext *oc;
2133
    AVFormatContext *ic;
2134
    AVFormatParameters ap1, *ap = &ap1;
2135

    
2136
    /* see if audio/video inputs are needed */
2137
    has_video = 0;
2138
    has_audio = 0;
2139
    memset(ap, 0, sizeof(*ap));
2140
    for(j=0;j<nb_output_files;j++) {
2141
        oc = output_files[j];
2142
        for(i=0;i<oc->nb_streams;i++) {
2143
            AVCodecContext *enc = &oc->streams[i]->codec;
2144
            switch(enc->codec_type) {
2145
            case CODEC_TYPE_AUDIO:
2146
                if (enc->sample_rate > ap->sample_rate)
2147
                    ap->sample_rate = enc->sample_rate;
2148
                if (enc->channels > ap->channels)
2149
                    ap->channels = enc->channels;
2150
                has_audio = 1;
2151
                break;
2152
            case CODEC_TYPE_VIDEO:
2153
                if (enc->width > ap->width)
2154
                    ap->width = enc->width;
2155
                if (enc->height > ap->height)
2156
                    ap->height = enc->height;
2157
                if (enc->frame_rate > ap->frame_rate)
2158
                    ap->frame_rate = enc->frame_rate;
2159
                has_video = 1;
2160
                break;
2161
            default:
2162
                abort();
2163
            }
2164
        }
2165
    }
2166
    
2167
    if (has_video == 0 && has_audio == 0) {
2168
        fprintf(stderr, "Output file must have at least one audio or video stream\n");
2169
        exit(1);
2170
    }
2171
    
2172
    if (has_video) {
2173
        ic = av_open_input_file("", "video_grab_device", 0, ap);
2174
        /* by now video grab has one stream */
2175
        ic->streams[0]->r_frame_rate = ap->frame_rate;
2176
        if (!ic) {
2177
            fprintf(stderr, "Could not open video grab device\n");
2178
            exit(1);
2179
        }
2180
        input_files[nb_input_files] = ic;
2181
        dump_format(ic, nb_input_files, v4l_device, 0);
2182
        nb_input_files++;
2183
    }
2184
    if (has_audio) {
2185
        ic = av_open_input_file("", "audio_device", 0, ap);
2186
        if (!ic) {
2187
            fprintf(stderr, "Could not open audio grab device\n");
2188
            exit(1);
2189
        }
2190
        input_files[nb_input_files] = ic;
2191
        dump_format(ic, nb_input_files, audio_device, 0);
2192
        nb_input_files++;
2193
    }
2194
}
2195

    
2196
#else
2197

    
2198
void prepare_grab(void)
2199
{
2200
    fprintf(stderr, "Must supply at least one input file\n");
2201
    exit(1);
2202
}
2203

    
2204
#endif
2205

    
2206
/* open the necessary output devices for playing */
2207
void prepare_play(void)
2208
{
2209
#ifndef __BEOS__
2210
    file_format = guess_format("audio_device", NULL, NULL);
2211
    if (!file_format) {
2212
        fprintf(stderr, "Could not find audio device\n");
2213
        exit(1);
2214
    }
2215
    
2216
    opt_output_file(audio_device);
2217
#endif
2218
}
2219

    
2220

    
2221
#ifndef CONFIG_WIN32
2222
INT64 getutime(void)
2223
{
2224
    struct rusage rusage;
2225

    
2226
    getrusage(RUSAGE_SELF, &rusage);
2227
    return (rusage.ru_utime.tv_sec * 1000000LL) + rusage.ru_utime.tv_usec;
2228
}
2229
#else
2230
INT64 getutime(void)
2231
{
2232
  return gettime();
2233
}
2234
#endif
2235

    
2236
void show_formats(void)
2237
{
2238
    AVFormat *f;
2239
    URLProtocol *up;
2240
    AVCodec *p;
2241
    const char **pp;
2242

    
2243
    printf("File formats:\n");
2244
    printf("  Encoding:");
2245
    for(f = first_format; f != NULL; f = f->next) {
2246
        if (f->write_header)
2247
            printf(" %s", f->name);
2248
    }
2249
    printf("\n");
2250
    printf("  Decoding:");
2251
    for(f = first_format; f != NULL; f = f->next) {
2252
        if (f->read_header)
2253
            printf(" %s", f->name);
2254
    }
2255
    printf("\n");
2256

    
2257
    printf("Codecs:\n");
2258
    printf("  Encoders:");
2259
    for(p = first_avcodec; p != NULL; p = p->next) {
2260
        if (p->encode)
2261
            printf(" %s", p->name);
2262
    }
2263
    printf("\n");
2264

    
2265
    printf("  Decoders:");
2266
    for(p = first_avcodec; p != NULL; p = p->next) {
2267
        if (p->decode)
2268
            printf(" %s", p->name);
2269
    }
2270
    printf("\n");
2271

    
2272
    printf("Supported file protocols:");
2273
    for(up = first_protocol; up != NULL; up = up->next)
2274
        printf(" %s:", up->name);
2275
    printf("\n");
2276
    
2277
    printf("Frame size abbreviations: sqcif qcif cif 4cif\n");
2278
    printf("Motion estimation methods:");
2279
    pp = motion_str;
2280
    while (*pp) {
2281
        printf(" %s", *pp);
2282
        if ((pp - motion_str + 1) == ME_ZERO) 
2283
            printf("(fastest)");
2284
        else if ((pp - motion_str + 1) == ME_FULL) 
2285
            printf("(slowest)");
2286
        else if ((pp - motion_str + 1) == ME_EPZS) 
2287
            printf("(default)");
2288
        pp++;
2289
    }
2290
    printf("\n");
2291
    exit(1);
2292
}
2293

    
2294
void show_help(void)
2295
{
2296
    const char *prog;
2297
    const OptionDef *po;
2298
    int i, expert;
2299
    
2300
    prog = do_play ? "ffplay" : "ffmpeg";
2301

    
2302
    printf("%s version " FFMPEG_VERSION ", Copyright (c) 2000, 2001 Gerard Lantau\n", 
2303
           prog);
2304
    
2305
    if (!do_play) {
2306
        printf("usage: ffmpeg [[options] -i input_file]... {[options] outfile}...\n"
2307
               "Hyper fast MPEG1/MPEG4/H263/RV and AC3/MPEG audio encoder\n");
2308
    } else {
2309
        printf("usage: ffplay [options] input_file...\n"
2310
               "Simple audio player\n");
2311
    }
2312
           
2313
    printf("\n"
2314
           "Main options are:\n");
2315
    for(i=0;i<2;i++) {
2316
        if (i == 1)
2317
            printf("\nAdvanced options are:\n");
2318
        for(po = options; po->name != NULL; po++) {
2319
            char buf[64];
2320
            expert = (po->flags & OPT_EXPERT) != 0;
2321
            if (expert == i) {
2322
                strcpy(buf, po->name);
2323
                if (po->flags & HAS_ARG) {
2324
                    strcat(buf, " ");
2325
                    strcat(buf, po->argname);
2326
                }
2327
                printf("-%-17s  %s\n", buf, po->help);
2328
            }
2329
        }
2330
    }
2331

    
2332
    exit(1);
2333
}
2334

    
2335
const OptionDef options[] = {
2336
    { "L", 0, {(void*)show_licence}, "show license" },
2337
    { "h", 0, {(void*)show_help}, "show help" },
2338
    { "formats", 0, {(void*)show_formats}, "show available formats, codecs, protocols, ..." },
2339
    { "f", HAS_ARG, {(void*)opt_format}, "force format", "fmt" },
2340
    { "vcd", OPT_BOOL, {(void*)&mpeg_vcd}, "output Video CD MPEG-PS compliant file" },
2341
    { "i", HAS_ARG, {(void*)opt_input_file}, "input file name", "filename" },
2342
    { "y", OPT_BOOL, {(void*)&file_overwrite}, "overwrite output files" },
2343
    { "map", HAS_ARG | OPT_EXPERT, {(void*)opt_map}, "set input stream mapping", "file:stream" },
2344
    { "t", HAS_ARG, {(void*)opt_recording_time}, "set the recording time", "duration" },
2345
    { "title", HAS_ARG | OPT_STRING, {(void*)&str_title}, "set the title", "string" },
2346
    { "author", HAS_ARG | OPT_STRING, {(void*)&str_author}, "set the author", "string" },
2347
    { "copyright", HAS_ARG | OPT_STRING, {(void*)&str_copyright}, "set the copyright", "string" },
2348
    { "comment", HAS_ARG | OPT_STRING, {(void*)&str_comment}, "set the comment", "string" },
2349
    /* video options */
2350
    { "b", HAS_ARG, {(void*)opt_video_bitrate}, "set video bitrate (in kbit/s)", "bitrate" },
2351
    { "r", HAS_ARG, {(void*)opt_frame_rate}, "set frame rate (in Hz)", "rate" },
2352
    { "s", HAS_ARG, {(void*)opt_frame_size}, "set frame size (WxH or abbreviation)", "size" },
2353
    { "g", HAS_ARG | OPT_EXPERT, {(void*)opt_gop_size}, "set the group of picture size", "gop_size" },
2354
    { "intra", OPT_BOOL | OPT_EXPERT, {(void*)&intra_only}, "use only intra frames"},
2355
    { "vn", OPT_BOOL, {(void*)&video_disable}, "disable video" },
2356
    { "qscale", HAS_ARG | OPT_EXPERT, {(void*)opt_qscale}, "use fixed video quantiser scale (VBR)", "q" },
2357
    { "qmin", HAS_ARG | OPT_EXPERT, {(void*)opt_qmin}, "min video quantiser scale (VBR)", "q" },
2358
    { "qmax", HAS_ARG | OPT_EXPERT, {(void*)opt_qmax}, "max video quantiser scale (VBR)", "q" },
2359
    { "qdiff", HAS_ARG | OPT_EXPERT, {(void*)opt_qdiff}, "max difference between the quantiser scale (VBR)", "q" },
2360
    { "qblur", HAS_ARG | OPT_EXPERT, {(void*)opt_qblur}, "video quantiser scale blur (VBR)", "blur" },
2361
    { "qcomp", HAS_ARG | OPT_EXPERT, {(void*)opt_qcomp}, "video quantiser scale compression (VBR)", "compression" },
2362
    { "bt", HAS_ARG, {(void*)opt_video_bitrate_tolerance}, "set video bitrate tolerance (in kbit/s)", "tolerance" },
2363
#ifdef CONFIG_GRAB
2364
    { "vd", HAS_ARG | OPT_EXPERT, {(void*)opt_video_device}, "set video device", "device" },
2365
#endif
2366
    { "vcodec", HAS_ARG | OPT_EXPERT, {(void*)opt_video_codec}, "force video codec", "codec" },
2367
    { "me", HAS_ARG | OPT_EXPERT, {(void*)opt_motion_estimation}, "set motion estimation method", 
2368
      "method" },
2369
    { "bf", HAS_ARG | OPT_EXPERT, {(void*)opt_b_frames}, "use 'frames' B frames (only MPEG-4)", "frames" },
2370
    { "hq", OPT_BOOL | OPT_EXPERT, {(void*)&use_hq}, "activate high quality settings" },
2371
    { "4mv", OPT_BOOL | OPT_EXPERT, {(void*)&use_4mv}, "use four motion vector by macroblock (only MPEG-4)" },
2372
    { "sameq", OPT_BOOL, {(void*)&same_quality}, 
2373
      "use same video quality as source (implies VBR)" },
2374
    /* audio options */
2375
    { "ab", HAS_ARG, {(void*)opt_audio_bitrate}, "set audio bitrate (in kbit/s)", "bitrate", },
2376
    { "ar", HAS_ARG, {(void*)opt_audio_rate}, "set audio sampling rate (in Hz)", "rate" },
2377
    { "ac", HAS_ARG, {(void*)opt_audio_channels}, "set number of audio channels", "channels" },
2378
    { "an", OPT_BOOL, {(void*)&audio_disable}, "disable audio" },
2379
#ifdef CONFIG_GRAB
2380
    { "ad", HAS_ARG | OPT_EXPERT, {(void*)opt_audio_device}, "set audio device", "device" },
2381
#endif
2382
    { "acodec", HAS_ARG | OPT_EXPERT, {(void*)opt_audio_codec}, "force audio codec", "codec" },
2383
    { "deinterlace", OPT_BOOL | OPT_EXPERT, {(void*)&do_deinterlace}, 
2384
      "deinterlace pictures" },
2385
    { "benchmark", OPT_BOOL | OPT_EXPERT, {(void*)&do_benchmark}, 
2386
      "add timings for benchmarking" },
2387
    { "hex", OPT_BOOL | OPT_EXPERT, {(void*)&do_hex_dump}, 
2388
      "dump each input packet" },
2389
    { "psnr", OPT_BOOL | OPT_EXPERT, {(void*)&do_psnr}, "calculate PSNR of compressed frames" },
2390
    { "vstats", OPT_BOOL | OPT_EXPERT, {(void*)&do_vstats}, "dump video coding statistics to file" }, 
2391

    
2392
    { NULL, },
2393
};
2394

    
2395
int main(int argc, char **argv)
2396
{
2397
    int optindex, i;
2398
    const char *opt, *arg;
2399
    const OptionDef *po;
2400
    INT64 ti;
2401
    
2402
    register_all();
2403

    
2404
    /* detect if invoked as player */
2405
    i = strlen(argv[0]);
2406
    if (i >= 6 && !strcmp(argv[0] + i - 6, "ffplay"))
2407
        do_play = 1;
2408

    
2409
    if (argc <= 1)
2410
        show_help();
2411
    
2412
    /* parse options */
2413
    optindex = 1;
2414
    while (optindex < argc) {
2415
        opt = argv[optindex++];
2416
        
2417
        if (opt[0] == '-' && opt[1] != '\0') {
2418
            po = options;
2419
            while (po->name != NULL) {
2420
                if (!strcmp(opt + 1, po->name))
2421
                    break;
2422
                po++;
2423
            }
2424
            if (!po->name) {
2425
                fprintf(stderr, "%s: unrecognized option '%s'\n", argv[0], opt);
2426
                exit(1);
2427
            }
2428
            arg = NULL;
2429
            if (po->flags & HAS_ARG)
2430
                arg = argv[optindex++];
2431
            if (po->flags & OPT_STRING) {
2432
                char *str;
2433
                str = strdup(arg);
2434
                *po->u.str_arg = str;
2435
            } else if (po->flags & OPT_BOOL) {
2436
                *po->u.int_arg = 1;
2437
            } else {
2438
                po->u.func_arg(arg);
2439
            }
2440
        } else {
2441
            if (!do_play) {
2442
                opt_output_file(opt);
2443
            } else {
2444
                opt_input_file(opt);
2445
            }
2446
        }
2447
    }
2448

    
2449

    
2450
    if (!do_play) {
2451
        /* file converter / grab */
2452
        if (nb_output_files <= 0) {
2453
            fprintf(stderr, "Must supply at least one output file\n");
2454
            exit(1);
2455
        }
2456
        
2457
        if (nb_input_files == 0) {
2458
            prepare_grab();
2459
        }
2460
    } else {
2461
        /* player */
2462
        if (nb_input_files <= 0) {
2463
            fprintf(stderr, "Must supply at least one input file\n");
2464
            exit(1);
2465
        }
2466
        prepare_play();
2467
    }
2468

    
2469
    ti = getutime();
2470
    av_encode(output_files, nb_output_files, input_files, nb_input_files, 
2471
              stream_maps, nb_stream_maps);
2472
    ti = getutime() - ti;
2473
    if (do_benchmark) {
2474
        printf("bench: utime=%0.3fs\n", ti / 1000000.0);
2475
    }
2476

    
2477
    /* close files */
2478
    for(i=0;i<nb_output_files;i++) {
2479
        if (!(output_files[i]->format->flags & AVFMT_NOFILE)) 
2480
            url_fclose(&output_files[i]->pb);
2481
    }
2482
    for(i=0;i<nb_input_files;i++) {
2483
        if (!(input_files[i]->format->flags & AVFMT_NOFILE)) 
2484
            url_fclose(&input_files[i]->pb);
2485
    }
2486

    
2487
    return 0;
2488
}