Statistics
| Branch: | Revision:

ffmpeg / ffmpeg.c @ 7002684e

History | View | Annotate | Download (80 KB)

1
/*
2
 * FFmpeg main 
3
 * Copyright (c) 2000, 2001, 2002 Fabrice Bellard
4
 *
5
 * This library is free software; you can redistribute it and/or
6
 * modify it under the terms of the GNU Lesser General Public
7
 * License as published by the Free Software Foundation; either
8
 * version 2 of the License, or (at your option) any later version.
9
 *
10
 * This library is distributed in the hope that it will be useful,
11
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13
 * Lesser General Public License for more details.
14
 *
15
 * You should have received a copy of the GNU Lesser General Public
16
 * License along with this library; if not, write to the Free Software
17
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
18
 */
19
#define HAVE_AV_CONFIG_H
20
#include "avformat.h"
21
#include "tick.h"
22

    
23
#ifndef CONFIG_WIN32
24
#include <unistd.h>
25
#include <fcntl.h>
26
#include <sys/ioctl.h>
27
#include <sys/time.h>
28
#include <termios.h>
29
#include <sys/resource.h>
30
#endif
31
#ifdef __BEOS__
32
/* for snooze() */
33
#include <OS.h>
34
#endif
35
#include <time.h>
36
#include <ctype.h>
37

    
38

    
39
#define MAXINT64 INT64_C(0x7fffffffffffffff)
40

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

    
57
/* select an input stream for an output stream */
58
typedef struct AVStreamMap {
59
    int file_index;
60
    int stream_index;
61
} AVStreamMap;
62

    
63
extern const OptionDef options[];
64

    
65
void show_help(void);
66

    
67
#define MAX_FILES 20
68

    
69
static AVFormatContext *input_files[MAX_FILES];
70
static int nb_input_files = 0;
71

    
72
static AVFormatContext *output_files[MAX_FILES];
73
static int nb_output_files = 0;
74

    
75
static AVStreamMap stream_maps[MAX_FILES];
76
static int nb_stream_maps;
77

    
78
static AVInputFormat *file_iformat;
79
static AVOutputFormat *file_oformat;
80
static int frame_width  = 160;
81
static int frame_height = 128;
82
static int frame_topBand  = 0;
83
static int frame_bottomBand = 0;
84
static int frame_leftBand  = 0;
85
static int frame_rightBand = 0;
86
static int frame_rate = 25 * FRAME_RATE_BASE;
87
static int video_bit_rate = 200*1000;
88
static int video_bit_rate_tolerance = 4000*1000;
89
static int video_qscale = 0;
90
static int video_qmin = 2;
91
static int video_qmax = 31;
92
static int video_qdiff = 3;
93
static float video_qblur = 0.5;
94
static float video_qcomp = 0.5;
95
static float video_rc_qsquish=1.0;
96
static float video_rc_qmod_amp=0;
97
static int video_rc_qmod_freq=0;
98
static char *video_rc_override_string=NULL;
99
static char *video_rc_eq="tex^qComp";
100
static int video_rc_buffer_size=0;
101
static float video_rc_buffer_aggressivity=1.0;
102
static int video_rc_max_rate=0;
103
static int video_rc_min_rate=0;
104
static float video_rc_initial_cplx=0;
105
static float video_b_qfactor = 1.25;
106
static float video_b_qoffset = 1.25;
107
static float video_i_qfactor = -0.8;
108
static float video_i_qoffset = 0.0;
109
static int me_method = 0;
110
static int video_disable = 0;
111
static int video_codec_id = CODEC_ID_NONE;
112
static int same_quality = 0;
113
static int b_frames = 0;
114
static int use_hq = 0;
115
static int use_4mv = 0;
116
static int do_deinterlace = 0;
117
static int workaround_bugs = FF_BUG_AUTODETECT;
118
static int error_resilience = 2;
119
static int error_concealment = 3;
120
static int dct_algo = 0;
121
static int idct_algo = 0;
122
static int use_part = 0;
123
static int packet_size = 0;
124

    
125
static int gop_size = 12;
126
static int intra_only = 0;
127
static int audio_sample_rate = 44100;
128
static int audio_bit_rate = 64000;
129
static int audio_disable = 0;
130
static int audio_channels = 1;
131
static int audio_codec_id = CODEC_ID_NONE;
132

    
133
static INT64 recording_time = 0;
134
static int file_overwrite = 0;
135
static char *str_title = NULL;
136
static char *str_author = NULL;
137
static char *str_copyright = NULL;
138
static char *str_comment = NULL;
139
static int do_benchmark = 0;
140
static int do_hex_dump = 0;
141
static int do_play = 0;
142
static int do_psnr = 0;
143
static int do_vstats = 0;
144
static int mpeg_vcd = 0;
145
static int do_pass = 0;
146
static char *pass_logfilename = NULL;
147
static int audio_stream_copy = 0;
148
static int video_stream_copy = 0;
149

    
150
#define DEFAULT_PASS_LOGFILENAME "ffmpeg2pass"
151

    
152
#ifndef CONFIG_AUDIO_OSS
153
const char *audio_device = "none";
154
#endif
155
#ifndef CONFIG_VIDEO4LINUX
156
const char *v4l_device = "none";
157
#endif
158

    
159
typedef struct AVOutputStream {
160
    int file_index;          /* file index */
161
    int index;               /* stream index in the output file */
162
    int source_index;        /* AVInputStream index */
163
    AVStream *st;            /* stream in the output file */
164
    int encoding_needed;   /* true if encoding needed for this stream */
165

    
166
    /* video only */
167
    AVPicture pict_tmp;         /* temporary image for resizing */
168
    int video_resample;
169
    ImgReSampleContext *img_resample_ctx; /* for image resampling */
170
    
171
    /* audio only */
172
    int audio_resample;
173
    ReSampleContext *resample; /* for audio resampling */
174
    FifoBuffer fifo;     /* for compression: one audio fifo per codec */
175
    FILE *logfile;
176
} AVOutputStream;
177

    
178
typedef struct AVInputStream {
179
    int file_index;
180
    int index;
181
    AVStream *st;
182
    int discard;             /* true if stream data should be discarded */
183
    int decoding_needed;     /* true if the packets must be decoded in 'raw_fifo' */
184
    Ticker pts_ticker;       /* Ticker for PTS calculation */
185
    int ticker_inited;       /* to signal if the ticker was initialized */
186
    INT64 pts;               /* current pts */
187
    int   pts_increment;     /* expected pts increment for next packet */
188
    int frame_number;        /* current frame */
189
    INT64 sample_index;      /* current sample */
190
} AVInputStream;
191

    
192
typedef struct AVInputFile {
193
    int eof_reached;      /* true if eof reached */
194
    int ist_index;        /* index of first stream in ist_table */
195
    int buffer_size;      /* current total buffer size */
196
    int buffer_size_max;  /* buffer size at which we consider we can stop
197
                             buffering */
198
    int nb_streams;       /* nb streams we are aware of */
199
} AVInputFile;
200

    
201
#ifndef CONFIG_WIN32
202

    
203
/* init terminal so that we can grab keys */
204
static struct termios oldtty;
205

    
206
static void term_exit(void)
207
{
208
    tcsetattr (0, TCSANOW, &oldtty);
209
}
210

    
211
static void term_init(void)
212
{
213
    struct termios tty;
214

    
215
    tcgetattr (0, &tty);
216
    oldtty = tty;
217

    
218
    tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
219
                          |INLCR|IGNCR|ICRNL|IXON);
220
    tty.c_oflag |= OPOST;
221
    tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
222
    tty.c_cflag &= ~(CSIZE|PARENB);
223
    tty.c_cflag |= CS8;
224
    tty.c_cc[VMIN] = 1;
225
    tty.c_cc[VTIME] = 0;
226
    
227
    tcsetattr (0, TCSANOW, &tty);
228

    
229
    atexit(term_exit);
230
}
231

    
232
/* read a key without blocking */
233
static int read_key(void)
234
{
235
    struct timeval tv;
236
    int n;
237
    unsigned char ch;
238
    fd_set rfds;
239

    
240
    FD_ZERO(&rfds);
241
    FD_SET(0, &rfds);
242
    tv.tv_sec = 0;
243
    tv.tv_usec = 0;
244
    n = select(1, &rfds, NULL, NULL, &tv);
245
    if (n > 0) {
246
        n = read(0, &ch, 1);
247
        if (n == 1)
248
            return ch;
249

    
250
        return n;
251
    }
252
    return -1;
253
}
254

    
255
#else
256

    
257
/* no interactive support */
258
static void term_exit(void)
259
{
260
}
261

    
262
static void term_init(void)
263
{
264
}
265

    
266
static int read_key(void)
267
{
268
    return 0;
269
}
270

    
271
#endif
272

    
273
int read_ffserver_streams(AVFormatContext *s, const char *filename)
274
{
275
    int i, err;
276
    AVFormatContext *ic;
277

    
278
    err = av_open_input_file(&ic, filename, NULL, FFM_PACKET_SIZE, NULL);
279
    if (err < 0)
280
        return err;
281
    /* copy stream format */
282
    s->nb_streams = ic->nb_streams;
283
    for(i=0;i<ic->nb_streams;i++) {
284
        AVStream *st;
285
        st = av_mallocz(sizeof(AVFormatContext));
286
        memcpy(st, ic->streams[i], sizeof(AVStream));
287
        s->streams[i] = st;
288
    }
289

    
290
    av_close_input_file(ic);
291
    return 0;
292
}
293

    
294
#define MAX_AUDIO_PACKET_SIZE 16384
295

    
296
static void do_audio_out(AVFormatContext *s, 
297
                         AVOutputStream *ost, 
298
                         AVInputStream *ist,
299
                         unsigned char *buf, int size)
300
{
301
    UINT8 *buftmp;
302
    UINT8 audio_buf[2*MAX_AUDIO_PACKET_SIZE]; /* XXX: allocate it */
303
    UINT8 audio_out[MAX_AUDIO_PACKET_SIZE]; /* XXX: allocate it */
304
    int size_out, frame_bytes, ret;
305
    AVCodecContext *enc;
306

    
307
    enc = &ost->st->codec;
308

    
309
    if (ost->audio_resample) {
310
        buftmp = audio_buf;
311
        size_out = audio_resample(ost->resample, 
312
                                  (short *)buftmp, (short *)buf,
313
                                  size / (ist->st->codec.channels * 2));
314
        size_out = size_out * enc->channels * 2;
315
    } else {
316
        buftmp = buf;
317
        size_out = size;
318
    }
319

    
320
    /* now encode as many frames as possible */
321
    if (enc->frame_size > 1) {
322
        /* output resampled raw samples */
323
        fifo_write(&ost->fifo, buftmp, size_out, 
324
                   &ost->fifo.wptr);
325

    
326
        frame_bytes = enc->frame_size * 2 * enc->channels;
327
        
328
        while (fifo_read(&ost->fifo, audio_buf, frame_bytes, 
329
                     &ost->fifo.rptr) == 0) {
330
            ret = avcodec_encode_audio(enc, audio_out, sizeof(audio_out), 
331
                                       (short *)audio_buf);
332
            s->oformat->write_packet(s, ost->index, audio_out, ret, 0);
333
        }
334
    } else {
335
        /* output a pcm frame */
336
        /* XXX: change encoding codec API to avoid this ? */
337
        switch(enc->codec->id) {
338
        case CODEC_ID_PCM_S16LE:
339
        case CODEC_ID_PCM_S16BE:
340
        case CODEC_ID_PCM_U16LE:
341
        case CODEC_ID_PCM_U16BE:
342
            break;
343
        default:
344
            size_out = size_out >> 1;
345
            break;
346
        }
347
        ret = avcodec_encode_audio(enc, audio_out, size_out, 
348
                                   (short *)buftmp);
349
        s->oformat->write_packet(s, ost->index, audio_out, ret, 0);
350
    }
351
}
352

    
353
/* write a picture to a raw mux */
354
static void write_picture(AVFormatContext *s, int index, AVPicture *picture, 
355
                          int pix_fmt, int w, int h)
