Statistics
| Branch: | Revision:

ffmpeg / ffmpeg.c @ daf8e955

History | View | Annotate | Download (68.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 <sys/poll.h>
28
#include <termios.h>
29
#include <sys/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_qscale = 0;
80
static int video_disable = 0;
81
static int video_codec_id = CODEC_ID_NONE;
82
static int same_quality = 0;
83
static int do_deinterlace = 0;
84

    
85
static int gop_size = 12;
86
static int intra_only = 0;
87
static int audio_sample_rate = 44100;
88
static int audio_bit_rate = 64000;
89
static int audio_disable = 0;
90
static int audio_channels = 1;
91
static int audio_codec_id = CODEC_ID_NONE;
92

    
93
static INT64 recording_time = 0;
94
static int file_overwrite = 0;
95
static char *str_title = NULL;
96
static char *str_author = NULL;
97
static char *str_copyright = NULL;
98
static char *str_comment = NULL;
99
static int do_benchmark = 0;
100

    
101
typedef struct AVOutputStream {
102
    int file_index;          /* file index */
103
    int index;               /* stream index in the output file */
104
    int source_index;        /* AVInputStream index */
105
    AVStream *st;            /* stream in the output file */
106
    int encoding_needed;   /* true if encoding needed for this stream */
107

    
108
    int fifo_packet_rptr;    /* read index in the corresponding
109
                                avinputstream packet fifo */
110
    /* video only */
111
    AVPicture pict_tmp;         /* temporary image for resizing */
112
    int video_resample;
113
    ImgReSampleContext *img_resample_ctx; /* for image resampling */
114
    
115
    /* audio only */
116
    int audio_resample;
117
    ReSampleContext *resample; /* for audio resampling */
118
    FifoBuffer fifo;     /* for compression: one audio fifo per codec */
119
} AVOutputStream;
120

    
121
typedef struct AVInputStream {
122
    int file_index;
123
    int index;
124
    AVStream *st;
125
    int discard;             /* true if stream data should be discarded */
126
    int decoding_needed;     /* true if the packets must be decoded in 'raw_fifo' */
127
    INT64 pts;               /* current pts */
128
    int frame_number;        /* current frame */
129
    INT64 sample_index;      /* current sample */
130
} AVInputStream;
131

    
132
typedef struct AVInputFile {
133
    int eof_reached;      /* true if eof reached */
134
    int ist_index;        /* index of first stream in ist_table */
135
    int buffer_size;      /* current total buffer size */
136
    int buffer_size_max;  /* buffer size at which we consider we can stop
137
                             buffering */
138
} AVInputFile;
139

    
140
#ifndef CONFIG_WIN32
141

    
142
/* init terminal so that we can grab keys */
143
static struct termios oldtty;
144

    
145
static void term_exit(void)
146
{
147
    tcsetattr (0, TCSANOW, &oldtty);
148
}
149

    
150
static void term_init(void)
151
{
152
    struct termios tty;
153

    
154
    tcgetattr (0, &tty);
155
    oldtty = tty;
156

    
157
    tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
158
                          |INLCR|IGNCR|ICRNL|IXON);
159
    tty.c_oflag |= OPOST;
160
    tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
161
    tty.c_cflag &= ~(CSIZE|PARENB);
162
    tty.c_cflag |= CS8;
163
    tty.c_cc[VMIN] = 1;
164
    tty.c_cc[VTIME] = 0;
165
    
166
    tcsetattr (0, TCSANOW, &tty);
167

    
168
    atexit(term_exit);
169
}
170

    
171
/* read a key without blocking */
172
static int read_key(void)
173
{
174
    struct timeval tv;
175
    int n;
176
    unsigned char ch;
177
    fd_set rfds;
178

    
179
    FD_ZERO(&rfds);
180
    FD_SET(0, &rfds);
181
    tv.tv_sec = 0;
182
    tv.tv_usec = 0;
183
    n = select(1, &rfds, NULL, NULL, &tv);
184
    if (n > 0) {
185
        if (read(0, &ch, 1) == 1)
186
            return ch;
187
    }
188
    return -1;
189
}
190

    
191
#define AUDIO_FIFO_SIZE 8192
192

    
193
/* main loop for grabbing */
194
int av_grab(AVFormatContext *s)
195
{
196
    UINT8 audio_buf[AUDIO_FIFO_SIZE/2];
197
    UINT8 audio_buf1[AUDIO_FIFO_SIZE/2];
198
    UINT8 audio_out[AUDIO_FIFO_SIZE/2];
199
    UINT8 video_buffer[128*1024];
200
    char buf[256];
201
    short *samples;
202
    URLContext *audio_handle = NULL, *video_handle = NULL;
203
    int ret;
204
    AVCodecContext *enc, *first_video_enc = NULL;
205
    int frame_size, frame_bytes;
206
    int use_audio, use_video;
207
    int frame_rate, sample_rate, channels;
208
    int width, height, frame_number, i, pix_fmt = 0;
209
    AVOutputStream *ost_table[s->nb_streams], *ost;
210
    UINT8 *picture_in_buf = NULL, *picture_420p = NULL;
211
    int audio_fifo_size = 0, picture_size = 0;
212
    INT64 time_start;
213

    
214
    /* init output stream info */
215
    for(i=0;i<s->nb_streams;i++)
216
        ost_table[i] = NULL;
217

    
218
    /* output stream init */
219
    for(i=0;i<s->nb_streams;i++) {
220
        ost = av_mallocz(sizeof(AVOutputStream));
221
        if (!ost)
222
            goto fail;
223
        ost->index = i;
224
        ost->st = s->streams[i];
225
        ost_table[i] = ost;
226
    }
227

    
228
    use_audio = 0;
229
    use_video = 0;
230
    frame_rate = 0;
231
    sample_rate = 0;
232
    frame_size = 0;
233
    channels = 1;
234
    width = 0;
235
    height = 0;
236
    frame_number = 0;
237
    
238
    for(i=0;i<s->nb_streams;i++) {
239
        AVCodec *codec;
240

    
241
        ost = ost_table[i];
242
        enc = &ost->st->codec;
243
        codec = avcodec_find_encoder(enc->codec_id);
244
        if (!codec) {
245
            fprintf(stderr, "Unknown codec\n");
246
            return -1;
247
        }
248
        if (avcodec_open(enc, codec) < 0) {
249
            fprintf(stderr, "Incorrect encode parameters\n");
250
            return -1;
251
        }
252
        switch(enc->codec_type) {
253
        case CODEC_TYPE_AUDIO:
254
            use_audio = 1;
255
            if (enc->sample_rate > sample_rate)
256
                sample_rate = enc->sample_rate;
257
            if (enc->frame_size > frame_size)
258
                frame_size = enc->frame_size;
259
            if (enc->channels > channels)
260
                channels = enc->channels;
261
            break;
262
        case CODEC_TYPE_VIDEO:
263
            if (!first_video_enc)
264
                first_video_enc = enc;
265
            use_video = 1;
266
            if (enc->frame_rate > frame_rate)
267
                frame_rate = enc->frame_rate;
268
            if (enc->width > width)
269
                width = enc->width;
270
            if (enc->height > height)
271
                height = enc->height;
272
            break;
273
        }
274
    }
275

    
276
    /* audio */
277
    samples = NULL;
278
    if (use_audio) {
279
        snprintf(buf, sizeof(buf), "audio:%d,%d", sample_rate, channels);
280
        ret = url_open(&audio_handle, buf, URL_RDONLY);
281
        if (ret < 0) {
282
            fprintf(stderr, "Could not open audio device: disabling audio capture\n");
283
            use_audio = 0;
284
        } else {
285
            URLFormat f;
286
            /* read back exact grab parameters */
287
            if (url_getformat(audio_handle, &f) < 0) {
288
                fprintf(stderr, "could not read back video grab parameters\n");
289
                goto fail;
290
            }
291
            sample_rate = f.sample_rate;
292
            channels = f.channels;
293
            audio_fifo_size = ((AUDIO_FIFO_SIZE / 2) / audio_handle->packet_size) * 
294
                audio_handle->packet_size;
295
            fprintf(stderr, "Audio sampling: %d Hz, %s\n", 
296
                    sample_rate, channels == 2 ? "stereo" : "mono");
297
        }
298
    }
299
    
300
    /* video */
301
    if (use_video) {
302
        snprintf(buf, sizeof(buf), "video:%d,%d,%f", 
303
                 width, height, (float)frame_rate / FRAME_RATE_BASE);
304

    
305
        ret = url_open(&video_handle, buf, URL_RDONLY);
306
        if (ret < 0) {
307
            fprintf(stderr,"Could not init video 4 linux capture: disabling video capture\n");
308
            use_video = 0;
309
        } else {
310
            URLFormat f;
311
            const char *pix_fmt_str;
312
            /* read back exact grab parameters */
313
            if (url_getformat(video_handle, &f) < 0) {
314
                fprintf(stderr, "could not read back video grab parameters\n");
315
                goto fail;
316
            }
317
            width = f.width;
318
            height = f.height;
319
            pix_fmt = f.pix_fmt;
320
            switch(pix_fmt) {
321
            case PIX_FMT_YUV420P:
322
                pix_fmt_str = "420P";
323
                break;
324
            case PIX_FMT_YUV422:
325
                pix_fmt_str = "422";
326
                break;
327
            case PIX_FMT_RGB24:
328
                pix_fmt_str = "RGB24";
329
                break;
330
            case PIX_FMT_BGR24:
331
                pix_fmt_str = "BGR24";
332
                break;
333
            default:
334
                pix_fmt_str = "???";
335
                break;
336
            }
337
            picture_size = video_handle->packet_size;
338
            picture_in_buf = malloc(picture_size);
339
            if (!picture_in_buf)
340
                goto fail;
341
            /* allocate a temporary picture if not grabbing in 420P format */
342
            if (pix_fmt != PIX_FMT_YUV420P) {
343
                picture_420p = malloc((width * height * 3) / 2);
344
            }
345
            fprintf(stderr, "Video sampling: %dx%d, %s format, %0.2f fps\n", 
346
                    width, height, pix_fmt_str, (float)frame_rate / FRAME_RATE_BASE);
347
        }
348
    }
349

    
350
    if (!use_video && !use_audio) {
351
        fprintf(stderr,"Could not open grab devices : exiting\n");
352
        exit(1);
353
    }
354

    
355
    /* init built in conversion functions */
356
    for(i=0;i<s->nb_streams;i++) {
357
        ost = ost_table[i];
358
        enc = &ost->st->codec;
359
        switch(enc->codec_type) {
360
        case CODEC_TYPE_AUDIO:
361
            ost->audio_resample = 0;
362
            if ((enc->channels != channels ||
363
                 enc->sample_rate != sample_rate)) {
364
                ost->audio_resample = 1;
365
                ost->resample = audio_resample_init(enc->channels, channels,
366
                                                    enc->sample_rate, sample_rate);
367
            }
368
            if (fifo_init(&ost->fifo, (2 * audio_fifo_size * enc->sample_rate) / 
369
                          sample_rate))
370
                goto fail;
371
            break;
372
        case CODEC_TYPE_VIDEO:
373
            ost->video_resample = 0;
374
            if (enc->width != width ||
375
                enc->height != height) {
376
                UINT8 *buf;
377
                ost->video_resample = 1;
378
                buf = malloc((enc->width * enc->height * 3) / 2);
379
                if (!buf)
380
                    goto fail;
381
                ost->pict_tmp.data[0] = buf;
382
                ost->pict_tmp.data[1] = buf + enc->width * height;
383
                ost->pict_tmp.data[2] = ost->pict_tmp.data[1] + (enc->width * height) / 4;
384
                ost->pict_tmp.linesize[0] = enc->width;
385
                ost->pict_tmp.linesize[1] = enc->width / 2;
386
                ost->pict_tmp.linesize[2] = enc->width / 2;
387
                ost->img_resample_ctx = img_resample_init(
388
                                  ost->st->codec.width, ost->st->codec.height,
389
                                  width, height);
390
            }
391
        }
392
    }
393

    
394
    fprintf(stderr, "Press [q] to stop encoding\n");
395

    
396
    s->format->write_header(s);
397
    time_start = gettime();
398
    term_init();
399
    
400
    for(;;) {
401
        /* if 'q' pressed, exits */
402
        if (read_key() == 'q')
403
            break;
404

    
405
        /* read & compress audio frames */
406
        if (use_audio) {
407
            int ret, nb_samples, nb_samples_out;
408
            UINT8 *buftmp;
409

    
410
            for(;;) {
411
                ret = url_read(audio_handle, audio_buf, audio_fifo_size);
412
                if (ret <= 0)
413
                    break;
414
                /* fill each codec fifo by doing the right sample
415
                   rate conversion. This is not optimal because we
416
                   do too much work, but it is easy to do */
417
                nb_samples = ret / (channels * 2);
418
                for(i=0;i<s->nb_streams;i++) {
419
                    ost = ost_table[i];
420
                    enc = &ost->st->codec;
421
                    if (enc->codec_type == CODEC_TYPE_AUDIO) {
422
                        /* rate & stereo convertion */
423
                        if (!ost->audio_resample) {
424
                            buftmp = audio_buf;
425
                            nb_samples_out = nb_samples;
426
                        } else {
427
                            buftmp = audio_buf1;
428
                            nb_samples_out = audio_resample(ost->resample, 
429
                                                            (short *)buftmp, (short *)audio_buf,
430
                                                            nb_samples);
431
                        }
432
                        fifo_write(&ost->fifo, buftmp, nb_samples_out * enc->channels * 2, 
433
                                   &ost->fifo.wptr);
434
                    }
435
                }
436
                
437
                /* compress as many frame as possible with each audio codec */
438
                for(i=0;i<s->nb_streams;i++) {
439
                    ost = ost_table[i];
440
                    enc = &ost->st->codec;
441
                    if (enc->codec_type == CODEC_TYPE_AUDIO) {
442
                        frame_bytes = enc->frame_size * 2 * enc->channels;
443
                        
444
                        while (fifo_read(&ost->fifo, audio_buf, 
445
                                         frame_bytes, &ost->fifo.rptr) == 0) {
446
                            ret = avcodec_encode_audio(enc,
447
                                                       audio_out, sizeof(audio_out), 
448
                                                       (short *)audio_buf);
449
                            s->format->write_packet(s, ost->index, audio_out, ret);
450
                        }
451
                    }
452
                }
453
            }
454
        }
455

    
456
        if (use_video) {
457
            AVPicture *picture1, *picture2, *picture;
458
            AVPicture picture_tmp0, picture_tmp1;
459

    
460
            ret = url_read(video_handle, picture_in_buf, picture_size);
461
            if (ret < 0)
462
                break;
463
            
464
            picture2 = &picture_tmp0;
465
            avpicture_fill(picture2, picture_in_buf, pix_fmt, width, height);
466

    
467
            if (pix_fmt != PIX_FMT_YUV420P) {
468
                picture = &picture_tmp1;
469
                img_convert(picture, PIX_FMT_YUV420P,
470
                            picture2, pix_fmt, 
471
                            width, height);
472
            } else {
473
                picture = picture2;
474
            }
475
            
476
            for(i=0;i<s->nb_streams;i++) {
477
                ost = ost_table[i];
478
                enc = &ost->st->codec;
479
                if (enc->codec_type == CODEC_TYPE_VIDEO) {
480
                    int n1, n2, nb;
481

    
482
                    /* feed each codec with its requested frame rate */
483
                    n1 = ((INT64)frame_number * enc->frame_rate) / frame_rate;
484
                    n2 = (((INT64)frame_number + 1) * enc->frame_rate) / frame_rate;
485
                    nb = n2 - n1;
486
                    if (nb > 0) {
487
                        /* resize the picture if needed */
488
                        if (ost->video_resample) {
489
                            picture1 = &ost->pict_tmp;
490
                            img_resample(ost->img_resample_ctx, 
491
                                         picture1, picture);
492
                        } else {
493
                            picture1 = picture;
494
                        }
495
                        ret = avcodec_encode_video(enc, video_buffer, 
496
                                                   sizeof(video_buffer), 
497
                                                   picture1);
498
                        s->format->write_packet(s, ost->index, video_buffer, ret);
499
                    }
500
                }
501
            }
502
            frame_number++;
503
        }
504
        
505
        /* write report */
506
        {
507
            char buf[1024];
508
            INT64 total_size;
509
            float ti, bitrate;
510
            static float last_ti;
511
            INT64 ti1;
512

    
513
            total_size = url_ftell(&s->pb);
514
            ti1 = gettime() - time_start;
515
            /* check elapsed time */
516
            if (recording_time && ti1 >= recording_time)
517
                break;
518

    
519
            ti = ti1 / 1000000.0;
520
            if (ti < 0.1)
521
                ti = 0.1;
522
            /* dispaly twice per second */
523
            if ((ti - last_ti) >= 0.5) {
524
                last_ti = ti;
525
                bitrate = (int)((total_size * 8) / ti / 1000.0);
526
                
527
                buf[0] = '\0';
528
                if (use_video) {
529
                    sprintf(buf + strlen(buf), "frame=%5d fps=%4.1f q=%2d ",
530
                            frame_number, (float)frame_number / ti, first_video_enc->quality);
531
                }
532
                
533
                sprintf(buf + strlen(buf), "size=%8LdkB time=%0.1f bitrate=%6.1fkbits/s", 
534
                        total_size / 1024, ti, bitrate);
535
                fprintf(stderr, "%s    \r", buf);
536
                fflush(stderr);
537
            }
538
        }
539
    }
540
    term_exit();
541

    
542
    for(i=0;i<s->nb_streams;i++) {
543
        ost = ost_table[i];
544
        enc = &ost->st->codec;
545
        avcodec_close(enc);
546
    }
547
    s->format->write_trailer(s);
548
    
549
    if (audio_handle)
550
        url_close(audio_handle);
551

    
552
    if (video_handle)
553
        url_close(video_handle);
554

    
555
    /* write report */
556
    {
557
        float ti, bitrate;
558
        INT64 total_size;
559

    
560
        total_size = url_ftell(&s->pb);
561

    
562
        ti = (gettime() - time_start) / 1000000.0;
563
        if (ti < 0.1)
564
            ti = 0.1;
565
        bitrate = (int)((total_size * 8) / ti / 1000.0);
566

    
567
        fprintf(stderr, "\033[K\nTotal time = %0.1f s, %Ld KBytes, %0.1f kbits/s\n", 
568
                ti, total_size / 1024, bitrate);
569
        if (use_video) {
570
            fprintf(stderr, "Total frames = %d\n", frame_number);
571
        }
572
    }
573

    
574
    ret = 0;
575
 fail1:
576
    if (picture_in_buf)
577
        free(picture_in_buf);
578
    if (picture_420p)
579
        free(picture_420p);
580
    for(i=0;i<s->nb_streams;i++) {
581
        ost = ost_table[i];
582
        if (ost) {
583
            if (ost->fifo.buffer)
584
                fifo_free(&ost->fifo);
585
            if (ost->pict_tmp.data[0])
586
                free(ost->pict_tmp.data[0]);
587
            if (ost->video_resample)
588
                img_resample_close(ost->img_resample_ctx);
589
            if (ost->audio_resample)
590
                audio_resample_close(ost->resample);
591
            free(ost);
592
        }
593
    }
594
    return ret;
595
 fail:
596
    ret = -ENOMEM;
597
    goto fail1;
598
}
599

    
600
#endif /* CONFIG_WIN32 */
601

    
602
int read_ffserver_streams(AVFormatContext *s, const char *filename)
603
{
604
    int i;
605
    AVFormatContext *ic;
606

    
607
    ic = av_open_input_file(filename, FFM_PACKET_SIZE);
608
    if (!ic)
609
        return -EIO;
610
    /* copy stream format */
611
    s->nb_streams = ic->nb_streams;
612
    for(i=0;i<ic->nb_streams;i++) {
613
        AVStream *st;
614
        st = av_mallocz(sizeof(AVFormatContext));
615
        memcpy(st, ic->streams[i], sizeof(AVStream));
616
        s->streams[i] = st;
617
    }
618

    
619
    av_close_input_file(ic);
620
    return 0;
621
}
622

    
623
#define MAX_AUDIO_PACKET_SIZE 16384
624

    
625
static void do_audio_out(AVFormatContext *s, 
626
                         AVOutputStream *ost, 
627
                         AVInputStream *ist,
628
                         unsigned char *buf, int size)
