Statistics
| Branch: | Revision:

ffmpeg / ffmpeg.c @ bc6caae2

History | View | Annotate | Download (67.9 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

    
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 <time.h>
29
#include <sys/resource.h>
30
#include <ctype.h>
31
#endif
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 AVFormat *file_format;
74
static int frame_width  = 160;
75
static int frame_height = 128;
76
static int frame_rate = 25 * FRAME_RATE_BASE;
77
static int video_bit_rate = 200000;
78
static int video_bit_rate_tolerance = 200000;
79
static int video_qscale = 0;
80
static int video_qmin = 3;
81
static int video_qmax = 15;
82
static int video_qdiff = 3;
83
static float video_qblur = 0.5;
84
static float video_qcomp = 0.5;
85
static int me_method = 0;
86
static int video_disable = 0;
87
static int video_codec_id = CODEC_ID_NONE;
88
static int same_quality = 0;
89
static int b_frames = 0;
90
static int use_hq = 0;
91
static int use_4mv = 0;
92
static int do_deinterlace = 0;
93

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

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

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

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

    
134
typedef struct AVInputStream {
135
    int file_index;
136
    int index;
137
    AVStream *st;
138
    int discard;             /* true if stream data should be discarded */
139
    int decoding_needed;     /* true if the packets must be decoded in 'raw_fifo' */
140
    INT64 pts;               /* current pts */
141
    int frame_number;        /* current frame */
142
    INT64 sample_index;      /* current sample */
143
} AVInputStream;
144

    
145
typedef struct AVInputFile {
146
    int eof_reached;      /* true if eof reached */
147
    int ist_index;        /* index of first stream in ist_table */
148
    int buffer_size;      /* current total buffer size */
149
    int buffer_size_max;  /* buffer size at which we consider we can stop
150
                             buffering */
151
} AVInputFile;
152

    
153
#ifndef CONFIG_WIN32
154

    
155
/* init terminal so that we can grab keys */
156
static struct termios oldtty;
157

    
158
static void term_exit(void)
159
{
160
    tcsetattr (0, TCSANOW, &oldtty);
161
}
162

    
163
static void term_init(void)
164
{
165
    struct termios tty;
166

    
167
    tcgetattr (0, &tty);
168
    oldtty = tty;
169

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

    
181
    atexit(term_exit);
182
}
183

    
184
/* read a key without blocking */
185
static int read_key(void)
186
{
187
    struct timeval tv;
188
    int n;
189
    unsigned char ch;
190
    fd_set rfds;
191

    
192
    FD_ZERO(&rfds);
193
    FD_SET(0, &rfds);
194
    tv.tv_sec = 0;
195
    tv.tv_usec = 0;
196
    n = select(1, &rfds, NULL, NULL, &tv);
197
    if (n > 0) {
198
        if (read(0, &ch, 1) == 1)
199
            return ch;
200
    }
201
    return -1;
202
}
203

    
204
#else
205

    
206
/* no interactive support */
207
static void term_exit(void)
208
{
209
}
210

    
211
static void term_init(void)
212
{
213
}
214

    
215
static int read_key(void)
216
{
217
    return -1;
218
}
219

    
220
#endif
221

    
222
int read_ffserver_streams(AVFormatContext *s, const char *filename)
223
{
224
    int i;
225
    AVFormatContext *ic;
226

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

    
239
    av_close_input_file(ic);
240
    return 0;
241
}
242

    
243
#define MAX_AUDIO_PACKET_SIZE 16384
244

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

    
256
    enc = &ost->st->codec;
257

    
258
    if (ost->audio_resample) {
259
        buftmp = audio_buf;
260
        size_out = audio_resample(ost->resample, 
261
                                  (short *)buftmp, (short *)buf,
262
                                  size / (ist->st->codec.channels * 2));
263
        size_out = size_out * enc->channels * 2;
264
    } else {
265
        buftmp = buf;
266
        size_out = size;
267
    }
268

    
269
    /* now encode as many frames as possible */
270
    if (enc->frame_size > 1) {
271
        /* output resampled raw samples */
272
        fifo_write(&ost->fifo, buftmp, size_out, 
273
                   &ost->fifo.wptr);
274

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

    
302
/* write a picture to a raw mux */
303
static void write_picture(AVFormatContext *s, int index, AVPicture *picture, 
304
                          int pix_fmt, int w, int h)
305
{
306
    UINT8 *buf, *src, *dest;
307
    int size, j, i;
308

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

    
398

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

    
412
    enc = &ost->st->codec;
413
    dec = &ist->st->codec;
414

    
415
    frame_number = ist->frame_number;
416
    /* first drop frame if needed */
417
    n1 = ((INT64)frame_number * enc->frame_rate) / dec->frame_rate;
418
    n2 = (((INT64)frame_number + 1) * enc->frame_rate) / dec->frame_rate;
419
    nb = n2 - n1;
420
    if (nb <= 0) 
421
        return;
422

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

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

    
436
        if (avpicture_deinterlace(picture2, picture1, 
437
                                  dec->pix_fmt, dec->width, dec->height) < 0) {
438
            /* if error, do not deinterlace */
439
            free(buf1);
440
            buf1 = NULL;
441
            picture2 = picture1;
442
        }
443
    } else {
444
        picture2 = picture1;
445
    }
446

    
447
    /* convert pixel format if needed */
448
    if (enc->pix_fmt != dec->pix_fmt) {
449
        int size;
450

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

    
469
    /* XXX: resampling could be done before raw format convertion in
470
       some cases to go faster */
471
    /* XXX: only works for YUV420P */
472
    if (ost->video_resample) {
473
        picture = &ost->pict_tmp;
474
        img_resample(ost->img_resample_ctx, picture, pict);
475
    } else {
476
        picture = pict;
477
    }
478

    
479
    /* duplicates frame if needed */
480
    /* XXX: pb because no interleaving */
481
    for(i=0;i<nb;i++) {
482
        if (enc->codec_id != CODEC_ID_RAWVIDEO) {
483
            /* handles sameq here. This is not correct because it may
484
               not be a global option */
485
            if (same_quality) {
486
                enc->quality = dec->quality;
487
            }
488
            ret = avcodec_encode_video(enc, 
489
                                       video_buffer, sizeof(video_buffer), 
490
                                       picture);
491
            s->format->write_packet(s, ost->index, video_buffer, ret, 0);
492
            *frame_size = ret;
493
        } else {
494
            write_picture(s, ost->index, picture, enc->pix_fmt, enc->width, enc->height);
495
        }
496
    }
497
    the_end:
498
    if (buf)
499
        free(buf);
500
    if (buf1)
501
        free(buf1);
502
}
503

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

    
556
    
557
    
558
}
559

    
560
static void hex_dump(UINT8 *buf, int size)
561
{
562
    int len, i, j, c;
563

    
564
    for(i=0;i<size;i+=16) {
565
        len = size - i;
566
        if (len > 16)
567
            len = 16;
568
        printf("%08x ", i);
569
        for(j=0;j<16;j++) {
570
            if (j < len)
571
                printf(" %02x", buf[i+j]);
572
            else
573
                printf("   ");
574
        }
575
        printf(" ");
576
        for(j=0;j<len;j++) {
577
            c = buf[i+j];
578
            if (c < ' ' || c > '~')
579
                c = '.';
580
            printf("%c", c);
581
        }
582
        printf("\n");
583
    }
584
}
585

    
586
/*
587
 * The following code is the main loop of the file converter
588
 */
589
static int av_encode(AVFormatContext **output_files,
590
                     int nb_output_files,
591
                     AVFormatContext **input_files,
592
                     int nb_input_files,
593
                     AVStreamMap *stream_maps, int nb_stream_maps)
594
{
595
    int ret, i, j, k, n, nb_istreams = 0, nb_ostreams = 0;
596
    AVFormatContext *is, *os;
597
    AVCodecContext *codec, *icodec;
598
    AVOutputStream *ost, **ost_table = NULL;
599
    AVInputStream *ist, **ist_table = NULL;
600
    INT64 min_pts, start_time;
601
    AVInputFile *file_table;
602

    
603
    file_table= (AVInputFile*) malloc(nb_input_files * sizeof(AVInputFile));
604
    if (!file_table)
605
        goto fail;
606

    
607
    memset(file_table, 0, sizeof(file_table));
608
    
609
    /* input stream init */
610
    j = 0;
611
    for(i=0;i<nb_input_files;i++) {
612
        is = input_files[i];
613
        file_table[i].ist_index = j;
614
        j += is->nb_streams;
615
    }
616
    nb_istreams = j;
617

    
618
    ist_table = av_mallocz(nb_istreams * sizeof(AVInputStream *));
619
    if (!ist_table)
620
        goto fail;
621
    
622
    for(i=0;i<nb_istreams;i++) {
623
        ist = av_mallocz(sizeof(AVInputStream));
624
        if (!ist)
625
            goto fail;
626
        ist_table[i] = ist;
627
    }
628
    j = 0;
629
    for(i=0;i<nb_input_files;i++) {
630
        is = input_files[i];
631
        for(k=0;k<is->nb_streams;k++) {
632
            ist = ist_table[j++];
633
            ist->st = is->streams[k];
634
            ist->file_index = i;
635
            ist->index = k;
636
            ist->discard = 1; /* the stream is discarded by default
637
                                 (changed later) */
638
        }
639
    }
640

    
641
    /* output stream init */
642
    nb_ostreams = 0;
643
    for(i=0;i<nb_output_files;i++) {
644
        os = output_files[i];
645
        nb_ostreams += os->nb_streams;
646
    }
647
    if (nb_stream_maps > 0 && nb_stream_maps != nb_ostreams) {
648
        fprintf(stderr, "Number of stream maps must match number of output streams\n");
649
        exit(1);
650
    }
651

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

    
707
    /* dump the stream mapping */
708
    fprintf(stderr, "Stream mapping:\n");
709
    for(i=0;i<nb_ostreams;i++) {
710
        ost = ost_table[i];
711
        fprintf(stderr, "  Stream #%d.%d -> #%d.%d\n",
712
                ist_table[ost->source_index]->file_index,
713
                ist_table[ost->source_index]->index,
714
                ost->file_index, 
715
                ost->index);
716
    }
717

    
718
    /* for each output stream, we compute the right encoding parameters */
719
    for(i=0;i<nb_ostreams;i++) {
720
        ost = ost_table[i];
721
        ist = ist_table[ost->source_index];
722

    
723
        codec = &ost->st->codec;
724
        icodec = &ist->st->codec;
725

    
726
        switch(codec->codec_type) {
727
        case CODEC_TYPE_AUDIO:
728
            /* check if same codec with same parameters. If so, no
729
               reencoding is needed */
730
            if (codec->codec_id == icodec->codec_id &&
731
                codec->bit_rate == icodec->bit_rate &&
732
                codec->sample_rate == icodec->sample_rate &&
733
                codec->channels == icodec->channels) {
734
                /* no reencoding */
735
                /* use the same frame size */
736
                codec->frame_size = icodec->frame_size;
737
                //codec->frame_size = 8*icodec->sample_rate*icodec->frame_size/
738
                //                    icodec->bit_rate;
739
                //fprintf(stderr,"\nFrame size: %d", codec->frame_size);
740
            } else {
741
                if (fifo_init(&ost->fifo, 2 * MAX_AUDIO_PACKET_SIZE))
742
                    goto fail;
743

    
744
                if (codec->channels == icodec->channels &&
745
                    codec->sample_rate == icodec->sample_rate) {
746
                    ost->audio_resample = 0;
747
                } else {
748
                    if (codec->channels != icodec->channels &&
749
                        icodec->codec_id == CODEC_ID_AC3) {
750
                        /* Special case for 5:1 AC3 input */
751
                        /* and mono or stereo output      */
752
                        ost->audio_resample = 0;
753
                        /* Request specific number of channels */
754
                        icodec->channels = codec->channels;
755
                    } else {
756
                        ost->audio_resample = 1; 
757
                        ost->resample = audio_resample_init(codec->channels, icodec->channels,
758
                                                        codec->sample_rate, 
759
                                                        icodec->sample_rate);
760
                    }
761
                }
762
                ist->decoding_needed = 1;
763
                ost->encoding_needed = 1;
764
            }
765
            break;
766
        case CODEC_TYPE_VIDEO:
767
            /* check if same codec with same parameters. If so, no
768
               reencoding is needed */
769
            if (codec->codec_id == icodec->codec_id &&
770
                codec->bit_rate == icodec->bit_rate &&
771
                codec->frame_rate == icodec->frame_rate &&
772
                codec->width == icodec->width &&
773
                codec->height == icodec->height) {
774
                /* no reencoding */
775
            } else {
776
                if (codec->width == icodec->width &&
777
                    codec->height == icodec->height) {
778
                    ost->video_resample = 0;
779
                } else {
780
                    UINT8 *buf;
781
                    ost->video_resample = 1;
782
                    buf = malloc((codec->width * codec->height * 3) / 2);
783
                    if (!buf)
784
                        goto fail;
785
                    ost->pict_tmp.data[0] = buf;
786
                    ost->pict_tmp.data[1] = ost->pict_tmp.data[0] + (codec->width * codec->height);
787
                    ost->pict_tmp.data[2] = ost->pict_tmp.data[1] + (codec->width * codec->height) / 4;
788
                    ost->pict_tmp.linesize[0] = codec->width;
789
                    ost->pict_tmp.linesize[1] = codec->width / 2;
790
                    ost->pict_tmp.linesize[2] = codec->width / 2;
791

    
792
                    ost->img_resample_ctx = img_resample_init( 
793
                                      ost->st->codec.width, ost->st->codec.height,
794
                                      ist->st->codec.width, ist->st->codec.height);
795
                }
796
                ost->encoding_needed = 1;
797
                ist->decoding_needed = 1;
798
            }
799
            break;
800
        }
801
    }
802

    
803
    /* open each encoder */
804
    for(i=0;i<nb_ostreams;i++) {
805
        ost = ost_table[i];
806
        if (ost->encoding_needed) {
807
            AVCodec *codec;
808
            codec = avcodec_find_encoder(ost->st->codec.codec_id);
809
            if (!codec) {
810
                fprintf(stderr, "Unsupported codec for output stream #%d.%d\n", 
811
                        ost->file_index, ost->index);
812
                exit(1);
813
            }
814
            if (avcodec_open(&ost->st->codec, codec) < 0) {
815
                fprintf(stderr, "Error while opening codec for stream #%d.%d - maybe incorrect parameters such as bit_rate, rate, width or height\n", 
816
                        ost->file_index, ost->index);
817
                exit(1);
818
            }
819
        }
820
    }
821

    
822
    /* open each decoder */
823
    for(i=0;i<nb_istreams;i++) {
824
        ist = ist_table[i];
825
        if (ist->decoding_needed) {
826
            AVCodec *codec;
827
            codec = avcodec_find_decoder(ist->st->codec.codec_id);
828
            if (!codec) {
829
                fprintf(stderr, "Unsupported codec for input stream #%d.%d\n", 
830
                        ist->file_index, ist->index);
831
                exit(1);
832
            }
833
            if (avcodec_open(&ist->st->codec, codec) < 0) {
834
                fprintf(stderr, "Error while opening codec for input stream #%d.%d\n", 
835
                        ist->file_index, ist->index);
836
                exit(1);
837
            }
838
        }
839
    }
840

    
841
    /* init pts */
842
    for(i=0;i<nb_istreams;i++) {
843
        ist = ist_table[i];
844
        ist->pts = 0;
845
        ist->frame_number = 0;
846
    }
847
    
848
    /* compute buffer size max (should use a complete heuristic) */
849
    for(i=0;i<nb_input_files;i++) {
850
        file_table[i].buffer_size_max = 2048;
851
    }
852

    
853
    /* open files and write file headers */
854
    for(i=0;i<nb_output_files;i++) {
855
        os = output_files[i];
856
        if (os->format->write_header(os) < 0) {
857
            fprintf(stderr, "Could not write header for output file #%d (incorrect codec paramters ?)\n", i);
858
            ret = -EINVAL;
859
            goto fail;
860
        }
861
    }
862

    
863
#ifndef CONFIG_WIN32
864
    if (!do_play) {
865
        fprintf(stderr, "Press [q] to stop encoding\n");
866
    } else {
867
        fprintf(stderr, "Press [q] to stop playing\n");
868
    }
869
#endif
870
    term_init();
871

    
872
    start_time = gettime();
873
    min_pts = 0;
874
    for(;;) {
875
        int file_index, ist_index;
876
        AVPacket pkt;
877
        UINT8 *ptr;
878
        int len;
879
        UINT8 *data_buf;
880
        int data_size, got_picture;
881
        AVPicture picture;
882
        short samples[AVCODEC_MAX_AUDIO_FRAME_SIZE / 2];
883

    
884
    redo:
885
        /* if 'q' pressed, exits */
886
        if (read_key() == 'q')
887
            break;
888

    
889
        /* select the input file with the smallest pts */
890
        file_index = -1;
891
        min_pts = MAXINT64;
892
        for(i=0;i<nb_istreams;i++) {
893
            ist = ist_table[i];
894
            if (!ist->discard && !file_table[ist->file_index].eof_reached && ist->pts < min_pts) {
895
                min_pts = ist->pts;
896
                file_index = ist->file_index;
897
            }
898
        }
899
        /* if none, if is finished */
900
        if (file_index < 0)
901
            break;
902
        /* finish if recording time exhausted */
903
        if (recording_time > 0 && min_pts >= recording_time)
904
            break;
905
        /* read a packet from it and output it in the fifo */
906
        is = input_files[file_index];
907
        if (av_read_packet(is, &pkt) < 0) {
908
            file_table[file_index].eof_reached = 1;
909
            continue;
910
        }
911
        ist_index = file_table[file_index].ist_index + pkt.stream_index;
912
        ist = ist_table[ist_index];
913
        if (ist->discard) {
914
            continue;
915
        }
916

    
917
        if (do_hex_dump) {
918
            printf("stream #%d, size=%d:\n", pkt.stream_index, pkt.size);
919
            hex_dump(pkt.data, pkt.size);
920
        }
921

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

    
924
        len = pkt.size;
925
        ptr = pkt.data;
926
        while (len > 0) {
927

    
928
            /* decode the packet if needed */
929
            data_buf = NULL; /* fail safe */
930
            data_size = 0;
931
            if (ist->decoding_needed) {
932
                switch(ist->st->codec.codec_type) {
933
                case CODEC_TYPE_AUDIO:
934
                    /* XXX: could avoid copy if PCM 16 bits with same
935
                       endianness as CPU */
936
                    ret = avcodec_decode_audio(&ist->st->codec, samples, &data_size,
937
                                               ptr, len);
938
                    if (ret < 0)
939
                        goto fail_decode;
940
                    if (data_size == 0) {
941
                        /* no audio frame */
942
                        ptr += ret;
943
                        len -= ret;
944
                        continue;
945
                    }
946
                    data_buf = (UINT8 *)samples;
947
                    break;
948
                case CODEC_TYPE_VIDEO:
949
                    if (ist->st->codec.codec_id == CODEC_ID_RAWVIDEO) {
950
                        int size;
951
                        size = (ist->st->codec.width * ist->st->codec.height);
952
                        avpicture_fill(&picture, ptr, 
953
                                     ist->st->codec.pix_fmt,
954
                                     ist->st->codec.width,
955
                                     ist->st->codec.height);
956
                        ret = len;
957
                    } else {
958
                        data_size = (ist->st->codec.width * ist->st->codec.height * 3) / 2;
959
                        ret = avcodec_decode_video(&ist->st->codec, 
960
                                                   &picture, &got_picture, ptr, len);
961
                        if (ret < 0) {
962
                        fail_decode:
963
                            fprintf(stderr, "Error while decoding stream #%d.%d\n",
964
                                    ist->file_index, ist->index);
965
                            av_free_packet(&pkt);
966
                            goto redo;
967
                        }
968
                        if (!got_picture) {
969
                            /* no picture yet */
970
                            ptr += ret;
971
                            len -= ret;
972
                            continue;
973
                        }
974
                    }
975
                    break;
976
                default:
977
                    goto fail_decode;
978
                }
979
            } else {
980
                data_buf = ptr;
981
                data_size = len;
982
                ret = len;
983
            }
984
            /* update pts */
985
            switch(ist->st->codec.codec_type) {
986
            case CODEC_TYPE_AUDIO:
987
                ist->pts = (INT64)1000000 * ist->sample_index / ist->st->codec.sample_rate;
988
                ist->sample_index += data_size / (2 * ist->st->codec.channels);
989
                break;
990
            case CODEC_TYPE_VIDEO:
991
                ist->frame_number++;
992
                ist->pts = ((INT64)ist->frame_number * 1000000 * FRAME_RATE_BASE) / 
993
                    ist->st->codec.frame_rate;
994
                break;
995
            }
996
            ptr += ret;
997
            len -= ret;
998

    
999
            /* transcode raw format, encode packets and output them */
1000
            
1001
            for(i=0;i<nb_ostreams;i++) {
1002
                int frame_size;
1003
                ost = ost_table[i];
1004
                if (ost->source_index == ist_index) {
1005
                    os = output_files[ost->file_index];
1006

    
1007
                    if (ost->encoding_needed) {
1008
                        switch(ost->st->codec.codec_type) {
1009
                        case CODEC_TYPE_AUDIO:
1010
                            do_audio_out(os, ost, ist, data_buf, data_size);
1011
                            break;
1012
                        case CODEC_TYPE_VIDEO:
1013
                            do_video_out(os, ost, ist, &picture, &frame_size);
1014
                            if (do_vstats)
1015
                                do_video_stats(ost, ist, frame_size);
1016
                            break;
1017
                        }
1018
                    } else {
1019
                        /* no reencoding needed : output the packet directly */
1020
                        /* force the input stream PTS */
1021
                        os->format->write_packet(os, ost->index, data_buf, data_size, pkt.pts);
1022
                    }
1023
                }
1024
            }
1025
        }
1026
        av_free_packet(&pkt);
1027
        
1028
        /* dump report by using the first video and audio streams */
1029
        {
1030
            char buf[1024];
1031
            AVFormatContext *oc;
1032
            INT64 total_size, ti;
1033
            AVCodecContext *enc;
1034
            int frame_number, vid;
1035
            double bitrate, ti1;
1036
            static INT64 last_time;
1037

    
1038
            if ((min_pts - last_time) >= 500000) {
1039
                last_time = min_pts;
1040
                
1041
                oc = output_files[0];
1042
                
1043
                total_size = url_ftell(&oc->pb);
1044
                
1045
                buf[0] = '\0';
1046
                ti = MAXINT64;
1047
                vid = 0;
1048
                for(i=0;i<nb_ostreams;i++) {
1049
                    ost = ost_table[i];
1050
                    enc = &ost->st->codec;
1051
                    ist = ist_table[ost->source_index];
1052
                    if (!vid && enc->codec_type == CODEC_TYPE_VIDEO) {
1053
                        frame_number = ist->frame_number;
1054
                        sprintf(buf + strlen(buf), "frame=%5d q=%2d ",
1055
                                frame_number, enc->quality);
1056
                        if (do_psnr)
1057
                            sprintf(buf + strlen(buf), "PSNR=%6.2f ", enc->psnr_y);
1058
                        vid = 1;
1059
                    }
1060
                    /* compute min pts value */
1061
                    if (!ist->discard && ist->pts < ti) {
1062
                        ti = ist->pts;
1063
                    }
1064
                }
1065

    
1066
                ti1 = (double)ti / 1000000.0;
1067
                if (ti1 < 0.01)
1068
                    ti1 = 0.01;
1069
                bitrate = (double)(total_size * 8) / ti1 / 1000.0;
1070

    
1071
                sprintf(buf + strlen(buf), 
1072
                        "size=%8.0fkB time=%0.1f bitrate=%6.1fkbits/s",
1073
                        (double)total_size / 1024, ti1, bitrate);
1074
                
1075
                fprintf(stderr, "%s   \r", buf);
1076
                fflush(stderr);
1077
            }
1078
        }
1079
    }
1080
    term_exit();
1081

    
1082
    /* dump report by using the first video and audio streams */
1083
    {
1084
        char buf[1024];
1085
        AVFormatContext *oc;
1086
        INT64 total_size, ti;
1087
        AVCodecContext *enc;
1088
        int frame_number, vid;
1089
        double bitrate, ti1;
1090

    
1091
        oc = output_files[0];
1092
        
1093
        total_size = url_ftell(&oc->pb);
1094
        
1095
        buf[0] = '\0';
1096
        ti = MAXINT64;
1097
        vid = 0;
1098
        for(i=0;i<nb_ostreams;i++) {
1099
            ost = ost_table[i];
1100
            enc = &ost->st->codec;
1101
            ist = ist_table[ost->source_index];
1102
            if (!vid && enc->codec_type == CODEC_TYPE_VIDEO) {
1103
                frame_number = ist->frame_number;
1104
                sprintf(buf + strlen(buf), "frame=%5d q=%2d ",
1105
                        frame_number, enc->quality);
1106
                if (do_psnr)
1107
                    sprintf(buf + strlen(buf), "PSNR=%6.2f ", enc->psnr_y);
1108
                vid = 1;
1109
            }
1110
            /* compute min pts value */
1111
            if (!ist->discard && ist->pts < ti) {
1112
                ti = ist->pts;
1113
            }
1114
        }
1115
        
1116
        ti1 = ti / 1000000.0;
1117
        if (ti1 < 0.01)
1118
            ti1 = 0.01;
1119
        bitrate = (double)(total_size * 8) / ti1 / 1000.0;
1120
        
1121
        sprintf(buf + strlen(buf), 
1122
                "size=%8.0fkB time=%0.1f bitrate=%6.1fkbits/s",
1123
                (double)total_size / 1024, ti1, bitrate);
1124
        
1125
        fprintf(stderr, "%s   \n", buf);
1126
    }
1127
    /* close each encoder */
1128
    for(i=0;i<nb_ostreams;i++) {
1129
        ost = ost_table[i];
1130
        if (ost->encoding_needed) {
1131
            avcodec_close(&ost->st->codec);
1132
        }
1133
    }
1134
    
1135
    /* close each decoder */
1136
    for(i=0;i<nb_istreams;i++) {
1137
        ist = ist_table[i];
1138
        if (ist->decoding_needed) {
1139
            avcodec_close(&ist->st->codec);
1140
        }
1141
    }
1142
    
1143

    
1144
    /* write the trailer if needed and close file */
1145
    for(i=0;i<nb_output_files;i++) {
1146
        os = output_files[i];
1147
        os->format->write_trailer(os);
1148
    }
1149
    /* finished ! */
1150
    
1151
    ret = 0;
1152
 fail1:
1153
    free(file_table);
1154

    
1155
    if (ist_table) {
1156
        for(i=0;i<nb_istreams;i++) {
1157
            ist = ist_table[i];
1158
            if (ist) {
1159
                free(ist);
1160
            }
1161
        }
1162
        free(ist_table);
1163
    }
1164
    if (ost_table) {
1165
        for(i=0;i<nb_ostreams;i++) {
1166
            ost = ost_table[i];
1167
            if (ost) {
1168
                if (ost->pict_tmp.data[0])
1169
                    free(ost->pict_tmp.data[0]);
1170
                if (ost->video_resample)
1171
                    img_resample_close(ost->img_resample_ctx);
1172
                if (ost->audio_resample)
1173
                    audio_resample_close(ost->resample);
1174
                free(ost);
1175
            }
1176
        }
1177
        free(ost_table);
1178
    }
1179
    return ret;
1180
 fail:
1181
    ret = -ENOMEM;
1182
    goto fail1;
1183
}
1184

    
1185
#if 0
1186
int file_read(const char *filename)
1187
{
1188
    URLContext *h;
1189
    unsigned char buffer[1024];
1190
    int len, i;
1191

1192
    if (url_open(&h, filename, O_RDONLY) < 0) {
1193
        printf("could not open '%s'\n", filename);
1194
        return -1;
1195
    }
1196
    for(;;) {
1197
        len = url_read(h, buffer, sizeof(buffer));
1198
        if (len <= 0)
1199
            break;
1200
        for(i=0;i<len;i++) putchar(buffer[i]);
1201
    }
1202
    url_close(h);
1203
    return 0;
1204
}
1205
#endif
1206

    
1207
void show_licence(void)
1208
{
1209
    printf(
1210
    "ffmpeg version " FFMPEG_VERSION "\n"
1211
    "Copyright (c) 2000,2001 Gerard Lantau\n"
1212
    "This program is free software; you can redistribute it and/or modify\n"
1213
    "it under the terms of the GNU General Public License as published by\n"
1214
    "the Free Software Foundation; either version 2 of the License, or\n"
1215
    "(at your option) any later version.\n"
1216
    "\n"
1217
    "This program is distributed in the hope that it will be useful,\n"
1218
    "but WITHOUT ANY WARRANTY; without even the implied warranty of\n"
1219
    "MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n"
1220
    "GNU General Public License for more details.\n"
1221
    "\n"
1222
    "You should have received a copy of the GNU General Public License\n"
1223
    "along with this program; if not, write to the Free Software\n"
1224
    "Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.\n"
1225
    );
1226
    exit(1);
1227
}
1228

    
1229
void opt_format(const char *arg)
1230
{
1231
    AVFormat *f;
1232
    f = first_format;
1233
    while (f != NULL && strcmp(f->name, arg) != 0) f = f->next;
1234
    if (f == NULL) {
1235
        fprintf(stderr, "Invalid format: %s\n", arg);
1236
        exit(1);
1237
    }
1238
    file_format = f;
1239
}
1240

    
1241
void opt_video_bitrate(const char *arg)
1242
{
1243
    video_bit_rate = atoi(arg) * 1000;
1244
}
1245

    
1246
void opt_video_bitrate_tolerance(const char *arg)
1247
{
1248
    video_bit_rate_tolerance = atoi(arg) * 1000;
1249
}
1250

    
1251
void opt_frame_rate(const char *arg)
1252
{
1253
    frame_rate = (int)(strtod(arg, 0) * FRAME_RATE_BASE);
1254
}
1255

    
1256
void opt_frame_size(const char *arg)
1257
{
1258
    parse_image_size(&frame_width, &frame_height, arg);
1259
    if (frame_width <= 0 || frame_height <= 0) {
1260
        fprintf(stderr, "Incorrect frame size\n");
1261
        exit(1);
1262
    }
1263
    if ((frame_width % 2) != 0 || (frame_height % 2) != 0) {
1264
        fprintf(stderr, "Frame size must be a multiple of 2\n");
1265
        exit(1);
1266
    }
1267
}
1268

    
1269
void opt_gop_size(const char *arg)
1270
{
1271
    gop_size = atoi(arg);
1272
}
1273

    
1274
void opt_b_frames(const char *arg)
1275
{
1276
    b_frames = atoi(arg);
1277
    if (b_frames > FF_MAX_B_FRAMES) {
1278
        fprintf(stderr, "\nCannot have more than %d B frames, increase FF_MAX_B_FRAMES.\n", FF_MAX_B_FRAMES);
1279
        exit(1);
1280
    } else if (b_frames < 1) {
1281
        fprintf(stderr, "\nNumber of B frames must be higher than 0\n");
1282
        exit(1);
1283
    }
1284
}
1285

    
1286
void opt_qscale(const char *arg)
1287
{
1288
    video_qscale = atoi(arg);
1289
    if (video_qscale < 0 ||
1290
        video_qscale > 31) {
1291
        fprintf(stderr, "qscale must be >= 1 and <= 31\n");
1292
        exit(1);
1293
    }
1294
}
1295

    
1296
void opt_qmin(const char *arg)
1297
{
1298
    video_qmin = atoi(arg);
1299
    if (video_qmin < 0 ||
1300
        video_qmin > 31) {
1301
        fprintf(stderr, "qmin must be >= 1 and <= 31\n");
1302
        exit(1);
1303
    }
1304
}
1305

    
1306
void opt_qmax(const char *arg)
1307
{
1308
    video_qmax = atoi(arg);
1309
    if (video_qmax < 0 ||
1310
        video_qmax > 31) {
1311
        fprintf(stderr, "qmax must be >= 1 and <= 31\n");
1312
        exit(1);
1313
    }
1314
}
1315

    
1316
void opt_qdiff(const char *arg)
1317
{
1318
    video_qdiff = atoi(arg);
1319
    if (video_qdiff < 0 ||
1320
        video_qdiff > 31) {
1321
        fprintf(stderr, "qdiff must be >= 1 and <= 31\n");
1322
        exit(1);
1323
    }
1324
}
1325

    
1326
void opt_qblur(const char *arg)
1327
{
1328
    video_qblur = atof(arg);
1329
}
1330

    
1331
void opt_qcomp(const char *arg)
1332
{
1333
    video_qcomp = atof(arg);
1334
}
1335

    
1336
void opt_audio_bitrate(const char *arg)
1337
{
1338
    audio_bit_rate = atoi(arg) * 1000;
1339
}
1340

    
1341
void opt_audio_rate(const char *arg)
1342
{
1343
    audio_sample_rate = atoi(arg);
1344
}
1345

    
1346
void opt_audio_channels(const char *arg)
1347
{
1348
    audio_channels = atoi(arg);
1349
}
1350

    
1351
#ifdef CONFIG_GRAB
1352
void opt_video_device(const char *arg)
1353
{
1354
    v4l_device = strdup(arg);
1355
}
1356

    
1357
void opt_audio_device(const char *arg)
1358
{
1359
    audio_device = strdup(arg);
1360
}
1361
#endif
1362

    
1363
void opt_audio_codec(const char *arg)
1364
{
1365
    AVCodec *p;
1366

    
1367
    p = first_avcodec;
1368
    while (p) {
1369
        if (!strcmp(p->name, arg) && p->type == CODEC_TYPE_AUDIO)
1370
            break;
1371
        p = p->next;
1372
    }
1373
    if (p == NULL) {
1374
        fprintf(stderr, "Unknown audio codec '%s'\n", arg);
1375
        exit(1);
1376
    } else {
1377
        audio_codec_id = p->id;
1378
    }
1379
}
1380

    
1381
const char *motion_str[] = {
1382
    "zero",
1383
    "full",
1384
    "log",
1385
    "phods",
1386
    "epzs",
1387
    "x1",
1388
    NULL,
1389
};
1390

    
1391
void opt_motion_estimation(const char *arg)
1392
{
1393
    const char **p;
1394
    p = motion_str;
1395
    for(;;) {
1396
        if (!*p) {
1397
            fprintf(stderr, "Unknown motion estimation method '%s'\n", arg);
1398
            exit(1);
1399
        }
1400
        if (!strcmp(*p, arg))
1401
            break;
1402
        p++;
1403
    }
1404
    me_method = (p - motion_str) + 1;
1405
}
1406

    
1407
void opt_video_codec(const char *arg)
1408
{
1409
    AVCodec *p;
1410

    
1411
    p = first_avcodec;
1412
    while (p) {
1413
        if (!strcmp(p->name, arg) && p->type == CODEC_TYPE_VIDEO)
1414
            break;
1415
        p = p->next;
1416
    }
1417
    if (p == NULL) {
1418
        fprintf(stderr, "Unknown video codec '%s'\n", arg);
1419
        exit(1);
1420
    } else {
1421
        video_codec_id = p->id;
1422
    }
1423
}
1424

    
1425
void opt_map(const char *arg)
1426
{
1427
    AVStreamMap *m;
1428
    const char *p;
1429

    
1430
    p = arg;
1431
    m = &stream_maps[nb_stream_maps++];
1432

    
1433
    m->file_index = strtol(arg, (char **)&p, 0);
1434
    if (*p)
1435
        p++;
1436
    m->stream_index = strtol(arg, (char **)&p, 0);
1437
}
1438

    
1439
void opt_recording_time(const char *arg)
1440
{
1441
    recording_time = parse_date(arg, 1);
1442
}
1443

    
1444
/* return the number of packet read to find the codec parameters */
1445
int find_codec_parameters(AVFormatContext *ic)
1446
{
1447
    int val, i, count, ret, got_picture, size;
1448
    AVCodec *codec;
1449
    AVCodecContext *enc;
1450
    AVStream *st;
1451
    AVPacket *pkt;
1452
    AVPicture picture;
1453
    AVPacketList *pktl, **ppktl;
1454
    short samples[AVCODEC_MAX_AUDIO_FRAME_SIZE / 2];
1455
    UINT8 *ptr;
1456

    
1457
    count = 0;
1458
    ppktl = &ic->packet_buffer;
1459
    for(;;) {
1460
        for(i=0;i<ic->nb_streams;i++) {
1461
            enc = &ic->streams[i]->codec;
1462
            
1463
            switch(enc->codec_type) {
1464
            case CODEC_TYPE_AUDIO:
1465
                val = enc->sample_rate;
1466
                break;
1467
            case CODEC_TYPE_VIDEO:
1468
                val = enc->width;
1469
                break;
1470
            default:
1471
                val = 1;
1472
                break;
1473
            }
1474
            /* if no parameters supplied, then we should read it from
1475
               the stream */
1476
            if (val == 0)
1477
                break;
1478
        }
1479
        if (i == ic->nb_streams) {
1480
            ret = count;
1481
            break;
1482
        }
1483

    
1484
        if (count == 0) {
1485
            /* open each codec */
1486
            for(i=0;i<ic->nb_streams;i++) {
1487
                st = ic->streams[i];
1488
                codec = avcodec_find_decoder(st->codec.codec_id);
1489
                if (codec == NULL) {
1490
                    ret = -1;
1491
                    goto the_end;
1492
                }
1493
                avcodec_open(&st->codec, codec);
1494
            }
1495
        }
1496
        pktl = av_mallocz(sizeof(AVPacketList));
1497
        if (!pktl) {
1498
            ret = -1;
1499
            break;
1500
        }
1501

    
1502
        /* add the packet in the buffered packet list */
1503
        *ppktl = pktl;
1504
        ppktl = &pktl->next;
1505

    
1506
        pkt = &pktl->pkt;
1507
        if (ic->format->read_packet(ic, pkt) < 0) {
1508
            ret = -1;
1509
            break;
1510
        }
1511
        st = ic->streams[pkt->stream_index];
1512

    
1513
        /* decode the data and update codec parameters */
1514
        ptr = pkt->data;
1515
        size = pkt->size;
1516
        while (size > 0) {
1517
            switch(st->codec.codec_type) {
1518
            case CODEC_TYPE_VIDEO:
1519
                ret = avcodec_decode_video(&st->codec, &picture, &got_picture, ptr, size);
1520
                break;
1521
            case CODEC_TYPE_AUDIO:
1522
                ret = avcodec_decode_audio(&st->codec, samples, &got_picture, ptr, size);
1523
                break;
1524
            default:
1525
                ret = -1;
1526
                break;
1527
            }
1528
            if (ret < 0) {
1529
                ret = -1;
1530
                goto the_end;
1531
            }
1532
            if (got_picture)
1533
                break;
1534
            ptr += ret;
1535
            size -= ret;
1536
        }
1537

    
1538
        count++;
1539
    }
1540
 the_end:
1541
    if (count > 0) {
1542
        /* close each codec */
1543
        for(i=0;i<ic->nb_streams;i++) {
1544
            st = ic->streams[i];
1545
            avcodec_close(&st->codec);
1546
        }
1547
    }
1548
    return ret;
1549
}
1550

    
1551
int filename_number_test(const char *filename)
1552
{
1553
    char buf[1024];
1554

    
1555
    if (get_frame_filename(buf, sizeof(buf), filename, 1) < 0) {
1556
        fprintf(stderr, "%s: Incorrect image filename syntax.\n"
1557
                "Use '%%d' to specify the image number:\n"
1558
                "  for img1.jpg, img2.jpg, ..., use 'img%%d.jpg';\n"
1559
                "  for img001.jpg, img002.jpg, ..., use 'img%%03d.jpg'.\n", 
1560
                filename);
1561
        return -1;
1562
    } else {
1563
        return 0;
1564
    }
1565
}
1566

    
1567
void opt_input_file(const char *filename)
1568
{
1569
    AVFormatContext *ic;
1570
    AVFormatParameters params, *ap = &params;
1571
    URLFormat url_format;
1572
    AVFormat *fmt;
1573
    int err, i, ret;
1574

    
1575
    ic = av_mallocz(sizeof(AVFormatContext));
1576
    strcpy(ic->filename, filename);
1577
    /* first format guess to know if we must open file */
1578
    fmt = file_format;
1579
    if (!fmt) 
1580
        fmt = guess_format(NULL, filename, NULL);
1581
    
1582
    if (fmt == NULL || !(fmt->flags & AVFMT_NOFILE)) {
1583
        /* open file */
1584
        if (url_fopen(&ic->pb, filename, URL_RDONLY) < 0) {
1585
            fprintf(stderr, "Could not open '%s'\n", filename);
1586
            exit(1);
1587
        }
1588
    
1589
        /* find format and set default parameters */
1590
        fmt = file_format;
1591
        err = url_getformat(url_fileno(&ic->pb), &url_format);
1592
        if (err >= 0) {
1593
            if (!fmt)
1594
                fmt = guess_format(url_format.format_name, NULL, NULL);
1595
            ap->sample_rate = url_format.sample_rate;
1596
            ap->frame_rate = url_format.frame_rate;
1597
            ap->channels = url_format.channels;
1598
            ap->width = url_format.width;
1599
            ap->height = url_format.height;
1600
            ap->pix_fmt = url_format.pix_fmt;
1601
        } else {
1602
            if (!fmt)
1603
                fmt = guess_format(NULL, filename, NULL);
1604
            memset(ap, 0, sizeof(*ap));
1605
        }
1606
    } else {
1607
        memset(ap, 0, sizeof(*ap));
1608
    }
1609

    
1610
    if (!fmt || !fmt->read_header) {
1611
        fprintf(stderr, "%s: Unknown file format\n", filename);
1612
        exit(1);
1613
    }
1614
    ic->format = fmt;
1615

    
1616
    /* get default parameters from command line */
1617
    if (!ap->sample_rate)
1618
        ap->sample_rate = audio_sample_rate;
1619
    if (!ap->channels)
1620
        ap->channels = audio_channels;
1621

    
1622
    if (!ap->frame_rate)
1623
        ap->frame_rate = frame_rate;
1624
    if (!ap->width)
1625
        ap->width = frame_width;
1626
    if (!ap->height)
1627
        ap->height = frame_height;
1628

    
1629
    /* check filename in case of an image number is expected */
1630
    if (ic->format->flags & AVFMT_NEEDNUMBER) {
1631
        if (filename_number_test(ic->filename) < 0)
1632
            exit(1);
1633
    }
1634
    
1635
    err = ic->format->read_header(ic, ap);
1636
    if (err < 0) {
1637
        fprintf(stderr, "%s: Error while parsing header\n", filename);
1638
        exit(1);
1639
    }
1640
    
1641
    /* If not enough info for the codecs, we decode the first frames
1642
       to get it. (used in mpeg case for example) */
1643
    ret = find_codec_parameters(ic);
1644
    if (ret < 0) {
1645
        fprintf(stderr, "%s: could not find codec parameters\n", filename);
1646
        exit(1);
1647
    }
1648

    
1649
    /* update the current parameters so that they match the one of the input stream */
1650
    for(i=0;i<ic->nb_streams;i++) {
1651
        AVCodecContext *enc = &ic->streams[i]->codec;
1652
        switch(enc->codec_type) {
1653
        case CODEC_TYPE_AUDIO:
1654
            //fprintf(stderr, "\nInput Audio channels: %d", enc->channels);
1655
            audio_channels = enc->channels;
1656
            audio_sample_rate = enc->sample_rate;
1657
            break;
1658
        case CODEC_TYPE_VIDEO:
1659
            frame_height = enc->height;
1660
            frame_width = enc->width;
1661
            frame_rate = enc->frame_rate;
1662
            break;
1663
        }
1664
    }
1665
    
1666
    input_files[nb_input_files] = ic;
1667
    /* dump the file content */
1668
    dump_format(ic, nb_input_files, filename, 0);
1669
    nb_input_files++;
1670
    file_format = NULL;
1671
}
1672

    
1673
void check_audio_video_inputs(int *has_video_ptr, int *has_audio_ptr)
1674
{
1675
    int has_video, has_audio, i, j;
1676
    AVFormatContext *ic;
1677

    
1678
    has_video = 0;
1679
    has_audio = 0;
1680
    for(j=0;j<nb_input_files;j++) {
1681
        ic = input_files[j];
1682
        for(i=0;i<ic->nb_streams;i++) {
1683
            AVCodecContext *enc = &ic->streams[i]->codec;
1684
            switch(enc->codec_type) {
1685
            case CODEC_TYPE_AUDIO:
1686
                has_audio = 1;
1687
                break;
1688
            case CODEC_TYPE_VIDEO:
1689
                has_video = 1;
1690
                break;
1691
            }
1692
        }
1693
    }
1694
    *has_video_ptr = has_video;
1695
    *has_audio_ptr = has_audio;
1696
}
1697

    
1698
void opt_output_file(const char *filename)
1699
{
1700
    AVStream *st;
1701
    AVFormatContext *oc;
1702
    int use_video, use_audio, nb_streams, input_has_video, input_has_audio;
1703
    int codec_id;
1704

    
1705
    if (!strcmp(filename, "-"))
1706
        filename = "pipe:";
1707

    
1708
    oc = av_mallocz(sizeof(AVFormatContext));
1709

    
1710
    if (!file_format) {
1711
        file_format = guess_format(NULL, filename, NULL);
1712
        if (!file_format)
1713
            file_format = &mpeg_mux_format;
1714
    }
1715
    
1716
    oc->format = file_format;
1717

    
1718
    if (!strcmp(file_format->name, "ffm") && 
1719
        strstart(filename, "http:", NULL)) {
1720
        /* special case for files sent to ffserver: we get the stream
1721
           parameters from ffserver */
1722
        if (read_ffserver_streams(oc, filename) < 0) {
1723
            fprintf(stderr, "Could not read stream parameters from '%s'\n", filename);
1724
            exit(1);
1725
        }
1726
    } else {
1727
        use_video = file_format->video_codec != CODEC_ID_NONE;
1728
        use_audio = file_format->audio_codec != CODEC_ID_NONE;
1729

    
1730
        /* disable if no corresponding type found and at least one
1731
           input file */
1732
        if (nb_input_files > 0) {
1733
            check_audio_video_inputs(&input_has_video, &input_has_audio);
1734
            if (!input_has_video)
1735
                use_video = 0;
1736
            if (!input_has_audio)
1737
                use_audio = 0;
1738
        }
1739

    
1740
        /* manual disable */
1741
        if (audio_disable) {
1742
            use_audio = 0;
1743
        }
1744
        if (video_disable) {
1745
            use_video = 0;
1746
        }
1747
        
1748
        nb_streams = 0;
1749
        if (use_video) {
1750
            AVCodecContext *video_enc;
1751
            
1752
            st = av_mallocz(sizeof(AVStream));
1753
            if (!st) {
1754
                fprintf(stderr, "Could not alloc stream\n");
1755
                exit(1);
1756
            }
1757
            video_enc = &st->codec;
1758

    
1759
            codec_id = file_format->video_codec;
1760
            if (video_codec_id != CODEC_ID_NONE)
1761
                codec_id = video_codec_id;
1762

    
1763
            video_enc->codec_id = codec_id;
1764
            video_enc->codec_type = CODEC_TYPE_VIDEO;
1765
            
1766
            video_enc->bit_rate = video_bit_rate;
1767
            video_enc->bit_rate_tolerance = video_bit_rate_tolerance;
1768
            video_enc->frame_rate = frame_rate; 
1769
            
1770
            video_enc->width = frame_width;
1771
            video_enc->height = frame_height;
1772
            if (!intra_only)
1773
                video_enc->gop_size = gop_size;
1774
            else
1775
                video_enc->gop_size = 0;
1776
            if (video_qscale || same_quality) {
1777
                video_enc->flags |= CODEC_FLAG_QSCALE;
1778
                video_enc->quality = video_qscale;
1779
            }
1780
            
1781
            if (use_hq) {
1782
                video_enc->flags |= CODEC_FLAG_HQ;
1783
            }
1784
            
1785
            if (use_4mv) {
1786
                video_enc->flags |= CODEC_FLAG_HQ;
1787
                video_enc->flags |= CODEC_FLAG_4MV;
1788
            }
1789
            
1790
            if (b_frames) {
1791
                if (codec_id != CODEC_ID_MPEG4) {
1792
                    fprintf(stderr, "\nB frames encoding only supported by MPEG-4.\n");
1793
                    exit(1);
1794
                }
1795
                video_enc->max_b_frames = b_frames;
1796
                video_enc->b_frame_strategy = 0;
1797
                video_enc->b_quant_factor = 2.0;
1798
            }
1799
            
1800
            video_enc->qmin = video_qmin;
1801
            video_enc->qmax = video_qmax;
1802
            video_enc->max_qdiff = video_qdiff;
1803
            video_enc->qblur = video_qblur;
1804
            video_enc->qcompress = video_qcomp;
1805
            
1806
            if (do_psnr)
1807
                video_enc->get_psnr = 1;
1808
            else
1809
                video_enc->get_psnr = 0;
1810
            
1811
            video_enc->me_method = me_method;
1812
            
1813
            /* XXX: need to find a way to set codec parameters */
1814
            if (oc->format == &ppm_format ||
1815
                oc->format == &ppmpipe_format) {
1816
                video_enc->pix_fmt = PIX_FMT_RGB24;
1817
            }
1818

    
1819
            oc->streams[nb_streams] = st;
1820
            nb_streams++;
1821
        }
1822
    
1823
        if (use_audio) {
1824
            AVCodecContext *audio_enc;
1825

    
1826
            st = av_mallocz(sizeof(AVStream));
1827
            if (!st) {
1828
                fprintf(stderr, "Could not alloc stream\n");
1829
                exit(1);
1830
            }
1831
            audio_enc = &st->codec;
1832
            codec_id = file_format->audio_codec;
1833
            if (audio_codec_id != CODEC_ID_NONE)
1834
                codec_id = audio_codec_id;
1835
            audio_enc->codec_id = codec_id;
1836
            audio_enc->codec_type = CODEC_TYPE_AUDIO;
1837
            
1838
            audio_enc->bit_rate = audio_bit_rate;
1839
            audio_enc->sample_rate = audio_sample_rate;
1840
            /* For audio codecs other than AC3 we limit */
1841
            /* the number of coded channels to stereo   */
1842
            if (audio_channels > 2 && codec_id != CODEC_ID_AC3) {
1843
                audio_enc->channels = 2;
1844
            } else
1845
                audio_enc->channels = audio_channels;
1846
            oc->streams[nb_streams] = st;
1847
            nb_streams++;
1848
        }
1849

    
1850
        oc->nb_streams = nb_streams;
1851

    
1852
        if (!nb_streams) {
1853
            fprintf(stderr, "No audio or video streams available\n");
1854
            exit(1);
1855
        }
1856

    
1857
        if (str_title)
1858
            nstrcpy(oc->title, sizeof(oc->title), str_title);
1859
        if (str_author)
1860
            nstrcpy(oc->author, sizeof(oc->author), str_author);
1861
        if (str_copyright)
1862
            nstrcpy(oc->copyright, sizeof(oc->copyright), str_copyright);
1863
        if (str_comment)
1864
            nstrcpy(oc->comment, sizeof(oc->comment), str_comment);
1865
    }
1866

    
1867
    output_files[nb_output_files] = oc;
1868
    /* dump the file content */
1869
    dump_format(oc, nb_output_files, filename, 1);
1870
    nb_output_files++;
1871

    
1872
    strcpy(oc->filename, filename);
1873

    
1874
    /* check filename in case of an image number is expected */
1875
    if (oc->format->flags & AVFMT_NEEDNUMBER) {
1876
        if (filename_number_test(oc->filename) < 0)
1877
            exit(1);
1878
    }
1879

    
1880
    if (!(oc->format->flags & AVFMT_NOFILE)) {
1881
        /* test if it already exists to avoid loosing precious files */
1882
        if (!file_overwrite && 
1883
            (strchr(filename, ':') == NULL ||
1884
             strstart(filename, "file:", NULL))) {
1885
            if (url_exist(filename)) {
1886
                int c;
1887
                
1888
                printf("File '%s' already exists. Overwrite ? [y/N] ", filename);
1889
                fflush(stdout);
1890
                c = getchar();
1891
                if (toupper(c) != 'Y') {
1892
                    fprintf(stderr, "Not overwriting - exiting\n");
1893
                    exit(1);
1894
                }
1895
            }
1896
        }
1897
        
1898
        /* open the file */
1899
        if (url_fopen(&oc->pb, filename, URL_WRONLY) < 0) {
1900
            fprintf(stderr, "Could not open '%s'\n", filename);
1901
            exit(1);
1902
        }
1903
    }
1904

    
1905
    /* reset some options */
1906
    file_format = NULL;
1907
    audio_disable = 0;
1908
    video_disable = 0;
1909
    audio_codec_id = CODEC_ID_NONE;
1910
    video_codec_id = CODEC_ID_NONE;
1911
}
1912

    
1913
#ifdef CONFIG_GRAB
1914

    
1915
/* prepare dummy protocols for grab */
1916
void prepare_grab(void)
1917
{
1918
    int has_video, has_audio, i, j;
1919
    AVFormatContext *oc;
1920
    AVFormatContext *ic;
1921
    AVFormatParameters ap1, *ap = &ap1;
1922

    
1923
    /* see if audio/video inputs are needed */
1924
    has_video = 0;
1925
    has_audio = 0;
1926
    memset(ap, 0, sizeof(*ap));
1927
    for(j=0;j<nb_output_files;j++) {
1928
        oc = output_files[j];
1929
        for(i=0;i<oc->nb_streams;i++) {
1930
            AVCodecContext *enc = &oc->streams[i]->codec;
1931
            switch(enc->codec_type) {
1932
            case CODEC_TYPE_AUDIO:
1933
                if (enc->sample_rate > ap->sample_rate)
1934
                    ap->sample_rate = enc->sample_rate;
1935
                if (enc->channels > ap->channels)
1936
                    ap->channels = enc->channels;
1937
                has_audio = 1;
1938
                break;
1939
            case CODEC_TYPE_VIDEO:
1940
                if (enc->width > ap->width)
1941
                    ap->width = enc->width;
1942
                if (enc->height > ap->height)
1943
                    ap->height = enc->height;
1944
                if (enc->frame_rate > ap->frame_rate)
1945
                    ap->frame_rate = enc->frame_rate;
1946
                has_video = 1;
1947
                break;
1948
            }
1949
        }
1950
    }
1951
    
1952
    if (has_video == 0 && has_audio == 0) {
1953
        fprintf(stderr, "Output file must have at least one audio or video stream\n");
1954
        exit(1);
1955
    }
1956
    
1957
    if (has_video) {
1958
        ic = av_open_input_file("", "video_grab_device", 0, ap);
1959
        if (!ic) {
1960
            fprintf(stderr, "Could not open video grab device\n");
1961
            exit(1);
1962
        }
1963
        input_files[nb_input_files] = ic;
1964
        dump_format(ic, nb_input_files, v4l_device, 0);
1965
        nb_input_files++;
1966
    }
1967
    if (has_audio) {
1968
        ic = av_open_input_file("", "audio_device", 0, ap);
1969
        if (!ic) {
1970
            fprintf(stderr, "Could not open audio grab device\n");
1971
            exit(1);
1972
        }
1973
        input_files[nb_input_files] = ic;
1974
        dump_format(ic, nb_input_files, audio_device, 0);
1975
        nb_input_files++;
1976
    }
1977
}
1978

    
1979
#else
1980

    
1981
void prepare_grab(void)
1982
{
1983
    fprintf(stderr, "Must supply at least one input file\n");
1984
    exit(1);
1985
}
1986

    
1987
#endif
1988

    
1989
/* open the necessary output devices for playing */
1990
void prepare_play(void)
1991
{
1992
#ifndef __BEOS__
1993
    file_format = guess_format("audio_device", NULL, NULL);
1994
    if (!file_format) {
1995
        fprintf(stderr, "Could not find audio device\n");
1996
        exit(1);
1997
    }
1998
    
1999
    opt_output_file(audio_device);
2000
#endif
2001
}
2002

    
2003

    
2004
#ifndef CONFIG_WIN32
2005
INT64 getutime(void)
2006
{
2007
    struct rusage rusage;
2008

    
2009
    getrusage(RUSAGE_SELF, &rusage);
2010
    return (rusage.ru_utime.tv_sec * 1000000LL) + rusage.ru_utime.tv_usec;
2011
}
2012
#else
2013
INT64 getutime(void)
2014
{
2015
  return gettime();
2016
}
2017
#endif
2018

    
2019
void show_formats(void)
2020
{
2021
    AVFormat *f;
2022
    URLProtocol *up;
2023
    AVCodec *p;
2024
    const char **pp;
2025

    
2026
    printf("File formats:\n");
2027
    printf("  Encoding:");
2028
    for(f = first_format; f != NULL; f = f->next) {
2029
        if (f->write_header)
2030
            printf(" %s", f->name);
2031
    }
2032
    printf("\n");
2033
    printf("  Decoding:");
2034
    for(f = first_format; f != NULL; f = f->next) {
2035
        if (f->read_header)
2036
            printf(" %s", f->name);
2037
    }
2038
    printf("\n");
2039

    
2040
    printf("Codecs:\n");
2041
    printf("  Encoders:");
2042
    for(p = first_avcodec; p != NULL; p = p->next) {
2043
        if (p->encode)
2044
            printf(" %s", p->name);
2045
    }
2046
    printf("\n");
2047

    
2048
    printf("  Decoders:");
2049
    for(p = first_avcodec; p != NULL; p = p->next) {
2050
        if (p->decode)
2051
            printf(" %s", p->name);
2052
    }
2053
    printf("\n");
2054

    
2055
    printf("Supported file protocols:");
2056
    for(up = first_protocol; up != NULL; up = up->next)
2057
        printf(" %s:", up->name);
2058
    printf("\n");
2059
    
2060
    printf("Frame size abbreviations: sqcif qcif cif 4cif\n");
2061
    printf("Motion estimation methods:");
2062
    pp = motion_str;
2063
    while (*pp) {
2064
        printf(" %s", *pp);
2065
        if ((pp - motion_str + 1) == ME_ZERO) 
2066
            printf("(fastest)");
2067
        else if ((pp - motion_str + 1) == ME_FULL) 
2068
            printf("(slowest)");
2069
        else if ((pp - motion_str + 1) == ME_EPZS) 
2070
            printf("(default)");
2071
        pp++;
2072
    }
2073
    printf("\n");
2074
    exit(1);
2075
}
2076

    
2077
void show_help(void)
2078
{
2079
    const char *prog;
2080
    const OptionDef *po;
2081
    int i, expert;
2082
    
2083
    prog = do_play ? "ffplay" : "ffmpeg";
2084

    
2085
    printf("%s version " FFMPEG_VERSION ", Copyright (c) 2000, 2001 Gerard Lantau\n", 
2086
           prog);
2087
    
2088
    if (!do_play) {
2089
        printf("usage: ffmpeg [[options] -i input_file]... {[options] outfile}...\n"
2090
               "Hyper fast MPEG1/MPEG4/H263/RV and AC3/MPEG audio encoder\n");
2091
    } else {
2092
        printf("usage: ffplay [options] input_file...\n"
2093
               "Simple audio player\n");
2094
    }
2095
           
2096
    printf("\n"
2097
           "Main options are:\n");
2098
    for(i=0;i<2;i++) {
2099
        if (i == 1)
2100
            printf("\nAdvanced options are:\n");
2101
        for(po = options; po->name != NULL; po++) {
2102
            char buf[64];
2103
            expert = (po->flags & OPT_EXPERT) != 0;
2104
            if (expert == i) {
2105
                strcpy(buf, po->name);
2106
                if (po->flags & HAS_ARG) {
2107
                    strcat(buf, " ");
2108
                    strcat(buf, po->argname);
2109
                }
2110
                printf("-%-17s  %s\n", buf, po->help);
2111
            }
2112
        }
2113
    }
2114

    
2115
    exit(1);
2116
}
2117

    
2118
const OptionDef options[] = {
2119
    { "L", 0, {(void*)show_licence}, "show license" },
2120
    { "h", 0, {(void*)show_help}, "show help" },
2121
    { "formats", 0, {(void*)show_formats}, "show available formats, codecs, protocols, ..." },
2122
    { "f", HAS_ARG, {(void*)opt_format}, "force format", "fmt" },
2123
    { "i", HAS_ARG, {(void*)opt_input_file}, "input file name", "filename" },
2124
    { "y", OPT_BOOL, {(void*)&file_overwrite}, "overwrite output files" },
2125
    { "map", HAS_ARG | OPT_EXPERT, {(void*)opt_map}, "set input stream mapping", "file:stream" },
2126
    { "t", HAS_ARG, {(void*)opt_recording_time}, "set the recording time", "duration" },
2127
    { "title", HAS_ARG | OPT_STRING, {(void*)&str_title}, "set the title", "string" },
2128
    { "author", HAS_ARG | OPT_STRING, {(void*)&str_author}, "set the author", "string" },
2129
    { "copyright", HAS_ARG | OPT_STRING, {(void*)&str_copyright}, "set the copyright", "string" },
2130
    { "comment", HAS_ARG | OPT_STRING, {(void*)&str_comment}, "set the comment", "string" },
2131
    /* video options */
2132
    { "b", HAS_ARG, {(void*)opt_video_bitrate}, "set video bitrate (in kbit/s)", "bitrate" },
2133
    { "r", HAS_ARG, {(void*)opt_frame_rate}, "set frame rate (in Hz)", "rate" },
2134
    { "s", HAS_ARG, {(void*)opt_frame_size}, "set frame size (WxH or abbreviation)", "size" },
2135
    { "g", HAS_ARG | OPT_EXPERT, {(void*)opt_gop_size}, "set the group of picture size", "gop_size" },
2136
    { "intra", OPT_BOOL | OPT_EXPERT, {(void*)&intra_only}, "use only intra frames"},
2137
    { "vn", OPT_BOOL, {(void*)&video_disable}, "disable video" },
2138
    { "qscale", HAS_ARG | OPT_EXPERT, {(void*)opt_qscale}, "use fixed video quantiser scale (VBR)", "q" },
2139
    { "qmin", HAS_ARG | OPT_EXPERT, {(void*)opt_qmin}, "min video quantiser scale (VBR)", "q" },
2140
    { "qmax", HAS_ARG | OPT_EXPERT, {(void*)opt_qmax}, "max video quantiser scale (VBR)", "q" },
2141
    { "qdiff", HAS_ARG | OPT_EXPERT, {(void*)opt_qdiff}, "max difference between the quantiser scale (VBR)", "q" },
2142
    { "qblur", HAS_ARG | OPT_EXPERT, {(void*)opt_qblur}, "video quantiser scale blur (VBR)", "blur" },
2143
    { "qcomp", HAS_ARG | OPT_EXPERT, {(void*)opt_qcomp}, "video quantiser scale compression (VBR)", "compression" },
2144
    { "bt", HAS_ARG, {(void*)opt_video_bitrate_tolerance}, "set video bitrate tolerance (in kbit/s)", "tolerance" },
2145
#ifdef CONFIG_GRAB
2146
    { "vd", HAS_ARG | OPT_EXPERT, {(void*)opt_video_device}, "set video device", "device" },
2147
#endif
2148
    { "vcodec", HAS_ARG | OPT_EXPERT, {(void*)opt_video_codec}, "force video codec", "codec" },
2149
    { "me", HAS_ARG | OPT_EXPERT, {(void*)opt_motion_estimation}, "set motion estimation method", 
2150
      "method" },
2151
    { "bf", HAS_ARG | OPT_EXPERT, {(void*)opt_b_frames}, "use 'frames' B frames (only MPEG-4)", "frames" },
2152
    { "hq", OPT_BOOL | OPT_EXPERT, {(void*)&use_hq}, "activate high quality settings" },
2153
    { "4mv", OPT_BOOL | OPT_EXPERT, {(void*)&use_4mv}, "use four motion vector by macroblock (only MPEG-4)" },
2154
    { "sameq", OPT_BOOL, {(void*)&same_quality}, 
2155
      "use same video quality as source (implies VBR)" },
2156
    /* audio options */
2157
    { "ab", HAS_ARG, {(void*)opt_audio_bitrate}, "set audio bitrate (in kbit/s)", "bitrate", },
2158
    { "ar", HAS_ARG, {(void*)opt_audio_rate}, "set audio sampling rate (in Hz)", "rate" },
2159
    { "ac", HAS_ARG, {(void*)opt_audio_channels}, "set number of audio channels", "channels" },
2160
    { "an", OPT_BOOL, {(void*)&audio_disable}, "disable audio" },
2161
#ifdef CONFIG_GRAB
2162
    { "ad", HAS_ARG | OPT_EXPERT, {(void*)opt_audio_device}, "set audio device", "device" },
2163
#endif
2164
    { "acodec", HAS_ARG | OPT_EXPERT, {(void*)opt_audio_codec}, "force audio codec", "codec" },
2165
    { "deinterlace", OPT_BOOL | OPT_EXPERT, {(void*)&do_deinterlace}, 
2166
      "deinterlace pictures" },
2167
    { "benchmark", OPT_BOOL | OPT_EXPERT, {(void*)&do_benchmark}, 
2168
      "add timings for benchmarking" },
2169
    { "hex", OPT_BOOL | OPT_EXPERT, {(void*)&do_hex_dump}, 
2170
      "dump each input packet" },
2171
    { "psnr", OPT_BOOL | OPT_EXPERT, {(void*)&do_psnr}, "calculate PSNR of compressed frames" },
2172
    { "vstats", OPT_BOOL | OPT_EXPERT, {(void*)&do_vstats}, "dump video coding statistics to file" }, 
2173

    
2174
    { NULL, },
2175
};
2176

    
2177
int main(int argc, char **argv)
2178
{
2179
    int optindex, i;
2180
    const char *opt, *arg;
2181
    const OptionDef *po;
2182
    INT64 ti;
2183
    
2184
    register_all();
2185

    
2186
    /* detect if invoked as player */
2187
    i = strlen(argv[0]);
2188
    if (i >= 6 && !strcmp(argv[0] + i - 6, "ffplay"))
2189
        do_play = 1;
2190

    
2191
    if (argc <= 1)
2192
        show_help();
2193
    
2194
    /* parse options */
2195
    optindex = 1;
2196
    while (optindex < argc) {
2197
        opt = argv[optindex++];
2198
        
2199
        if (opt[0] == '-' && opt[1] != '\0') {
2200
            po = options;
2201
            while (po->name != NULL) {
2202
                if (!strcmp(opt + 1, po->name))
2203
                    break;
2204
                po++;
2205
            }
2206
            if (!po->name) {
2207
                fprintf(stderr, "%s: unrecognized option '%s'\n", argv[0], opt);
2208
                exit(1);
2209
            }
2210
            arg = NULL;
2211
            if (po->flags & HAS_ARG)
2212
                arg = argv[optindex++];
2213
            if (po->flags & OPT_STRING) {
2214
                char *str;
2215
                str = strdup(arg);
2216
                *po->u.str_arg = str;
2217
            } else if (po->flags & OPT_BOOL) {
2218
                *po->u.int_arg = 1;
2219
            } else {
2220
                po->u.func_arg(arg);
2221
            }
2222
        } else {
2223
            if (!do_play) {
2224
                opt_output_file(opt);
2225
            } else {
2226
                opt_input_file(opt);
2227
            }
2228
        }
2229
    }
2230

    
2231

    
2232
    if (!do_play) {
2233
        /* file converter / grab */
2234
        if (nb_output_files <= 0) {
2235
            fprintf(stderr, "Must supply at least one output file\n");
2236
            exit(1);
2237
        }
2238
        
2239
        if (nb_input_files == 0) {
2240
            prepare_grab();
2241
        }
2242
    } else {
2243
        /* player */
2244
        if (nb_input_files <= 0) {
2245
            fprintf(stderr, "Must supply at least one input file\n");
2246
            exit(1);
2247
        }
2248
        prepare_play();
2249
    }
2250

    
2251
    ti = getutime();
2252
    av_encode(output_files, nb_output_files, input_files, nb_input_files, 
2253
              stream_maps, nb_stream_maps);
2254
    ti = getutime() - ti;
2255
    if (do_benchmark) {
2256
        printf("bench: utime=%0.3fs\n", ti / 1000000.0);
2257
    }
2258

    
2259
    /* close files */
2260
    for(i=0;i<nb_output_files;i++) {
2261
        if (!(output_files[i]->format->flags & AVFMT_NOFILE)) 
2262
            url_fclose(&output_files[i]->pb);
2263
    }
2264
    for(i=0;i<nb_input_files;i++) {
2265
        if (!(input_files[i]->format->flags & AVFMT_NOFILE)) 
2266
            url_fclose(&input_files[i]->pb);
2267
    }
2268

    
2269
    return 0;
2270
}