356
{
357
    UINT8 *buf, *src, *dest;
358
    int size, j, i;
359

    
360
    /* XXX: not efficient, should add test if we can take
361
       directly the AVPicture */
362
    switch(pix_fmt) {
363
    case PIX_FMT_YUV420P:
364
        size = avpicture_get_size(pix_fmt, w, h);
365
        buf = av_malloc(size);
366
        if (!buf)
367
            return;
368
        dest = buf;
369
        for(i=0;i<3;i++) {
370
            if (i == 1) {
371
                w >>= 1;
372
                h >>= 1;
373
            }
374
            src = picture->data[i];
375
            for(j=0;j<h;j++) {
376
                memcpy(dest, src, w);
377
                dest += w;
378
                src += picture->linesize[i];
379
            }
380
        }
381
        break;
382
    case PIX_FMT_YUV422P:
383
        size = (w * h) * 2; 
384
        buf = av_malloc(size);
385
        if (!buf)
386
            return;
387
        dest = buf;
388
        for(i=0;i<3;i++) {
389
            if (i == 1) {
390
                w >>= 1;
391
            }
392
            src = picture->data[i];
393
            for(j=0;j<h;j++) {
394
                memcpy(dest, src, w);
395
                dest += w;
396
                src += picture->linesize[i];
397
            }
398
        }
399
        break;
400
    case PIX_FMT_YUV444P:
401
        size = (w * h) * 3; 
402
        buf = av_malloc(size);
403
        if (!buf)
404
            return;
405
        dest = buf;
406
        for(i=0;i<3;i++) {
407
            src = picture->data[i];
408
            for(j=0;j<h;j++) {
409
                memcpy(dest, src, w);
410
                dest += w;
411
                src += picture->linesize[i];
412
            }
413
        }
414
        break;
415
    case PIX_FMT_YUV422:
416
        size = (w * h) * 2; 
417
        buf = av_malloc(size);
418
        if (!buf)
419
            return;
420
        dest = buf;
421
        src = picture->data[0];
422
        for(j=0;j<h;j++) {
423
            memcpy(dest, src, w * 2);
424
            dest += w * 2;
425
            src += picture->linesize[0];
426
        }
427
        break;
428
    case PIX_FMT_RGB24:
429
    case PIX_FMT_BGR24:
430
        size = (w * h) * 3; 
431
        buf = av_malloc(size);
432
        if (!buf)
433
            return;
434
        dest = buf;
435
        src = picture->data[0];
436
        for(j=0;j<h;j++) {
437
            memcpy(dest, src, w * 3);
438
            dest += w * 3;
439
            src += picture->linesize[0];
440
        }
441
        break;
442
    default:
443
        return;
444
    }
445
    s->oformat->write_packet(s, index, buf, size, 0);
446
    av_free(buf);
447
}
448

    
449

    
450
static void do_video_out(AVFormatContext *s, 
451
                         AVOutputStream *ost, 
452
                         AVInputStream *ist,
453
                         AVPicture *picture1,
454
                         int *frame_size)
455
{
456
    int n1, n2, nb, i, ret, frame_number, dec_frame_rate;
457
    AVPicture *picture, *picture2, *pict;
458
    AVPicture picture_tmp1, picture_tmp2;
459
    static UINT8 *video_buffer;
460
    UINT8 *buf = NULL, *buf1 = NULL;
461
    AVCodecContext *enc, *dec;
462

    
463
#define VIDEO_BUFFER_SIZE (1024*1024)
464

    
465
    enc = &ost->st->codec;
466
    dec = &ist->st->codec;
467

    
468
    frame_number = ist->frame_number;
469
    dec_frame_rate = ist->st->r_frame_rate;
470
    //    fprintf(stderr, "\n%d", dec_frame_rate);
471
    /* first drop frame if needed */
472
    n1 = ((INT64)frame_number * enc->frame_rate) / dec_frame_rate;
473
    n2 = (((INT64)frame_number + 1) * enc->frame_rate) / dec_frame_rate;
474
    nb = n2 - n1;
475
    if (nb <= 0) 
476
        return;
477

    
478
    if (!video_buffer)
479
        video_buffer= av_malloc(VIDEO_BUFFER_SIZE);
480
    if(!video_buffer) return;
481

    
482
    /* deinterlace : must be done before any resize */
483
    if (do_deinterlace) {
484
        int size;
485

    
486
        /* create temporary picture */
487
        size = avpicture_get_size(dec->pix_fmt, dec->width, dec->height);
488
        buf1 = av_malloc(size);
489
        if (!buf1)
490
            return;
491
        
492
        picture2 = &picture_tmp2;
493
        avpicture_fill(picture2, buf1, dec->pix_fmt, dec->width, dec->height);
494

    
495
        if (avpicture_deinterlace(picture2, picture1, 
496
                                  dec->pix_fmt, dec->width, dec->height) < 0) {
497
            /* if error, do not deinterlace */
498
            av_free(buf1);
499
            buf1 = NULL;
500
            picture2 = picture1;
501
        }
502
    } else {
503
        picture2 = picture1;
504
    }
505

    
506
    /* convert pixel format if needed */
507
    if (enc->pix_fmt != dec->pix_fmt) {
508
        int size;
509

    
510
        /* create temporary picture */
511
        size = avpicture_get_size(enc->pix_fmt, dec->width, dec->height);
512
        buf = av_malloc(size);
513
        if (!buf)
514
            return;
515
        pict = &picture_tmp1;
516
        avpicture_fill(pict, buf, enc->pix_fmt, dec->width, dec->height);
517
        
518
        if (img_convert(pict, enc->pix_fmt, 
519
                        picture2, dec->pix_fmt, 
520
                        dec->width, dec->height) < 0) {
521
            fprintf(stderr, "pixel format conversion not handled\n");
522
            goto the_end;
523
        }
524
    } else {
525
        pict = picture2;
526
    }
527

    
528
    /* XXX: resampling could be done before raw format convertion in
529
       some cases to go faster */
530
    /* XXX: only works for YUV420P */
531
    if (ost->video_resample) {
532
        picture = &ost->pict_tmp;
533
        img_resample(ost->img_resample_ctx, picture, pict);
534
    } else {
535
        picture = pict;
536
    }
537
    nb=1;
538
    /* duplicates frame if needed */
539
    /* XXX: pb because no interleaving */
540
    for(i=0;i<nb;i++) {
541
        if (enc->codec_id != CODEC_ID_RAWVIDEO) {
542
            /* handles sameq here. This is not correct because it may
543
               not be a global option */
544
            if (same_quality) {
545
                enc->quality = dec->quality;
546
            }
547
            
548
            ret = avcodec_encode_video(enc, 
549
                                       video_buffer, VIDEO_BUFFER_SIZE,
550
                                       picture);
551
            //enc->frame_number = enc->real_pict_num;
552
            s->oformat->write_packet(s, ost->index, video_buffer, ret, 0);
553
            *frame_size = ret;
554
            //fprintf(stderr,"\nFrame: %3d %3d size: %5d type: %d",
555
            //        enc->frame_number-1, enc->real_pict_num, ret,
556
            //        enc->pict_type);
557
            /* if two pass, output log */
558
            if (ost->logfile && enc->stats_out) {
559
                fprintf(ost->logfile, "%s", enc->stats_out);
560
            }
561
        } else {
562
            if (s->oformat->flags & AVFMT_RAWPICTURE) {
563
                /* raw pictures are written as AVPicture structure to
564
                   avoid any copies. We support temorarily the older
565
                   method. */
566
                s->oformat->write_packet(s, ost->index, 
567
                                         (UINT8 *)picture, sizeof(AVPicture), 0);
568
            } else {
569
                write_picture(s, ost->index, picture, enc->pix_fmt, enc->width, enc->height);
570
            }
571
        }
572
    }
573
    the_end:
574
    av_free(buf);
575
    av_free(buf1);
576
}
577

    
578
static void do_video_stats(AVOutputStream *ost, 
579
                         AVInputStream *ist,
580
                         int frame_size)
581
{
582
    static FILE *fvstats=NULL;
583
    static INT64 total_size = 0;
584
    char filename[40];
585
    time_t today2;
586
    struct tm *today;
587
    AVCodecContext *enc;
588
    int frame_number;
589
    INT64 ti;
590
    double ti1, bitrate, avg_bitrate;
591
    
592
    if (!fvstats) {
593
        today2 = time(NULL);
594
        today = localtime(&today2);
595
        sprintf(filename, "vstats_%02d%02d%02d.log", today->tm_hour,
596
                                               today->tm_min,
597
                                               today->tm_sec);
598
        fvstats = fopen(filename,"w");
599
        if (!fvstats) {
600
            perror("fopen");
601
            exit(1);
602
        }
603
    }
604
    
605
    ti = MAXINT64;
606
    enc = &ost->st->codec;
607
    total_size += frame_size;
608
    if (enc->codec_type == CODEC_TYPE_VIDEO) {
609
        frame_number = ist->frame_number;
610
        fprintf(fvstats, "frame= %5d q= %2d ", frame_number, enc->quality);
611
        if (do_psnr)
612
            fprintf(fvstats, "PSNR= %6.2f ", enc->psnr_y);
613
        
614
        fprintf(fvstats,"f_size= %6d ", frame_size);
615
        /* compute min pts value */
616
        if (!ist->discard && ist->pts < ti) {
617
            ti = ist->pts;
618
        }
619
        ti1 = (double)ti / 1000000.0;
620
        if (ti1 < 0.01)
621
            ti1 = 0.01;
622
    
623
        bitrate = (double)(frame_size * 8) * enc->frame_rate / FRAME_RATE_BASE / 1000.0;
624
        avg_bitrate = (double)(total_size * 8) / ti1 / 1000.0;
625
        fprintf(fvstats, "s_size= %8.0fkB time= %0.3f br= %7.1fkbits/s avg_br= %7.1fkbits/s ",
626
            (double)total_size / 1024, ti1, bitrate, avg_bitrate);
627
        fprintf(fvstats,"type= %s\n", enc->key_frame == 1 ? "I" : "P");        
628
    }
629

    
630
    
631
    
632
}
633

    
634
/*
635
 * The following code is the main loop of the file converter
636
 */
637
static int av_encode(AVFormatContext **output_files,
638
                     int nb_output_files,
639
                     AVFormatContext **input_files,
640
                     int nb_input_files,
641
                     AVStreamMap *stream_maps, int nb_stream_maps)