629
{
630
    UINT8 *buftmp;
631
    UINT8 audio_buf[2*MAX_AUDIO_PACKET_SIZE]; /* XXX: allocate it */
632
    UINT8 audio_out[MAX_AUDIO_PACKET_SIZE]; /* XXX: allocate it */
633
    int size_out, frame_bytes, ret;
634
    AVCodecContext *enc;
635

    
636
    enc = &ost->st->codec;
637

    
638
    if (ost->audio_resample) {
639
        buftmp = audio_buf;
640
        size_out = audio_resample(ost->resample, 
641
                                  (short *)buftmp, (short *)buf,
642
                                  size / (ist->st->codec.channels * 2));
643
        size_out = size_out * enc->channels * 2;
644
    } else {
645
        buftmp = buf;
646
        size_out = size;
647
    }
648

    
649
    /* now encode as many frames as possible */
650
    if (enc->codec_id != CODEC_ID_PCM) {
651
        /* output resampled raw samples */
652
        fifo_write(&ost->fifo, buftmp, size_out, 
653
                   &ost->fifo.wptr);
654

    
655
        frame_bytes = enc->frame_size * 2 * enc->channels;
656
        
657
        while (fifo_read(&ost->fifo, audio_buf, frame_bytes, 
658
                     &ost->fifo.rptr) == 0) {
659
            ret = avcodec_encode_audio(enc,
660
                                       audio_out, sizeof(audio_out), (short *)audio_buf);
661
            s->format->write_packet(s, ost->index, audio_out, ret);
662
        }
663
    } else {
664
        /* XXX: handle endianness */
665
        s->format->write_packet(s, ost->index, buftmp, size_out);
666
    }
667
}
668

    
669
/* write a picture to a raw mux */
670
static void write_picture(AVFormatContext *s, int index, AVPicture *picture, 
671
                          int pix_fmt, int w, int h)
