Statistics
| Branch: | Revision:

ffmpeg / ffmpeg.c @ 5727b222

History | View | Annotate | Download (65 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
#include <stdlib.h>
20
#include <stdio.h>
21
#include <unistd.h>
22
#include <fcntl.h>
23
#include <sys/ioctl.h>
24
#include <errno.h>
25
#include <sys/time.h>
26
#include <string.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

    
33
#include "avformat.h"
34

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

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

    
57
extern const OptionDef options[];
58

    
59
void show_help(void);
60

    
61
#define MAX_FILES 20
62

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

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

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

    
72
static AVFormat *file_format;
73
static int frame_width  = 160;
74
static int frame_height = 128;
75
static int frame_rate = 25 * FRAME_RATE_BASE;
76
static int video_bit_rate = 200000;
77
static int video_qscale = 0;
78
static int video_disable = 0;
79
static int video_codec_id = CODEC_ID_NONE;
80
static int same_quality = 0;
81

    
82
static int gop_size = 12;
83
static int intra_only = 0;
84
static int audio_sample_rate = 44100;
85
static int audio_bit_rate = 64000;
86
static int audio_disable = 0;
87
static int audio_channels = 1;
88
static int audio_codec_id = CODEC_ID_NONE;
89

    
90
static INT64 recording_time = 0;
91
static int file_overwrite = 0;
92
static char *str_title = NULL;
93
static char *str_author = NULL;
94
static char *str_copyright = NULL;
95
static char *str_comment = NULL;
96
static int do_benchmark = 0;
97

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

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

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

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

    
137
/* init terminal so that we can grab keys */
138
static struct termios oldtty;
139

    
140
static void term_exit(void)
141
{
142
    tcsetattr (0, TCSANOW, &oldtty);
143
}
144

    
145
static void term_init(void)
146
{
147
    struct termios tty;
148

    
149
    tcgetattr (0, &tty);
150
    oldtty = tty;
151

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

    
163
    atexit(term_exit);
164
}
165

    
166
/* read a key without blocking */
167
static int read_key(void)
168
{
169
    struct timeval tv;
170
    int n;
171
    unsigned char ch;
172
    fd_set rfds;
173

    
174
    FD_ZERO(&rfds);
175
    FD_SET(0, &rfds);
176
    tv.tv_sec = 0;
177
    tv.tv_usec = 0;
178
    n = select(1, &rfds, NULL, NULL, &tv);
179
    if (n > 0) {
180
        if (read(0, &ch, 1) == 1)
181
            return ch;
182
    }
183
    return -1;
184
}
185

    
186
#define AUDIO_FIFO_SIZE 8192
187

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

    
209
    /* init output stream info */
210
    for(i=0;i<s->nb_streams;i++)
211
        ost_table[i] = NULL;
212

    
213
    /* output stream init */
214
    for(i=0;i<s->nb_streams;i++) {
215
        ost = av_mallocz(sizeof(AVOutputStream));
216
        if (!ost)
217
            goto fail;
218
        ost->index = i;
219
        ost->st = s->streams[i];
220
        ost_table[i] = ost;
221
    }
222

    
223
    use_audio = 0;
224
    use_video = 0;
225
    frame_rate = 0;
226
    sample_rate = 0;
227
    frame_size = 0;
228
    channels = 1;
229
    width = 0;
230
    height = 0;
231
    frame_number = 0;
232
    
233
    for(i=0;i<s->nb_streams;i++) {
234
        AVCodec *codec;
235

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

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

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

    
345
    if (!use_video && !use_audio) {
346
        fprintf(stderr,"Could not open grab devices : exiting\n");
347
        exit(1);
348
    }
349

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

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

    
391
    s->format->write_header(s);
392
    time_start = gettime();
393
    term_init();
394
    
395
    for(;;) {
396
        /* if 'q' pressed, exits */
397
        if (read_key() == 'q')
398
            break;
399

    
400
        /* read & compress audio frames */
401
        if (use_audio) {
402
            int ret, nb_samples, nb_samples_out;
403
            UINT8 *buftmp;
404

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

    
451
        if (use_video) {
452
            AVPicture *picture1;
453
            AVPicture picture;
454
            UINT8 *pict_buffer;
455

    
456
            ret = url_read(video_handle, picture_in_buf, picture_size);
457
            if (ret < 0)
458
                break;
459
            if (pix_fmt != PIX_FMT_YUV420P) {
460
                pict_buffer = picture_420p;
461
                img_convert_to_yuv420(pict_buffer, picture_in_buf, pix_fmt, width, height);
462
            } else {
463
                pict_buffer = picture_in_buf;
464
            }
465
            /* build a picture storage */
466
            picture.data[0] = pict_buffer;
467
            picture.data[1] = picture.data[0] + width * height;
468
            picture.data[2] = picture.data[1] + (width * height) / 4;
469
            picture.linesize[0] = width;
470
            picture.linesize[1] = width / 2;
471
            picture.linesize[2] = width / 2;
472
            
473
            for(i=0;i<s->nb_streams;i++) {
474
                ost = ost_table[i];
475
                enc = &ost->st->codec;
476
                if (enc->codec_type == CODEC_TYPE_VIDEO) {
477
                    int n1, n2, nb;
478

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

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

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

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

    
549
    if (video_handle)
550
        url_close(video_handle);
551

    
552
    /* write report */
553
    {
554
        float ti, bitrate;
555
        INT64 total_size;
556

    
557
        total_size = url_ftell(&s->pb);
558

    
559
        ti = (gettime() - time_start) / 1000000.0;
560
        if (ti < 0.1)
561
            ti = 0.1;
562
        bitrate = (int)((total_size * 8) / ti / 1000.0);
563

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

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

    
597
int read_ffserver_streams(AVFormatContext *s, const char *filename)
598
{
599
    int i;
600
    AVFormatContext *ic;
601

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

    
614
    av_close_input_file(ic);
615
    return 0;
616
}
617

    
618
#define MAX_AUDIO_PACKET_SIZE 16384
619

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

    
631
    enc = &ost->st->codec;
632

    
633
    if (ost->audio_resample) {
634
        buftmp = audio_buf;
635
        size_out = audio_resample(ost->resample, 
636
                                  (short *)buftmp, (short *)buf,
637
                                  size / (ist->st->codec.channels * 2));
638
        size_out = size_out * enc->channels * 2;
639
    } else {
640
        buftmp = buf;
641
        size_out = size;
642
    }
643

    
644
    /* now encode as many frames as possible */
645
    if (enc->codec_id != CODEC_ID_PCM) {
646
        /* output resampled raw samples */
647
        fifo_write(&ost->fifo, buftmp, size_out, 
648
                   &ost->fifo.wptr);
649

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

    
664
/* write a picture to a raw mux */
665
static void write_picture(AVFormatContext *s, int index, AVPicture *picture, int w, int h)
666
{
667
    UINT8 *buf, *src, *dest;
668
    int size, j, i;
669
    /* XXX: not efficient, should add test if we can take
670
       directly the AVPicture */
671
    size = (w * h) * 3 / 2; 
672
    buf = malloc(size);
673
    dest = buf;
674
    for(i=0;i<3;i++) {
675
        if (i == 1) {
676
            w >>= 1;
677
            h >>= 1;
678
        }
679
        src = picture->data[i];
680
        for(j=0;j<h;j++) {
681
            memcpy(dest, src, w);
682
            dest += w;
683
            src += picture->linesize[i];
684
        }
685
    }
686
    s->format->write_packet(s, index, buf, size);
687
    free(buf);
688
}
689

    
690

    
691
static void do_video_out(AVFormatContext *s, 
692
                         AVOutputStream *ost, 
693
                         AVInputStream *ist,
694
                         AVPicture *pict)
695
{
696
    int n1, n2, nb, i, ret, frame_number;
697
    AVPicture *picture;
698
    UINT8 video_buffer[128*1024];
699
    AVCodecContext *enc;
700

    
701
    enc = &ost->st->codec;
702

    
703
    frame_number = ist->frame_number;
704
    /* first drop frame if needed */
705
    n1 = ((INT64)frame_number * enc->frame_rate) / ist->st->codec.frame_rate;
706
    n2 = (((INT64)frame_number + 1) * enc->frame_rate) / ist->st->codec.frame_rate;
707
    nb = n2 - n1;
708
    if (nb <= 0)
709
        return;
710
    
711
    if (ost->video_resample) {
712
        picture = &ost->pict_tmp;
713
        img_resample(ost->img_resample_ctx, picture, pict);
714
    } else {
715
        picture = pict;
716
    }
717

    
718
    /* duplicates frame if needed */
719
    /* XXX: pb because no interleaving */
720
    for(i=0;i<nb;i++) {
721
        if (enc->codec_id != CODEC_ID_RAWVIDEO) {
722
            /* handles sameq here. This is not correct because it may
723
               not be a global option */
724
            if (same_quality) {
725
                ost->st->codec.quality = ist->st->codec.quality;
726
            }
727
            ret = avcodec_encode_video(&ost->st->codec, 
728
                                       video_buffer, sizeof(video_buffer), 
729
                                       picture);
730
            s->format->write_packet(s, ost->index, video_buffer, ret);
731
        } else {
732
            write_picture(s, ost->index, picture, enc->width, enc->height);
733
        }
734
    }
735
}
736

    
737
//#define HEX_DUMP
738

    
739
#ifdef HEX_DUMP
740
static void hex_dump(UINT8 *buf, int size)
741
{
742
    int len, i, j, c;
743

    
744
    for(i=0;i<size;i+=16) {
745
        len = size - i;
746
        if (len > 16)
747
            len = 16;
748
        printf("%08x ", i);
749
        for(j=0;j<16;j++) {
750
            if (j < len)
751
                printf(" %02x", buf[i+j]);
752
            else
753
                printf("   ");
754
        }
755
        printf(" ");
756
        for(j=0;j<len;j++) {
757
            c = buf[i+j];
758
            if (c < ' ' || c > '~')
759
                c = '.';
760
            printf("%c", c);
761
        }
762
        printf("\n");
763
    }
764
}
765
#endif
766

    
767
/*
768
 * The following code is the main loop of the file converter
769
 */
770
static int av_encode(AVFormatContext **output_files,
771
                     int nb_output_files,
772
                     AVFormatContext **input_files,
773
                     int nb_input_files,
774
                     AVStreamMap *stream_maps, int nb_stream_maps)
775
{
776
    int ret, i, j, k, n, nb_istreams, nb_ostreams = 0;
777
    AVFormatContext *is, *os;
778
    AVCodecContext *codec, *icodec;
779
    AVOutputStream *ost, **ost_table = NULL;
780
    AVInputStream *ist, **ist_table = NULL;
781
    INT64 min_pts, start_time;
782
    AVInputFile file_table[nb_input_files];
783

    
784
    memset(file_table, 0, sizeof(file_table));
785
    
786
    /* input stream init */
787
    j = 0;
788
    for(i=0;i<nb_input_files;i++) {
789
        is = input_files[i];
790
        file_table[i].ist_index = j;
791
        j += is->nb_streams;
792
    }
793
    nb_istreams = j;
794

    
795
    ist_table = av_mallocz(nb_istreams * sizeof(AVInputStream *));
796
    if (!ist_table)
797
        return -ENOMEM;
798
    
799
    for(i=0;i<nb_istreams;i++) {
800
        ist = av_mallocz(sizeof(AVInputStream));
801
        if (!ist)
802
            goto fail;
803
        ist_table[i] = ist;
804
    }
805
    j = 0;
806
    for(i=0;i<nb_input_files;i++) {
807
        is = input_files[i];
808
        for(k=0;k<is->nb_streams;k++) {
809
            ist = ist_table[j++];
810
            ist->st = is->streams[k];
811
            ist->file_index = i;
812
            ist->index = k;
813
            ist->discard = 1; /* the stream is discarded by default
814
                                 (changed later) */
815
        }
816
    }
817

    
818
    /* output stream init */
819
    nb_ostreams = 0;
820
    for(i=0;i<nb_output_files;i++) {
821
        os = output_files[i];
822
        nb_ostreams += os->nb_streams;
823
    }
824
    if (nb_stream_maps > 0 && nb_stream_maps != nb_ostreams) {
825
        fprintf(stderr, "Number of stream maps must match number of output streams\n");
826
        exit(1);
827
    }
828

    
829
    ost_table = av_mallocz(sizeof(AVOutputStream *) * nb_ostreams);
830
    if (!ost_table)
831
        goto fail;
832
    for(i=0;i<nb_ostreams;i++) {
833
        ost = av_mallocz(sizeof(AVOutputStream));
834
        if (!ost)
835
            goto fail;
836
        ost_table[i] = ost;
837
    }
838
    
839
    n = 0;
840
    for(k=0;k<nb_output_files;k++) {
841
        os = output_files[k];
842
        for(i=0;i<os->nb_streams;i++) {
843
            int found;
844
            ost = ost_table[n++];
845
            ost->file_index = k;
846
            ost->index = i;
847
            ost->st = os->streams[i];
848
            if (nb_stream_maps > 0) {
849
                ost->source_index = file_table[stream_maps[n-1].file_index].ist_index + 
850
                    stream_maps[n-1].stream_index;
851
            } else {
852
                /* get corresponding input stream index : we select the first one with the right type */
853
                found = 0;
854
                for(j=0;j<nb_istreams;j++) {
855
                    ist = ist_table[j];
856
                    if (ist->discard && 
857
                        ist->st->codec.codec_type == ost->st->codec.codec_type) {
858
                        ost->source_index = j;
859
                        found = 1;
860
                    }
861
                }
862
                
863
                if (!found) {
864
                    /* try again and reuse existing stream */
865
                    for(j=0;j<nb_istreams;j++) {
866
                        ist = ist_table[j];
867
                        if (ist->st->codec.codec_type == ost->st->codec.codec_type) {
868
                            ost->source_index = j;
869
                            found = 1;
870
                        }
871
                    }
872
                    if (!found) {
873
                        fprintf(stderr, "Could not find input stream matching output stream #%d.%d\n",
874
                                ost->file_index, ost->index);
875
                        exit(1);
876
                    }
877
                }
878
            }
879
            ist = ist_table[ost->source_index];
880
            ist->discard = 0;
881
        }
882
    }
883

    
884
    /* dump the stream mapping */
885
    fprintf(stderr, "Stream mapping:\n");
886
    for(i=0;i<nb_ostreams;i++) {
887
        ost = ost_table[i];
888
        fprintf(stderr, "  Stream #%d.%d -> #%d.%d\n",
889
                ist_table[ost->source_index]->file_index,
890
                ist_table[ost->source_index]->index,
891
                ost->file_index, 
892
                ost->index);
893
    }
894

    
895
    /* for each output stream, we compute the right encoding parameters */
896
    for(i=0;i<nb_ostreams;i++) {
897
        ost = ost_table[i];
898
        ist = ist_table[ost->source_index];
899

    
900
        codec = &ost->st->codec;
901
        icodec = &ist->st->codec;
902

    
903
        switch(codec->codec_type) {
904
        case CODEC_TYPE_AUDIO:
905
            /* check if same codec with same parameters. If so, no
906
               reencoding is needed */
907
            if (codec->codec_id == icodec->codec_id &&
908
                codec->bit_rate == icodec->bit_rate &&
909
                codec->sample_rate == icodec->sample_rate &&
910
                codec->channels == icodec->channels) {
911
                /* no reencoding */
912
            } else {
913
                if (fifo_init(&ost->fifo, 2 * MAX_AUDIO_PACKET_SIZE))
914
                    goto fail;
915

    
916
                if (codec->channels == icodec->channels &&
917
                    codec->sample_rate == icodec->sample_rate) {
918
                    ost->audio_resample = 0;
919
                } else {
920
                    ost->audio_resample = 1;
921
                    ost->resample = audio_resample_init(codec->channels, icodec->channels,
922
                                                        codec->sample_rate, 
923
                                                        icodec->sample_rate);
924
                }
925
                ist->decoding_needed = 1;
926
                ost->encoding_needed = 1;
927
            }
928
            break;
929
        case CODEC_TYPE_VIDEO:
930
            /* check if same codec with same parameters. If so, no
931
               reencoding is needed */
932
            if (codec->codec_id == icodec->codec_id &&
933
                codec->bit_rate == icodec->bit_rate &&
934
                codec->frame_rate == icodec->frame_rate &&
935
                codec->width == icodec->width &&
936
                codec->height == icodec->height) {
937
                /* no reencoding */
938
            } else {
939
                if (codec->width == icodec->width &&
940
                    codec->height == icodec->height) {
941
                    ost->video_resample = 0;
942
                } else {
943
                    UINT8 *buf;
944
                    ost->video_resample = 1;
945
                    buf = malloc((codec->width * codec->height * 3) / 2);
946
                    if (!buf)
947
                        goto fail;
948
                    ost->pict_tmp.data[0] = buf;
949
                    ost->pict_tmp.data[1] = ost->pict_tmp.data[0] + (codec->width * codec->height);
950
                    ost->pict_tmp.data[2] = ost->pict_tmp.data[1] + (codec->width * codec->height) / 4;
951
                    ost->pict_tmp.linesize[0] = codec->width;
952
                    ost->pict_tmp.linesize[1] = codec->width / 2;
953
                    ost->pict_tmp.linesize[2] = codec->width / 2;
954

    
955
                    ost->img_resample_ctx = img_resample_init( 
956
                                      ost->st->codec.width, ost->st->codec.height,
957
                                      ist->st->codec.width, ist->st->codec.height);
958
                }
959
                ost->encoding_needed = 1;
960
                ist->decoding_needed = 1;
961
            }
962
            break;
963
        }
964
    }
965

    
966
    /* open each encoder */
967
    for(i=0;i<nb_ostreams;i++) {
968
        ost = ost_table[i];
969
        if (ost->encoding_needed) {
970
            AVCodec *codec;
971
            codec = avcodec_find_encoder(ost->st->codec.codec_id);
972
            if (!codec) {
973
                fprintf(stderr, "Unsupported codec for output stream #%d.%d\n", 
974
                        ost->file_index, ost->index);
975
                exit(1);
976
            }
977
            if (avcodec_open(&ost->st->codec, codec) < 0) {
978
                fprintf(stderr, "Error while opening codec for stream #%d.%d - maybe incorrect parameters such as bit_rate, rate, width or height\n", 
979
                        ost->file_index, ost->index);
980
                exit(1);
981
            }
982
        }
983
    }
984

    
985
    /* open each decoder */
986
    for(i=0;i<nb_istreams;i++) {
987
        ist = ist_table[i];
988
        if (ist->decoding_needed) {
989
            AVCodec *codec;
990
            codec = avcodec_find_decoder(ist->st->codec.codec_id);
991
            if (!codec) {
992
                fprintf(stderr, "Unsupported codec for input stream #%d.%d\n", 
993
                        ist->file_index, ist->index);
994
                exit(1);
995
            }
996
            if (avcodec_open(&ist->st->codec, codec) < 0) {
997
                fprintf(stderr, "Error while opening codec for input stream #%d.%d\n", 
998
                        ist->file_index, ist->index);
999
                exit(1);
1000
            }
1001
        }
1002
    }
1003

    
1004
    /* init pts */
1005
    for(i=0;i<nb_istreams;i++) {
1006
        ist = ist_table[i];
1007
        ist->pts = 0;
1008
        ist->frame_number = 0;
1009
    }
1010
    
1011
    /* compute buffer size max (should use a complete heuristic) */
1012
    for(i=0;i<nb_input_files;i++) {
1013
        file_table[i].buffer_size_max = 2048;
1014
    }
1015

    
1016
    /* open files and write file headers */
1017
    for(i=0;i<nb_output_files;i++) {
1018
        os = output_files[i];
1019
        os->format->write_header(os);
1020
    }
1021

    
1022
    start_time = gettime();
1023
    min_pts = 0;
1024
    for(;;) {
1025
        int file_index, ist_index;
1026
        AVPacket pkt;
1027
        UINT8 *ptr;
1028
        int len;
1029
        UINT8 *data_buf;
1030
        int data_size, got_picture;
1031
        AVPicture picture;
1032
        short samples[AVCODEC_MAX_AUDIO_FRAME_SIZE / 2];
1033

    
1034
        /* select the input file with the smallest pts */
1035
    redo:
1036
        file_index = -1;
1037
        min_pts = (1ULL << 63) - 1;
1038
        for(i=0;i<nb_istreams;i++) {
1039
            ist = ist_table[i];
1040
            if (!ist->discard && !file_table[ist->file_index].eof_reached && ist->pts < min_pts) {
1041
                min_pts = ist->pts;
1042
                file_index = ist->file_index;
1043
            }
1044
        }
1045
        /* if none, if is finished */
1046
        if (file_index < 0)
1047
            break;
1048
        /* finish if recording time exhausted */
1049
        if (recording_time > 0 && min_pts >= recording_time)
1050
            break;
1051
        /* read a packet from it and output it in the fifo */
1052
        
1053
        is = input_files[file_index];
1054
        if (av_read_packet(is, &pkt) < 0) {
1055
            file_table[file_index].eof_reached = 1;
1056
            continue;
1057
        }
1058
        ist_index = file_table[file_index].ist_index + pkt.stream_index;
1059
        ist = ist_table[ist_index];
1060
        if (ist->discard) {
1061
            continue;
1062
        }
1063

    
1064
#ifdef HEX_DUMP
1065
        printf("stream #%d, size=%d:\n", pkt.stream_index, pkt.size);
1066
        hex_dump(pkt.data, pkt.size);
1067
#endif
1068

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

    
1071
        len = pkt.size;
1072
        ptr = pkt.data;
1073
        while (len > 0) {
1074

    
1075
            /* decode the packet if needed */
1076
            data_buf = NULL; /* fail safe */
1077
            data_size = 0;
1078
            if (ist->decoding_needed) {
1079
                switch(ist->st->codec.codec_type) {
1080
                case CODEC_TYPE_AUDIO:
1081
                    if (ist->st->codec.codec_id == CODEC_ID_PCM) {
1082
                        /* no need to call a codec */
1083
                        data_buf = ptr;
1084
                        data_size = len;
1085
                        ret = len;
1086
                    } else {
1087
                        ret = avcodec_decode_audio(&ist->st->codec, samples, &data_size,
1088
                                                   ptr, len);
1089
                        if (ret < 0)
1090
                            goto fail_decode;
1091
                        if (data_size == 0) {
1092
                            /* no audio frame */
1093
                            ptr += ret;
1094
                            len -= ret;
1095
                            continue;
1096
                        }
1097
                        data_buf = (UINT8 *)samples;
1098
                    }
1099
                    break;
1100
                case CODEC_TYPE_VIDEO:
1101
                    if (ist->st->codec.codec_id == CODEC_ID_RAWVIDEO) {
1102
                        int size;
1103
                        size = (ist->st->codec.width * ist->st->codec.height);
1104
                        
1105
                        picture.data[0] = ptr;
1106
                        picture.data[1] = picture.data[0] + size;
1107
                        picture.data[2] = picture.data[1] + size / 4;
1108
                        picture.linesize[0] = ist->st->codec.width;
1109
                        picture.linesize[1] = ist->st->codec.width / 2;
1110
                        picture.linesize[2] = ist->st->codec.width / 2;
1111
                        ret = len;
1112
                    } else {
1113
                        data_size = (ist->st->codec.width * ist->st->codec.height * 3) / 2;
1114
                        ret = avcodec_decode_video(&ist->st->codec, 
1115
                                                   &picture, &got_picture, ptr, len);
1116
                        if (ret < 0) {
1117
                        fail_decode:
1118
                            fprintf(stderr, "Error while decoding stream #%d.%d\n",
1119
                                    ist->file_index, ist->index);
1120
                            av_free_packet(&pkt);
1121
                            goto redo;
1122
                        }
1123
                        if (!got_picture) {
1124
                            /* no picture yet */
1125
                            ptr += ret;
1126
                            len -= ret;
1127
                            continue;
1128
                        }
1129
                    }
1130
                    break;
1131
                default:
1132
                    goto fail_decode;
1133
                }
1134
            } else {
1135
                data_buf = ptr;
1136
                data_size = len;
1137
                ret = len;
1138
            }
1139
            /* update pts */
1140
            switch(ist->st->codec.codec_type) {
1141
            case CODEC_TYPE_AUDIO:
1142
                ist->pts = (INT64)1000000 * ist->sample_index / ist->st->codec.sample_rate;
1143
                ist->sample_index += data_size / (2 * ist->st->codec.channels);
1144
                break;
1145
            case CODEC_TYPE_VIDEO:
1146
                ist->frame_number++;
1147
                ist->pts = ((INT64)ist->frame_number * 1000000 * FRAME_RATE_BASE) / 
1148
                    ist->st->codec.frame_rate;
1149
                break;
1150
            }
1151
            ptr += ret;
1152
            len -= ret;
1153

    
1154
            /* transcode raw format, encode packets and output them */
1155
            
1156
            for(i=0;i<nb_ostreams;i++) {
1157
                ost = ost_table[i];
1158
                if (ost->source_index == ist_index) {
1159
                    os = output_files[ost->file_index];
1160

    
1161
                    if (ost->encoding_needed) {
1162
                        switch(ost->st->codec.codec_type) {
1163
                        case CODEC_TYPE_AUDIO:
1164
                            do_audio_out(os, ost, ist, data_buf, data_size);
1165
                            break;
1166
                        case CODEC_TYPE_VIDEO:
1167
                            do_video_out(os, ost, ist, &picture);
1168
                            break;
1169
                        }
1170
                    } else {
1171
                        /* no reencoding needed : output the packet directly */
1172
                        os->format->write_packet(os, ost->index, data_buf, data_size);
1173
                    }
1174
                }
1175
            }
1176
        }
1177
        av_free_packet(&pkt);
1178
        
1179
        /* dump report by using the first video and audio streams */
1180
        {
1181
            char buf[1024];
1182
            AVFormatContext *oc;
1183
            INT64 total_size, ti;
1184
            AVCodecContext *enc;
1185
            int frame_number, vid;
1186
            double bitrate, ti1;
1187
            static INT64 last_time;
1188

    
1189
            if ((min_pts - last_time) >= 500000) {
1190
                last_time = min_pts;
1191
                
1192
                oc = output_files[0];
1193
                
1194
                total_size = url_ftell(&oc->pb);
1195
                
1196
                buf[0] = '\0';
1197
                ti = (1ULL << 63) - 1;
1198
                vid = 0;
1199
                for(i=0;i<nb_ostreams;i++) {
1200
                    ost = ost_table[i];
1201
                    enc = &ost->st->codec;
1202
                    ist = ist_table[ost->source_index];
1203
                    if (!vid && enc->codec_type == CODEC_TYPE_VIDEO) {
1204
                        frame_number = ist->frame_number;
1205
                        sprintf(buf + strlen(buf), "frame=%5d q=%2d ",
1206
                                frame_number, enc->quality);
1207
                        vid = 1;
1208
                    }
1209
                    /* compute min pts value */
1210
                    if (!ist->discard && ist->pts < ti) {
1211
                        ti = ist->pts;
1212
                    }
1213
                }
1214

    
1215
                ti1 = ti / 1000000.0;
1216
                if (ti1 < 0.1)
1217
                    ti1 = 0.1;
1218
                bitrate = (double)(total_size * 8) / ti1 / 1000.0;
1219

    
1220
                sprintf(buf + strlen(buf), "size=%8LdkB time=%0.1f bitrate=%6.1fkbits/s", 
1221
                        total_size / 1024, ti1, bitrate);
1222
                
1223
                fprintf(stderr, "%s    \r", buf);
1224
                fflush(stderr);
1225
            }
1226
        }
1227
    }
1228

    
1229
    /* dump report by using the first video and audio streams */
1230
    {
1231
        char buf[1024];
1232
        AVFormatContext *oc;
1233
        INT64 total_size, ti;
1234
        AVCodecContext *enc;
1235
        int frame_number, vid;
1236
        double bitrate, ti1;
1237

    
1238
        oc = output_files[0];
1239
        
1240
        total_size = url_ftell(&oc->pb);
1241
        
1242
        buf[0] = '\0';
1243
        ti = (1ULL << 63) - 1;
1244
        vid = 0;
1245
        for(i=0;i<nb_ostreams;i++) {
1246
            ost = ost_table[i];
1247
            enc = &ost->st->codec;
1248
            ist = ist_table[ost->source_index];
1249
            if (!vid && enc->codec_type == CODEC_TYPE_VIDEO) {
1250
                frame_number = ist->frame_number;
1251
                sprintf(buf + strlen(buf), "frame=%5d q=%2d ",
1252
                        frame_number, enc->quality);
1253
                vid = 1;
1254
            }
1255
            /* compute min pts value */
1256
            if (!ist->discard && ist->pts < ti) {
1257
                ti = ist->pts;
1258
            }
1259
        }
1260
        
1261
        ti1 = ti / 1000000.0;
1262
        if (ti1 < 0.1)
1263
            ti1 = 0.1;
1264
        bitrate = (double)(total_size * 8) / ti1 / 1000.0;
1265
        
1266
        sprintf(buf + strlen(buf), "size=%8LdkB time=%0.1f bitrate=%6.1fkbits/s", 
1267
                total_size / 1024, ti1, bitrate);
1268
        
1269
        fprintf(stderr, "%s    \n", buf);
1270
    }
1271
    /* close each encoder */
1272
    for(i=0;i<nb_ostreams;i++) {
1273
        ost = ost_table[i];
1274
        if (ost->encoding_needed) {
1275
            avcodec_close(&ost->st->codec);
1276
        }
1277
    }
1278
    
1279
    /* close each decoder */
1280
    for(i=0;i<nb_istreams;i++) {
1281
        ist = ist_table[i];
1282
        if (ist->decoding_needed) {
1283
            avcodec_close(&ist->st->codec);
1284
        }
1285
    }
1286
    
1287

    
1288
    /* write the trailer if needed and close file */
1289
    for(i=0;i<nb_output_files;i++) {
1290
        os = output_files[i];
1291
        os->format->write_trailer(os);
1292
    }
1293
    /* finished ! */
1294
    
1295
    ret = 0;
1296
 fail1:
1297
    if (ist_table) {
1298
        for(i=0;i<nb_istreams;i++) {
1299
            ist = ist_table[i];
1300
            if (ist) {
1301
                free(ist);
1302
            }
1303
        }
1304
        free(ist_table);
1305
    }
1306
    if (ost_table) {
1307
        for(i=0;i<nb_ostreams;i++) {
1308
            ost = ost_table[i];
1309
            if (ost) {
1310
                if (ost->pict_tmp.data[0])
1311
                    free(ost->pict_tmp.data[0]);
1312
                if (ost->video_resample)
1313
                    img_resample_close(ost->img_resample_ctx);
1314
                if (ost->audio_resample)
1315
                    audio_resample_close(ost->resample);
1316
                free(ost);
1317
            }
1318
        }
1319
        free(ost_table);
1320
    }
1321
    return ret;
1322
 fail:
1323
    ret = -ENOMEM;
1324
    goto fail1;
1325
}
1326

    
1327
#if 0
1328
int file_read(const char *filename)
1329
{
1330
    URLContext *h;
1331
    unsigned char buffer[1024];
1332
    int len, i;
1333

1334
    if (url_open(&h, filename, O_RDONLY) < 0) {
1335
        printf("could not open '%s'\n", filename);
1336
        return -1;
1337
    }
1338
    for(;;) {
1339
        len = url_read(h, buffer, sizeof(buffer));
1340
        if (len <= 0)
1341
            break;
1342
        for(i=0;i<len;i++) putchar(buffer[i]);
1343
    }
1344
    url_close(h);
1345
    return 0;
1346
}
1347
#endif
1348

    
1349
void show_licence(void)
1350
{
1351
    printf(
1352
    "ffmpeg version " FFMPEG_VERSION "\n"
1353
    "Copyright (c) 2000,2001 Gerard Lantau\n"
1354
    "This program is free software; you can redistribute it and/or modify\n"
1355
    "it under the terms of the GNU General Public License as published by\n"
1356
    "the Free Software Foundation; either version 2 of the License, or\n"
1357
    "(at your option) any later version.\n"
1358
    "\n"
1359
    "This program is distributed in the hope that it will be useful,\n"
1360
    "but WITHOUT ANY WARRANTY; without even the implied warranty of\n"
1361
    "MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n"
1362
    "GNU General Public License for more details.\n"
1363
    "\n"
1364
    "You should have received a copy of the GNU General Public License\n"
1365
    "along with this program; if not, write to the Free Software\n"
1366
    "Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.\n"
1367
    );
1368
    exit(1);
1369
}
1370

    
1371
void opt_format(const char *arg)
1372
{
1373
    AVFormat *f;
1374
    f = first_format;
1375
    while (f != NULL && strcmp(f->name, arg) != 0) f = f->next;
1376
    if (f == NULL) {
1377
        fprintf(stderr, "Invalid format: %s\n", arg);
1378
        exit(1);
1379
    }
1380
    file_format = f;
1381
}
1382

    
1383
void opt_video_bitrate(const char *arg)
1384
{
1385
    video_bit_rate = atoi(arg) * 1000;
1386
}
1387

    
1388
void opt_frame_rate(const char *arg)
1389
{
1390
    frame_rate = (int)(strtod(arg, 0) * FRAME_RATE_BASE);
1391
}
1392

    
1393
void opt_frame_size(const char *arg)
1394
{
1395
    parse_image_size(&frame_width, &frame_height, arg);
1396
    if (frame_width <= 0 || frame_height <= 0) {
1397
        fprintf(stderr, "Incorrect frame size\n");
1398
        exit(1);
1399
    }
1400
    if ((frame_width % 2) != 0 || (frame_height % 2) != 0) {
1401
        fprintf(stderr, "Frame size must be a multiple of 2\n");
1402
        exit(1);
1403
    }
1404
}
1405

    
1406
void opt_gop_size(const char *arg)
1407
{
1408
    gop_size = atoi(arg);
1409
}
1410

    
1411
void opt_qscale(const char *arg)
1412
{
1413
    video_qscale = atoi(arg);
1414
    if (video_qscale < 0 ||
1415
        video_qscale > 31) {
1416
        fprintf(stderr, "qscale must be >= 1 and <= 31\n");
1417
        exit(1);
1418
    }
1419
}
1420

    
1421

    
1422
void opt_audio_bitrate(const char *arg)
1423
{
1424
    audio_bit_rate = atoi(arg) * 1000;
1425
}
1426

    
1427
void opt_audio_rate(const char *arg)
1428
{
1429
    audio_sample_rate = atoi(arg);
1430
}
1431

    
1432
void opt_audio_channels(const char *arg)
1433
{
1434
    audio_channels = atoi(arg);
1435
}
1436

    
1437
void opt_video_device(const char *arg)
1438
{
1439
    v4l_device = strdup(arg);
1440
}
1441

    
1442
void opt_audio_device(const char *arg)
1443
{
1444
    audio_device = strdup(arg);
1445
}
1446

    
1447
void opt_audio_codec(const char *arg)
1448
{
1449
    AVCodec *p;
1450

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

    
1465
const char *motion_str[] = {
1466
    "zero",
1467
    "full",
1468
    "log",
1469
    "phods",
1470
    NULL,
1471
};
1472

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

    
1489
void opt_video_codec(const char *arg)
1490
{
1491
    AVCodec *p;
1492

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

    
1507
void opt_map(const char *arg)
1508
{
1509
    AVStreamMap *m;
1510
    const char *p;
1511

    
1512
    p = arg;
1513
    m = &stream_maps[nb_stream_maps++];
1514

    
1515
    m->file_index = strtol(arg, (char **)&p, 0);
1516
    if (*p)
1517
        p++;
1518
    m->stream_index = strtol(arg, (char **)&p, 0);
1519
}
1520

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

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

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

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

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

    
1588
        pkt = &pktl->pkt;
1589
        if (ic->format->read_packet(ic, pkt) < 0) {
1590
            ret = -1;
1591
            break;
1592
        }
1593
        st = ic->streams[pkt->stream_index];
1594

    
1595
        /* decode the data and update codec parameters */
1596
        ptr = pkt->data;
1597
        size = pkt->size;
1598
        while (size > 0) {
1599
            switch(st->codec.codec_type) {
1600
            case CODEC_TYPE_VIDEO:
1601
                ret = avcodec_decode_video(&st->codec, &picture, &got_picture, ptr, size);
1602
                break;
1603
            case CODEC_TYPE_AUDIO:
1604
                ret = avcodec_decode_audio(&st->codec, samples, &got_picture, ptr, size);
1605
                break;
1606
            default:
1607
                ret = -1;
1608
                break;
1609
            }
1610
            if (ret < 0) {
1611
                ret = -1;
1612
                goto the_end;
1613
            }
1614
            if (got_picture)
1615
                break;
1616
            ptr += ret;
1617
            size -= ret;
1618
        }
1619

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

    
1633

    
1634
void opt_input_file(const char *filename)
1635
{
1636
    AVFormatContext *ic;
1637
    AVFormatParameters params, *ap = &params;
1638
    URLFormat url_format;
1639
    AVFormat *fmt;
1640
    int err, i, ret;
1641

    
1642
    ic = av_mallocz(sizeof(AVFormatContext));
1643
    strcpy(ic->filename, filename);
1644
    /* first format guess to know if we must open file */
1645
    fmt = file_format;
1646
    if (!fmt) 
1647
        fmt = guess_format(NULL, filename, NULL);
1648
    
1649
    if (fmt == NULL || !(fmt->flags & AVFMT_NOFILE)) {
1650
        /* open file */
1651
        if (url_fopen(&ic->pb, filename, URL_RDONLY) < 0) {
1652
            fprintf(stderr, "Could not open '%s'\n", filename);
1653
            exit(1);
1654
        }
1655
    
1656
        /* find format and set default parameters */
1657
        fmt = file_format;
1658
        err = url_getformat(url_fileno(&ic->pb), &url_format);
1659
        if (err >= 0) {
1660
            if (!fmt)
1661
                fmt = guess_format(url_format.format_name, NULL, NULL);
1662
            ap->sample_rate = url_format.sample_rate;
1663
            ap->frame_rate = url_format.frame_rate;
1664
            ap->channels = url_format.channels;
1665
            ap->width = url_format.width;
1666
            ap->height = url_format.height;
1667
            ap->pix_fmt = url_format.pix_fmt;
1668
        } else {
1669
            if (!fmt)
1670
                fmt = guess_format(NULL, filename, NULL);
1671
            memset(ap, 0, sizeof(*ap));
1672
        }
1673
    } else {
1674
        memset(ap, 0, sizeof(*ap));
1675
    }
1676

    
1677
    if (!fmt || !fmt->read_header) {
1678
        fprintf(stderr, "%s: Unknown file format\n", filename);
1679
        exit(1);
1680
    }
1681
    ic->format = fmt;
1682

    
1683
    /* get default parameters from command line */
1684
    if (!ap->sample_rate)
1685
        ap->sample_rate = audio_sample_rate;
1686
    if (!ap->channels)
1687
        ap->channels = audio_channels;
1688

    
1689
    if (!ap->frame_rate)
1690
        ap->frame_rate = frame_rate;
1691
    if (!ap->width)
1692
        ap->width = frame_width;
1693
    if (!ap->height)
1694
        ap->height = frame_height;
1695
    
1696
    err = ic->format->read_header(ic, ap);
1697
    if (err < 0) {
1698
        fprintf(stderr, "%s: Error while parsing header\n", filename);
1699
        exit(1);
1700
    }
1701
    
1702
    /* If not enough info for the codecs, we decode the first frames
1703
       to get it. (used in mpeg case for example) */
1704
    ret = find_codec_parameters(ic);
1705
    if (ret < 0) {
1706
        fprintf(stderr, "%s: could not find codec parameters\n", filename);
1707
        exit(1);
1708
    }
1709

    
1710
    /* update the current parameters so that they match the one of the input stream */
1711
    for(i=0;i<ic->nb_streams;i++) {
1712
        AVCodecContext *enc = &ic->streams[i]->codec;
1713
        switch(enc->codec_type) {
1714
        case CODEC_TYPE_AUDIO:
1715
            audio_channels = enc->channels;
1716
            audio_sample_rate = enc->sample_rate;
1717
            break;
1718
        case CODEC_TYPE_VIDEO:
1719
            frame_height = enc->height;
1720
            frame_width = enc->width;
1721
            frame_rate = enc->frame_rate;
1722
            break;
1723
        }
1724
    }
1725
    
1726
    input_files[nb_input_files] = ic;
1727
    /* dump the file content */
1728
    dump_format(ic, nb_input_files, filename, 0);
1729
    nb_input_files++;
1730
    file_format = NULL;
1731
}
1732

    
1733
void opt_output_file(const char *filename)
1734
{
1735
    AVStream *st;
1736
    AVFormatContext *oc;
1737
    int use_video, use_audio, nb_streams;
1738
    int codec_id;
1739

    
1740
    if (!strcmp(filename, "-"))
1741
        filename = "pipe:";
1742

    
1743
    oc = av_mallocz(sizeof(AVFormatContext));
1744

    
1745
    if (!file_format) {
1746
        file_format = guess_format(NULL, filename, NULL);
1747
        if (!file_format)
1748
            file_format = &mpeg_mux_format;
1749
    }
1750
    
1751
    oc->format = file_format;
1752

    
1753
    if (!strcmp(file_format->name, "ffm") && 
1754
        strstart(filename, "http:", NULL)) {
1755
        /* special case for files sent to ffserver: we get the stream
1756
           parameters from ffserver */
1757
        if (read_ffserver_streams(oc, filename) < 0) {
1758
            fprintf(stderr, "Could not read stream parameters from '%s'\n", filename);
1759
            exit(1);
1760
        }
1761
    } else {
1762
        use_video = file_format->video_codec != CODEC_ID_NONE;
1763
        use_audio = file_format->audio_codec != CODEC_ID_NONE;
1764
        
1765
        if (audio_disable) {
1766
            use_audio = 0;
1767
        }
1768
        if (video_disable) {
1769
            use_video = 0;
1770
        }
1771
        
1772
        nb_streams = 0;
1773
        if (use_video) {
1774
            AVCodecContext *video_enc;
1775
            
1776
            st = av_mallocz(sizeof(AVStream));
1777
            if (!st) {
1778
                fprintf(stderr, "Could not alloc stream\n");
1779
                exit(1);
1780
            }
1781
            video_enc = &st->codec;
1782

    
1783
            codec_id = file_format->video_codec;
1784
            if (video_codec_id != CODEC_ID_NONE)
1785
                codec_id = video_codec_id;
1786

    
1787
            video_enc->codec_id = codec_id;
1788
            video_enc->codec_type = CODEC_TYPE_VIDEO;
1789
            
1790
            video_enc->bit_rate = video_bit_rate;
1791
            video_enc->frame_rate = frame_rate; 
1792
            
1793
            video_enc->width = frame_width;
1794
            video_enc->height = frame_height;
1795
            if (!intra_only)
1796
                video_enc->gop_size = gop_size;
1797
            else
1798
                video_enc->gop_size = 0;
1799
            if (video_qscale || same_quality) {
1800
                video_enc->flags |= CODEC_FLAG_QSCALE;
1801
                video_enc->quality = video_qscale;
1802
            }
1803

    
1804
            oc->streams[nb_streams] = st;
1805
            nb_streams++;
1806
        }
1807
    
1808
        if (use_audio) {
1809
            AVCodecContext *audio_enc;
1810

    
1811
            st = av_mallocz(sizeof(AVStream));
1812
            if (!st) {
1813
                fprintf(stderr, "Could not alloc stream\n");
1814
                exit(1);
1815
            }
1816
            audio_enc = &st->codec;
1817
            codec_id = file_format->audio_codec;
1818
            if (audio_codec_id != CODEC_ID_NONE)
1819
                codec_id = audio_codec_id;
1820
            audio_enc->codec_id = codec_id;
1821
            audio_enc->codec_type = CODEC_TYPE_AUDIO;
1822
            
1823
            audio_enc->bit_rate = audio_bit_rate;
1824
            audio_enc->sample_rate = audio_sample_rate;
1825
            audio_enc->channels = audio_channels;
1826
            oc->streams[nb_streams] = st;
1827
            nb_streams++;
1828
        }
1829

    
1830
        oc->nb_streams = nb_streams;
1831

    
1832
        if (!nb_streams) {
1833
            fprintf(stderr, "No audio or video selected\n");
1834
            exit(1);
1835
        }
1836

    
1837
        if (str_title)
1838
            nstrcpy(oc->title, sizeof(oc->title), str_title);
1839
        if (str_author)
1840
            nstrcpy(oc->author, sizeof(oc->author), str_author);
1841
        if (str_copyright)
1842
            nstrcpy(oc->copyright, sizeof(oc->copyright), str_copyright);
1843
        if (str_comment)
1844
            nstrcpy(oc->comment, sizeof(oc->comment), str_comment);
1845
    }
1846

    
1847
    output_files[nb_output_files] = oc;
1848
    /* dump the file content */
1849
    dump_format(oc, nb_output_files, filename, 1);
1850
    nb_output_files++;
1851

    
1852
    strcpy(oc->filename, filename);
1853
    if (!(oc->format->flags & AVFMT_NOFILE)) {
1854
        /* test if it already exists to avoid loosing precious files */
1855
        if (!file_overwrite && 
1856
            (strchr(filename, ':') == NULL ||
1857
             strstart(filename, "file:", NULL))) {
1858
            if (url_exist(filename)) {
1859
                int c;
1860
                
1861
                printf("File '%s' already exists. Overwrite ? [y/N] ", filename);
1862
                fflush(stdout);
1863
                c = getchar();
1864
                if (toupper(c) != 'Y') {
1865
                    fprintf(stderr, "Not overwriting - exiting\n");
1866
                    exit(1);
1867
                }
1868
            }
1869
        }
1870
        
1871
        /* open the file */
1872
        if (url_fopen(&oc->pb, filename, URL_WRONLY) < 0) {
1873
            fprintf(stderr, "Could not open '%s'\n", filename);
1874
            exit(1);
1875
        }
1876
    }
1877

    
1878
    /* reset some options */
1879
    file_format = NULL;
1880
    audio_disable = 0;
1881
    video_disable = 0;
1882
    audio_codec_id = CODEC_ID_NONE;
1883
    video_codec_id = CODEC_ID_NONE;
1884
}
1885

    
1886
INT64 getutime(void)
1887
{
1888
    struct rusage rusage;
1889

    
1890
    getrusage(RUSAGE_SELF, &rusage);
1891
    return (rusage.ru_utime.tv_sec * 1000000LL) + rusage.ru_utime.tv_usec;
1892
}
1893

    
1894
void show_formats(void)
1895
{
1896
    AVFormat *f;
1897
    URLProtocol *up;
1898
    AVCodec *p;
1899
    const char **pp;
1900

    
1901
    printf("File formats:\n");
1902
    printf("  Encoding:");
1903
    for(f = first_format; f != NULL; f = f->next) {
1904
        if (f->write_header)
1905
            printf(" %s", f->name);
1906
    }
1907
    printf("\n");
1908
    printf("  Decoding:");
1909
    for(f = first_format; f != NULL; f = f->next) {
1910
        if (f->read_header)
1911
            printf(" %s", f->name);
1912
    }
1913
    printf("\n");
1914

    
1915
    printf("Codecs:\n");
1916
    printf("  Encoders:");
1917
    for(p = first_avcodec; p != NULL; p = p->next) {
1918
        if (p->encode)
1919
            printf(" %s", p->name);
1920
    }
1921
    printf("\n");
1922

    
1923
    printf("  Decoders:");
1924
    for(p = first_avcodec; p != NULL; p = p->next) {
1925
        if (p->decode)
1926
            printf(" %s", p->name);
1927
    }
1928
    printf("\n");
1929

    
1930
    printf("Supported file protocols:");
1931
    for(up = first_protocol; up != NULL; up = up->next)
1932
        printf(" %s:", up->name);
1933
    printf("\n");
1934
    
1935
    printf("Frame size abbreviations: sqcif qcif cif 4cif\n");
1936
    printf("Motion estimation methods:");
1937
    pp = motion_str;
1938
    while (*pp) {
1939
        printf(" %s", *pp);
1940
        if ((pp - motion_str) == ME_ZERO) 
1941
            printf("(fastest)");
1942
        else if ((pp - motion_str) == ME_FULL) 
1943
            printf("(slowest)");
1944
        else if ((pp - motion_str) == ME_LOG) 
1945
            printf("(default)");
1946
        pp++;
1947
    }
1948
    printf("\n");
1949
    exit(1);
1950
}
1951

    
1952
void show_help(void)
1953
{
1954
    const OptionDef *po;
1955
    int i, expert;
1956

    
1957
    printf("ffmpeg version " FFMPEG_VERSION ", Copyright (c) 2000,2001 Gerard Lantau\n"
1958
           "usage: ffmpeg [[options] -i input_file]... {[options] outfile}...\n"
1959
           "Hyper fast MPEG1/MPEG4/H263/RV and AC3/MPEG audio encoder\n"
1960
           "\n"
1961
           "Main options are:\n");
1962
    for(i=0;i<2;i++) {
1963
        if (i == 1)
1964
            printf("\nAdvanced options are:\n");
1965
        for(po = options; po->name != NULL; po++) {
1966
            char buf[64];
1967
            expert = (po->flags & OPT_EXPERT) != 0;
1968
            if (expert == i) {
1969
                strcpy(buf, po->name);
1970
                if (po->flags & HAS_ARG) {
1971
                    strcat(buf, " ");
1972
                    strcat(buf, po->argname);
1973
                }
1974
                printf("-%-17s  %s\n", buf, po->help);
1975
            }
1976
        }
1977
    }
1978

    
1979
    exit(1);
1980
}
1981

    
1982
const OptionDef options[] = {
1983
    { "L", 0, {show_licence}, "show license" },
1984
    { "h", 0, {show_help}, "show help" },
1985
    { "formats", 0, {show_formats}, "show available formats, codecs, protocols, ..." },
1986
    { "f", HAS_ARG, {opt_format}, "force format", "fmt" },
1987
    { "i", HAS_ARG, {opt_input_file}, "input file name", "filename" },
1988
    { "y", OPT_BOOL, {int_arg:&file_overwrite}, "overwrite output files" },
1989
    { "map", HAS_ARG | OPT_EXPERT, {opt_map}, "set input stream mapping", "file:stream" },
1990
    { "t", HAS_ARG, {opt_recording_time}, "set the recording time", "duration" },
1991
    { "title", HAS_ARG | OPT_STRING, {str_arg: &str_title}, "set the title", "string" },
1992
    { "author", HAS_ARG | OPT_STRING, {str_arg: &str_author}, "set the author", "string" },
1993
    { "copyright", HAS_ARG | OPT_STRING, {str_arg: &str_copyright}, "set the copyright", "string" },
1994
    { "comment", HAS_ARG | OPT_STRING, {str_arg: &str_comment}, "set the comment", "string" },
1995
    /* video options */
1996
    { "b", HAS_ARG, {opt_video_bitrate}, "set video bitrate (in kbit/s)", "bitrate" },
1997
    { "r", HAS_ARG, {opt_frame_rate}, "set frame rate (in Hz)", "rate" },
1998
    { "s", HAS_ARG, {opt_frame_size}, "set frame size (WxH or abbreviation)", "size" },
1999
    { "g", HAS_ARG | OPT_EXPERT, {opt_gop_size}, "set the group of picture size", "gop_size" },
2000
    { "intra", OPT_BOOL | OPT_EXPERT, {int_arg: &intra_only}, "use only intra frames"},
2001
    { "vn", OPT_BOOL, {int_arg: &video_disable}, "disable video" },
2002
    { "qscale", HAS_ARG | OPT_EXPERT, {opt_qscale}, "use fixed video quantiser scale (VBR)", "q" },
2003
    { "vd", HAS_ARG | OPT_EXPERT, {opt_video_device}, "set video device", "device" },
2004
    { "vcodec", HAS_ARG | OPT_EXPERT, {opt_video_codec}, "force video codec", "codec" },
2005
    { "me", HAS_ARG | OPT_EXPERT, {opt_motion_estimation}, "set motion estimation method", 
2006
      "method" },
2007
    { "sameq", OPT_BOOL, {int_arg: &same_quality}, 
2008
      "use same video quality as source (implies VBR)" },
2009
    /* audio options */
2010
    { "ab", HAS_ARG, {opt_audio_bitrate}, "set audio bitrate (in kbit/s)", "bitrate", },
2011
    { "ar", HAS_ARG, {opt_audio_rate}, "set audio sampling rate (in Hz)", "rate" },
2012
    { "ac", HAS_ARG, {opt_audio_channels}, "set number of audio channels", "channels" },
2013
    { "an", OPT_BOOL, {int_arg: &audio_disable}, "disable audio" },
2014
    { "ad", HAS_ARG | OPT_EXPERT, {opt_audio_device}, "set audio device", "device" },
2015
    { "acodec", HAS_ARG | OPT_EXPERT, {opt_audio_codec}, "force audio codec", "codec" },
2016
    { "benchmark", OPT_BOOL | OPT_EXPERT, {int_arg: &do_benchmark}, 
2017
      "add timings for benchmarking" },
2018

    
2019
    { NULL, },
2020
};
2021

    
2022
int main(int argc, char **argv)
2023
{
2024
    int optindex, i;
2025
    const char *opt, *arg;
2026
    const OptionDef *po;
2027
    
2028
    register_all();
2029

    
2030
    if (argc <= 1)
2031
        show_help();
2032

    
2033
    optindex = 1;
2034
    while (optindex < argc) {
2035
        opt = argv[optindex++];
2036
        
2037
        if (opt[0] == '-' && opt[1] != '\0') {
2038
            po = options;
2039
            while (po->name != NULL) {
2040
                if (!strcmp(opt + 1, po->name))
2041
                    break;
2042
                po++;
2043
            }
2044
            if (!po->name) {
2045
                fprintf(stderr, "%s: unrecognized option '%s'\n", argv[0], opt);
2046
                exit(1);
2047
            }
2048
            arg = NULL;
2049
            if (po->flags & HAS_ARG)
2050
                arg = argv[optindex++];
2051
            if (po->flags & OPT_STRING) {
2052
                char *str;
2053
                str = strdup(arg);
2054
                *po->u.str_arg = str;
2055
            } else if (po->flags & OPT_BOOL) {
2056
                *po->u.int_arg = 1;
2057
            } else {
2058
                po->u.func_arg(arg);
2059
            }
2060
        } else {
2061
            opt_output_file(opt);
2062
        }
2063
    }
2064

    
2065

    
2066
    if (nb_input_files == 0) {
2067
        if (nb_output_files != 1) {
2068
            fprintf(stderr, "Only one output file supported when grabbing\n");
2069
            exit(1);
2070
        }
2071
        av_grab(output_files[0]);
2072
    } else {
2073
        INT64 ti;
2074

    
2075
        if (nb_output_files <= 0) {
2076
            fprintf(stderr, "Must supply at least one output file\n");
2077
            exit(1);
2078
        }
2079
        ti = getutime();
2080
        av_encode(output_files, nb_output_files, input_files, nb_input_files, 
2081
                  stream_maps, nb_stream_maps);
2082
        ti = getutime() - ti;
2083
        if (do_benchmark) {
2084
            printf("bench: utime=%0.3fs\n", ti / 1000000.0);
2085
        }
2086
    }
2087

    
2088
    /* close files */
2089
    for(i=0;i<nb_output_files;i++) {
2090
        if (!(output_files[i]->format->flags & AVFMT_NOFILE)) 
2091
            url_fclose(&output_files[i]->pb);
2092
    }
2093
    for(i=0;i<nb_input_files;i++) {
2094
        if (!(input_files[i]->format->flags & AVFMT_NOFILE)) 
2095
            url_fclose(&input_files[i]->pb);
2096
    }
2097

    
2098
    return 0;
2099
}