642
{
643
    int ret, i, j, k, n, nb_istreams = 0, nb_ostreams = 0;
644
    AVFormatContext *is, *os;
645
    AVCodecContext *codec, *icodec;
646
    AVOutputStream *ost, **ost_table = NULL;
647
    AVInputStream *ist, **ist_table = NULL;
648
    INT64 min_pts, start_time;
649
    AVInputFile *file_table;
650
    AVFormatContext *stream_no_data;
651
    int key;
652

    
653
    file_table= (AVInputFile*) av_mallocz(nb_input_files * sizeof(AVInputFile));
654
    if (!file_table)
655
        goto fail;
656

    
657
    /* input stream init */
658
    j = 0;
659
    for(i=0;i<nb_input_files;i++) {
660
        is = input_files[i];
661
        file_table[i].ist_index = j;
662
        file_table[i].nb_streams = is->nb_streams;
663
        j += is->nb_streams;
664
    }
665
    nb_istreams = j;
666

    
667
    ist_table = av_mallocz(nb_istreams * sizeof(AVInputStream *));
668
    if (!ist_table)
669
        goto fail;
670
    
671
    for(i=0;i<nb_istreams;i++) {
672
        ist = av_mallocz(sizeof(AVInputStream));
673
        if (!ist)
674
            goto fail;
675
        ist_table[i] = ist;
676
    }
677
    j = 0;
678
    for(i=0;i<nb_input_files;i++) {
679
        is = input_files[i];
680
        for(k=0;k<is->nb_streams;k++) {
681
            ist = ist_table[j++];
682
            ist->st = is->streams[k];
683
            ist->file_index = i;
684
            ist->index = k;
685
            ist->discard = 1; /* the stream is discarded by default
686
                                 (changed later) */
687
        }
688
    }
689

    
690
    /* output stream init */
691
    nb_ostreams = 0;
692
    for(i=0;i<nb_output_files;i++) {
693
        os = output_files[i];
694
        nb_ostreams += os->nb_streams;
695
        if (mpeg_vcd)
696
            os->flags |= AVF_FLAG_VCD;
697
    }
698
    if (nb_stream_maps > 0 && nb_stream_maps != nb_ostreams) {
699
        fprintf(stderr, "Number of stream maps must match number of output streams\n");
700
        exit(1);
701
    }
702

    
703
    ost_table = av_mallocz(sizeof(AVOutputStream *) * nb_ostreams);
704
    if (!ost_table)
705
        goto fail;
706
    for(i=0;i<nb_ostreams;i++) {
707
        ost = av_mallocz(sizeof(AVOutputStream));
708
        if (!ost)
709
            goto fail;
710
        ost_table[i] = ost;
711
    }
712
    
713
    n = 0;
714
    for(k=0;k<nb_output_files;k++) {
715
        os = output_files[k];
716
        for(i=0;i<os->nb_streams;i++) {
717
            int found;
718
            ost = ost_table[n++];
719
            ost->file_index = k;
720
            ost->index = i;
721
            ost->st = os->streams[i];
722
            if (nb_stream_maps > 0) {
723
                ost->source_index = file_table[stream_maps[n-1].file_index].ist_index + 
724
                    stream_maps[n-1].stream_index;
725
            } else {
726
                /* get corresponding input stream index : we select the first one with the right type */
727
                found = 0;
728
                for(j=0;j<nb_istreams;j++) {
729
                    ist = ist_table[j];
730
                    if (ist->discard && 
731
                        ist->st->codec.codec_type == ost->st->codec.codec_type) {
732
                        ost->source_index = j;
733
                        found = 1;
734
                    }
735
                }
736
                
737
                if (!found) {
738
                    /* try again and reuse existing stream */
739
                    for(j=0;j<nb_istreams;j++) {
740
                        ist = ist_table[j];
741
                        if (ist->st->codec.codec_type == ost->st->codec.codec_type) {
742
                            ost->source_index = j;
743
                            found = 1;
744
                        }
745
                    }
746
                    if (!found) {
747
                        fprintf(stderr, "Could not find input stream matching output stream #%d.%d\n",
748
                                ost->file_index, ost->index);
749
                        exit(1);
750
                    }
751
                }
752
            }
753
            ist = ist_table[ost->source_index];
754
            ist->discard = 0;
755
        }
756
    }
757

    
758
    /* for each output stream, we compute the right encoding parameters */
759
    for(i=0;i<nb_ostreams;i++) {
760
        ost = ost_table[i];
761
        ist = ist_table[ost->source_index];
762

    
763
        codec = &ost->st->codec;
764
        icodec = &ist->st->codec;
765

    
766
        if (ost->st->stream_copy) {
767
            /* if stream_copy is selected, no need to decode or encode */
768
            codec->codec_id = icodec->codec_id;
769
            codec->codec_type = icodec->codec_type;
770
            codec->codec_tag = icodec->codec_tag;
771
            codec->bit_rate = icodec->bit_rate;
772
            switch(codec->codec_type) {
773
            case CODEC_TYPE_AUDIO:
774
                codec->sample_rate = icodec->sample_rate;
775
                codec->channels = icodec->channels;
776
                break;
777
            case CODEC_TYPE_VIDEO:
778
                codec->frame_rate = icodec->frame_rate;
779
                codec->width = icodec->width;
780
                codec->height = icodec->height;
781
                break;
782
            default:
783
                av_abort();
784
            }
785
        } else {
786
            switch(codec->codec_type) {
787
            case CODEC_TYPE_AUDIO:
788
                if (fifo_init(&ost->fifo, 2 * MAX_AUDIO_PACKET_SIZE))
789
                    goto fail;
790
                
791
                if (codec->channels == icodec->channels &&
792
                    codec->sample_rate == icodec->sample_rate) {
793
                    ost->audio_resample = 0;
794
                } else {
795
                    if (codec->channels != icodec->channels &&
796
                        icodec->codec_id == CODEC_ID_AC3) {
797
                        /* Special case for 5:1 AC3 input */
798
                        /* and mono or stereo output      */
799
                        /* Request specific number of channels */
800
                        icodec->channels = codec->channels;
801
                        if (codec->sample_rate == icodec->sample_rate)
802
                            ost->audio_resample = 0;
803
                        else {
804
                            ost->audio_resample = 1;
805
                            ost->resample = audio_resample_init(codec->channels, icodec->channels,
806
                                                        codec->sample_rate, 
807
                                                        icodec->sample_rate);
808
                        }
809
                        /* Request specific number of channels */
810
                        icodec->channels = codec->channels;
811
                    } else {
812
                        ost->audio_resample = 1; 
813
                        ost->resample = audio_resample_init(codec->channels, icodec->channels,
814
                                                        codec->sample_rate, 
815
                                                        icodec->sample_rate);
816
                    }
817
                }
818
                ist->decoding_needed = 1;
819
                ost->encoding_needed = 1;
820
                break;
821
            case CODEC_TYPE_VIDEO:
822
                if (codec->width == icodec->width &&
823
                    codec->height == icodec->height) {
824
                    ost->video_resample = 0;
825
                } else {
826
                    UINT8 *buf;
827
                    ost->video_resample = 1;
828
                    buf = av_malloc((codec->width * codec->height * 3) / 2);
829
                    if (!buf)
830
                        goto fail;
831
                    ost->pict_tmp.data[0] = buf;
832
                    ost->pict_tmp.data[1] = ost->pict_tmp.data[0] + (codec->width * codec->height);
833
                    ost->pict_tmp.data[2] = ost->pict_tmp.data[1] + (codec->width * codec->height) / 4;
834
                    ost->pict_tmp.linesize[0] = codec->width;
835
                    ost->pict_tmp.linesize[1] = codec->width / 2;
836
                    ost->pict_tmp.linesize[2] = codec->width / 2;
837

    
838
                    ost->img_resample_ctx = img_resample_full_init( 
839
                                      ost->st->codec.width, ost->st->codec.height,
840
                                      ist->st->codec.width, ist->st->codec.height,
841
                                      frame_topBand, frame_bottomBand,
842
                                      frame_leftBand, frame_rightBand);
843
                }
844
                ost->encoding_needed = 1;
845
                ist->decoding_needed = 1;
846
                break;
847
            default:
848
                av_abort();
849
            }
850
            /* two pass mode */
851
            if (ost->encoding_needed && 
852
                (codec->flags & (CODEC_FLAG_PASS1 | CODEC_FLAG_PASS2))) {
853
                char logfilename[1024];
854
                FILE *f;
855
                int size;
856
                char *logbuffer;
857
                
858
                snprintf(logfilename, sizeof(logfilename), "%s-%d.log", 
859
                         pass_logfilename ? 
860
                         pass_logfilename : DEFAULT_PASS_LOGFILENAME, i);
861
                if (codec->flags & CODEC_FLAG_PASS1) {
862
                    f = fopen(logfilename, "w");
863
                    if (!f) {
864
                        perror(logfilename);
865
                        exit(1);
866
                    }
867
                    ost->logfile = f;
868
                } else {
869
                    /* read the log file */
870
                    f = fopen(logfilename, "r");
871
                    if (!f) {
872
                        perror(logfilename);
873
                        exit(1);
874
                    }
875
                    fseek(f, 0, SEEK_END);
876
                    size = ftell(f);
877
                    fseek(f, 0, SEEK_SET);
878
                    logbuffer = av_malloc(size + 1);
879
                    if (!logbuffer) {
880
                        fprintf(stderr, "Could not allocate log buffer\n");
881
                        exit(1);
882
                    }
883
                    fread(logbuffer, 1, size, f);
884
                    fclose(f);
885
                    logbuffer[size] = '\0';
886
                    codec->stats_in = logbuffer;
887
                }
888
            }
889
        }
890
    }
891

    
892
    /* dump the file output parameters - cannot be done before in case
893
       of stream copy */
894
    for(i=0;i<nb_output_files;i++) {
895
        dump_format(output_files[i], i, output_files[i]->filename, 1);
896
    }
897

    
898
    /* dump the stream mapping */
899
    fprintf(stderr, "Stream mapping:\n");
900
    for(i=0;i<nb_ostreams;i++) {
901
        ost = ost_table[i];
902
        fprintf(stderr, "  Stream #%d.%d -> #%d.%d\n",
903
                ist_table[ost->source_index]->file_index,
904
                ist_table[ost->source_index]->index,
905
                ost->file_index, 
906
                ost->index);
907
    }
908

    
909
    /* open each encoder */
910
    for(i=0;i<nb_ostreams;i++) {
911
        ost = ost_table[i];
912
        if (ost->encoding_needed) {
913
            AVCodec *codec;
914
            codec = avcodec_find_encoder(ost->st->codec.codec_id);
915
            if (!codec) {
916
                fprintf(stderr, "Unsupported codec for output stream #%d.%d\n", 
917
                        ost->file_index, ost->index);
918
                exit(1);
919
            }
920
            if (avcodec_open(&ost->st->codec, codec) < 0) {
921
                fprintf(stderr, "Error while opening codec for stream #%d.%d - maybe incorrect parameters such as bit_rate, rate, width or height\n", 
922
                        ost->file_index, ost->index);
923
                exit(1);
924
            }
925
        }
926
    }
927

    
928
    /* open each decoder */
929
    for(i=0;i<nb_istreams;i++) {
930
        ist = ist_table[i];
931
        if (ist->decoding_needed) {
932
            AVCodec *codec;
933
            codec = avcodec_find_decoder(ist->st->codec.codec_id);
934
            if (!codec) {
935
                fprintf(stderr, "Unsupported codec for input stream #%d.%d\n", 
936
                        ist->file_index, ist->index);
937
                exit(1);
938
            }
939
            if (avcodec_open(&ist->st->codec, codec) < 0) {
940
                fprintf(stderr, "Error while opening codec for input stream #%d.%d\n", 
941
                        ist->file_index, ist->index);
942
                exit(1);
943
            }
944
            //if (ist->st->codec.codec_type == CODEC_TYPE_VIDEO)
945
            //    ist->st->codec.flags |= CODEC_FLAG_REPEAT_FIELD;
946
        }
947
    }
948

    
949
    /* init pts */
950
    for(i=0;i<nb_istreams;i++) {
951
        ist = ist_table[i];
952
        ist->pts = 0;
953
        ist->frame_number = 0;
954
    }
955
    
956
    /* compute buffer size max (should use a complete heuristic) */
957
    for(i=0;i<nb_input_files;i++) {
958
        file_table[i].buffer_size_max = 2048;
959
    }
960

    
961
    /* open files and write file headers */
962
    for(i=0;i<nb_output_files;i++) {
963
        os = output_files[i];
964
        if (av_write_header(os) < 0) {
965
            fprintf(stderr, "Could not write header for output file #%d (incorrect codec paramters ?)\n", i);
966
            ret = -EINVAL;
967
            goto fail;
968
        }
969
    }
970

    
971
#ifndef CONFIG_WIN32
972
    if (!do_play) {
973
        fprintf(stderr, "Press [q] to stop encoding\n");
974
    } else {
975
        fprintf(stderr, "Press [q] to stop playing\n");
976
    }
977
#endif
978
    term_init();
979

    
980
    start_time = av_gettime();
981
    min_pts = 0;
982
    stream_no_data = 0;
983
    key = -1;
984

    
985
    for(;;) {
986
        int file_index, ist_index;
987
        AVPacket pkt;
988
        UINT8 *ptr;
989
        int len;
990
        UINT8 *data_buf;
991
        int data_size, got_picture;
992
        AVPicture picture;
993
        short samples[AVCODEC_MAX_AUDIO_FRAME_SIZE / 2];
994

    
995
    redo:
996
        /* if 'q' pressed, exits */
997
        if (key) {
998
            /* read_key() returns 0 on EOF */
999
            key = read_key();
1000
            if (key == 'q')
1001
                break;
1002
        }
1003

    
1004
        /* select the input file with the smallest pts */
1005
        file_index = -1;
1006
        min_pts = MAXINT64;
1007
        for(i=0;i<nb_istreams;i++) {
1008
            ist = ist_table[i];
1009
            /* For some reason, the pts_increment code breaks q estimation?!? */
1010
            if (!ist->discard && !file_table[ist->file_index].eof_reached && 
1011
                ist->pts /* + ist->pts_increment */ < min_pts && input_files[ist->file_index] != stream_no_data) {
1012
                min_pts = ist->pts /* + ist->pts_increment */;
1013
                file_index = ist->file_index;
1014
            }
1015
        }
1016
        /* if none, if is finished */
1017
        if (file_index < 0) {
1018
            if (stream_no_data) {
1019
#ifndef CONFIG_WIN32 /* no usleep in VisualC ? */
1020
#ifdef __BEOS__
1021
                snooze(10 * 1000); /* mmu_man */ /* in microsec */
1022
#elif defined(__CYGWIN__)
1023
                usleep(10 * 1000); 
1024
#else
1025
                struct timespec ts;
1026

    
1027
                ts.tv_sec = 0;
1028
                ts.tv_nsec = 1000 * 1000 * 10;
1029
                nanosleep(&ts, 0);
1030
#endif
1031
#endif
1032
                stream_no_data = 0;
1033
                continue;
1034
            }
1035
            break;
1036
        }    
1037
        /* finish if recording time exhausted */
1038
        if (recording_time > 0 && min_pts >= recording_time)
1039
            break;
1040
        /* read a packet from it and output it in the fifo */
1041
        is = input_files[file_index];
1042
        if (av_read_packet(is, &pkt) < 0) {
1043
            file_table[file_index].eof_reached = 1;
1044
            continue;
1045
        }
1046
        if (!pkt.size) {
1047
            stream_no_data = is;
1048
        } else {
1049
            stream_no_data = 0;
1050
        }
1051
        /* the following test is needed in case new streams appear
1052
           dynamically in stream : we ignore them */
1053
        if (pkt.stream_index >= file_table[file_index].nb_streams)
1054
            goto discard_packet;
1055
        ist_index = file_table[file_index].ist_index + pkt.stream_index;
1056
        ist = ist_table[ist_index];
1057
        if (ist->discard)
1058
            goto discard_packet;
1059

    
1060
        if (pkt.flags & PKT_FLAG_DROPPED_FRAME)
1061
            ist->frame_number++;
1062

    
1063
        if (do_hex_dump) {
1064
            printf("stream #%d, size=%d:\n", pkt.stream_index, pkt.size);
1065
            av_hex_dump(pkt.data, pkt.size);
1066
        }
1067

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

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

    
1074
            /* decode the packet if needed */
1075
            data_buf = NULL; /* fail safe */
1076
            data_size = 0;
1077
            if (ist->decoding_needed) {
1078
                switch(ist->st->codec.codec_type) {
1079
                case CODEC_TYPE_AUDIO:
1080
                    /* XXX: could avoid copy if PCM 16 bits with same
1081
                       endianness as CPU */
1082
                    ret = avcodec_decode_audio(&ist->st->codec, samples, &data_size,
1083
                                               ptr, len);
1084
                    if (ret < 0)
1085
                        goto fail_decode;
1086
                    /* Some bug in mpeg audio decoder gives */
1087
                    /* data_size < 0, it seems they are overflows */
1088
                    if (data_size <= 0) {
1089
                        /* no audio frame */
1090
                        ptr += ret;
1091
                        len -= ret;
1092
                        continue;
1093
                    }
1094
                    data_buf = (UINT8 *)samples;
1095
                    break;
1096
                case CODEC_TYPE_VIDEO:
1097
                    if (ist->st->codec.codec_id == CODEC_ID_RAWVIDEO) {
1098
                        int size;
1099

    
1100
                        size = (ist->st->codec.width * ist->st->codec.height);
1101
                        avpicture_fill(&picture, ptr, 
1102
                                     ist->st->codec.pix_fmt,
1103
                                     ist->st->codec.width,
1104
                                     ist->st->codec.height);
1105
                        ret = len;
1106
                    } else {
1107
                        data_size = (ist->st->codec.width * ist->st->codec.height * 3) / 2;
1108
                        ret = avcodec_decode_video(&ist->st->codec, 
1109
                                                   &picture, &got_picture, ptr, len);
1110
                        if (ret < 0) {
1111
                        fail_decode:
1112
                            fprintf(stderr, "Error while decoding stream #%d.%d\n",
1113
                                    ist->file_index, ist->index);
1114
                            av_free_packet(&pkt);
1115
                            goto redo;
1116
                        }
1117
                        if (!got_picture) {
1118
                            /* no picture yet */
1119
                            ptr += ret;
1120
                            len -= ret;
1121
                            continue;
1122
                        }
1123
                                  
1124
                    }
1125
                    break;
1126
                default:
1127
                    goto fail_decode;
1128
                }
1129
            } else {
1130
                data_buf = ptr;
1131
                data_size = len;
1132
                ret = len;
1133
            }
1134
            /* init tickers */
1135
            if (!ist->ticker_inited) {
1136
                switch (ist->st->codec.codec_type) {
1137
                case CODEC_TYPE_AUDIO:
1138
                    ticker_init(&ist->pts_ticker,
1139
                            (INT64)ist->st->codec.sample_rate,
1140
                            (INT64)(1000000));
1141
                    ist->ticker_inited = 1;
1142
                    break;
1143
                case CODEC_TYPE_VIDEO:
1144
                    ticker_init(&ist->pts_ticker,
1145
                            (INT64)ist->st->r_frame_rate,
1146
                            ((INT64)1000000 * FRAME_RATE_BASE));
1147
                    ist->ticker_inited = 1;
1148
                    break;
1149
                default:
1150
                    av_abort();
1151
                }
1152
            }
1153
            /* update pts */
1154
            switch(ist->st->codec.codec_type) {
1155
            case CODEC_TYPE_AUDIO:
1156
                //ist->pts = (INT64)1000000 * ist->sample_index / ist->st->codec.sample_rate;
1157
                ist->pts = ticker_abs(&ist->pts_ticker, ist->sample_index);
1158
                ist->sample_index += data_size / (2 * ist->st->codec.channels);
1159
                ist->pts_increment = (INT64) (data_size / (2 * ist->st->codec.channels)) * 1000000 / ist->st->codec.sample_rate;
1160
                break;
1161
            case CODEC_TYPE_VIDEO:
1162
                ist->frame_number++;
1163
                //ist->pts = ((INT64)ist->frame_number * 1000000 * FRAME_RATE_BASE) / 
1164
                //    ist->st->codec.frame_rate;
1165
                ist->pts = ticker_abs(&ist->pts_ticker, ist->frame_number);
1166
                ist->pts_increment = ((INT64) 1000000 * FRAME_RATE_BASE) / 
1167
                    ist->st->codec.frame_rate;
1168
                break;
1169
            default:
1170
                av_abort();
1171
            }
1172
            ptr += ret;
1173
            len -= ret;
1174

    
1175
            /* transcode raw format, encode packets and output them */
1176
            
1177
            for(i=0;i<nb_ostreams;i++) {
1178
                int frame_size;
1179
                ost = ost_table[i];
1180
                if (ost->source_index == ist_index) {
1181
                    os = output_files[ost->file_index];
1182

    
1183
                    if (ost->encoding_needed) {
1184
                        switch(ost->st->codec.codec_type) {
1185
                        case CODEC_TYPE_AUDIO:
1186
                            do_audio_out(os, ost, ist, data_buf, data_size);
1187
                            break;
1188
                        case CODEC_TYPE_VIDEO:
1189
                            do_video_out(os, ost, ist, &picture, &frame_size);
1190
                            if (do_vstats)
1191
                                do_video_stats(ost, ist, frame_size);
1192
                            break;
1193
                        default:
1194
                            av_abort();
1195
                        }
1196
                    } else {
1197
                        /* no reencoding needed : output the packet directly */
1198
                        /* force the input stream PTS */
1199
                        os->oformat->write_packet(os, ost->index, data_buf, data_size, pkt.pts);
1200
                    }
1201
                }
1202
            }
1203
        }
1204
    discard_packet:
1205
        av_free_packet(&pkt);
1206
        
1207
        /* dump report by using the first video and audio streams */
1208
        {
1209
            char buf[1024];
1210
            AVFormatContext *oc;
1211
            INT64 total_size, ti;
1212
            AVCodecContext *enc;
1213
            int frame_number, vid;
1214
            double bitrate, ti1;
1215
            static INT64 last_time;
1216

    
1217
            if ((min_pts - last_time) >= 500000) {
1218
                last_time = min_pts;
1219
                
1220
                oc = output_files[0];
1221
                
1222
                total_size = url_ftell(&oc->pb);
1223
                
1224
                buf[0] = '\0';
1225
                ti = MAXINT64;
1226
                vid = 0;
1227
                for(i=0;i<nb_ostreams;i++) {
1228
                    ost = ost_table[i];
1229
                    enc = &ost->st->codec;
1230
                    ist = ist_table[ost->source_index];
1231
                    if (!vid && enc->codec_type == CODEC_TYPE_VIDEO) {
1232
                        frame_number = ist->frame_number;
1233
                        sprintf(buf + strlen(buf), "frame=%5d q=%2d ",
1234
                                frame_number, enc->quality);
1235
                        if (do_psnr)
1236
                            sprintf(buf + strlen(buf), "PSNR=%6.2f ", enc->psnr_y);
1237
                        vid = 1;
1238
                    }
1239
                    /* compute min pts value */
1240
                    if (!ist->discard && ist->pts < ti) {
1241
                        ti = ist->pts;
1242
                    }
1243
                }
1244

    
1245
                ti1 = (double)ti / 1000000.0;
1246
                if (ti1 < 0.01)
1247
                    ti1 = 0.01;
1248
                bitrate = (double)(total_size * 8) / ti1 / 1000.0;
1249

    
1250
                sprintf(buf + strlen(buf), 
1251
                        "size=%8.0fkB time=%0.1f bitrate=%6.1fkbits/s",
1252
                        (double)total_size / 1024, ti1, bitrate);
1253
                
1254
                fprintf(stderr, "%s   \r", buf);
1255
                fflush(stderr);
1256
            }
1257
        }
1258
    }