672
{
673
    UINT8 *buf, *src, *dest;
674
    int size, j, i;
675

    
676
    size = avpicture_get_size(pix_fmt, w, h);
677
    buf = malloc(size);
678
    if (!buf)
679
        return;
680

    
681
    /* XXX: not efficient, should add test if we can take
682
       directly the AVPicture */
683
    switch(pix_fmt) {
684
    case PIX_FMT_YUV420P:
685
        dest = buf;
686
        for(i=0;i<3;i++) {
687
            if (i == 1) {
688
                w >>= 1;
689
                h >>= 1;
690
            }
691
            src = picture->data[i];
692
            for(j=0;j<h;j++) {
693
                memcpy(dest, src, w);
694
                dest += w;
695
                src += picture->linesize[i];
696
            }
697
        }
698
        break;
699
    case PIX_FMT_YUV422P:
700
        size = (w * h) * 2; 
701
        buf = malloc(size);
702
        dest = buf;
703
        for(i=0;i<3;i++) {
704
            if (i == 1) {
705
                w >>= 1;
706
            }
707
            src = picture->data[i];
708
            for(j=0;j<h;j++) {
709
                memcpy(dest, src, w);
710
                dest += w;
711
                src += picture->linesize[i];
712
            }
713
        }
714
        break;
715
    case PIX_FMT_YUV444P:
716
        size = (w * h) * 3; 
717
        buf = malloc(size);
718
        dest = buf;
719
        for(i=0;i<3;i++) {
720
            src = picture->data[i];
721
            for(j=0;j<h;j++) {
722
                memcpy(dest, src, w);
723
                dest += w;
724
                src += picture->linesize[i];
725
            }
726
        }
727
        break;
728
    case PIX_FMT_YUV422:
729
        size = (w * h) * 2; 
730
        buf = malloc(size);
731
        dest = buf;
732
        src = picture->data[0];
733
        for(j=0;j<h;j++) {
734
            memcpy(dest, src, w * 2);
735
            dest += w * 2;
736
            src += picture->linesize[0];
737
        }
738
        break;
739
    case PIX_FMT_RGB24:
740
    case PIX_FMT_BGR24:
741
        size = (w * h) * 3; 
742
        buf = malloc(size);
743
        dest = buf;
744
        src = picture->data[0];
745
        for(j=0;j<h;j++) {
746
            memcpy(dest, src, w * 3);
747
            dest += w * 3;
748
            src += picture->linesize[0];
749
        }
750
        break;
751
    default:
752
        return;
753
    }
754
    s->format->write_packet(s, index, buf, size);
755
    free(buf);
756
}
757

    
758

    
759
static void do_video_out(AVFormatContext *s, 
760
                         AVOutputStream *ost, 
761
                         AVInputStream *ist,
762
                         AVPicture *picture1)
763
{
764
    int n1, n2, nb, i, ret, frame_number;
765
    AVPicture *picture, *picture2, *pict;
766
    AVPicture picture_tmp1, picture_tmp2;
767
    UINT8 video_buffer[128*1024];
768
    UINT8 *buf = NULL, *buf1 = NULL;
769
    AVCodecContext *enc, *dec;
770

    
771
    enc = &ost->st->codec;
772
    dec = &ist->st->codec;
773

    
774
    frame_number = ist->frame_number;
775
    /* first drop frame if needed */
776
    n1 = ((INT64)frame_number * enc->frame_rate) / dec->frame_rate;
777
    n2 = (((INT64)frame_number + 1) * enc->frame_rate) / dec->frame_rate;
778
    nb = n2 - n1;
779
    if (nb <= 0)
780
        return;
781
    
782
    /* deinterlace : must be done before any resize */
783
    if (do_deinterlace) {
784
        int size;
785

    
786
        /* create temporary picture */
787
        size = avpicture_get_size(dec->pix_fmt, dec->width, dec->height);
788
        buf1 = malloc(size);
789
        if (!buf1)
790
            return;
791
        
792
        picture2 = &picture_tmp2;
793
        avpicture_fill(picture2, buf1, dec->pix_fmt, dec->width, dec->height);
794

    
795
        if (avpicture_deinterlace(picture2, picture1, 
796
                                  dec->pix_fmt, dec->width, dec->height) < 0) {
797
            /* if error, do not deinterlace */
798
            free(buf1);
799
            buf1 = NULL;
800
            picture2 = picture1;
801
        }
802
    } else {
803
        picture2 = picture1;
804
    }
805

    
806
    /* convert pixel format if needed */
807
    if (enc->pix_fmt != dec->pix_fmt) {
808
        int size;
809

    
810
        /* create temporary picture */
811
        size = avpicture_get_size(enc->pix_fmt, dec->width, dec->height);
812
        buf = malloc(size);
813
        if (!buf)
814
            return;
815
        pict = &picture_tmp1;
816
        avpicture_fill(pict, buf, enc->pix_fmt, dec->width, dec->height);
817
        
818
        if (img_convert(pict, enc->pix_fmt, 
819
                        picture2, dec->pix_fmt, 
820
                        dec->width, dec->height) < 0) {
821
            fprintf(stderr, "pixel format conversion not handled\n");
822
            goto the_end;
823
        }
824
    } else {
825
        pict = picture2;
826
    }
827

    
828
    /* XXX: resampling could be done before raw format convertion in
829
       some cases to go faster */
830
    /* XXX: only works for YUV420P */
831
    if (ost->video_resample) {
832
        picture = &ost->pict_tmp;
833
        img_resample(ost->img_resample_ctx, picture, pict);
834
    } else {
835
        picture = pict;
836
    }
837

    
838
    /* duplicates frame if needed */
839
    /* XXX: pb because no interleaving */
840
    for(i=0;i<nb;i++) {
841
        if (enc->codec_id != CODEC_ID_RAWVIDEO) {
842
            /* handles sameq here. This is not correct because it may
843
               not be a global option */
844
            if (same_quality) {
845
                enc->quality = dec->quality;
846
            }
847
            ret = avcodec_encode_video(enc, 
848
                                       video_buffer, sizeof(video_buffer), 
849
                                       picture);
850
            s->format->write_packet(s, ost->index, video_buffer, ret);
851
        } else {
852
            write_picture(s, ost->index, picture, enc->pix_fmt, enc->width, enc->height);
853
        }
854
    }
855
    the_end:
856
    if (buf)
857
        free(buf);
858
    if (buf1)
859
        free(buf1);
860
}
861

    
862
//#define HEX_DUMP
863

    
864
#ifdef HEX_DUMP
865
static void hex_dump(UINT8 *buf, int size)
866
{
867
    int len, i, j, c;
868

    
869
    for(i=0;i<size;i+=16) {
870
        len = size - i;
871
        if (len > 16)
872
            len = 16;
873
        printf("%08x ", i);
874
        for(j=0;j<16;j++) {
875
            if (j < len)
876
                printf(" %02x", buf[i+j]);
877
            else
878
                printf("   ");
879
        }
880
        printf(" ");
881
        for(j=0;j<len;j++) {
882
            c = buf[i+j];
883
            if (c < ' ' || c > '~')
884
                c = '.';
885
            printf("%c", c);
886
        }
887
        printf("\n");
888
    }
889
}
890
#endif
891

    
892
/*
893
 * The following code is the main loop of the file converter
894
 */
895
static int av_encode(AVFormatContext **output_files,
896
                     int nb_output_files,
897
                     AVFormatContext **input_files,
898
                     int nb_input_files,
899
                     AVStreamMap *stream_maps, int nb_stream_maps)
900
{
901
    int ret, i, j, k, n, nb_istreams = 0, nb_ostreams = 0;
902
    AVFormatContext *is, *os;
903
    AVCodecContext *codec, *icodec;
904
    AVOutputStream *ost, **ost_table = NULL;
905
    AVInputStream *ist, **ist_table = NULL;
906
    INT64 min_pts, start_time;
907
    AVInputFile *file_table;
908

    
909
    file_table= (AVInputFile*) malloc(nb_input_files * sizeof(AVInputFile));
910
    if (!file_table)
911
        goto fail;
912

    
913
    memset(file_table, 0, sizeof(file_table));
914
    
915
    /* input stream init */
916
    j = 0;
917
    for(i=0;i<nb_input_files;i++) {
918
        is = input_files[i];
919
        file_table[i].ist_index = j;
920
        j += is->nb_streams;
921
    }
922
    nb_istreams = j;
923

    
924
    ist_table = av_mallocz(nb_istreams * sizeof(AVInputStream *));
925
    if (!ist_table)
926
        goto fail;
927
    
928
    for(i=0;i<nb_istreams;i++) {
929
        ist = av_mallocz(sizeof(AVInputStream));
930
        if (!ist)
931
            goto fail;
932
        ist_table[i] = ist;
933
    }
934
    j = 0;
935
    for(i=0;i<nb_input_files;i++) {
936
        is = input_files[i];
937
        for(k=0;k<is->nb_streams;k++) {
938
            ist = ist_table[j++];
939
            ist->st = is->streams[k];
940
            ist->file_index = i;
941
            ist->index = k;
942
            ist->discard = 1; /* the stream is discarded by default
943
                                 (changed later) */
944
        }
945
    }
946

    
947
    /* output stream init */
948
    nb_ostreams = 0;
949
    for(i=0;i<nb_output_files;i++) {
950
        os = output_files[i];
951
        nb_ostreams += os->nb_streams;
952
    }
953
    if (nb_stream_maps > 0 && nb_stream_maps != nb_ostreams) {
954
        fprintf(stderr, "Number of stream maps must match number of output streams\n");
955
        exit(1);
956
    }
957

    
958
    ost_table = av_mallocz(sizeof(AVOutputStream *) * nb_ostreams);
959
    if (!ost_table)
960
        goto fail;
961
    for(i=0;i<nb_ostreams;i++) {
962
        ost = av_mallocz(sizeof(AVOutputStream));
963
        if (!ost)
964
            goto fail;
965
        ost_table[i] = ost;
966
    }
967
    
968
    n = 0;
969
    for(k=0;k<nb_output_files;k++) {
970
        os = output_files[k];
971
        for(i=0;i<os->nb_streams;i++) {
972
            int found;
973
            ost = ost_table[n++];
974
            ost->file_index = k;
975
            ost->index = i;
976
            ost->st = os->streams[i];
977
            if (nb_stream_maps > 0) {
978
                ost->source_index = file_table[stream_maps[n-1].file_index].ist_index + 
979
                    stream_maps[n-1].stream_index;
980
            } else {
981
                /* get corresponding input stream index : we select the first one with the right type */
982
                found = 0;
983
                for(j=0;j<nb_istreams;j++) {
984
                    ist = ist_table[j];
985
                    if (ist->discard && 
986
                        ist->st->codec.codec_type == ost->st->codec.codec_type) {
987
                        ost->source_index = j;
988
                        found = 1;
989
                    }
990
                }
991
                
992
                if (!found) {
993
                    /* try again and reuse existing stream */
994
                    for(j=0;j<nb_istreams;j++) {
995
                        ist = ist_table[j];
996
                        if (ist->st->codec.codec_type == ost->st->codec.codec_type) {
997
                            ost->source_index = j;
998
                            found = 1;
999
                        }
1000
                    }
1001
                    if (!found) {
1002
                        fprintf(stderr, "Could not find input stream matching output stream #%d.%d\n",
1003
                                ost->file_index, ost->index);
1004
                        exit(1);
1005
                    }
1006
                }
1007
            }
1008
            ist = ist_table[ost->source_index];
1009
            ist->discard = 0;
1010
        }
1011
    }
1012

    
1013
    /* dump the stream mapping */
1014
    fprintf(stderr, "Stream mapping:\n");
1015
    for(i=0;i<nb_ostreams;i++) {
1016
        ost = ost_table[i];
1017
        fprintf(stderr, "  Stream #%d.%d -> #%d.%d\n",
1018
                ist_table[ost->source_index]->file_index,
1019
                ist_table[ost->source_index]->index,
1020
                ost->file_index, 
1021
                ost->index);
1022
    }
1023

    
1024
    /* for each output stream, we compute the right encoding parameters */
1025
    for(i=0;i<nb_ostreams;i++) {
1026
        ost = ost_table[i];
1027
        ist = ist_table[ost->source_index];
1028

    
1029
        codec = &ost->st->codec;
1030
        icodec = &ist->st->codec;
1031

    
1032
        switch(codec->codec_type) {
1033
        case CODEC_TYPE_AUDIO:
1034
            /* check if same codec with same parameters. If so, no
1035
               reencoding is needed */
1036
            if (codec->codec_id == icodec->codec_id &&
1037
                codec->bit_rate == icodec->bit_rate &&
1038
                codec->sample_rate == icodec->sample_rate &&
1039
                codec->channels == icodec->channels) {
1040
                /* no reencoding */
1041
            } else {
1042
                if (fifo_init(&ost->fifo, 2 * MAX_AUDIO_PACKET_SIZE))
1043
                    goto fail;
1044

    
1045
                if (codec->channels == icodec->channels &&
1046
                    codec->sample_rate == icodec->sample_rate) {
1047
                    ost->audio_resample = 0;
1048
                } else {
1049
                    ost->audio_resample = 1;
1050
                    ost->resample = audio_resample_init(codec->channels, icodec->channels,
1051
                                                        codec->sample_rate, 
1052
                                                        icodec->sample_rate);
1053
                }
1054
                ist->decoding_needed = 1;
1055
                ost->encoding_needed = 1;
1056
            }
1057
            break;
1058
        case CODEC_TYPE_VIDEO:
1059
            /* check if same codec with same parameters. If so, no
1060
               reencoding is needed */
1061
            if (codec->codec_id == icodec->codec_id &&
1062
                codec->bit_rate == icodec->bit_rate &&
1063
                codec->frame_rate == icodec->frame_rate &&
1064
                codec->width == icodec->width &&
1065
                codec->height == icodec->height) {
1066
                /* no reencoding */
1067
            } else {
1068
                if (codec->width == icodec->width &&
1069
                    codec->height == icodec->height) {
1070
                    ost->video_resample = 0;
1071
                } else {
1072
                    UINT8 *buf;
1073
                    ost->video_resample = 1;
1074
                    buf = malloc((codec->width * codec->height * 3) / 2);
1075
                    if (!buf)
1076
                        goto fail;
1077
                    ost->pict_tmp.data[0] = buf;
1078
                    ost->pict_tmp.data[1] = ost->pict_tmp.data[0] + (codec->width * codec->height);
1079
                    ost->pict_tmp.data[2] = ost->pict_tmp.data[1] + (codec->width * codec->height) / 4;
1080
                    ost->pict_tmp.linesize[0] = codec->width;
1081
                    ost->pict_tmp.linesize[1] = codec->width / 2;
1082
                    ost->pict_tmp.linesize[2] = codec->width / 2;
1083

    
1084
                    ost->img_resample_ctx = img_resample_init( 
1085
                                      ost->st->codec.width, ost->st->codec.height,
1086
                                      ist->st->codec.width, ist->st->codec.height);
1087
                }
1088
                ost->encoding_needed = 1;
1089
                ist->decoding_needed = 1;
1090
            }
1091
            break;
1092
        }
1093
    }
1094

    
1095
    /* open each encoder */
1096
    for(i=0;i<nb_ostreams;i++) {
1097
        ost = ost_table[i];
1098
        if (ost->encoding_needed) {
1099
            AVCodec *codec;
1100
            codec = avcodec_find_encoder(ost->st->codec.codec_id);
1101
            if (!codec) {
1102
                fprintf(stderr, "Unsupported codec for output stream #%d.%d\n", 
1103
                        ost->file_index, ost->index);
1104
                exit(1);
1105
            }
1106
            if (avcodec_open(&ost->st->codec, codec) < 0) {
1107
                fprintf(stderr, "Error while opening codec for stream #%d.%d - maybe incorrect parameters such as bit_rate, rate, width or height\n", 
1108
                        ost->file_index, ost->index);
1109
                exit(1);
1110
            }
1111
        }
1112
    }
1113

    
1114
    /* open each decoder */
1115
    for(i=0;i<nb_istreams;i++) {
1116
        ist = ist_table[i];
1117
        if (ist->decoding_needed) {
1118
            AVCodec *codec;
1119
            codec = avcodec_find_decoder(ist->st->codec.codec_id);
1120
            if (!codec) {
1121
                fprintf(stderr, "Unsupported codec for input stream #%d.%d\n", 
1122
                        ist->file_index, ist->index);
1123
                exit(1);
1124
            }
1125
            if (avcodec_open(&ist->st->codec, codec) < 0) {
1126
                fprintf(stderr, "Error while opening codec for input stream #%d.%d\n", 
1127
                        ist->file_index, ist->index);
1128
                exit(1);
1129
            }
1130
        }
1131
    }
1132

    
1133
    /* init pts */
1134
    for(i=0;i<nb_istreams;i++) {
1135
        ist = ist_table[i];
1136
        ist->pts = 0;
1137
        ist->frame_number = 0;
1138
    }
1139
    
1140
    /* compute buffer size max (should use a complete heuristic) */
1141
    for(i=0;i<nb_input_files;i++) {
1142
        file_table[i].buffer_size_max = 2048;
1143
    }
1144

    
1145
    /* open files and write file headers */
1146
    for(i=0;i<nb_output_files;i++) {
1147
        os = output_files[i];
1148
        os->format->write_header(os);
1149
    }
1150

    
1151
    start_time = gettime();
1152
    min_pts = 0;
1153
    for(;;) {
1154
        int file_index, ist_index;
1155
        AVPacket pkt;
1156
        UINT8 *ptr;
1157
        int len;
1158
        UINT8 *data_buf;
1159
        int data_size, got_picture;
1160
        AVPicture picture;
1161
        short samples[AVCODEC_MAX_AUDIO_FRAME_SIZE / 2];
1162

    
1163
        /* select the input file with the smallest pts */
1164
    redo:
1165
        file_index = -1;
1166
        min_pts = MAXINT64;
1167
        for(i=0;i<nb_istreams;i++) {
1168
            ist = ist_table[i];
1169
            if (!ist->discard && !file_table[ist->file_index].eof_reached && ist->pts < min_pts) {
1170
                min_pts = ist->pts;
1171
                file_index = ist->file_index;
1172
            }
1173
        }
1174
        /* if none, if is finished */
1175
        if (file_index < 0)
1176
            break;
1177
        /* finish if recording time exhausted */
1178
        if (recording_time > 0 && min_pts >= recording_time)
1179
            break;
1180
        /* read a packet from it and output it in the fifo */
1181
        
1182
        is = input_files[file_index];
1183
        if (av_read_packet(is, &pkt) < 0) {
1184
            file_table[file_index].eof_reached = 1;
1185
            continue;
1186
        }
1187
        ist_index = file_table[file_index].ist_index + pkt.stream_index;
1188
        ist = ist_table[ist_index];
1189
        if (ist->discard) {
1190
            continue;
1191
        }
1192

    
1193
#ifdef HEX_DUMP
1194
        printf("stream #%d, size=%d:\n", pkt.stream_index, pkt.size);
1195
        hex_dump(pkt.data, pkt.size);
1196
#endif
1197

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

    
1200
        len = pkt.size;
1201
        ptr = pkt.data;
1202
        while (len > 0) {
1203

    
1204
            /* decode the packet if needed */
1205
            data_buf = NULL; /* fail safe */
1206
            data_size = 0;
1207
            if (ist->decoding_needed) {
1208
                switch(ist->st->codec.codec_type) {
1209
                case CODEC_TYPE_AUDIO:
1210
                    if (ist->st->codec.codec_id == CODEC_ID_PCM) {
1211
                        /* no need to call a codec */
1212
                        data_buf = ptr;
1213
                        data_size = len;
1214
                        ret = len;
1215
                    } else {
1216
                        ret = avcodec_decode_audio(&ist->st->codec, samples, &data_size,
1217
                                                   ptr, len);
1218
                        if (ret < 0)
1219
                            goto fail_decode;
1220
                        if (data_size == 0) {
1221
                            /* no audio frame */
1222
                            ptr += ret;
1223
                            len -= ret;
1224
                            continue;
1225
                        }
1226
                        data_buf = (UINT8 *)samples;
1227
                    }
1228
                    break;
1229
                case CODEC_TYPE_VIDEO:
1230
                    if (ist->st->codec.codec_id == CODEC_ID_RAWVIDEO) {
1231
                        int size;
1232
                        size = (ist->st->codec.width * ist->st->codec.height);
1233
                        avpicture_fill(&picture, ptr, 
1234
                                     ist->st->codec.pix_fmt,
1235
                                     ist->st->codec.width,
1236
                                     ist->st->codec.height);
1237
                        ret = len;
1238
                    } else {
1239
                        data_size = (ist->st->codec.width * ist->st->codec.height * 3) / 2;
1240
                        ret = avcodec_decode_video(&ist->st->codec, 
1241
                                                   &picture, &got_picture, ptr, len);
1242
                        if (ret < 0) {
1243
                        fail_decode:
1244
                            fprintf(stderr, "Error while decoding stream #%d.%d\n",
1245
                                    ist->file_index, ist->index);
1246
                            av_free_packet(&pkt);
1247
                            goto redo;
1248
                        }
1249
                        if (!got_picture) {
1250
                            /* no picture yet */
1251
                            ptr += ret;
1252
                            len -= ret;
1253
                            continue;
1254
                        }
1255
                    }
1256
                    break;
1257
                default:
1258
                    goto fail_decode;
1259
                }
1260
            } else {
1261
                data_buf = ptr;
1262
                data_size = len;
1263
                ret = len;
1264
            }
1265
            /* update pts */
1266
            switch(ist->st->codec.codec_type) {
1267
            case CODEC_TYPE_AUDIO:
1268
                ist->pts = (INT64)1000000 * ist->sample_index / ist->st->codec.sample_rate;
1269
                ist->sample_index += data_size / (2 * ist->st->codec.channels);
1270
                break;
1271
            case CODEC_TYPE_VIDEO:
1272
                ist->frame_number++;
1273
                ist->pts = ((INT64)ist->frame_number * 1000000 * FRAME_RATE_BASE) / 
1274
                    ist->st->codec.frame_rate;
1275
                break;
1276
            }
1277
            ptr += ret;
1278
            len -= ret;
1279

    
1280
            /* transcode raw format, encode packets and output them */
1281
            
1282
            for(i=0;i<nb_ostreams;i++) {
1283
                ost = ost_table[i];
1284
                if (ost->source_index == ist_index) {
1285
                    os = output_files[ost->file_index];
1286

    
1287
                    if (ost->encoding_needed) {
1288
                        switch(ost->st->codec.codec_type) {
1289
                        case CODEC_TYPE_AUDIO:
1290
                            do_audio_out(os, ost, ist, data_buf, data_size);
1291
                            break;
1292
                        case CODEC_TYPE_VIDEO:
1293
                            do_video_out(os, ost, ist, &picture);
1294
                            break;
1295
                        }
1296
                    } else {
1297
                        /* no reencoding needed : output the packet directly */
1298
                        os->format->write_packet(os, ost->index, data_buf, data_size);
1299
                    }
1300
                }
1301
            }
1302
        }
1303
        av_free_packet(&pkt);
1304
        
1305
        /* dump report by using the first video and audio streams */
1306
        {
1307
            char buf[1024];
1308
            AVFormatContext *oc;
1309
            INT64 total_size, ti;
1310
            AVCodecContext *enc;
1311
            int frame_number, vid;
1312
            double bitrate, ti1;
1313
            static INT64 last_time;
1314

    
1315
            if ((min_pts - last_time) >= 500000) {
1316
                last_time = min_pts;
1317
                
1318
                oc = output_files[0];
1319
                
1320
                total_size = url_ftell(&oc->pb);
1321
                
1322
                buf[0] = '\0';
1323
                ti = MAXINT64;
1324
                vid = 0;
1325
                for(i=0;i<nb_ostreams;i++) {
1326
                    ost = ost_table[i];
1327
                    enc = &ost->st->codec;
1328
                    ist = ist_table[ost->source_index];
1329
                    if (!vid && enc->codec_type == CODEC_TYPE_VIDEO) {
1330
                        frame_number = ist->frame_number;
1331
                        sprintf(buf + strlen(buf), "frame=%5d q=%2d ",
1332
                                frame_number, enc->quality);
1333
                        vid = 1;
1334
                    }
1335
                    /* compute min pts value */
1336
                    if (!ist->discard && ist->pts < ti) {
1337
                        ti = ist->pts;
1338
                    }
1339
                }
1340

    
1341
                ti1 = (double)ti / 1000000.0;
1342
                if (ti1 < 0.1)
1343
                    ti1 = 0.1;
1344
                bitrate = (double)(total_size * 8) / ti1 / 1000.0;
1345

    
1346
                sprintf(buf + strlen(buf), 
1347
                        "size=%8.0fkB time=%0.1f bitrate=%6.1fkbits/s",
1348
                        (double)total_size / 1024, ti1, bitrate);
1349
                
1350
                fprintf(stderr, "%s    \r", buf);
1351
                fflush(stderr);
1352
            }
1353
        }
1354
    }
1355

    
1356
    /* dump report by using the first video and audio streams */
1357
    {
1358
        char buf[1024];
1359
        AVFormatContext *oc;
1360
        INT64 total_size, ti;
1361
        AVCodecContext *enc;
1362
        int frame_number, vid;
1363
        double bitrate, ti1;
1364

    
1365
        oc = output_files[0];
1366
        
1367
        total_size = url_ftell(&oc->pb);
1368
        
1369
        buf[0] = '\0';
1370
        ti = MAXINT64;
1371
        vid = 0;
1372
        for(i=0;i<nb_ostreams;i++) {
1373
            ost = ost_table[i];
1374
            enc = &ost->st->codec;
1375
            ist = ist_table[ost->source_index];
1376
            if (!vid && enc->codec_type == CODEC_TYPE_VIDEO) {
1377
                frame_number = ist->frame_number;
1378
                sprintf(buf + strlen(buf), "frame=%5d q=%2d ",
1379
                        frame_number, enc->quality);
1380
                vid = 1;
1381
            }
1382
            /* compute min pts value */
1383
            if (!ist->discard && ist->pts < ti) {
1384
                ti = ist->pts;
1385
            }
1386
        }
1387
        
1388
        ti1 = ti / 1000000.0;
1389
        if (ti1 < 0.1)
1390
            ti1 = 0.1;
1391
        bitrate = (double)(total_size * 8) / ti1 / 1000.0;
1392
        
1393
        sprintf(buf + strlen(buf), 
1394
                "size=%8.0fkB time=%0.1f bitrate=%6.1fkbits/s",
1395
                (double)total_size / 1024, ti1, bitrate);
1396
        
1397
        fprintf(stderr, "%s    \n", buf);
1398
    }
1399
    /* close each encoder */
1400
    for(i=0;i<nb_ostreams;i++) {
1401
        ost = ost_table[i];
1402
        if (ost->encoding_needed) {
1403
            avcodec_close(&ost->st->codec);
1404
        }
1405
    }
1406
    
1407
    /* close each decoder */
1408
    for(i=0;i<nb_istreams;i++) {
1409
        ist = ist_table[i];
1410
        if (ist->decoding_needed) {
1411
            avcodec_close(&ist->st->codec);
1412
        }
1413
    }
1414
    
1415

    
1416
    /* write the trailer if needed and close file */
1417
    for(i=0;i<nb_output_files;i++) {
1418
        os = output_files[i];
1419
        os->format->write_trailer(os);
1420
    }
1421
    /* finished ! */
1422
    
1423
    ret = 0;
1424
 fail1:
1425
    free(file_table);
1426

    
1427
    if (ist_table) {
1428
        for(i=0;i<nb_istreams;i++) {
1429
            ist = ist_table[i];
1430
            if (ist) {
1431
                free(ist);
1432
            }
1433
        }
1434
        free(ist_table);
1435
    }
1436
    if (ost_table) {
1437
        for(i=0;i<nb_ostreams;i++) {
1438
            ost = ost_table[i];
1439
            if (ost) {
1440
                if (ost->pict_tmp.data[0])
1441
                    free(ost->pict_tmp.data[0]);
1442
                if (ost->video_resample)
1443
                    img_resample_close(ost->img_resample_ctx);
1444
                if (ost->audio_resample)
1445
                    audio_resample_close(ost->resample);
1446
                free(ost);
1447
            }
1448
        }
1449
        free(ost_table);
1450
    }
1451
    return ret;
1452
 fail:
1453
    ret = -ENOMEM;
1454
    goto fail1;
1455
}
1456

    
1457
#if 0
1458
int file_read(const char *filename)
1459
{
1460
    URLContext *h;
1461
    unsigned char buffer[1024];
1462
    int len, i;
1463

1464
    if (url_open(&h, filename, O_RDONLY) < 0) {
1465
        printf("could not open '%s'\n", filename);
1466
        return -1;
1467
    }
1468
    for(;;) {
1469
        len = url_read(h, buffer, sizeof(buffer));
1470
        if (len <= 0)
1471
            break;
1472
        for(i=0;i<len;i++) putchar(buffer[i]);
1473
    }
1474
    url_close(h);
1475
    return 0;
1476
}
1477
#endif
1478

    
1479
void show_licence(void)
1480
{
1481
    printf(
1482
    "ffmpeg version " FFMPEG_VERSION "\n"
1483
    "Copyright (c) 2000,2001 Gerard Lantau\n"
1484
    "This program is free software; you can redistribute it and/or modify\n"
1485
    "it under the terms of the GNU General Public License as published by\n"
1486
    "the Free Software Foundation; either version 2 of the License, or\n"
1487
    "(at your option) any later version.\n"
1488
    "\n"
1489
    "This program is distributed in the hope that it will be useful,\n"
1490
    "but WITHOUT ANY WARRANTY; without even the implied warranty of\n"
1491
    "MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n"
1492
    "GNU General Public License for more details.\n"
1493
    "\n"
1494
    "You should have received a copy of the GNU General Public License\n"
1495
    "along with this program; if not, write to the Free Software\n"
1496
    "Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.\n"
1497
    );
1498
    exit(1);
1499
}
1500

    
1501
void opt_format(const char *arg)
1502
{
1503
    AVFormat *f;
1504
    f = first_format;
1505
    while (f != NULL && strcmp(f->name, arg) != 0) f = f->next;
1506
    if (f == NULL) {
1507
        fprintf(stderr, "Invalid format: %s\n", arg);
1508
        exit(1);
1509
    }
1510
    file_format = f;
1511
}
1512

    
1513
void opt_video_bitrate(const char *arg)
1514
{
1515
    video_bit_rate = atoi(arg) * 1000;
1516
}
1517

    
1518
void opt_frame_rate(const char *arg)
1519
{
1520
    frame_rate = (int)(strtod(arg, 0) * FRAME_RATE_BASE);
1521
}
1522

    
1523
void opt_frame_size(const char *arg)
1524
{
1525
    parse_image_size(&frame_width, &frame_height, arg);
1526
    if (frame_width <= 0 || frame_height <= 0) {
1527
        fprintf(stderr, "Incorrect frame size\n");
1528
        exit(1);
1529
    }
1530
    if ((frame_width % 2) != 0 || (frame_height % 2) != 0) {
1531
        fprintf(stderr, "Frame size must be a multiple of 2\n");
1532
        exit(1);
1533
    }
1534
}
1535

    
1536
void opt_gop_size(const char *arg)
1537
{
1538
    gop_size = atoi(arg);
1539
}
1540

    
1541
void opt_qscale(const char *arg)
1542
{
1543
    video_qscale = atoi(arg);
1544
    if (video_qscale < 0 ||
1545
        video_qscale > 31) {
1546
        fprintf(stderr, "qscale must be >= 1 and <= 31\n");
1547
        exit(1);
1548
    }
1549
}
1550

    
1551

    
1552
void opt_audio_bitrate(const char *arg)
1553
{
1554
    audio_bit_rate = atoi(arg) * 1000;
1555
}
1556

    
1557
void opt_audio_rate(const char *arg)
1558
{
1559
    audio_sample_rate = atoi(arg);
1560
}
1561

    
1562
void opt_audio_channels(const char *arg)
1563
{
1564
    audio_channels = atoi(arg);
1565
}
1566

    
1567
#ifdef CONFIG_GRAB
1568
void opt_video_device(const char *arg)
1569
{
1570
    v4l_device = strdup(arg);
1571
}
1572

    
1573
void opt_audio_device(const char *arg)
1574
{
1575
    audio_device = strdup(arg);
1576
}
1577
#endif
1578

    
1579
void opt_audio_codec(const char *arg)
1580
{
1581
    AVCodec *p;
1582

    
1583
    p = first_avcodec;
1584
    while (p) {
1585
        if (!strcmp(p->name, arg) && p->type == CODEC_TYPE_AUDIO)
1586
            break;
1587
        p = p->next;
1588
    }
1589
    if (p == NULL) {
1590
        fprintf(stderr, "Unknown audio codec '%s'\n", arg);
1591
        exit(1);
1592
    } else {
1593
        audio_codec_id = p->id;
1594
    }
1595
}
1596

    
1597
const char *motion_str[] = {
1598
    "zero",
1599
    "full",
1600
    "log",
1601
    "phods",
1602
    NULL,
1603
};
1604

    
1605
void opt_motion_estimation(const char *arg)
1606
{
1607
    const char **p;
1608
    p = motion_str;
1609
    for(;;) {
1610
        if (!*p) {
1611
            fprintf(stderr, "Unknown motion estimation method '%s'\n", arg);
1612
            exit(1);
1613
        }
1614
        if (!strcmp(*p, arg))
1615
            break;
1616
        p++;
1617
    }
1618
    motion_estimation_method = p - motion_str;
1619
}
1620

    
1621
void opt_video_codec(const char *arg)
1622
{
1623
    AVCodec *p;
1624

    
1625
    p = first_avcodec;
1626
    while (p) {
1627
        if (!strcmp(p->name, arg) && p->type == CODEC_TYPE_VIDEO)
1628
            break;
1629
        p = p->next;
1630
    }
1631
    if (p == NULL) {
1632
        fprintf(stderr, "Unknown video codec '%s'\n", arg);
1633
        exit(1);
1634
    } else {
1635
        video_codec_id = p->id;
1636
    }
1637
}
1638

    
1639
void opt_map(const char *arg)
1640
{
1641
    AVStreamMap *m;
1642
    const char *p;
1643

    
1644
    p = arg;
1645
    m = &stream_maps[nb_stream_maps++];
1646

    
1647
    m->file_index = strtol(arg, (char **)&p, 0);
1648
    if (*p)
1649
        p++;
1650
    m->stream_index = strtol(arg, (char **)&p, 0);
1651
}
1652

    
1653
void opt_recording_time(const char *arg)
1654
{
1655
    recording_time = parse_date(arg, 1);
1656
}
1657

    
1658
/* return the number of packet read to find the codec parameters */
1659
int find_codec_parameters(AVFormatContext *ic)
1660
{
1661
    int val, i, count, ret, got_picture, size;
1662
    AVCodec *codec;
1663
    AVCodecContext *enc;
1664
    AVStream *st;
1665
    AVPacket *pkt;
1666
    AVPicture picture;
1667
    AVPacketList *pktl, **ppktl;
1668
    short samples[AVCODEC_MAX_AUDIO_FRAME_SIZE / 2];
1669
    UINT8 *ptr;
1670

    
1671
    count = 0;
1672
    ppktl = &ic->packet_buffer;
1673
    for(;;) {
1674
        for(i=0;i<ic->nb_streams;i++) {
1675
            enc = &ic->streams[i]->codec;
1676
            
1677
            switch(enc->codec_type) {
1678
            case CODEC_TYPE_AUDIO:
1679
                val = enc->sample_rate;
1680
                break;
1681
            case CODEC_TYPE_VIDEO:
1682
                val = enc->width;
1683
                break;
1684
            default:
1685
                val = 1;
1686
                break;
1687
            }
1688
            /* if no parameters supplied, then we should read it from
1689
               the stream */
1690
            if (val == 0)
1691
                break;
1692
        }
1693
        if (i == ic->nb_streams) {
1694
            ret = count;
1695
            break;
1696
        }
1697

    
1698
        if (count == 0) {
1699
            /* open each codec */
1700
            for(i=0;i<ic->nb_streams;i++) {
1701
                st = ic->streams[i];
1702
                codec = avcodec_find_decoder(st->codec.codec_id);
1703
                if (codec == NULL) {
1704
                    ret = -1;
1705
                    goto the_end;
1706
                }
1707
                avcodec_open(&st->codec, codec);
1708
            }
1709
        }
1710
        pktl = av_mallocz(sizeof(AVPacketList));
1711
        if (!pktl) {
1712
            ret = -1;
1713
            break;
1714
        }
1715

    
1716
        /* add the packet in the buffered packet list */
1717
        *ppktl = pktl;
1718
        ppktl = &pktl->next;
1719

    
1720
        pkt = &pktl->pkt;
1721
        if (ic->format->read_packet(ic, pkt) < 0) {
1722
            ret = -1;
1723
            break;
1724
        }
1725
        st = ic->streams[pkt->stream_index];
1726

    
1727
        /* decode the data and update codec parameters */
1728
        ptr = pkt->data;
1729
        size = pkt->size;
1730
        while (size > 0) {
1731
            switch(st->codec.codec_type) {
1732
            case CODEC_TYPE_VIDEO:
1733
                ret = avcodec_decode_video(&st->codec, &picture, &got_picture, ptr, size);
1734
                break;
1735
            case CODEC_TYPE_AUDIO:
1736
                ret = avcodec_decode_audio(&st->codec, samples, &got_picture, ptr, size);
1737
                break;
1738
            default:
1739
                ret = -1;
1740
                break;
1741
            }
1742
            if (ret < 0) {
1743
                ret = -1;
1744
                goto the_end;
1745
            }
1746
            if (got_picture)
1747
                break;
1748
            ptr += ret;
1749
            size -= ret;
1750
        }
1751

    
1752
        count++;
1753
    }
1754
 the_end:
1755
    if (count > 0) {
1756
        /* close each codec */
1757
        for(i=0;i<ic->nb_streams;i++) {
1758
            st = ic->streams[i];
1759
            avcodec_close(&st->codec);
1760
        }
1761
    }
1762
    return ret;
1763
}
1764

    
1765

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

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

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

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

    
1821
    if (!ap->frame_rate)