1259
    term_exit();
1260

    
1261
    /* dump report by using the first video and audio streams */
1262
    {
1263
        char buf[1024];
1264
        AVFormatContext *oc;
1265
        INT64 total_size, ti;
1266
        AVCodecContext *enc;
1267
        int frame_number, vid;
1268
        double bitrate, ti1;
1269

    
1270
        oc = output_files[0];
1271
        
1272
        total_size = url_ftell(&oc->pb);
1273
        
1274
        buf[0] = '\0';
1275
        ti = MAXINT64;
1276
        vid = 0;
1277
        for(i=0;i<nb_ostreams;i++) {
1278
            ost = ost_table[i];
1279
            enc = &ost->st->codec;
1280
            ist = ist_table[ost->source_index];
1281
            if (!vid && enc->codec_type == CODEC_TYPE_VIDEO) {
1282
                frame_number = ist->frame_number;
1283
                sprintf(buf + strlen(buf), "frame=%5d q=%2d ",
1284
                        frame_number, enc->quality);
1285
                if (do_psnr)
1286
                    sprintf(buf + strlen(buf), "PSNR=%6.2f ", enc->psnr_y);
1287
                vid = 1;
1288
            }
1289
            /* compute min pts value */
1290
            if (!ist->discard && ist->pts < ti) {
1291
                ti = ist->pts;
1292
            }
1293
        }
1294
        
1295
        ti1 = ti / 1000000.0;
1296
        if (ti1 < 0.01)
1297
            ti1 = 0.01;
1298
        bitrate = (double)(total_size * 8) / ti1 / 1000.0;
1299
        
1300
        sprintf(buf + strlen(buf), 
1301
                "size=%8.0fkB time=%0.1f bitrate=%6.1fkbits/s",
1302
                (double)total_size / 1024, ti1, bitrate);
1303
        
1304
        fprintf(stderr, "%s   \n", buf);
1305
    }