1822
        ap->frame_rate = frame_rate;
1823
    if (!ap->width)
1824
        ap->width = frame_width;
1825
    if (!ap->height)
1826
        ap->height = frame_height;
1827
    
1828
    err = ic->format->read_header(ic, ap);
1829
    if (err < 0) {
1830
        fprintf(stderr, "%s: Error while parsing header\n", filename);
1831
        exit(1);
1832
    }
1833
    
1834
    /* If not enough info for the codecs, we decode the first frames
1835
       to get it. (used in mpeg case for example) */
1836
    ret = find_codec_parameters(ic);
1837
    if (ret < 0) {
1838
        fprintf(stderr, "%s: could not find codec parameters\n", filename);
1839
        exit(1);
1840
    }
1841

    
1842
    /* update the current parameters so that they match the one of the input stream */
1843
    for(i=0;i<ic->nb_streams;i++) {
1844
        AVCodecContext *enc = &ic->streams[i]->codec;
1845
        switch(enc->codec_type) {
1846
        case CODEC_TYPE_AUDIO:
1847
            audio_channels = enc->channels;
1848
            audio_sample_rate = enc->sample_rate;
1849
            break;
1850
        case CODEC_TYPE_VIDEO:
1851
            frame_height = enc->height;
1852
            frame_width = enc->width;
1853
            frame_rate = enc->frame_rate;
1854
            break;
1855
        }
1856
    }
1857
    
1858
    input_files[nb_input_files] = ic;
1859
    /* dump the file content */
1860
    dump_format(ic, nb_input_files, filename, 0);
1861
    nb_input_files++;
1862
    file_format = NULL;
1863
}
1864

    
1865
void opt_output_file(const char *filename)
1866
{
1867
    AVStream *st;
1868
    AVFormatContext *oc;
1869
    int use_video, use_audio, nb_streams;
1870
    int codec_id;
1871

    
1872
    if (!strcmp(filename, "-"))
1873
        filename = "pipe:";
1874

    
1875
    oc = av_mallocz(sizeof(AVFormatContext));
1876

    
1877
    if (!file_format) {
1878
        file_format = guess_format(NULL, filename, NULL);
1879
        if (!file_format)
1880
            file_format = &mpeg_mux_format;
1881
    }
1882
    
1883
    oc->format = file_format;
1884

    
1885
    if (!strcmp(file_format->name, "ffm") && 
1886
        strstart(filename, "http:", NULL)) {
1887
        /* special case for files sent to ffserver: we get the stream
1888
           parameters from ffserver */
1889
        if (read_ffserver_streams(oc, filename) < 0) {
1890
            fprintf(stderr, "Could not read stream parameters from '%s'\n", filename);
1891
            exit(1);
1892
        }
1893
    } else {
1894
        use_video = file_format->video_codec != CODEC_ID_NONE;
1895
        use_audio = file_format->audio_codec != CODEC_ID_NONE;
1896
        
1897
        if (audio_disable) {
1898
            use_audio = 0;
1899
        }
1900
        if (video_disable) {
1901
            use_video = 0;
1902
        }
1903
        
1904
        nb_streams = 0;
1905
        if (use_video) {
1906
            AVCodecContext *video_enc;
1907
            
1908
            st = av_mallocz(sizeof(AVStream));
1909
            if (!st) {
1910
                fprintf(stderr, "Could not alloc stream\n");
1911
                exit(1);
1912
            }
1913
            video_enc = &st->codec;
1914

    
1915
            codec_id = file_format->video_codec;
1916
            if (video_codec_id != CODEC_ID_NONE)
1917
                codec_id = video_codec_id;
1918

    
1919
            video_enc->codec_id = codec_id;
1920
            video_enc->codec_type = CODEC_TYPE_VIDEO;
1921
            
1922
            video_enc->bit_rate = video_bit_rate;
1923
            video_enc->frame_rate = frame_rate; 
1924
            
1925
            video_enc->width = frame_width;
1926
            video_enc->height = frame_height;
1927
            if (!intra_only)
1928
                video_enc->gop_size = gop_size;
1929
            else
1930
                video_enc->gop_size = 0;
1931
            if (video_qscale || same_quality) {
1932
                video_enc->flags |= CODEC_FLAG_QSCALE;
1933
                video_enc->quality = video_qscale;
1934
            }
1935
            /* XXX: need to find a way to set codec parameters */
1936
            if (oc->format == &ppm_format ||
1937
                oc->format == &ppmpipe_format) {
1938
                video_enc->pix_fmt = PIX_FMT_RGB24;
1939
            }
1940

    
1941
            oc->streams[nb_streams] = st;
1942
            nb_streams++;
1943
        }
1944
    
1945
        if (use_audio) {
1946
            AVCodecContext *audio_enc;
1947

    
1948
            st = av_mallocz(sizeof(AVStream));
1949
            if (!st) {
1950
                fprintf(stderr, "Could not alloc stream\n");
1951
                exit(1);
1952
            }
1953
            audio_enc = &st->codec;
1954
            codec_id = file_format->audio_codec;
1955
            if (audio_codec_id != CODEC_ID_NONE)
1956
                codec_id = audio_codec_id;
1957
            audio_enc->codec_id = codec_id;
1958
            audio_enc->codec_type = CODEC_TYPE_AUDIO;
1959
            
1960
            audio_enc->bit_rate = audio_bit_rate;
1961
            audio_enc->sample_rate = audio_sample_rate;
1962
            audio_enc->channels = audio_channels;
1963
            oc->streams[nb_streams] = st;
1964
            nb_streams++;
1965
        }
1966

    
1967
        oc->nb_streams = nb_streams;
1968

    
1969
        if (!nb_streams) {
1970
            fprintf(stderr, "No audio or video selected\n");
1971
            exit(1);
1972
        }
1973

    
1974
        if (str_title)
1975
            nstrcpy(oc->title, sizeof(oc->title), str_title);
1976
        if (str_author)
1977
            nstrcpy(oc->author, sizeof(oc->author), str_author);
1978
        if (str_copyright)
1979
            nstrcpy(oc->copyright, sizeof(oc->copyright), str_copyright);
1980
        if (str_comment)
1981
            nstrcpy(oc->comment, sizeof(oc->comment), str_comment);
1982
    }
1983

    
1984
    output_files[nb_output_files] = oc;
1985
    /* dump the file content */
1986
    dump_format(oc, nb_output_files, filename, 1);
1987
    nb_output_files++;
1988

    
1989
    strcpy(oc->filename, filename);
1990
    if (!(oc->format->flags & AVFMT_NOFILE)) {
1991
        /* test if it already exists to avoid loosing precious files */
1992
        if (!file_overwrite && 
1993
            (strchr(filename, ':') == NULL ||
1994
             strstart(filename, "file:", NULL))) {
1995
            if (url_exist(filename)) {
1996
                int c;
1997
                
1998
                printf("File '%s' already exists. Overwrite ? [y/N] ", filename);
1999
                fflush(stdout);
2000
                c = getchar();
2001
                if (toupper(c) != 'Y') {
2002
                    fprintf(stderr, "Not overwriting - exiting\n");
2003
                    exit(1);
2004
                }
2005
            }
2006
        }
2007
        
2008
        /* open the file */
2009
        if (url_fopen(&oc->pb, filename, URL_WRONLY) < 0) {
2010
            fprintf(stderr, "Could not open '%s'\n", filename);
2011
            exit(1);
2012
        }
2013
    }
2014

    
2015
    /* reset some options */
2016
    file_format = NULL;
2017
    audio_disable = 0;
2018
    video_disable = 0;
2019
    audio_codec_id = CODEC_ID_NONE;
2020
    video_codec_id = CODEC_ID_NONE;
2021
}
2022

    
2023
#ifndef CONFIG_WIN32
2024
INT64 getutime(void)
2025
{
2026
    struct rusage rusage;
2027

    
2028
    getrusage(RUSAGE_SELF, &rusage);
2029
    return (rusage.ru_utime.tv_sec * 1000000LL) + rusage.ru_utime.tv_usec;
2030
}
2031
#else
2032
INT64 getutime(void)
2033
{
2034
  return gettime();
2035
}
2036
#endif
2037

    
2038
void show_formats(void)
2039
{
2040
    AVFormat *f;
2041
    URLProtocol *up;
2042
    AVCodec *p;
2043
    const char **pp;
2044

    
2045
    printf("File formats:\n");
2046
    printf("  Encoding:");
2047
    for(f = first_format; f != NULL; f = f->next) {
2048
        if (f->write_header)
2049
            printf(" %s", f->name);
2050
    }
2051
    printf("\n");
2052
    printf("  Decoding:");
2053
    for(f = first_format; f != NULL; f = f->next) {
2054
        if (f->read_header)
2055
            printf(" %s", f->name);
2056
    }
2057
    printf("\n");
2058

    
2059
    printf("Codecs:\n");
2060
    printf("  Encoders:");
2061
    for(p = first_avcodec; p != NULL; p = p->next) {
2062
        if (p->encode)
2063
            printf(" %s", p->name);
2064
    }
2065
    printf("\n");
2066

    
2067
    printf("  Decoders:");
2068
    for(p = first_avcodec; p != NULL; p = p->next) {
2069
        if (p->decode)
2070
            printf(" %s", p->name);
2071
    }
2072
    printf("\n");
2073

    
2074
    printf("Supported file protocols:");
2075
    for(up = first_protocol; up != NULL; up = up->next)
2076
        printf(" %s:", up->name);
2077
    printf("\n");
2078
    
2079
    printf("Frame size abbreviations: sqcif qcif cif 4cif\n");
2080
    printf("Motion estimation methods:");
2081
    pp = motion_str;
2082
    while (*pp) {
2083
        printf(" %s", *pp);
2084
        if ((pp - motion_str) == ME_ZERO) 
2085
            printf("(fastest)");
2086
        else if ((pp - motion_str) == ME_FULL) 
2087
            printf("(slowest)");
2088
        else if ((pp - motion_str) == ME_LOG) 
2089
            printf("(default)");
2090
        pp++;
2091
    }
2092
    printf("\n");
2093
    exit(1);
2094
}
2095

    
2096
void show_help(void)
2097
{
2098
    const OptionDef *po;
2099
    int i, expert;
2100

    
2101
    printf("ffmpeg version " FFMPEG_VERSION ", Copyright (c) 2000,2001 Gerard Lantau\n"
2102
           "usage: ffmpeg [[options] -i input_file]... {[options] outfile}...\n"
2103
           "Hyper fast MPEG1/MPEG4/H263/RV and AC3/MPEG audio encoder\n"
2104
           "\n"
2105
           "Main options are:\n");
2106
    for(i=0;i<2;i++) {
2107
        if (i == 1)
2108
            printf("\nAdvanced options are:\n");
2109
        for(po = options; po->name != NULL; po++) {
2110
            char buf[64];
2111
            expert = (po->flags & OPT_EXPERT) != 0;
2112
            if (expert == i) {
2113
                strcpy(buf, po->name);
2114
                if (po->flags & HAS_ARG) {
2115
                    strcat(buf, " ");
2116
                    strcat(buf, po->argname);
2117
                }
2118
                printf("-%-17s  %s\n", buf, po->help);
2119
            }
2120
        }
2121
    }
2122

    
2123
    exit(1);
2124
}
2125

    
2126
const OptionDef options[] = {
2127
    { "L", 0, {(void*)show_licence}, "show license" },
2128
    { "h", 0, {(void*)show_help}, "show help" },
2129
    { "formats", 0, {(void*)show_formats}, "show available formats, codecs, protocols, ..." },
2130
    { "f", HAS_ARG, {(void*)opt_format}, "force format", "fmt" },
2131
    { "i", HAS_ARG, {(void*)opt_input_file}, "input file name", "filename" },
2132
    { "y", OPT_BOOL, {(void*)&file_overwrite}, "overwrite output files" },
2133
    { "map", HAS_ARG | OPT_EXPERT, {(void*)opt_map}, "set input stream mapping", "file:stream" },
2134
    { "t", HAS_ARG, {(void*)opt_recording_time}, "set the recording time", "duration" },
2135
    { "title", HAS_ARG | OPT_STRING, {(void*)&str_title}, "set the title", "string" },
2136
    { "author", HAS_ARG | OPT_STRING, {(void*)&str_author}, "set the author", "string" },
2137
    { "copyright", HAS_ARG | OPT_STRING, {(void*)&str_copyright}, "set the copyright", "string" },
2138
    { "comment", HAS_ARG | OPT_STRING, {(void*)&str_comment}, "set the comment", "string" },
2139
    /* video options */
2140
    { "b", HAS_ARG, {(void*)opt_video_bitrate}, "set video bitrate (in kbit/s)", "bitrate" },
2141
    { "r", HAS_ARG, {(void*)opt_frame_rate}, "set frame rate (in Hz)", "rate" },
2142
    { "s", HAS_ARG, {(void*)opt_frame_size}, "set frame size (WxH or abbreviation)", "size" },
2143
    { "g", HAS_ARG | OPT_EXPERT, {(void*)opt_gop_size}, "set the group of picture size", "gop_size" },
2144
    { "intra", OPT_BOOL | OPT_EXPERT, {(void*)&intra_only}, "use only intra frames"},
2145
    { "vn", OPT_BOOL, {(void*)&video_disable}, "disable video" },
2146
    { "qscale", HAS_ARG | OPT_EXPERT, {(void*)opt_qscale}, "use fixed video quantiser scale (VBR)", "q" },
2147
#ifdef CONFIG_GRAB
2148
    { "vd", HAS_ARG | OPT_EXPERT, {(void*)opt_video_device}, "set video device", "device" },
2149
#endif
2150
    { "vcodec", HAS_ARG | OPT_EXPERT, {(void*)opt_video_codec}, "force video codec", "codec" },
2151
    { "me", HAS_ARG | OPT_EXPERT, {(void*)opt_motion_estimation}, "set motion estimation method", 
2152
      "method" },
2153
    { "sameq", OPT_BOOL, {(void*)&same_quality}, 
2154
      "use same video quality as source (implies VBR)" },
2155
    /* audio options */
2156
    { "ab", HAS_ARG, {(void*)opt_audio_bitrate}, "set audio bitrate (in kbit/s)", "bitrate", },
2157
    { "ar", HAS_ARG, {(void*)opt_audio_rate}, "set audio sampling rate (in Hz)", "rate" },
2158
    { "ac", HAS_ARG, {(void*)opt_audio_channels}, "set number of audio channels", "channels" },
2159
    { "an", OPT_BOOL, {(void*)&audio_disable}, "disable audio" },
2160
#ifdef CONFIG_GRAB
2161
    { "ad", HAS_ARG | OPT_EXPERT, {(void*)opt_audio_device}, "set audio device", "device" },
2162
#endif
2163
    { "acodec", HAS_ARG | OPT_EXPERT, {(void*)opt_audio_codec}, "force audio codec", "codec" },
2164
    { "deinterlace", OPT_BOOL | OPT_EXPERT, {(void*)&do_deinterlace}, 
2165
      "deinterlace pictures" },
2166
    { "benchmark", OPT_BOOL | OPT_EXPERT, {(void*)&do_benchmark}, 
2167
      "add timings for benchmarking" },
2168

    
2169
    { NULL, },
2170
};
2171

    
2172
int main(int argc, char **argv)
2173
{
2174
    int optindex, i;
2175
    const char *opt, *arg;
2176
    const OptionDef *po;
2177
    
2178
    register_all();
2179

    
2180
    if (argc <= 1)
2181
        show_help();
2182

    
2183
    optindex = 1;
2184
    while (optindex < argc) {
2185
        opt = argv[optindex++];
2186
        
2187
        if (opt[0] == '-' && opt[1] != '\0') {
2188
            po = options;
2189
            while (po->name != NULL) {
2190
                if (!strcmp(opt + 1, po->name))
2191
                    break;
2192
                po++;
2193
            }
2194
            if (!po->name) {
2195
                fprintf(stderr, "%s: unrecognized option '%s'\n", argv[0], opt);
2196
                exit(1);
2197
            }
2198
            arg = NULL;
2199
            if (po->flags & HAS_ARG)
2200
                arg = argv[optindex++];
2201
            if (po->flags & OPT_STRING) {
2202
                char *str;
2203
                str = strdup(arg);
2204
                *po->u.str_arg = str;
2205
            } else if (po->flags & OPT_BOOL) {
2206
                *po->u.int_arg = 1;
2207
            } else {
2208
                po->u.func_arg(arg);
2209
            }
2210
        } else {
2211
            opt_output_file(opt);
2212
        }
2213
    }
2214

    
2215

    
2216
    if (nb_input_files == 0) {
2217
#ifdef CONFIG_GRAB
2218
        if (nb_output_files != 1) {
2219
            fprintf(stderr, "Only one output file supported when grabbing\n");
2220
            exit(1);
2221
        }
2222
        av_grab(output_files[0]);
2223
#else
2224
        fprintf(stderr, "Must supply at least one input file\n");
2225
#endif
2226
    } else {
2227
        INT64 ti;
2228

    
2229
        if (nb_output_files <= 0) {
2230
            fprintf(stderr, "Must supply at least one output file\n");
2231
            exit(1);
2232
        }
2233
        ti = getutime();
2234
        av_encode(output_files, nb_output_files, input_files, nb_input_files, 
2235
                  stream_maps, nb_stream_maps);
2236
        ti = getutime() - ti;
2237
        if (do_benchmark) {
2238
            printf("bench: utime=%0.3fs\n", ti / 1000000.0);
2239
        }
2240
    }
2241

    
2242
    /* close files */
2243
    for(i=0;i<nb_output_files;i++) {
2244
        if (!(output_files[i]->format->flags & AVFMT_NOFILE)) 
2245
            url_fclose(&output_files[i]->pb);
2246
    }
2247
    for(i=0;i<nb_input_files;i++) {
2248
        if (!(input_files[i]->format->flags & AVFMT_NOFILE)) 
2249
            url_fclose(&input_files[i]->pb);
2250
    }
2251

    
2252
    return 0;
2253
}