1306
    /* close each encoder */
1307
    for(i=0;i<nb_ostreams;i++) {
1308
        ost = ost_table[i];
1309
        if (ost->encoding_needed) {
1310
            av_freep(&ost->st->codec.stats_in);
1311
            avcodec_close(&ost->st->codec);
1312
        }
1313
    }
1314
    
1315
    /* close each decoder */
1316
    for(i=0;i<nb_istreams;i++) {
1317
        ist = ist_table[i];
1318
        if (ist->decoding_needed) {
1319
            avcodec_close(&ist->st->codec);
1320
        }
1321
    }
1322
    
1323

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

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

    
1368
#if 0
1369
int file_read(const char *filename)
1370
{
1371
    URLContext *h;
1372
    unsigned char buffer[1024];
1373
    int len, i;
1374

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

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

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

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

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

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

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

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

    
1447
void opt_video_rc_eq(char *arg)
1448
{
1449
    video_rc_eq = arg;
1450
}
1451

    
1452

    
1453
void opt_workaround_bugs(const char *arg)
1454
{
1455
    workaround_bugs = atoi(arg);
1456
}
1457

    
1458
void opt_dct_algo(const char *arg)
1459
{
1460
    dct_algo = atoi(arg);
1461
}
1462

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

    
1468

    
1469
void opt_error_resilience(const char *arg)
1470
{
1471
    error_resilience = atoi(arg);
1472
}
1473

    
1474
void opt_error_concealment(const char *arg)
1475
{
1476
    error_concealment = atoi(arg);
1477
}
1478

    
1479

    
1480
void opt_frame_rate(const char *arg)
1481
{
1482
    frame_rate = (int)(strtod(arg, 0) * FRAME_RATE_BASE);
1483
}
1484

    
1485

    
1486
void opt_frame_crop_top(const char *arg)
1487
{
1488
    frame_topBand = atoi(arg); 
1489
    if (frame_topBand < 0) {
1490
        fprintf(stderr, "Incorrect top crop size\n");
1491
        exit(1);
1492
    }
1493
    if ((frame_topBand % 2) != 0) {
1494
        fprintf(stderr, "Top crop size must be a multiple of 2\n");
1495
        exit(1);
1496
    }
1497
    if ((frame_topBand) >= frame_height){
1498
            fprintf(stderr, "Vertical crop dimensions are outside the range of the original image.\nRemember to crop first and scale second.\n");
1499
        exit(1);
1500
    }
1501
    frame_height -= frame_topBand;
1502
}
1503

    
1504
void opt_frame_crop_bottom(const char *arg)
1505
{
1506
    frame_bottomBand = atoi(arg);
1507
    if (frame_bottomBand < 0) {
1508
        fprintf(stderr, "Incorrect bottom crop size\n");
1509
        exit(1);
1510
    }
1511
    if ((frame_bottomBand % 2) != 0) {
1512
        fprintf(stderr, "Bottom crop size must be a multiple of 2\n");
1513
        exit(1);        
1514
    }
1515
    if ((frame_bottomBand) >= frame_height){
1516
            fprintf(stderr, "Vertical crop dimensions are outside the range of the original image.\nRemember to crop first and scale second.\n");
1517
        exit(1);
1518
    }
1519
    frame_height -= frame_bottomBand;
1520
}
1521

    
1522
void opt_frame_crop_left(const char *arg)
1523
{
1524
    frame_leftBand = atoi(arg);
1525
    if (frame_leftBand < 0) {
1526
        fprintf(stderr, "Incorrect left crop size\n");
1527
        exit(1);
1528
    }
1529
    if ((frame_leftBand % 2) != 0) {
1530
        fprintf(stderr, "Left crop size must be a multiple of 2\n");
1531
        exit(1);
1532
    }
1533
    if ((frame_leftBand) >= frame_width){
1534
            fprintf(stderr, "Horizontal crop dimensions are outside the range of the original image.\nRemember to crop first and scale second.\n");
1535
        exit(1);
1536
    }
1537
    frame_width -= frame_leftBand;
1538
}
1539

    
1540
void opt_frame_crop_right(const char *arg)
1541
{
1542
    frame_rightBand = atoi(arg);
1543
    if (frame_rightBand < 0) {
1544
        fprintf(stderr, "Incorrect right crop size\n");
1545
        exit(1);
1546
    }
1547
    if ((frame_rightBand % 2) != 0) {
1548
        fprintf(stderr, "Right crop size must be a multiple of 2\n");
1549
        exit(1);        
1550
    }
1551
    if ((frame_rightBand) >= frame_width){
1552
            fprintf(stderr, "Horizontal crop dimensions are outside the range of the original image.\nRemember to crop first and scale second.\n");
1553
        exit(1);
1554
    }
1555
    frame_width -= frame_rightBand;
1556
}
1557

    
1558
void opt_frame_size(const char *arg)
1559
{
1560
    parse_image_size(&frame_width, &frame_height, arg);
1561
    if (frame_width <= 0 || frame_height <= 0) {
1562
        fprintf(stderr, "Incorrect frame size\n");
1563
        exit(1);
1564
    }
1565
    if ((frame_width % 2) != 0 || (frame_height % 2) != 0) {
1566
        fprintf(stderr, "Frame size must be a multiple of 2\n");
1567
        exit(1);
1568
    }
1569
}
1570

    
1571
void opt_gop_size(const char *arg)
1572
{
1573
    gop_size = atoi(arg);
1574
}
1575

    
1576
void opt_b_frames(const char *arg)
1577
{
1578
    b_frames = atoi(arg);
1579
    if (b_frames > FF_MAX_B_FRAMES) {
1580
        fprintf(stderr, "\nCannot have more than %d B frames, increase FF_MAX_B_FRAMES.\n", FF_MAX_B_FRAMES);
1581
        exit(1);
1582
    } else if (b_frames < 1) {
1583
        fprintf(stderr, "\nNumber of B frames must be higher than 0\n");
1584
        exit(1);
1585
    }
1586
}
1587

    
1588
void opt_qscale(const char *arg)
1589
{
1590
    video_qscale = atoi(arg);
1591
    if (video_qscale < 0 ||
1592
        video_qscale > 31) {
1593
        fprintf(stderr, "qscale must be >= 1 and <= 31\n");
1594
        exit(1);
1595
    }
1596
}
1597

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

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

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

    
1628
void opt_qblur(const char *arg)
1629
{
1630
    video_qblur = atof(arg);
1631
}
1632

    
1633
void opt_qcomp(const char *arg)
1634
{
1635
    video_qcomp = atof(arg);
1636
}
1637

    
1638
void opt_b_qfactor(const char *arg)
1639
{
1640
    video_b_qfactor = atof(arg);
1641
}
1642
void opt_i_qfactor(const char *arg)
1643
{
1644
    video_i_qfactor = atof(arg);
1645
}
1646
void opt_b_qoffset(const char *arg)
1647
{
1648
    video_b_qoffset = atof(arg);
1649
}
1650
void opt_i_qoffset(const char *arg)
1651
{
1652
    video_i_qoffset = atof(arg);
1653
}
1654

    
1655
void opt_packet_size(const char *arg)
1656
{
1657
    packet_size= atoi(arg);
1658
}
1659

    
1660
void opt_audio_bitrate(const char *arg)
1661
{
1662
    audio_bit_rate = atoi(arg) * 1000;
1663
}
1664

    
1665
void opt_audio_rate(const char *arg)
1666
{
1667
    audio_sample_rate = atoi(arg);
1668
}
1669

    
1670
void opt_audio_channels(const char *arg)
1671
{
1672
    audio_channels = atoi(arg);
1673
}
1674

    
1675
void opt_video_device(const char *arg)
1676
{
1677
    v4l_device = strdup(arg);
1678
}
1679

    
1680
void opt_audio_device(const char *arg)
1681
{
1682
    audio_device = strdup(arg);
1683
}
1684

    
1685
void opt_audio_codec(const char *arg)
1686
{
1687
    AVCodec *p;
1688

    
1689
    if (!strcmp(arg, "copy")) {
1690
        audio_stream_copy = 1;
1691
    } else {
1692
        p = first_avcodec;
1693
        while (p) {
1694
            if (!strcmp(p->name, arg) && p->type == CODEC_TYPE_AUDIO)
1695
                break;
1696
            p = p->next;
1697
        }
1698
        if (p == NULL) {
1699
            fprintf(stderr, "Unknown audio codec '%s'\n", arg);
1700
            exit(1);
1701
        } else {
1702
            audio_codec_id = p->id;
1703
        }
1704
    }
1705
}
1706

    
1707
const char *motion_str[] = {
1708
    "zero",
1709
    "full",
1710
    "log",
1711
    "phods",
1712
    "epzs",
1713
    "x1",
1714
    NULL,
1715
};
1716

    
1717
void opt_motion_estimation(const char *arg)
1718
{
1719
    const char **p;
1720
    p = motion_str;
1721
    for(;;) {
1722
        if (!*p) {
1723
            fprintf(stderr, "Unknown motion estimation method '%s'\n", arg);
1724
            exit(1);
1725
        }
1726
        if (!strcmp(*p, arg))
1727
            break;
1728
        p++;
1729
    }
1730
    me_method = (p - motion_str) + 1;
1731
}
1732

    
1733
void opt_video_codec(const char *arg)
1734
{
1735
    AVCodec *p;
1736

    
1737
    if (!strcmp(arg, "copy")) {
1738
        video_stream_copy = 1;
1739
    } else {
1740
        p = first_avcodec;
1741
        while (p) {
1742
            if (!strcmp(p->name, arg) && p->type == CODEC_TYPE_VIDEO)
1743
                break;
1744
            p = p->next;
1745
        }
1746
        if (p == NULL) {
1747
            fprintf(stderr, "Unknown video codec '%s'\n", arg);
1748
            exit(1);
1749
        } else {
1750
            video_codec_id = p->id;
1751
        }
1752
    }
1753
}
1754

    
1755
void opt_map(const char *arg)
1756
{
1757
    AVStreamMap *m;
1758
    const char *p;
1759

    
1760
    p = arg;
1761
    m = &stream_maps[nb_stream_maps++];
1762

    
1763
    m->file_index = strtol(arg, (char **)&p, 0);
1764
    if (*p)
1765
        p++;
1766

    
1767
    m->stream_index = strtol(p, (char **)&p, 0);
1768
}
1769

    
1770
void opt_recording_time(const char *arg)
1771
{
1772
    recording_time = parse_date(arg, 1);
1773
}
1774

    
1775
void print_error(const char *filename, int err)
1776
{
1777
    switch(err) {
1778
    case AVERROR_NUMEXPECTED:
1779
        fprintf(stderr, "%s: Incorrect image filename syntax.\n"
1780
                "Use '%%d' to specify the image number:\n"
1781
                "  for img1.jpg, img2.jpg, ..., use 'img%%d.jpg';\n"
1782
                "  for img001.jpg, img002.jpg, ..., use 'img%%03d.jpg'.\n", 
1783
                filename);
1784
        break;
1785
    case AVERROR_INVALIDDATA:
1786
        fprintf(stderr, "%s: Error while parsing header\n", filename);
1787
        break;
1788
    case AVERROR_NOFMT:
1789
        fprintf(stderr, "%s: Unknown format\n", filename);
1790
        break;
1791
    default:
1792
        fprintf(stderr, "%s: Error while opening file\n", filename);
1793
        break;
1794
    }
1795
}
1796

    
1797
void opt_input_file(const char *filename)
1798
{
1799
    AVFormatContext *ic;
1800
    AVFormatParameters params, *ap = &params;
1801
    int err, i, ret, rfps;
1802

    
1803
    /* get default parameters from command line */
1804
    memset(ap, 0, sizeof(*ap));
1805
    ap->sample_rate = audio_sample_rate;
1806
    ap->channels = audio_channels;
1807
    ap->frame_rate = frame_rate;
1808
    ap->width = frame_width;
1809
    ap->height = frame_height;
1810

    
1811
    /* open the input file with generic libav function */
1812
    err = av_open_input_file(&ic, filename, file_iformat, 0, ap);
1813
    if (err < 0) {
1814
        print_error(filename, err);
1815
        exit(1);
1816
    }
1817
    
1818
    /* If not enough info to get the stream parameters, we decode the
1819
       first frames to get it. (used in mpeg case for example) */
1820
    ret = av_find_stream_info(ic);
1821
    if (ret < 0) {
1822
        fprintf(stderr, "%s: could not find codec parameters\n", filename);
1823
        exit(1);
1824
    }
1825

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

    
1864
void check_audio_video_inputs(int *has_video_ptr, int *has_audio_ptr)
1865
{
1866
    int has_video, has_audio, i, j;
1867
    AVFormatContext *ic;
1868

    
1869
    has_video = 0;
1870
    has_audio = 0;
1871
    for(j=0;j<nb_input_files;j++) {
1872
        ic = input_files[j];
1873
        for(i=0;i<ic->nb_streams;i++) {
1874
            AVCodecContext *enc = &ic->streams[i]->codec;
1875
            switch(enc->codec_type) {
1876
            case CODEC_TYPE_AUDIO:
1877
                has_audio = 1;
1878
                break;
1879
            case CODEC_TYPE_VIDEO:
1880
                has_video = 1;
1881
                break;
1882
            default:
1883
                av_abort();
1884
            }
1885
        }
1886
    }
1887
    *has_video_ptr = has_video;
1888
    *has_audio_ptr = has_audio;
1889
}
1890

    
1891
void opt_output_file(const char *filename)
1892
{
1893
    AVStream *st;
1894
    AVFormatContext *oc;
1895
    int use_video, use_audio, nb_streams, input_has_video, input_has_audio;
1896
    int codec_id;
1897

    
1898
    if (!strcmp(filename, "-"))
1899
        filename = "pipe:";
1900

    
1901
    oc = av_mallocz(sizeof(AVFormatContext));
1902

    
1903
    if (!file_oformat) {
1904
        file_oformat = guess_format(NULL, filename, NULL);
1905
        if (!file_oformat) {
1906
            fprintf(stderr, "Unable for find a suitable output format for '%s'\n",
1907
                    filename);
1908
            exit(1);
1909
        }
1910
    }
1911
    
1912
    oc->oformat = file_oformat;
1913

    
1914
    if (!strcmp(file_oformat->name, "ffm") && 
1915
        strstart(filename, "http:", NULL)) {
1916
        /* special case for files sent to ffserver: we get the stream
1917
           parameters from ffserver */
1918
        if (read_ffserver_streams(oc, filename) < 0) {
1919
            fprintf(stderr, "Could not read stream parameters from '%s'\n", filename);
1920
            exit(1);
1921
        }
1922
    } else {
1923
        use_video = file_oformat->video_codec != CODEC_ID_NONE;
1924
        use_audio = file_oformat->audio_codec != CODEC_ID_NONE;
1925

    
1926
        /* disable if no corresponding type found and at least one
1927
           input file */
1928
        if (nb_input_files > 0) {
1929
            check_audio_video_inputs(&input_has_video, &input_has_audio);
1930
            if (!input_has_video)
1931
                use_video = 0;
1932
            if (!input_has_audio)
1933
                use_audio = 0;
1934
        }
1935

    
1936
        /* manual disable */
1937
        if (audio_disable) {
1938
            use_audio = 0;
1939
        }
1940
        if (video_disable) {
1941
            use_video = 0;
1942
        }
1943
        
1944
        nb_streams = 0;
1945
        if (use_video) {
1946
            AVCodecContext *video_enc;
1947
            
1948
            st = av_mallocz(sizeof(AVStream));
1949
            if (!st) {
1950
                fprintf(stderr, "Could not alloc stream\n");
1951
                exit(1);
1952
            }
1953

    
1954
            video_enc = &st->codec;
1955
            if (video_stream_copy) {
1956
                st->stream_copy = 1;
1957
                video_enc->codec_type = CODEC_TYPE_VIDEO;
1958
            } else {
1959
                codec_id = file_oformat->video_codec;
1960
                if (video_codec_id != CODEC_ID_NONE)
1961
                    codec_id = video_codec_id;
1962
                
1963
                video_enc->codec_id = codec_id;
1964
                
1965
                video_enc->bit_rate = video_bit_rate;
1966
                video_enc->bit_rate_tolerance = video_bit_rate_tolerance;
1967
                video_enc->frame_rate = frame_rate; 
1968
                
1969
                video_enc->width = frame_width;
1970
                video_enc->height = frame_height;
1971

    
1972
                if (!intra_only)
1973
                    video_enc->gop_size = gop_size;
1974
                else
1975
                    video_enc->gop_size = 0;
1976
                if (video_qscale || same_quality) {
1977
                    video_enc->flags |= CODEC_FLAG_QSCALE;
1978
                    video_enc->quality = video_qscale;
1979
                }
1980
            
1981
                if (use_hq) {
1982
                    video_enc->flags |= CODEC_FLAG_HQ;
1983
                }
1984
            
1985
                if (use_4mv) {
1986
                    video_enc->flags |= CODEC_FLAG_HQ;
1987
                    video_enc->flags |= CODEC_FLAG_4MV;
1988
                }
1989
            
1990
                if(use_part)
1991
                    video_enc->flags |= CODEC_FLAG_PART;
1992
               
1993
            
1994
                if (b_frames) {
1995
                    if (codec_id != CODEC_ID_MPEG4) {
1996
                        fprintf(stderr, "\nB frames encoding only supported by MPEG-4.\n");
1997
                        exit(1);
1998
                    }
1999
                    video_enc->max_b_frames = b_frames;
2000
                    video_enc->b_frame_strategy = 0;
2001
                    video_enc->b_quant_factor = 2.0;
2002
                }
2003
            
2004
                video_enc->qmin = video_qmin;
2005
                video_enc->qmax = video_qmax;
2006
                video_enc->max_qdiff = video_qdiff;
2007
                video_enc->qblur = video_qblur;
2008
                video_enc->qcompress = video_qcomp;
2009
                video_enc->rc_eq = video_rc_eq;
2010
                video_enc->rc_max_rate = video_rc_max_rate;
2011
                video_enc->rc_min_rate = video_rc_min_rate;
2012
                video_enc->rc_buffer_size = video_rc_buffer_size;
2013
                video_enc->rc_buffer_aggressivity= video_rc_buffer_aggressivity;
2014
                video_enc->i_quant_factor = video_i_qfactor;
2015
                video_enc->b_quant_factor = video_b_qfactor;
2016
                video_enc->i_quant_offset = video_i_qoffset;
2017
                video_enc->b_quant_offset = video_b_qoffset;
2018
                video_enc->dct_algo = dct_algo;
2019
                video_enc->idct_algo = idct_algo;
2020
                if(packet_size){
2021
                    video_enc->rtp_mode= 1;
2022
                    video_enc->rtp_payload_size= packet_size;
2023
                }
2024
            
2025
                if (do_psnr)
2026
                    video_enc->get_psnr = 1;
2027
                else
2028
                    video_enc->get_psnr = 0;
2029
            
2030
                video_enc->me_method = me_method;
2031

    
2032
                /* two pass mode */
2033
                if (do_pass) {
2034
                    if (do_pass == 1) {
2035
                        video_enc->flags |= CODEC_FLAG_PASS1;
2036
                    } else {
2037
                        video_enc->flags |= CODEC_FLAG_PASS2;
2038
                    }
2039
                }
2040
            
2041
                /* XXX: need to find a way to set codec parameters */
2042
                if (oc->oformat->flags & AVFMT_RGB24) {
2043
                    video_enc->pix_fmt = PIX_FMT_RGB24;
2044
                }
2045
            }
2046
            oc->streams[nb_streams] = st;
2047
            nb_streams++;
2048
        }
2049
    
2050
        if (use_audio) {
2051
            AVCodecContext *audio_enc;
2052

    
2053
            st = av_mallocz(sizeof(AVStream));
2054
            if (!st) {
2055
                fprintf(stderr, "Could not alloc stream\n");
2056
                exit(1);
2057
            }
2058

    
2059
            audio_enc = &st->codec;
2060
            audio_enc->codec_type = CODEC_TYPE_AUDIO;
2061
            if (audio_stream_copy) {
2062
                st->stream_copy = 1;
2063
            } else {
2064
                codec_id = file_oformat->audio_codec;
2065
                if (audio_codec_id != CODEC_ID_NONE)
2066
                    codec_id = audio_codec_id;
2067
                audio_enc->codec_id = codec_id;
2068
                
2069
                audio_enc->bit_rate = audio_bit_rate;
2070
                audio_enc->sample_rate = audio_sample_rate;
2071
                /* For audio codecs other than AC3 we limit */
2072
                /* the number of coded channels to stereo   */
2073
                if (audio_channels > 2 && codec_id != CODEC_ID_AC3) {
2074
                    audio_enc->channels = 2;
2075
                } else
2076
                    audio_enc->channels = audio_channels;
2077
            }
2078
            oc->streams[nb_streams] = st;
2079
            nb_streams++;
2080
        }
2081

    
2082
        oc->nb_streams = nb_streams;
2083

    
2084
        if (!nb_streams) {
2085
            fprintf(stderr, "No audio or video streams available\n");
2086
            exit(1);
2087
        }
2088

    
2089
        if (str_title)
2090
            pstrcpy(oc->title, sizeof(oc->title), str_title);
2091
        if (str_author)
2092
            pstrcpy(oc->author, sizeof(oc->author), str_author);
2093
        if (str_copyright)
2094
            pstrcpy(oc->copyright, sizeof(oc->copyright), str_copyright);
2095
        if (str_comment)
2096
            pstrcpy(oc->comment, sizeof(oc->comment), str_comment);
2097
    }
2098

    
2099
    output_files[nb_output_files++] = oc;
2100

    
2101
    strcpy(oc->filename, filename);
2102

    
2103
    /* check filename in case of an image number is expected */
2104
    if (oc->oformat->flags & AVFMT_NEEDNUMBER) {
2105
        if (filename_number_test(oc->filename) < 0) {
2106
            print_error(oc->filename, AVERROR_NUMEXPECTED);
2107
            exit(1);
2108
        }
2109
    }
2110

    
2111
    if (!(oc->oformat->flags & AVFMT_NOFILE)) {
2112
        /* test if it already exists to avoid loosing precious files */
2113
        if (!file_overwrite && 
2114
            (strchr(filename, ':') == NULL ||
2115
             strstart(filename, "file:", NULL))) {
2116
            if (url_exist(filename)) {
2117
                int c;
2118
                
2119
                printf("File '%s' already exists. Overwrite ? [y/N] ", filename);
2120
                fflush(stdout);
2121
                c = getchar();
2122
                if (toupper(c) != 'Y') {
2123
                    fprintf(stderr, "Not overwriting - exiting\n");
2124
                    exit(1);
2125
                }
2126
            }
2127
        }
2128
        
2129
        /* open the file */
2130
        if (url_fopen(&oc->pb, filename, URL_WRONLY) < 0) {
2131
            fprintf(stderr, "Could not open '%s'\n", filename);
2132
            exit(1);
2133
        }
2134
    }
2135

    
2136
    /* reset some options */
2137
    file_oformat = NULL;
2138
    file_iformat = NULL;
2139
    audio_disable = 0;
2140
    video_disable = 0;
2141
    audio_codec_id = CODEC_ID_NONE;
2142
    video_codec_id = CODEC_ID_NONE;
2143
    audio_stream_copy = 0;
2144
    video_stream_copy = 0;
2145
}
2146

    
2147
/* prepare dummy protocols for grab */
2148
void prepare_grab(void)
2149
{
2150
    int has_video, has_audio, i, j;
2151
    AVFormatContext *oc;
2152
    AVFormatContext *ic;
2153
    AVFormatParameters ap1, *ap = &ap1;
2154

    
2155
    /* see if audio/video inputs are needed */
2156
    has_video = 0;
2157
    has_audio = 0;
2158
    memset(ap, 0, sizeof(*ap));
2159
    for(j=0;j<nb_output_files;j++) {
2160
        oc = output_files[j];
2161
        for(i=0;i<oc->nb_streams;i++) {
2162
            AVCodecContext *enc = &oc->streams[i]->codec;
2163
            switch(enc->codec_type) {
2164
            case CODEC_TYPE_AUDIO:
2165
                if (enc->sample_rate > ap->sample_rate)
2166
                    ap->sample_rate = enc->sample_rate;
2167
                if (enc->channels > ap->channels)
2168
                    ap->channels = enc->channels;
2169
                has_audio = 1;
2170
                break;
2171
            case CODEC_TYPE_VIDEO:
2172
                if (enc->width > ap->width)
2173
                    ap->width = enc->width;
2174
                if (enc->height > ap->height)
2175
                    ap->height = enc->height;
2176
                if (enc->frame_rate > ap->frame_rate)
2177
                    ap->frame_rate = enc->frame_rate;
2178
                has_video = 1;
2179
                break;
2180
            default:
2181
                av_abort();
2182
            }
2183
        }
2184
    }
2185
    
2186
    if (has_video == 0 && has_audio == 0) {
2187
        fprintf(stderr, "Output file must have at least one audio or video stream\n");
2188
        exit(1);
2189
    }
2190
    
2191
    if (has_video) {
2192
        AVInputFormat *fmt1;
2193
        fmt1 = av_find_input_format("video_grab_device");
2194
        if (av_open_input_file(&ic, "", fmt1, 0, ap) < 0) {
2195
            fprintf(stderr, "Could not find video grab device\n");
2196
            exit(1);
2197
        }
2198
        /* by now video grab has one stream */
2199
        ic->streams[0]->r_frame_rate = ap->frame_rate;
2200
        input_files[nb_input_files] = ic;
2201
        dump_format(ic, nb_input_files, v4l_device, 0);
2202
        nb_input_files++;
2203
    }
2204
    if (has_audio) {
2205
        AVInputFormat *fmt1;
2206
        fmt1 = av_find_input_format("audio_device");
2207
        if (av_open_input_file(&ic, "", fmt1, 0, ap) < 0) {
2208
            fprintf(stderr, "Could not find audio grab device\n");
2209
            exit(1);
2210
        }
2211
        input_files[nb_input_files] = ic;
2212
        dump_format(ic, nb_input_files, audio_device, 0);
2213
        nb_input_files++;
2214
    }
2215
}
2216

    
2217
/* open the necessary output devices for playing */
2218
void prepare_play(void)
2219
{
2220
    file_iformat = NULL;
2221
    file_oformat = guess_format("audio_device", NULL, NULL);
2222
    if (!file_oformat) {
2223
        fprintf(stderr, "Could not find audio device\n");
2224
        exit(1);
2225
    }
2226
    
2227
    opt_output_file(audio_device);
2228
}
2229

    
2230
/* same option as mencoder */
2231
void opt_pass(const char *pass_str)
2232
{
2233
    int pass;
2234
    pass = atoi(pass_str);
2235
    if (pass != 1 && pass != 2) {
2236
        fprintf(stderr, "pass number can be only 1 or 2\n");
2237
        exit(1);
2238
    }
2239
    do_pass = pass;
2240
}
2241

    
2242
#ifndef CONFIG_WIN32
2243
INT64 getutime(void)
2244
{
2245
    struct rusage rusage;
2246

    
2247
    getrusage(RUSAGE_SELF, &rusage);
2248
    return (rusage.ru_utime.tv_sec * 1000000LL) + rusage.ru_utime.tv_usec;
2249
}
2250
#else
2251
INT64 getutime(void)
2252
{
2253
  return av_gettime();
2254
}
2255
#endif
2256

    
2257
extern int ffm_nopts;
2258

    
2259
void opt_bitexact(void)
2260
{
2261
    avcodec_set_bit_exact();
2262
    /* disable generate of real time pts in ffm (need to be supressed anyway) */
2263
    ffm_nopts = 1;
2264
}
2265

    
2266
void show_formats(void)
2267
{
2268
    AVInputFormat *ifmt;
2269
    AVOutputFormat *ofmt;
2270
    URLProtocol *up;
2271
    AVCodec *p;
2272
    const char **pp;
2273

    
2274
    printf("File formats:\n");
2275
    printf("  Encoding:");
2276
    for(ofmt = first_oformat; ofmt != NULL; ofmt = ofmt->next) {
2277
        printf(" %s", ofmt->name);
2278
    }
2279
    printf("\n");
2280
    printf("  Decoding:");
2281
    for(ifmt = first_iformat; ifmt != NULL; ifmt = ifmt->next) {
2282
        printf(" %s", ifmt->name);
2283
    }
2284
    printf("\n");
2285

    
2286
    printf("Codecs:\n");
2287
    printf("  Encoders:");
2288
    for(p = first_avcodec; p != NULL; p = p->next) {
2289
        if (p->encode)
2290
            printf(" %s", p->name);
2291
    }
2292
    printf("\n");
2293

    
2294
    printf("  Decoders:");
2295
    for(p = first_avcodec; p != NULL; p = p->next) {
2296
        if (p->decode)
2297
            printf(" %s", p->name);
2298
    }
2299
    printf("\n");
2300

    
2301
    printf("Supported file protocols:");
2302
    for(up = first_protocol; up != NULL; up = up->next)
2303
        printf(" %s:", up->name);
2304
    printf("\n");
2305
    
2306
    printf("Frame size abbreviations: sqcif qcif cif 4cif\n");
2307
    printf("Motion estimation methods:");
2308
    pp = motion_str;
2309
    while (*pp) {
2310
        printf(" %s", *pp);
2311
        if ((pp - motion_str + 1) == ME_ZERO) 
2312
            printf("(fastest)");
2313
        else if ((pp - motion_str + 1) == ME_FULL) 
2314
            printf("(slowest)");
2315
        else if ((pp - motion_str + 1) == ME_EPZS) 
2316
            printf("(default)");
2317
        pp++;
2318
    }
2319
    printf("\n");
2320
    exit(1);
2321
}
2322

    
2323
void show_help(void)
2324
{
2325
    const char *prog;
2326
    const OptionDef *po;
2327
    int i, expert;
2328
    
2329
    prog = do_play ? "ffplay" : "ffmpeg";
2330

    
2331
    printf("%s version " FFMPEG_VERSION ", Copyright (c) 2000, 2001, 2002 Fabrice Bellard\n",
2332
           prog);
2333
    
2334
    if (!do_play) {
2335
        printf("usage: ffmpeg [[options] -i input_file]... {[options] outfile}...\n"
2336
               "Hyper fast MPEG1/MPEG4/H263/RV and AC3/MPEG audio encoder\n");
2337
    } else {
2338
        printf("usage: ffplay [options] input_file...\n"
2339
               "Simple audio player\n");
2340
    }
2341
           
2342
    printf("\n"
2343
           "Main options are:\n");
2344
    for(i=0;i<2;i++) {
2345
        if (i == 1)
2346
            printf("\nAdvanced options are:\n");
2347
        for(po = options; po->name != NULL; po++) {
2348
            char buf[64];
2349
            expert = (po->flags & OPT_EXPERT) != 0;
2350
            if (expert == i) {
2351
                strcpy(buf, po->name);
2352
                if (po->flags & HAS_ARG) {
2353
                    strcat(buf, " ");
2354
                    strcat(buf, po->argname);
2355
                }
2356
                printf("-%-17s  %s\n", buf, po->help);
2357
            }
2358
        }
2359
    }
2360

    
2361
    exit(1);
2362
}
2363

    
2364
const OptionDef options[] = {
2365
    { "L", 0, {(void*)show_licence}, "show license" },
2366
    { "h", 0, {(void*)show_help}, "show help" },
2367
    { "formats", 0, {(void*)show_formats}, "show available formats, codecs, protocols, ..." },
2368
    { "f", HAS_ARG, {(void*)opt_format}, "force format", "fmt" },
2369
    { "vcd", OPT_BOOL, {(void*)&mpeg_vcd}, "output Video CD MPEG-PS compliant file" },
2370
    { "i", HAS_ARG, {(void*)opt_input_file}, "input file name", "filename" },
2371
    { "y", OPT_BOOL, {(void*)&file_overwrite}, "overwrite output files" },
2372
    { "map", HAS_ARG | OPT_EXPERT, {(void*)opt_map}, "set input stream mapping", "file:stream" },
2373
    { "t", HAS_ARG, {(void*)opt_recording_time}, "set the recording time", "duration" },
2374
    { "title", HAS_ARG | OPT_STRING, {(void*)&str_title}, "set the title", "string" },
2375
    { "author", HAS_ARG | OPT_STRING, {(void*)&str_author}, "set the author", "string" },
2376
    { "copyright", HAS_ARG | OPT_STRING, {(void*)&str_copyright}, "set the copyright", "string" },
2377
    { "comment", HAS_ARG | OPT_STRING, {(void*)&str_comment}, "set the comment", "string" },
2378
    { "pass", HAS_ARG, {(void*)&opt_pass}, "select the pass number (1 or 2)", "n" },
2379
    { "passlogfile", HAS_ARG | OPT_STRING, {(void*)&pass_logfilename}, "select two pass log file name", "file" },
2380
    /* video options */
2381
    { "b", HAS_ARG, {(void*)opt_video_bitrate}, "set video bitrate (in kbit/s)", "bitrate" },
2382
    { "r", HAS_ARG, {(void*)opt_frame_rate}, "set frame rate (in Hz)", "rate" },
2383
    { "s", HAS_ARG, {(void*)opt_frame_size}, "set frame size (WxH or abbreviation)", "size" },
2384
    { "croptop", HAS_ARG, {(void*)opt_frame_crop_top}, "set top crop band size (in pixels)", "size" },
2385
    { "cropbottom", HAS_ARG, {(void*)opt_frame_crop_bottom}, "set bottom crop band size (in pixels)", "size" },
2386
    { "cropleft", HAS_ARG, {(void*)opt_frame_crop_left}, "set left crop band size (in pixels)", "size" },
2387
    { "cropright", HAS_ARG, {(void*)opt_frame_crop_right}, "set right crop band size (in pixels)", "size" },
2388
    { "g", HAS_ARG | OPT_EXPERT, {(void*)opt_gop_size}, "set the group of picture size", "gop_size" },
2389
    { "intra", OPT_BOOL | OPT_EXPERT, {(void*)&intra_only}, "use only intra frames"},
2390
    { "vn", OPT_BOOL, {(void*)&video_disable}, "disable video" },
2391
    { "qscale", HAS_ARG | OPT_EXPERT, {(void*)opt_qscale}, "use fixed video quantiser scale (VBR)", "q" },
2392
    { "qmin", HAS_ARG | OPT_EXPERT, {(void*)opt_qmin}, "min video quantiser scale (VBR)", "q" },
2393
    { "qmax", HAS_ARG | OPT_EXPERT, {(void*)opt_qmax}, "max video quantiser scale (VBR)", "q" },
2394
    { "qdiff", HAS_ARG | OPT_EXPERT, {(void*)opt_qdiff}, "max difference between the quantiser scale (VBR)", "q" },
2395
    { "qblur", HAS_ARG | OPT_EXPERT, {(void*)opt_qblur}, "video quantiser scale blur (VBR)", "blur" },
2396
    { "qcomp", HAS_ARG | OPT_EXPERT, {(void*)opt_qcomp}, "video quantiser scale compression (VBR)", "compression" },
2397
    { "b_qfactor", HAS_ARG | OPT_EXPERT, {(void*)opt_b_qfactor}, "qp factor between p and b frames", "factor" },
2398
    { "i_qfactor", HAS_ARG | OPT_EXPERT, {(void*)opt_i_qfactor}, "qp factor between p and i frames", "factor" },
2399
    { "b_qoffset", HAS_ARG | OPT_EXPERT, {(void*)opt_b_qoffset}, "qp offset between p and b frames", "offset" },
2400
    { "i_qoffset", HAS_ARG | OPT_EXPERT, {(void*)opt_i_qoffset}, "qp offset between p and i frames", "offset" },
2401
    { "rc_eq", HAS_ARG | OPT_EXPERT, {(void*)opt_video_rc_eq}, "", "equation" },
2402
    { "bt", HAS_ARG, {(void*)opt_video_bitrate_tolerance}, "set video bitrate tolerance (in kbit/s)", "tolerance" },
2403
    { "maxrate", HAS_ARG, {(void*)opt_video_bitrate_max}, "set max video bitrate tolerance (in kbit/s)", "bitrate" },
2404
    { "minrate", HAS_ARG, {(void*)opt_video_bitrate_min}, "set min video bitrate tolerance (in kbit/s)", "bitrate" },
2405
    { "bufsize", HAS_ARG, {(void*)opt_video_buffer_size}, "set ratecontrol buffere size (in kbit)", "size" },
2406
    { "vd", HAS_ARG | OPT_EXPERT, {(void*)opt_video_device}, "set video grab device", "device" },
2407
    { "vcodec", HAS_ARG | OPT_EXPERT, {(void*)opt_video_codec}, "force video codec ('copy' to copy stream)", "codec" },
2408
    { "me", HAS_ARG | OPT_EXPERT, {(void*)opt_motion_estimation}, "set motion estimation method", 
2409
      "method" },
2410
    { "dct_algo", HAS_ARG | OPT_EXPERT, {(void*)opt_dct_algo}, "set dct algo",  "algo" },
2411
    { "idct_algo", HAS_ARG | OPT_EXPERT, {(void*)opt_idct_algo}, "set idct algo",  "algo" },
2412
    { "er", HAS_ARG | OPT_EXPERT, {(void*)opt_error_resilience}, "set error resilience",  "" },
2413
    { "ec", HAS_ARG | OPT_EXPERT, {(void*)opt_error_resilience}, "set error concealment",  "" },
2414
    { "bf", HAS_ARG | OPT_EXPERT, {(void*)opt_b_frames}, "use 'frames' B frames (only MPEG-4)", "frames" },
2415
    { "hq", OPT_BOOL | OPT_EXPERT, {(void*)&use_hq}, "activate high quality settings" },
2416
    { "4mv", OPT_BOOL | OPT_EXPERT, {(void*)&use_4mv}, "use four motion vector by macroblock (only MPEG-4)" },
2417
    { "part", OPT_BOOL | OPT_EXPERT, {(void*)&use_part}, "use data partitioning (only MPEG-4)" },
2418
    { "bug", HAS_ARG | OPT_EXPERT, {(void*)opt_workaround_bugs}, "workaround not auto detected encoder bugs", "param" },
2419
    { "ps", HAS_ARG | OPT_EXPERT, {(void*)opt_packet_size}, "packet size", "size in bits" },
2420
    { "sameq", OPT_BOOL, {(void*)&same_quality}, 
2421
      "use same video quality as source (implies VBR)" },
2422
    /* audio options */
2423
    { "ab", HAS_ARG, {(void*)opt_audio_bitrate}, "set audio bitrate (in kbit/s)", "bitrate", },
2424
    { "ar", HAS_ARG, {(void*)opt_audio_rate}, "set audio sampling rate (in Hz)", "rate" },
2425
    { "ac", HAS_ARG, {(void*)opt_audio_channels}, "set number of audio channels", "channels" },
2426
    { "an", OPT_BOOL, {(void*)&audio_disable}, "disable audio" },
2427
    { "ad", HAS_ARG | OPT_EXPERT, {(void*)opt_audio_device}, "set audio device", "device" },
2428
    { "acodec", HAS_ARG | OPT_EXPERT, {(void*)opt_audio_codec}, "force audio codec ('copy' to copy stream)", "codec" },
2429
    { "deinterlace", OPT_BOOL | OPT_EXPERT, {(void*)&do_deinterlace}, 
2430
      "deinterlace pictures" },
2431
    { "benchmark", OPT_BOOL | OPT_EXPERT, {(void*)&do_benchmark}, 
2432
      "add timings for benchmarking" },
2433
    { "hex", OPT_BOOL | OPT_EXPERT, {(void*)&do_hex_dump}, 
2434
      "dump each input packet" },
2435
    { "psnr", OPT_BOOL | OPT_EXPERT, {(void*)&do_psnr}, "calculate PSNR of compressed frames" },
2436
    { "vstats", OPT_BOOL | OPT_EXPERT, {(void*)&do_vstats}, "dump video coding statistics to file" }, 
2437
    { "bitexact", OPT_EXPERT, {(void*)opt_bitexact}, "only use bit exact algorithms (for codec testing)" }, 
2438
    { NULL, },
2439
};
2440

    
2441
int main(int argc, char **argv)
2442
{
2443
    int optindex, i;
2444
    const char *opt, *arg;
2445
    const OptionDef *po;
2446
    INT64 ti;
2447
    
2448
    av_register_all();
2449

    
2450
    /* detect if invoked as player */
2451
    i = strlen(argv[0]);
2452
    if (i >= 6 && !strcmp(argv[0] + i - 6, "ffplay"))
2453
        do_play = 1;
2454

    
2455
    if (argc <= 1)
2456
        show_help();
2457
    
2458
    /* parse options */
2459
    optindex = 1;
2460
    while (optindex < argc) {
2461
        opt = argv[optindex++];
2462
        
2463
        if (opt[0] == '-' && opt[1] != '\0') {
2464
            po = options;
2465
            while (po->name != NULL) {
2466
                if (!strcmp(opt + 1, po->name))
2467
                    break;
2468
                po++;
2469
            }
2470
            if (!po->name) {
2471
                fprintf(stderr, "%s: unrecognized option '%s'\n", argv[0], opt);
2472
                exit(1);
2473
            }
2474
            arg = NULL;
2475
            if (po->flags & HAS_ARG)
2476
                arg = argv[optindex++];
2477
            if (po->flags & OPT_STRING) {
2478
                char *str;
2479
                str = strdup(arg);
2480
                *po->u.str_arg = str;
2481
            } else if (po->flags & OPT_BOOL) {
2482
                *po->u.int_arg = 1;
2483
            } else {
2484
                po->u.func_arg(arg);
2485
            }
2486
        } else {
2487
            if (!do_play) {
2488
                opt_output_file(opt);
2489
            } else {
2490
                opt_input_file(opt);
2491
            }
2492
        }
2493
    }
2494

    
2495

    
2496
    if (!do_play) {
2497
        /* file converter / grab */
2498
        if (nb_output_files <= 0) {
2499
            fprintf(stderr, "Must supply at least one output file\n");
2500
            exit(1);
2501
        }
2502
        
2503
        if (nb_input_files == 0) {
2504
            prepare_grab();
2505
        }
2506
    } else {
2507
        /* player */
2508
        if (nb_input_files <= 0) {
2509
            fprintf(stderr, "Must supply at least one input file\n");
2510
            exit(1);
2511
        }
2512
        prepare_play();
2513
    }
2514

    
2515
    ti = getutime();
2516
    av_encode(output_files, nb_output_files, input_files, nb_input_files, 
2517
              stream_maps, nb_stream_maps);
2518
    ti = getutime() - ti;
2519
    if (do_benchmark) {
2520
        printf("bench: utime=%0.3fs\n", ti / 1000000.0);
2521
    }
2522

    
2523
    /* close files */
2524
    for(i=0;i<nb_output_files;i++) {
2525
        if (!(output_files[i]->oformat->flags & AVFMT_NOFILE)) 
2526
            url_fclose(&output_files[i]->pb);
2527
    }
2528
    for(i=0;i<nb_input_files;i++)
2529
        av_close_input_file(input_files[i]);
2530

    
2531
    return 0;
2532
}