Statistics
| Branch: | Revision:

ffmpeg / ffmpeg.c @ 140cb663

History | View | Annotate | Download (85.2 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 "framehook.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
#include <time.h>
32
#include <ctype.h>
33

    
34

    
35
#define MAXINT64 INT64_C(0x7fffffffffffffff)
36

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

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

    
59
extern const OptionDef options[];
60

    
61
void show_help(void);
62

    
63
#define MAX_FILES 20
64

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

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

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

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

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

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

    
147
#define DEFAULT_PASS_LOGFILENAME "ffmpeg2pass"
148

    
149
#if !defined(CONFIG_AUDIO_OSS) && !defined(CONFIG_AUDIO_BEOS)
150
const char *audio_device = "none";
151
#endif
152
#ifndef CONFIG_VIDEO4LINUX
153
const char *v4l_device = "none";
154
#endif
155

    
156
typedef struct AVOutputStream {
157
    int file_index;          /* file index */
158
    int index;               /* stream index in the output file */
159
    int source_index;        /* AVInputStream index */
160
    AVStream *st;            /* stream in the output file */
161
    int encoding_needed;     /* true if encoding needed for this stream */
162
    int frame_number;
163
    /* input pts and corresponding output pts
164
       for A/V sync */
165
    double sync_ipts;
166
    double sync_ipts_offset;
167
    INT64 sync_opts;
168
    /* video only */
169
    AVPicture pict_tmp;         /* temporary image for resizing */
170
    int video_resample;
171
    ImgReSampleContext *img_resample_ctx; /* for image resampling */
172
    
173
    /* audio only */
174
    int audio_resample;
175
    ReSampleContext *resample; /* for audio resampling */
176
    FifoBuffer fifo;     /* for compression: one audio fifo per codec */
177
    FILE *logfile;
178
} AVOutputStream;
179

    
180
typedef struct AVInputStream {
181
    int file_index;
182
    int index;
183
    AVStream *st;
184
    int discard;             /* true if stream data should be discarded */
185
    int decoding_needed;     /* true if the packets must be decoded in 'raw_fifo' */
186
    INT64 sample_index;      /* current sample */
187
    int frame_decoded;       /* true if a video or audio frame has been decoded */
188
} AVInputStream;
189

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

    
199
#ifndef CONFIG_WIN32
200

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

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

    
209
static void term_init(void)
210
{
211
    struct termios tty;
212

    
213
    tcgetattr (0, &tty);
214
    oldtty = tty;
215

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

    
227
    atexit(term_exit);
228
#ifdef CONFIG_BEOS_NETSERVER
229
    fcntl(0, F_SETFL, fcntl(0, F_GETFL) | O_NONBLOCK);
230
#endif
231
}
232

    
233
/* read a key without blocking */
234
static int read_key(void)
235
{
236
    int n = 1;
237
    unsigned char ch;
238
#ifndef CONFIG_BEOS_NETSERVER
239
    struct timeval tv;
240
    fd_set rfds;
241

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

    
253
        return n;
254
    }
255
    return -1;
256
}
257

    
258
#else
259

    
260
/* no interactive support */
261
static void term_exit(void)
262
{
263
}
264

    
265
static void term_init(void)
266
{
267
}
268

    
269
static int read_key(void)
270
{
271
    return 0;
272
}
273

    
274
#endif
275

    
276
int read_ffserver_streams(AVFormatContext *s, const char *filename)
277
{
278
    int i, err;
279
    AVFormatContext *ic;
280

    
281
    err = av_open_input_file(&ic, filename, NULL, FFM_PACKET_SIZE, NULL);
282
    if (err < 0)
283
        return err;
284
    /* copy stream format */
285
    s->nb_streams = ic->nb_streams;
286
    for(i=0;i<ic->nb_streams;i++) {
287
        AVStream *st;
288

    
289
        st = av_mallocz(sizeof(AVFormatContext));
290
        memcpy(st, ic->streams[i], sizeof(AVStream));
291
        s->streams[i] = st;
292
    }
293

    
294
    av_close_input_file(ic);
295
    return 0;
296
}
297

    
298
#define MAX_AUDIO_PACKET_SIZE 16384
299

    
300
static void do_audio_out(AVFormatContext *s, 
301
                         AVOutputStream *ost, 
302
                         AVInputStream *ist,
303
                         unsigned char *buf, int size)
304
{
305
    UINT8 *buftmp;
306
    UINT8 audio_buf[2*MAX_AUDIO_PACKET_SIZE]; /* XXX: allocate it */
307
    UINT8 audio_out[4*MAX_AUDIO_PACKET_SIZE]; /* XXX: allocate it - yep really WMA */
308
    int size_out, frame_bytes, ret;
309
    AVCodecContext *enc;
310

    
311
    enc = &ost->st->codec;
312

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

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

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

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

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

    
453
static void pre_process_video_frame(AVInputStream *ist, AVPicture *picture, void **bufp)
454
{
455
    AVCodecContext *dec;
456
    AVPicture *picture2;
457
    AVPicture picture_tmp;
458
    UINT8 *buf = 0;
459

    
460
    dec = &ist->st->codec;
461

    
462
    /* deinterlace : must be done before any resize */
463
    if (do_deinterlace) {
464
        int size;
465

    
466
        /* create temporary picture */
467
        size = avpicture_get_size(dec->pix_fmt, dec->width, dec->height);
468
        buf = av_malloc(size);
469
        if (!buf)
470
            return;
471
        
472
        picture2 = &picture_tmp;
473
        avpicture_fill(picture2, buf, dec->pix_fmt, dec->width, dec->height);
474

    
475
        if (avpicture_deinterlace(picture2, picture, 
476
                                  dec->pix_fmt, dec->width, dec->height) < 0) {
477
            /* if error, do not deinterlace */
478
            av_free(buf);
479
            buf = NULL;
480
            picture2 = picture;
481
        }
482
    } else {
483
        picture2 = picture;
484
    }
485

    
486
    frame_hook_process(picture2, dec->pix_fmt, dec->width, dec->height);
487

    
488
    if (picture != picture2)
489
        *picture = *picture2;
490
    *bufp = buf;
491
}
492

    
493
/* we begin to correct av delay at this threshold */
494
#define AV_DELAY_MAX 0.100
495

    
496
static void do_video_out(AVFormatContext *s, 
497
                         AVOutputStream *ost, 
498
                         AVInputStream *ist,
499
                         AVPicture *picture1,
500
                         int *frame_size, AVOutputStream *audio_sync)
501
{
502
    int nb_frames, i, ret;
503
    AVPicture *picture, *pict;
504
    AVPicture picture_tmp1;
505
    static UINT8 *video_buffer;
506
    UINT8 *buf = NULL, *buf1 = NULL;
507
    AVCodecContext *enc, *dec;
508

    
509
#define VIDEO_BUFFER_SIZE (1024*1024)
510

    
511
    enc = &ost->st->codec;
512
    dec = &ist->st->codec;
513

    
514
    /* by default, we output a single frame */
515
    nb_frames = 1;
516

    
517
    /* NOTE: the A/V sync is always done by considering the audio is
518
       the master clock. It is suffisant for transcoding or playing,
519
       but not for the general case */
520
    if (audio_sync) {
521
        /* compute the A-V delay and duplicate/remove frames if needed */
522
        double adelta, vdelta, apts, vpts, av_delay;
523
        
524
        if (audio_sync->sync_ipts != AV_NOPTS_VALUE &&
525
            ost->sync_ipts != AV_NOPTS_VALUE) {
526
            
527
            adelta = (double)(ost->st->pts.val - audio_sync->sync_opts) * 
528
                s->pts_num / s->pts_den;
529
            apts = audio_sync->sync_ipts + adelta; 
530
            
531
            vdelta = (double)(ost->st->pts.val - ost->sync_opts) *
532
                s->pts_num / s->pts_den;
533
            vpts = ost->sync_ipts + vdelta;
534
            
535
            av_delay = apts - vpts;
536
            //            printf("delay=%f\n", av_delay);
537
            if (av_delay < -AV_DELAY_MAX)
538
                nb_frames = 2;
539
            else if (av_delay > AV_DELAY_MAX)
540
                nb_frames = 0;
541
        }
542
    } else {
543
        double vdelta;
544

    
545
        if (ost->sync_ipts != AV_NOPTS_VALUE) {
546
            vdelta = (double)(ost->st->pts.val) * s->pts_num / s->pts_den - (ost->sync_ipts - ost->sync_ipts_offset);
547
            if (vdelta < 100 && vdelta > -100) {
548
                if (vdelta < -AV_DELAY_MAX)
549
                    nb_frames = 2;
550
                else if (vdelta > AV_DELAY_MAX)
551
                    nb_frames = 0;
552
            } else {
553
                ost->sync_ipts_offset -= vdelta;
554
            }
555

    
556
#if 0
557
            {
558
                static char *action[] = { "drop frame", "copy frame", "dup frame" };
559
                printf("Input PTS %12.6f, output PTS %12.6f: %s\n",
560
                    (double) ost->sync_ipts, (double) ost->st->pts.val * s->pts_num / s->pts_den,
561
                    action[nb_frames]);
562
            }
563
#endif
564
        }
565
    }
566
    if (nb_frames <= 0) 
567
        return;
568

    
569
    if (!video_buffer)
570
        video_buffer = av_malloc(VIDEO_BUFFER_SIZE);
571
    if (!video_buffer)
572
        return;
573

    
574
    /* convert pixel format if needed */
575
    if (enc->pix_fmt != dec->pix_fmt) {
576
        int size;
577

    
578
        /* create temporary picture */
579
        size = avpicture_get_size(enc->pix_fmt, dec->width, dec->height);
580
        buf = av_malloc(size);
581
        if (!buf)
582
            return;
583
        pict = &picture_tmp1;
584
        avpicture_fill(pict, buf, enc->pix_fmt, dec->width, dec->height);
585
        
586
        if (img_convert(pict, enc->pix_fmt, 
587
                        picture1, dec->pix_fmt, 
588
                        dec->width, dec->height) < 0) {
589
            fprintf(stderr, "pixel format conversion not handled\n");
590
            goto the_end;
591
        }
592
    } else {
593
        pict = picture1;
594
    }
595

    
596
    /* XXX: resampling could be done before raw format convertion in
597
       some cases to go faster */
598
    /* XXX: only works for YUV420P */
599
    if (ost->video_resample) {
600
        picture = &ost->pict_tmp;
601
        img_resample(ost->img_resample_ctx, picture, pict);
602
    } else {
603
        picture = pict;
604
    }
605
    /* duplicates frame if needed */
606
    /* XXX: pb because no interleaving */
607
    for(i=0;i<nb_frames;i++) {
608
        if (enc->codec_id != CODEC_ID_RAWVIDEO) {
609
            AVVideoFrame big_picture;
610
            
611
            memset(&big_picture, 0, sizeof(AVVideoFrame));
612
            *(AVPicture*)&big_picture= *picture;
613
                        
614
            /* handles sameq here. This is not correct because it may
615
               not be a global option */
616
            if (same_quality) {
617
                big_picture.quality = ist->st->quality;
618
            }else
619
                big_picture.quality = ost->st->quality;
620
            
621
            ret = avcodec_encode_video(enc, 
622
                                       video_buffer, VIDEO_BUFFER_SIZE,
623
                                       &big_picture);
624
            //enc->frame_number = enc->real_pict_num;
625
            av_write_frame(s, ost->index, video_buffer, ret);
626
            *frame_size = ret;
627
            //fprintf(stderr,"\nFrame: %3d %3d size: %5d type: %d",
628
            //        enc->frame_number-1, enc->real_pict_num, ret,
629
            //        enc->pict_type);
630
            /* if two pass, output log */
631
            if (ost->logfile && enc->stats_out) {
632
                fprintf(ost->logfile, "%s", enc->stats_out);
633
            }
634
        } else {
635
            if (s->oformat->flags & AVFMT_RAWPICTURE) {
636
                /* raw pictures are written as AVPicture structure to
637
                   avoid any copies. We support temorarily the older
638
                   method. */
639
                av_write_frame(s, ost->index, 
640
                               (UINT8 *)picture, sizeof(AVPicture));
641
            } else {
642
                write_picture(s, ost->index, picture, enc->pix_fmt, 
643
                              enc->width, enc->height);
644
            }
645
        }
646
        ost->frame_number++;
647
    }
648
 the_end:
649
    av_free(buf);
650
    av_free(buf1);
651
}
652

    
653
static double psnr(double d){
654
    if(d==0) return INFINITY;
655
    return -10.0*log(d)/log(10);
656
}
657

    
658
static void do_video_stats(AVFormatContext *os, AVOutputStream *ost, 
659
                           int frame_size)
660
{
661
    static FILE *fvstats=NULL;
662
    static INT64 total_size = 0;
663
    char filename[40];
664
    time_t today2;
665
    struct tm *today;
666
    AVCodecContext *enc;
667
    int frame_number;
668
    INT64 ti;
669
    double ti1, bitrate, avg_bitrate;
670
    
671
    if (!fvstats) {
672
        today2 = time(NULL);
673
        today = localtime(&today2);
674
        sprintf(filename, "vstats_%02d%02d%02d.log", today->tm_hour,
675
                                               today->tm_min,
676
                                               today->tm_sec);
677
        fvstats = fopen(filename,"w");
678
        if (!fvstats) {
679
            perror("fopen");
680
            exit(1);
681
        }
682
    }
683
    
684
    ti = MAXINT64;
685
    enc = &ost->st->codec;
686
    total_size += frame_size;
687
    if (enc->codec_type == CODEC_TYPE_VIDEO) {
688
        frame_number = ost->frame_number;
689
        fprintf(fvstats, "frame= %5d q= %2.1f ", frame_number, enc->coded_picture->quality);
690
        if (enc->flags&CODEC_FLAG_PSNR)
691
            fprintf(fvstats, "PSNR= %6.2f ", psnr(enc->coded_picture->error[0]/(enc->width*enc->height*255.0*255.0)));
692
        
693
        fprintf(fvstats,"f_size= %6d ", frame_size);
694
        /* compute pts value */
695
        ti1 = (double)ost->st->pts.val * os->pts_num / os->pts_den;
696
        if (ti1 < 0.01)
697
            ti1 = 0.01;
698
    
699
        bitrate = (double)(frame_size * 8) * enc->frame_rate / FRAME_RATE_BASE / 1000.0;
700
        avg_bitrate = (double)(total_size * 8) / ti1 / 1000.0;
701
        fprintf(fvstats, "s_size= %8.0fkB time= %0.3f br= %7.1fkbits/s avg_br= %7.1fkbits/s ",
702
            (double)total_size / 1024, ti1, bitrate, avg_bitrate);
703
        fprintf(fvstats,"type= %s\n", enc->coded_picture->key_frame == 1 ? "I" : "P");        
704
    }
705
}
706

    
707
void print_report(AVFormatContext **output_files, 
708
                  AVOutputStream **ost_table, int nb_ostreams,
709
                  int is_last_report)
710
{
711
    char buf[1024];
712
    AVOutputStream *ost;
713
    AVFormatContext *oc, *os;
714
    INT64 total_size;
715
    AVCodecContext *enc;
716
    int frame_number, vid, i;
717
    double bitrate, ti1, pts;
718
    static INT64 last_time = -1;
719
    
720
    if (!is_last_report) {
721
        INT64 cur_time;
722
        /* display the report every 0.5 seconds */
723
        cur_time = av_gettime();
724
        if (last_time == -1) {
725
            last_time = cur_time;
726
            return;
727
        } 
728
        if ((cur_time - last_time) < 500000)
729
            return;
730
        last_time = cur_time;
731
    }
732

    
733

    
734
    oc = output_files[0];
735

    
736
    total_size = url_ftell(&oc->pb);
737
    
738
    buf[0] = '\0';
739
    ti1 = 1e10;
740
    vid = 0;
741
    for(i=0;i<nb_ostreams;i++) {
742
        ost = ost_table[i];
743
        os = output_files[ost->file_index];
744
        enc = &ost->st->codec;
745
        if (vid && enc->codec_type == CODEC_TYPE_VIDEO) {
746
            sprintf(buf + strlen(buf), "q=%2.1f ",
747
                    enc->coded_picture->quality);
748
        }
749
        if (!vid && enc->codec_type == CODEC_TYPE_VIDEO) {
750
            frame_number = ost->frame_number;
751
            sprintf(buf + strlen(buf), "frame=%5d q=%2.1f ",
752
                    frame_number, enc->coded_picture ? enc->coded_picture->quality : 0);
753
            if (enc->flags&CODEC_FLAG_PSNR)
754
                sprintf(buf + strlen(buf), "PSNR= %6.2f ", psnr(enc->coded_picture->error[0]/(enc->width*enc->height*255.0*255.0)));
755
            vid = 1;
756
        }
757
        /* compute min output value */
758
        pts = (double)ost->st->pts.val * os->pts_num / os->pts_den;
759
        if ((pts < ti1) && (pts > 0))
760
            ti1 = pts;
761
    }
762
    if (ti1 < 0.01)
763
        ti1 = 0.01;
764
    bitrate = (double)(total_size * 8) / ti1 / 1000.0;
765
    
766
    sprintf(buf + strlen(buf), 
767
            "size=%8.0fkB time=%0.1f bitrate=%6.1fkbits/s",
768
            (double)total_size / 1024, ti1, bitrate);
769
    
770
    fprintf(stderr, "%s   ", buf);
771
    
772
    if (is_last_report) {
773
        fprintf(stderr, "\n");
774
    } else {
775
        fprintf(stderr, "\r");
776
        fflush(stderr);
777
    }
778
}
779

    
780
/*
781
 * The following code is the main loop of the file converter
782
 */
783
static int av_encode(AVFormatContext **output_files,
784
                     int nb_output_files,
785
                     AVFormatContext **input_files,
786
                     int nb_input_files,
787
                     AVStreamMap *stream_maps, int nb_stream_maps)
788
{
789
    int ret, i, j, k, n, nb_istreams = 0, nb_ostreams = 0, pts_set;
790
    AVFormatContext *is, *os;
791
    AVCodecContext *codec, *icodec;
792
    AVOutputStream *ost, **ost_table = NULL;
793
    AVInputStream *ist, **ist_table = NULL;
794
    AVInputFile *file_table;
795
    AVFormatContext *stream_no_data;
796
    int key;
797

    
798
    file_table= (AVInputFile*) av_mallocz(nb_input_files * sizeof(AVInputFile));
799
    if (!file_table)
800
        goto fail;
801

    
802
    /* input stream init */
803
    j = 0;
804
    for(i=0;i<nb_input_files;i++) {
805
        is = input_files[i];
806
        file_table[i].ist_index = j;
807
        file_table[i].nb_streams = is->nb_streams;
808
        j += is->nb_streams;
809
    }
810
    nb_istreams = j;
811

    
812
    ist_table = av_mallocz(nb_istreams * sizeof(AVInputStream *));
813
    if (!ist_table)
814
        goto fail;
815
    
816
    for(i=0;i<nb_istreams;i++) {
817
        ist = av_mallocz(sizeof(AVInputStream));
818
        if (!ist)
819
            goto fail;
820
        ist_table[i] = ist;
821
    }
822
    j = 0;
823
    for(i=0;i<nb_input_files;i++) {
824
        is = input_files[i];
825
        for(k=0;k<is->nb_streams;k++) {
826
            ist = ist_table[j++];
827
            ist->st = is->streams[k];
828
            ist->file_index = i;
829
            ist->index = k;
830
            ist->discard = 1; /* the stream is discarded by default
831
                                 (changed later) */
832
        }
833
    }
834

    
835
    /* output stream init */
836
    nb_ostreams = 0;
837
    for(i=0;i<nb_output_files;i++) {
838
        os = output_files[i];
839
        nb_ostreams += os->nb_streams;
840
    }
841
    if (nb_stream_maps > 0 && nb_stream_maps != nb_ostreams) {
842
        fprintf(stderr, "Number of stream maps must match number of output streams\n");
843
        exit(1);
844
    }
845

    
846
    ost_table = av_mallocz(sizeof(AVOutputStream *) * nb_ostreams);
847
    if (!ost_table)
848
        goto fail;
849
    for(i=0;i<nb_ostreams;i++) {
850
        ost = av_mallocz(sizeof(AVOutputStream));
851
        if (!ost)
852
            goto fail;
853
        ost_table[i] = ost;
854
    }
855
    
856
    n = 0;
857
    for(k=0;k<nb_output_files;k++) {
858
        os = output_files[k];
859
        for(i=0;i<os->nb_streams;i++) {
860
            int found;
861
            ost = ost_table[n++];
862
            ost->file_index = k;
863
            ost->index = i;
864
            ost->st = os->streams[i];
865
            if (nb_stream_maps > 0) {
866
                ost->source_index = file_table[stream_maps[n-1].file_index].ist_index + 
867
                    stream_maps[n-1].stream_index;
868
            } else {
869
                /* get corresponding input stream index : we select the first one with the right type */
870
                found = 0;
871
                for(j=0;j<nb_istreams;j++) {
872
                    ist = ist_table[j];
873
                    if (ist->discard && 
874
                        ist->st->codec.codec_type == ost->st->codec.codec_type) {
875
                        ost->source_index = j;
876
                        found = 1;
877
                    }
878
                }
879
                
880
                if (!found) {
881
                    /* try again and reuse existing stream */
882
                    for(j=0;j<nb_istreams;j++) {
883
                        ist = ist_table[j];
884
                        if (ist->st->codec.codec_type == ost->st->codec.codec_type) {
885
                            ost->source_index = j;
886
                            found = 1;
887
                        }
888
                    }
889
                    if (!found) {
890
                        fprintf(stderr, "Could not find input stream matching output stream #%d.%d\n",
891
                                ost->file_index, ost->index);
892
                        exit(1);
893
                    }
894
                }
895
            }
896
            ist = ist_table[ost->source_index];
897
            ist->discard = 0;
898
        }
899
    }
900

    
901
    /* for each output stream, we compute the right encoding parameters */
902
    for(i=0;i<nb_ostreams;i++) {
903
        ost = ost_table[i];
904
        ist = ist_table[ost->source_index];
905

    
906
        codec = &ost->st->codec;
907
        icodec = &ist->st->codec;
908

    
909
        if (ost->st->stream_copy) {
910
            /* if stream_copy is selected, no need to decode or encode */
911
            codec->codec_id = icodec->codec_id;
912
            codec->codec_type = icodec->codec_type;
913
            codec->codec_tag = icodec->codec_tag;
914
            codec->bit_rate = icodec->bit_rate;
915
            switch(codec->codec_type) {
916
            case CODEC_TYPE_AUDIO:
917
                codec->sample_rate = icodec->sample_rate;
918
                codec->channels = icodec->channels;
919
                break;
920
            case CODEC_TYPE_VIDEO:
921
                codec->frame_rate = icodec->frame_rate;
922
                codec->width = icodec->width;
923
                codec->height = icodec->height;
924
                break;
925
            default:
926
                av_abort();
927
            }
928
        } else {
929
            switch(codec->codec_type) {
930
            case CODEC_TYPE_AUDIO:
931
                if (fifo_init(&ost->fifo, 2 * MAX_AUDIO_PACKET_SIZE))
932
                    goto fail;
933
                
934
                if (codec->channels == icodec->channels &&
935
                    codec->sample_rate == icodec->sample_rate) {
936
                    ost->audio_resample = 0;
937
                } else {
938
                    if (codec->channels != icodec->channels &&
939
                        icodec->codec_id == CODEC_ID_AC3) {
940
                        /* Special case for 5:1 AC3 input */
941
                        /* and mono or stereo output      */
942
                        /* Request specific number of channels */
943
                        icodec->channels = codec->channels;
944
                        if (codec->sample_rate == icodec->sample_rate)
945
                            ost->audio_resample = 0;
946
                        else {
947
                            ost->audio_resample = 1;
948
                            ost->resample = audio_resample_init(codec->channels, icodec->channels,
949
                                                        codec->sample_rate, 
950
                                                        icodec->sample_rate);
951
                        }
952
                        /* Request specific number of channels */
953
                        icodec->channels = codec->channels;
954
                    } else {
955
                        ost->audio_resample = 1; 
956
                        ost->resample = audio_resample_init(codec->channels, icodec->channels,
957
                                                        codec->sample_rate, 
958
                                                        icodec->sample_rate);
959
                    }
960
                }
961
                ist->decoding_needed = 1;
962
                ost->encoding_needed = 1;
963
                break;
964
            case CODEC_TYPE_VIDEO:
965
                if (codec->width == icodec->width &&
966
                    codec->height == icodec->height) {
967
                    ost->video_resample = 0;
968
                } else {
969
                    UINT8 *buf;
970
                    ost->video_resample = 1;
971
                    buf = av_malloc((codec->width * codec->height * 3) / 2);
972
                    if (!buf)
973
                        goto fail;
974
                    ost->pict_tmp.data[0] = buf;
975
                    ost->pict_tmp.data[1] = ost->pict_tmp.data[0] + (codec->width * codec->height);
976
                    ost->pict_tmp.data[2] = ost->pict_tmp.data[1] + (codec->width * codec->height) / 4;
977
                    ost->pict_tmp.linesize[0] = codec->width;
978
                    ost->pict_tmp.linesize[1] = codec->width / 2;
979
                    ost->pict_tmp.linesize[2] = codec->width / 2;
980

    
981
                    ost->img_resample_ctx = img_resample_full_init( 
982
                                      ost->st->codec.width, ost->st->codec.height,
983
                                      ist->st->codec.width, ist->st->codec.height,
984
                                      frame_topBand, frame_bottomBand,
985
                                      frame_leftBand, frame_rightBand);
986
                }
987
                ost->encoding_needed = 1;
988
                ist->decoding_needed = 1;
989
                break;
990
            default:
991
                av_abort();
992
            }
993
            /* two pass mode */
994
            if (ost->encoding_needed && 
995
                (codec->flags & (CODEC_FLAG_PASS1 | CODEC_FLAG_PASS2))) {
996
                char logfilename[1024];
997
                FILE *f;
998
                int size;
999
                char *logbuffer;
1000
                
1001
                snprintf(logfilename, sizeof(logfilename), "%s-%d.log", 
1002
                         pass_logfilename ? 
1003
                         pass_logfilename : DEFAULT_PASS_LOGFILENAME, i);
1004
                if (codec->flags & CODEC_FLAG_PASS1) {
1005
                    f = fopen(logfilename, "w");
1006
                    if (!f) {
1007
                        perror(logfilename);
1008
                        exit(1);
1009
                    }
1010
                    ost->logfile = f;
1011
                } else {
1012
                    /* read the log file */
1013
                    f = fopen(logfilename, "r");
1014
                    if (!f) {
1015
                        perror(logfilename);
1016
                        exit(1);
1017
                    }
1018
                    fseek(f, 0, SEEK_END);
1019
                    size = ftell(f);
1020
                    fseek(f, 0, SEEK_SET);
1021
                    logbuffer = av_malloc(size + 1);
1022
                    if (!logbuffer) {
1023
                        fprintf(stderr, "Could not allocate log buffer\n");
1024
                        exit(1);
1025
                    }
1026
                    fread(logbuffer, 1, size, f);
1027
                    fclose(f);
1028
                    logbuffer[size] = '\0';
1029
                    codec->stats_in = logbuffer;
1030
                }
1031
            }
1032
        }
1033
    }
1034

    
1035
    /* dump the file output parameters - cannot be done before in case
1036
       of stream copy */
1037
    for(i=0;i<nb_output_files;i++) {
1038
        dump_format(output_files[i], i, output_files[i]->filename, 1);
1039
    }
1040

    
1041
    /* dump the stream mapping */
1042
    fprintf(stderr, "Stream mapping:\n");
1043
    for(i=0;i<nb_ostreams;i++) {
1044
        ost = ost_table[i];
1045
        fprintf(stderr, "  Stream #%d.%d -> #%d.%d\n",
1046
                ist_table[ost->source_index]->file_index,
1047
                ist_table[ost->source_index]->index,
1048
                ost->file_index, 
1049
                ost->index);
1050
    }
1051

    
1052
    /* open each encoder */
1053
    for(i=0;i<nb_ostreams;i++) {
1054
        ost = ost_table[i];
1055
        if (ost->encoding_needed) {
1056
            AVCodec *codec;
1057
            codec = avcodec_find_encoder(ost->st->codec.codec_id);
1058
            if (!codec) {
1059
                fprintf(stderr, "Unsupported codec for output stream #%d.%d\n", 
1060
                        ost->file_index, ost->index);
1061
                exit(1);
1062
            }
1063
            if (avcodec_open(&ost->st->codec, codec) < 0) {
1064
                fprintf(stderr, "Error while opening codec for stream #%d.%d - maybe incorrect parameters such as bit_rate, rate, width or height\n", 
1065
                        ost->file_index, ost->index);
1066
                exit(1);
1067
            }
1068
        }
1069
    }
1070

    
1071
    /* open each decoder */
1072
    for(i=0;i<nb_istreams;i++) {
1073
        ist = ist_table[i];
1074
        if (ist->decoding_needed) {
1075
            AVCodec *codec;
1076
            codec = avcodec_find_decoder(ist->st->codec.codec_id);
1077
            if (!codec) {
1078
                fprintf(stderr, "Unsupported codec (id=%d) for input stream #%d.%d\n", 
1079
                        ist->st->codec.codec_id, ist->file_index, ist->index);
1080
                exit(1);
1081
            }
1082
            if (avcodec_open(&ist->st->codec, codec) < 0) {
1083
                fprintf(stderr, "Error while opening codec for input stream #%d.%d\n", 
1084
                        ist->file_index, ist->index);
1085
                exit(1);
1086
            }
1087
            //if (ist->st->codec.codec_type == CODEC_TYPE_VIDEO)
1088
            //    ist->st->codec.flags |= CODEC_FLAG_REPEAT_FIELD;
1089
            ist->frame_decoded = 1;
1090
        }
1091
    }
1092

    
1093
    /* init pts */
1094
    for(i=0;i<nb_istreams;i++) {
1095
        ist = ist_table[i];
1096
    }
1097
    
1098
    /* compute buffer size max (should use a complete heuristic) */
1099
    for(i=0;i<nb_input_files;i++) {
1100
        file_table[i].buffer_size_max = 2048;
1101
    }
1102

    
1103
    /* open files and write file headers */
1104
    for(i=0;i<nb_output_files;i++) {
1105
        os = output_files[i];
1106
        if (av_write_header(os) < 0) {
1107
            fprintf(stderr, "Could not write header for output file #%d (incorrect codec paramters ?)\n", i);
1108
            ret = -EINVAL;
1109
            goto fail;
1110
        }
1111
    }
1112

    
1113
#ifndef CONFIG_WIN32
1114
    if (!do_play) {
1115
        fprintf(stderr, "Press [q] to stop encoding\n");
1116
    } else {
1117
        fprintf(stderr, "Press [q] to stop playing\n");
1118
    }
1119
#endif
1120
    term_init();
1121

    
1122
    stream_no_data = 0;
1123
    key = -1;
1124

    
1125
    for(;;) {
1126
        int file_index, ist_index;
1127
        AVPacket pkt;
1128
        UINT8 *ptr;
1129
        int len;
1130
        UINT8 *data_buf;
1131
        int data_size, got_picture;
1132
        AVPicture picture;
1133
        short samples[AVCODEC_MAX_AUDIO_FRAME_SIZE / 2];
1134
        void *buffer_to_free;
1135
        double pts_min;
1136
        
1137
    redo:
1138
        /* if 'q' pressed, exits */
1139
        if (key) {
1140
            /* read_key() returns 0 on EOF */
1141
            key = read_key();
1142
            if (key == 'q')
1143
                break;
1144
        }
1145

    
1146
        /* select the stream that we must read now by looking at the
1147
           smallest output pts */
1148
        file_index = -1;
1149
        pts_min = 1e10;
1150
        for(i=0;i<nb_ostreams;i++) {
1151
            double pts;
1152
            ost = ost_table[i];
1153
            os = output_files[ost->file_index];
1154
            ist = ist_table[ost->source_index];
1155
            pts = (double)ost->st->pts.val * os->pts_num / os->pts_den;
1156
            if (!file_table[ist->file_index].eof_reached && 
1157
                pts < pts_min) {
1158
                pts_min = pts;
1159
                file_index = ist->file_index;
1160
            }
1161
        }
1162
        /* if none, if is finished */
1163
        if (file_index < 0) {
1164
            break;
1165
        }
1166

    
1167
        /* finish if recording time exhausted */
1168
        if (recording_time > 0 && pts_min >= (recording_time / 1000000.0))
1169
            break;
1170

    
1171
        /* read a packet from it and output it in the fifo */
1172
        is = input_files[file_index];
1173
        if (av_read_packet(is, &pkt) < 0) {
1174
            file_table[file_index].eof_reached = 1;
1175
            continue;
1176
        }
1177
        if (!pkt.size) {
1178
            stream_no_data = is;
1179
        } else {
1180
            stream_no_data = 0;
1181
        }
1182
        /* the following test is needed in case new streams appear
1183
           dynamically in stream : we ignore them */
1184
        if (pkt.stream_index >= file_table[file_index].nb_streams)
1185
            goto discard_packet;
1186
        ist_index = file_table[file_index].ist_index + pkt.stream_index;
1187
        ist = ist_table[ist_index];
1188
        if (ist->discard)
1189
            goto discard_packet;
1190

    
1191
        if (do_hex_dump) {
1192
            printf("stream #%d, size=%d:\n", pkt.stream_index, pkt.size);
1193
            av_hex_dump(pkt.data, pkt.size);
1194
        }
1195

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

    
1198
        len = pkt.size;
1199
        ptr = pkt.data;
1200
        pts_set = 0;
1201
        while (len > 0) {
1202
            INT64 ipts;
1203

    
1204
            ipts = AV_NOPTS_VALUE;
1205

    
1206
            /* decode the packet if needed */
1207
            data_buf = NULL; /* fail safe */
1208
            data_size = 0;
1209
            if (ist->decoding_needed) {
1210
                /* NOTE1: we only take into account the PTS if a new
1211
                   frame has begun (MPEG semantics) */
1212
                /* NOTE2: even if the fraction is not initialized,
1213
                   av_frac_set can be used to set the integer part */
1214
                if (ist->frame_decoded && 
1215
                    pkt.pts != AV_NOPTS_VALUE && 
1216
                    !pts_set) {
1217
                    ipts = pkt.pts;
1218
                    ist->frame_decoded = 0;
1219
                    pts_set = 1;
1220
                }
1221

    
1222
                switch(ist->st->codec.codec_type) {
1223
                case CODEC_TYPE_AUDIO:
1224
                    /* XXX: could avoid copy if PCM 16 bits with same
1225
                       endianness as CPU */
1226
                    ret = avcodec_decode_audio(&ist->st->codec, samples, &data_size,
1227
                                               ptr, len);
1228
                    if (ret < 0)
1229
                        goto fail_decode;
1230
                    /* Some bug in mpeg audio decoder gives */
1231
                    /* data_size < 0, it seems they are overflows */
1232
                    if (data_size <= 0) {
1233
                        /* no audio frame */
1234
                        ptr += ret;
1235
                        len -= ret;
1236
                        continue;
1237
                    }
1238
                    data_buf = (UINT8 *)samples;
1239
                    break;
1240
                case CODEC_TYPE_VIDEO:
1241
                    if (ist->st->codec.codec_id == CODEC_ID_RAWVIDEO) {
1242
                        int size;
1243

    
1244
                        size = (ist->st->codec.width * ist->st->codec.height);
1245
                        avpicture_fill(&picture, ptr, 
1246
                                     ist->st->codec.pix_fmt,
1247
                                     ist->st->codec.width,
1248
                                     ist->st->codec.height);
1249
                        ret = len;
1250
                    } else {
1251
                        AVVideoFrame big_picture;
1252

    
1253
                        data_size = (ist->st->codec.width * ist->st->codec.height * 3) / 2;
1254
                        ret = avcodec_decode_video(&ist->st->codec, 
1255
                                                   &big_picture, &got_picture, ptr, len);
1256
                        picture= *(AVPicture*)&big_picture;
1257
                        ist->st->quality= big_picture.quality;
1258
                        if (ret < 0) {
1259
                        fail_decode:
1260
                            fprintf(stderr, "Error while decoding stream #%d.%d\n",
1261
                                    ist->file_index, ist->index);
1262
                            av_free_packet(&pkt);
1263
                            goto redo;
1264
                        }
1265
                        if (!got_picture) {
1266
                            /* no picture yet */
1267
                            ptr += ret;
1268
                            len -= ret;
1269
                            continue;
1270
                        }
1271
                                  
1272
                    }
1273
                    break;
1274
                default:
1275
                    goto fail_decode;
1276
                }
1277
            } else {
1278
                data_buf = ptr;
1279
                data_size = len;
1280
                ret = len;
1281
            }
1282
            ptr += ret;
1283
            len -= ret;
1284

    
1285
            buffer_to_free = 0;
1286
            if (ist->st->codec.codec_type == CODEC_TYPE_VIDEO) {
1287
                pre_process_video_frame(ist, &picture, &buffer_to_free);
1288
            }
1289

    
1290
            ist->frame_decoded = 1;
1291

    
1292
#if 0
1293
            /* mpeg PTS deordering : if it is a P or I frame, the PTS
1294
               is the one of the next displayed one */
1295
            /* XXX: add mpeg4 too ? */
1296
            if (ist->st->codec.codec_id == CODEC_ID_MPEG1VIDEO) {
1297
                if (ist->st->codec.pict_type != B_TYPE) {
1298
                    INT64 tmp;
1299
                    tmp = ist->last_ip_pts;
1300
                    ist->last_ip_pts  = ist->frac_pts.val;
1301
                    ist->frac_pts.val = tmp;
1302
                }
1303
            }
1304
#endif
1305
            /* transcode raw format, encode packets and output them */
1306

    
1307
            for(i=0;i<nb_ostreams;i++) {
1308
                int frame_size;
1309

    
1310
                ost = ost_table[i];
1311
                if (ost->source_index == ist_index) {
1312
                    os = output_files[ost->file_index];
1313

    
1314
                    if (ipts != AV_NOPTS_VALUE) {
1315
#if 0
1316
                        printf("%d: got pts=%f %f\n", 
1317
                               i, pkt.pts / 90000.0, 
1318
                               (ipts - ost->st->pts.val) / 90000.0);
1319
#endif
1320
                        /* set the input output pts pairs */
1321
                        ost->sync_ipts = (double)ipts * is->pts_num / 
1322
                            is->pts_den;
1323
                        /* XXX: take into account the various fifos,
1324
                           in particular for audio */
1325
                        ost->sync_opts = ost->st->pts.val;
1326
                        //printf("ipts=%lld sync_ipts=%f sync_opts=%lld pts.val=%lld pkt.pts=%lld\n", ipts, ost->sync_ipts, ost->sync_opts, ost->st->pts.val, pkt.pts); 
1327
                    } else {
1328
                        //printf("pts.val=%lld\n", ost->st->pts.val); 
1329
                    }
1330

    
1331
                    if (ost->encoding_needed) {
1332
                        switch(ost->st->codec.codec_type) {
1333
                        case CODEC_TYPE_AUDIO:
1334
                            do_audio_out(os, ost, ist, data_buf, data_size);
1335
                            break;
1336
                        case CODEC_TYPE_VIDEO:
1337
                            /* find an audio stream for synchro */
1338
                            {
1339
                                int i;
1340
                                AVOutputStream *audio_sync, *ost1;
1341
                                audio_sync = NULL;
1342
                                for(i=0;i<nb_ostreams;i++) {
1343
                                    ost1 = ost_table[i];
1344
                                    if (ost1->file_index == ost->file_index &&
1345
                                        ost1->st->codec.codec_type == CODEC_TYPE_AUDIO) {
1346
                                        audio_sync = ost1;
1347
                                        break;
1348
                                    }
1349
                                }
1350

    
1351
                                do_video_out(os, ost, ist, &picture, &frame_size, audio_sync);
1352
                                if (do_vstats)
1353
                                    do_video_stats(os, ost, frame_size);
1354
                            }
1355
                            break;
1356
                        default:
1357
                            av_abort();
1358
                        }
1359
                    } else {
1360
                        /* no reencoding needed : output the packet directly */
1361
                        /* force the input stream PTS */
1362
                        av_write_frame(os, ost->index, data_buf, data_size);
1363
                        ost->st->codec.frame_number++;
1364
                        ost->frame_number++;
1365
                    }
1366
                }
1367
            }
1368
            av_free(buffer_to_free);
1369
            ipts = AV_NOPTS_VALUE;
1370
        }
1371
    discard_packet:
1372
        av_free_packet(&pkt);
1373
        
1374
        /* dump report by using the output first video and audio streams */
1375
        print_report(output_files, ost_table, nb_ostreams, 0);
1376
    }
1377
    term_exit();
1378

    
1379
    /* dump report by using the first video and audio streams */
1380
    print_report(output_files, ost_table, nb_ostreams, 1);
1381

    
1382
    /* close each encoder */
1383
    for(i=0;i<nb_ostreams;i++) {
1384
        ost = ost_table[i];
1385
        if (ost->encoding_needed) {
1386
            av_freep(&ost->st->codec.stats_in);
1387
            avcodec_close(&ost->st->codec);
1388
        }
1389
    }
1390
    
1391
    /* close each decoder */
1392
    for(i=0;i<nb_istreams;i++) {
1393
        ist = ist_table[i];
1394
        if (ist->decoding_needed) {
1395
            avcodec_close(&ist->st->codec);
1396
        }
1397
    }
1398
    
1399

    
1400
    /* write the trailer if needed and close file */
1401
    for(i=0;i<nb_output_files;i++) {
1402
        os = output_files[i];
1403
        av_write_trailer(os);
1404
    }
1405
    /* finished ! */
1406
    
1407
    ret = 0;
1408
 fail1:
1409
    av_free(file_table);
1410

    
1411
    if (ist_table) {
1412
        for(i=0;i<nb_istreams;i++) {
1413
            ist = ist_table[i];
1414
            av_free(ist);
1415
        }
1416
        av_free(ist_table);
1417
    }
1418
    if (ost_table) {
1419
        for(i=0;i<nb_ostreams;i++) {
1420
            ost = ost_table[i];
1421
            if (ost) {
1422
                if (ost->logfile) {
1423
                    fclose(ost->logfile);
1424
                    ost->logfile = NULL;
1425
                }
1426
                fifo_free(&ost->fifo); /* works even if fifo is not
1427
                                          initialized but set to zero */
1428
                av_free(ost->pict_tmp.data[0]);
1429
                if (ost->video_resample)
1430
                    img_resample_close(ost->img_resample_ctx);
1431
                if (ost->audio_resample)
1432
                    audio_resample_close(ost->resample);
1433
                av_free(ost);
1434
            }
1435
        }
1436
        av_free(ost_table);
1437
    }
1438
    return ret;
1439
 fail:
1440
    ret = -ENOMEM;
1441
    goto fail1;
1442
}
1443

    
1444
#if 0
1445
int file_read(const char *filename)
1446
{
1447
    URLContext *h;
1448
    unsigned char buffer[1024];
1449
    int len, i;
1450

1451
    if (url_open(&h, filename, O_RDONLY) < 0) {
1452
        printf("could not open '%s'\n", filename);
1453
        return -1;
1454
    }
1455
    for(;;) {
1456
        len = url_read(h, buffer, sizeof(buffer));
1457
        if (len <= 0)
1458
            break;
1459
        for(i=0;i<len;i++) putchar(buffer[i]);
1460
    }
1461
    url_close(h);
1462
    return 0;
1463
}
1464
#endif
1465

    
1466
void show_licence(void)
1467
{
1468
    printf(
1469
    "ffmpeg version " FFMPEG_VERSION "\n"
1470
    "Copyright (c) 2000, 2001, 2002 Fabrice Bellard\n"
1471
    "This library is free software; you can redistribute it and/or\n"
1472
    "modify it under the terms of the GNU Lesser General Public\n"
1473
    "License as published by the Free Software Foundation; either\n"
1474
    "version 2 of the License, or (at your option) any later version.\n"
1475
    "\n"
1476
    "This library is distributed in the hope that it will be useful,\n"
1477
    "but WITHOUT ANY WARRANTY; without even the implied warranty of\n"
1478
    "MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n"
1479
    "Lesser General Public License for more details.\n"
1480
    "\n"
1481
    "You should have received a copy of the GNU Lesser General Public\n"
1482
    "License along with this library; if not, write to the Free Software\n"
1483
    "Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA\n"
1484
    );
1485
    exit(1);
1486
}
1487

    
1488
void opt_format(const char *arg)
1489
{
1490
    file_iformat = av_find_input_format(arg);
1491
    file_oformat = guess_format(arg, NULL, NULL);
1492
    if (!file_iformat && !file_oformat) {
1493
        fprintf(stderr, "Unknown input or output format: %s\n", arg);
1494
        exit(1);
1495
    }
1496
}
1497

    
1498
void opt_video_bitrate(const char *arg)
1499
{
1500
    video_bit_rate = atoi(arg) * 1000;
1501
}
1502

    
1503
void opt_video_bitrate_tolerance(const char *arg)
1504
{
1505
    video_bit_rate_tolerance = atoi(arg) * 1000;
1506
}
1507

    
1508
void opt_video_bitrate_max(const char *arg)
1509
{
1510
    video_rc_max_rate = atoi(arg) * 1000;
1511
}
1512

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

    
1518
void opt_video_buffer_size(const char *arg)
1519
{
1520
    video_rc_buffer_size = atoi(arg) * 1000;
1521
}
1522

    
1523
void opt_video_rc_eq(char *arg)
1524
{
1525
    video_rc_eq = arg;
1526
}
1527

    
1528
void opt_video_rc_override_string(char *arg)
1529
{
1530
    video_rc_override_string = arg;
1531
}
1532

    
1533

    
1534
void opt_workaround_bugs(const char *arg)
1535
{
1536
    workaround_bugs = atoi(arg);
1537
}
1538

    
1539
void opt_dct_algo(const char *arg)
1540
{
1541
    dct_algo = atoi(arg);
1542
}
1543

    
1544
void opt_idct_algo(const char *arg)
1545
{
1546
    idct_algo = atoi(arg);
1547
}
1548

    
1549

    
1550
void opt_error_resilience(const char *arg)
1551
{
1552
    error_resilience = atoi(arg);
1553
}
1554

    
1555
void opt_error_concealment(const char *arg)
1556
{
1557
    error_concealment = atoi(arg);
1558
}
1559

    
1560

    
1561
void opt_frame_rate(const char *arg)
1562
{
1563
    frame_rate = (int)(strtod(arg, 0) * FRAME_RATE_BASE);
1564
}
1565

    
1566

    
1567
void opt_frame_crop_top(const char *arg)
1568
{
1569
    frame_topBand = atoi(arg); 
1570
    if (frame_topBand < 0) {
1571
        fprintf(stderr, "Incorrect top crop size\n");
1572
        exit(1);
1573
    }
1574
    if ((frame_topBand % 2) != 0) {
1575
        fprintf(stderr, "Top crop size must be a multiple of 2\n");
1576
        exit(1);
1577
    }
1578
    if ((frame_topBand) >= frame_height){
1579
            fprintf(stderr, "Vertical crop dimensions are outside the range of the original image.\nRemember to crop first and scale second.\n");
1580
        exit(1);
1581
    }
1582
    frame_height -= frame_topBand;
1583
}
1584

    
1585
void opt_frame_crop_bottom(const char *arg)
1586
{
1587
    frame_bottomBand = atoi(arg);
1588
    if (frame_bottomBand < 0) {
1589
        fprintf(stderr, "Incorrect bottom crop size\n");
1590
        exit(1);
1591
    }
1592
    if ((frame_bottomBand % 2) != 0) {
1593
        fprintf(stderr, "Bottom crop size must be a multiple of 2\n");
1594
        exit(1);        
1595
    }
1596
    if ((frame_bottomBand) >= frame_height){
1597
            fprintf(stderr, "Vertical crop dimensions are outside the range of the original image.\nRemember to crop first and scale second.\n");
1598
        exit(1);
1599
    }
1600
    frame_height -= frame_bottomBand;
1601
}
1602

    
1603
void opt_frame_crop_left(const char *arg)
1604
{
1605
    frame_leftBand = atoi(arg);
1606
    if (frame_leftBand < 0) {
1607
        fprintf(stderr, "Incorrect left crop size\n");
1608
        exit(1);
1609
    }
1610
    if ((frame_leftBand % 2) != 0) {
1611
        fprintf(stderr, "Left crop size must be a multiple of 2\n");
1612
        exit(1);
1613
    }
1614
    if ((frame_leftBand) >= frame_width){
1615
            fprintf(stderr, "Horizontal crop dimensions are outside the range of the original image.\nRemember to crop first and scale second.\n");
1616
        exit(1);
1617
    }
1618
    frame_width -= frame_leftBand;
1619
}
1620

    
1621
void opt_frame_crop_right(const char *arg)
1622
{
1623
    frame_rightBand = atoi(arg);
1624
    if (frame_rightBand < 0) {
1625
        fprintf(stderr, "Incorrect right crop size\n");
1626
        exit(1);
1627
    }
1628
    if ((frame_rightBand % 2) != 0) {
1629
        fprintf(stderr, "Right crop size must be a multiple of 2\n");
1630
        exit(1);        
1631
    }
1632
    if ((frame_rightBand) >= frame_width){
1633
            fprintf(stderr, "Horizontal crop dimensions are outside the range of the original image.\nRemember to crop first and scale second.\n");
1634
        exit(1);
1635
    }
1636
    frame_width -= frame_rightBand;
1637
}
1638

    
1639
void opt_frame_size(const char *arg)
1640
{
1641
    parse_image_size(&frame_width, &frame_height, arg);
1642
    if (frame_width <= 0 || frame_height <= 0) {
1643
        fprintf(stderr, "Incorrect frame size\n");
1644
        exit(1);
1645
    }
1646
    if ((frame_width % 2) != 0 || (frame_height % 2) != 0) {
1647
        fprintf(stderr, "Frame size must be a multiple of 2\n");
1648
        exit(1);
1649
    }
1650
}
1651

    
1652
void opt_gop_size(const char *arg)
1653
{
1654
    gop_size = atoi(arg);
1655
}
1656

    
1657
void opt_b_frames(const char *arg)
1658
{
1659
    b_frames = atoi(arg);
1660
    if (b_frames > FF_MAX_B_FRAMES) {
1661
        fprintf(stderr, "\nCannot have more than %d B frames, increase FF_MAX_B_FRAMES.\n", FF_MAX_B_FRAMES);
1662
        exit(1);
1663
    } else if (b_frames < 1) {
1664
        fprintf(stderr, "\nNumber of B frames must be higher than 0\n");
1665
        exit(1);
1666
    }
1667
}
1668

    
1669
void opt_qscale(const char *arg)
1670
{
1671
    video_qscale = atoi(arg);
1672
    if (video_qscale < 0 ||
1673
        video_qscale > 31) {
1674
        fprintf(stderr, "qscale must be >= 1 and <= 31\n");
1675
        exit(1);
1676
    }
1677
}
1678

    
1679
void opt_qmin(const char *arg)
1680
{
1681
    video_qmin = atoi(arg);
1682
    if (video_qmin < 0 ||
1683
        video_qmin > 31) {
1684
        fprintf(stderr, "qmin must be >= 1 and <= 31\n");
1685
        exit(1);
1686
    }
1687
}
1688

    
1689
void opt_qmax(const char *arg)
1690
{
1691
    video_qmax = atoi(arg);
1692
    if (video_qmax < 0 ||
1693
        video_qmax > 31) {
1694
        fprintf(stderr, "qmax must be >= 1 and <= 31\n");
1695
        exit(1);
1696
    }
1697
}
1698

    
1699
void opt_qdiff(const char *arg)
1700
{
1701
    video_qdiff = atoi(arg);
1702
    if (video_qdiff < 0 ||
1703
        video_qdiff > 31) {
1704
        fprintf(stderr, "qdiff must be >= 1 and <= 31\n");
1705
        exit(1);
1706
    }
1707
}
1708

    
1709
void opt_qblur(const char *arg)
1710
{
1711
    video_qblur = atof(arg);
1712
}
1713

    
1714
void opt_qcomp(const char *arg)
1715
{
1716
    video_qcomp = atof(arg);
1717
}
1718

    
1719
void opt_rc_initial_cplx(const char *arg)
1720
{
1721
    video_rc_initial_cplx = atof(arg);
1722
}
1723
void opt_b_qfactor(const char *arg)
1724
{
1725
    video_b_qfactor = atof(arg);
1726
}
1727
void opt_i_qfactor(const char *arg)
1728
{
1729
    video_i_qfactor = atof(arg);
1730
}
1731
void opt_b_qoffset(const char *arg)
1732
{
1733
    video_b_qoffset = atof(arg);
1734
}
1735
void opt_i_qoffset(const char *arg)
1736
{
1737
    video_i_qoffset = atof(arg);
1738
}
1739

    
1740
void opt_packet_size(const char *arg)
1741
{
1742
    packet_size= atoi(arg);
1743
}
1744

    
1745
void opt_audio_bitrate(const char *arg)
1746
{
1747
    audio_bit_rate = atoi(arg) * 1000;
1748
}
1749

    
1750
void opt_audio_rate(const char *arg)
1751
{
1752
    audio_sample_rate = atoi(arg);
1753
}
1754

    
1755
void opt_audio_channels(const char *arg)
1756
{
1757
    audio_channels = atoi(arg);
1758
}
1759

    
1760
void opt_video_device(const char *arg)
1761
{
1762
    v4l_device = strdup(arg);
1763
}
1764

    
1765
void opt_audio_device(const char *arg)
1766
{
1767
    audio_device = strdup(arg);
1768
}
1769

    
1770
void opt_audio_codec(const char *arg)
1771
{
1772
    AVCodec *p;
1773

    
1774
    if (!strcmp(arg, "copy")) {
1775
        audio_stream_copy = 1;
1776
    } else {
1777
        p = first_avcodec;
1778
        while (p) {
1779
            if (!strcmp(p->name, arg) && p->type == CODEC_TYPE_AUDIO)
1780
                break;
1781
            p = p->next;
1782
        }
1783
        if (p == NULL) {
1784
            fprintf(stderr, "Unknown audio codec '%s'\n", arg);
1785
            exit(1);
1786
        } else {
1787
            audio_codec_id = p->id;
1788
        }
1789
    }
1790
}
1791

    
1792
void add_frame_hooker(const char *arg)
1793
{
1794
    int argc = 0;
1795
    char *argv[64];
1796
    int i;
1797
    char *args = strdup(arg);
1798

    
1799
    argv[0] = strtok(args, " ");
1800
    while (argc < 62 && (argv[++argc] = strtok(NULL, " "))) {
1801
    }
1802

    
1803
    i = frame_hook_add(argc, argv);
1804

    
1805
    if (i != 0) {
1806
        fprintf(stderr, "Failed to add video hook function: %s\n", arg);
1807
        exit(1);
1808
    }
1809
}
1810

    
1811
const char *motion_str[] = {
1812
    "zero",
1813
    "full",
1814
    "log",
1815
    "phods",
1816
    "epzs",
1817
    "x1",
1818
    NULL,
1819
};
1820

    
1821
void opt_motion_estimation(const char *arg)
1822
{
1823
    const char **p;
1824
    p = motion_str;
1825
    for(;;) {
1826
        if (!*p) {
1827
            fprintf(stderr, "Unknown motion estimation method '%s'\n", arg);
1828
            exit(1);
1829
        }
1830
        if (!strcmp(*p, arg))
1831
            break;
1832
        p++;
1833
    }
1834
    me_method = (p - motion_str) + 1;
1835
}
1836

    
1837
void opt_video_codec(const char *arg)
1838
{
1839
    AVCodec *p;
1840

    
1841
    if (!strcmp(arg, "copy")) {
1842
        video_stream_copy = 1;
1843
    } else {
1844
        p = first_avcodec;
1845
        while (p) {
1846
            if (!strcmp(p->name, arg) && p->type == CODEC_TYPE_VIDEO)
1847
                break;
1848
            p = p->next;
1849
        }
1850
        if (p == NULL) {
1851
            fprintf(stderr, "Unknown video codec '%s'\n", arg);
1852
            exit(1);
1853
        } else {
1854
            video_codec_id = p->id;
1855
        }
1856
    }
1857
}
1858

    
1859
void opt_map(const char *arg)
1860
{
1861
    AVStreamMap *m;
1862
    const char *p;
1863

    
1864
    p = arg;
1865
    m = &stream_maps[nb_stream_maps++];
1866

    
1867
    m->file_index = strtol(arg, (char **)&p, 0);
1868
    if (*p)
1869
        p++;
1870

    
1871
    m->stream_index = strtol(p, (char **)&p, 0);
1872
}
1873

    
1874
void opt_recording_time(const char *arg)
1875
{
1876
    recording_time = parse_date(arg, 1);
1877
}
1878

    
1879
void print_error(const char *filename, int err)
1880
{
1881
    switch(err) {
1882
    case AVERROR_NUMEXPECTED:
1883
        fprintf(stderr, "%s: Incorrect image filename syntax.\n"
1884
                "Use '%%d' to specify the image number:\n"
1885
                "  for img1.jpg, img2.jpg, ..., use 'img%%d.jpg';\n"
1886
                "  for img001.jpg, img002.jpg, ..., use 'img%%03d.jpg'.\n", 
1887
                filename);
1888
        break;
1889
    case AVERROR_INVALIDDATA:
1890
        fprintf(stderr, "%s: Error while parsing header\n", filename);
1891
        break;
1892
    case AVERROR_NOFMT:
1893
        fprintf(stderr, "%s: Unknown format\n", filename);
1894
        break;
1895
    default:
1896
        fprintf(stderr, "%s: Error while opening file\n", filename);
1897
        break;
1898
    }
1899
}
1900

    
1901
void opt_input_file(const char *filename)
1902
{
1903
    AVFormatContext *ic;
1904
    AVFormatParameters params, *ap = &params;
1905
    int err, i, ret, rfps;
1906

    
1907
    if (!strcmp(filename, "-"))
1908
        filename = "pipe:";
1909

    
1910
    /* get default parameters from command line */
1911
    memset(ap, 0, sizeof(*ap));
1912
    ap->sample_rate = audio_sample_rate;
1913
    ap->channels = audio_channels;
1914
    ap->frame_rate = frame_rate;
1915
    ap->width = frame_width;
1916
    ap->height = frame_height;
1917

    
1918
    /* open the input file with generic libav function */
1919
    err = av_open_input_file(&ic, filename, file_iformat, 0, ap);
1920
    if (err < 0) {
1921
        print_error(filename, err);
1922
        exit(1);
1923
    }
1924
    
1925
    /* If not enough info to get the stream parameters, we decode the
1926
       first frames to get it. (used in mpeg case for example) */
1927
    ret = av_find_stream_info(ic);
1928
    if (ret < 0) {
1929
        fprintf(stderr, "%s: could not find codec parameters\n", filename);
1930
        exit(1);
1931
    }
1932

    
1933
    /* update the current parameters so that they match the one of the input stream */
1934
    for(i=0;i<ic->nb_streams;i++) {
1935
        AVCodecContext *enc = &ic->streams[i]->codec;
1936
        switch(enc->codec_type) {
1937
        case CODEC_TYPE_AUDIO:
1938
            //fprintf(stderr, "\nInput Audio channels: %d", enc->channels);
1939
            audio_channels = enc->channels;
1940
            audio_sample_rate = enc->sample_rate;
1941
            break;
1942
        case CODEC_TYPE_VIDEO:
1943
            frame_height = enc->height;
1944
            frame_width = enc->width;
1945
            rfps = ic->streams[i]->r_frame_rate;
1946
            enc->workaround_bugs = workaround_bugs;
1947
            enc->error_resilience = error_resilience; 
1948
            enc->error_concealment = error_concealment; 
1949
            enc->idct_algo= idct_algo;
1950
/*            if(enc->codec->capabilities & CODEC_CAP_TRUNCATED)
1951
                enc->flags|= CODEC_FLAG_TRUNCATED; */
1952
            if(/*enc->codec_id==CODEC_ID_MPEG4 || */enc->codec_id==CODEC_ID_MPEG1VIDEO)
1953
                enc->flags|= CODEC_FLAG_TRUNCATED;
1954

    
1955
            if (enc->frame_rate != rfps) {
1956
                fprintf(stderr,"\nSeems that stream %d comes from film source: %2.2f->%2.2f\n",
1957
                    i, (float)enc->frame_rate / FRAME_RATE_BASE,
1958
                    (float)rfps / FRAME_RATE_BASE);
1959
            }
1960
            /* update the current frame rate to match the stream frame rate */
1961
            frame_rate = rfps;
1962
            break;
1963
        default:
1964
            av_abort();
1965
        }
1966
    }
1967
    
1968
    input_files[nb_input_files] = ic;
1969
    /* dump the file content */
1970
    dump_format(ic, nb_input_files, filename, 0);
1971
    nb_input_files++;
1972
    file_iformat = NULL;
1973
    file_oformat = NULL;
1974
}
1975

    
1976
void check_audio_video_inputs(int *has_video_ptr, int *has_audio_ptr)
1977
{
1978
    int has_video, has_audio, i, j;
1979
    AVFormatContext *ic;
1980

    
1981
    has_video = 0;
1982
    has_audio = 0;
1983
    for(j=0;j<nb_input_files;j++) {
1984
        ic = input_files[j];
1985
        for(i=0;i<ic->nb_streams;i++) {
1986
            AVCodecContext *enc = &ic->streams[i]->codec;
1987
            switch(enc->codec_type) {
1988
            case CODEC_TYPE_AUDIO:
1989
                has_audio = 1;
1990
                break;
1991
            case CODEC_TYPE_VIDEO:
1992
                has_video = 1;
1993
                break;
1994
            default:
1995
                av_abort();
1996
            }
1997
        }
1998
    }
1999
    *has_video_ptr = has_video;
2000
    *has_audio_ptr = has_audio;
2001
}
2002

    
2003
void opt_output_file(const char *filename)
2004
{
2005
    AVStream *st;
2006
    AVFormatContext *oc;
2007
    int use_video, use_audio, nb_streams, input_has_video, input_has_audio;
2008
    int codec_id;
2009

    
2010
    if (!strcmp(filename, "-"))
2011
        filename = "pipe:";
2012

    
2013
    oc = av_mallocz(sizeof(AVFormatContext));
2014

    
2015
    if (!file_oformat) {
2016
        file_oformat = guess_format(NULL, filename, NULL);
2017
        if (!file_oformat) {
2018
            fprintf(stderr, "Unable for find a suitable output format for '%s'\n",
2019
                    filename);
2020
            exit(1);
2021
        }
2022
    }
2023
    
2024
    oc->oformat = file_oformat;
2025

    
2026
    if (!strcmp(file_oformat->name, "ffm") && 
2027
        strstart(filename, "http:", NULL)) {
2028
        /* special case for files sent to ffserver: we get the stream
2029
           parameters from ffserver */
2030
        if (read_ffserver_streams(oc, filename) < 0) {
2031
            fprintf(stderr, "Could not read stream parameters from '%s'\n", filename);
2032
            exit(1);
2033
        }
2034
    } else {
2035
        use_video = file_oformat->video_codec != CODEC_ID_NONE;
2036
        use_audio = file_oformat->audio_codec != CODEC_ID_NONE;
2037

    
2038
        /* disable if no corresponding type found and at least one
2039
           input file */
2040
        if (nb_input_files > 0) {
2041
            check_audio_video_inputs(&input_has_video, &input_has_audio);
2042
            if (!input_has_video)
2043
                use_video = 0;
2044
            if (!input_has_audio)
2045
                use_audio = 0;
2046
        }
2047

    
2048
        /* manual disable */
2049
        if (audio_disable) {
2050
            use_audio = 0;
2051
        }
2052
        if (video_disable) {
2053
            use_video = 0;
2054
        }
2055
        
2056
        nb_streams = 0;
2057
        if (use_video) {
2058
            AVCodecContext *video_enc;
2059
            
2060
            st = av_mallocz(sizeof(AVStream));
2061
            if (!st) {
2062
                fprintf(stderr, "Could not alloc stream\n");
2063
                exit(1);
2064
            }
2065
            avcodec_get_context_defaults(&st->codec);
2066

    
2067
            video_enc = &st->codec;
2068
            if (video_stream_copy) {
2069
                st->stream_copy = 1;
2070
                video_enc->codec_type = CODEC_TYPE_VIDEO;
2071
            } else {
2072
                char *p;
2073
                int i;
2074
            
2075
                codec_id = file_oformat->video_codec;
2076
                if (video_codec_id != CODEC_ID_NONE)
2077
                    codec_id = video_codec_id;
2078
                
2079
                video_enc->codec_id = codec_id;
2080
                
2081
                video_enc->bit_rate = video_bit_rate;
2082
                video_enc->bit_rate_tolerance = video_bit_rate_tolerance;
2083
                video_enc->frame_rate = frame_rate; 
2084
                
2085
                video_enc->width = frame_width;
2086
                video_enc->height = frame_height;
2087

    
2088
                if (!intra_only)
2089
                    video_enc->gop_size = gop_size;
2090
                else
2091
                    video_enc->gop_size = 0;
2092
                if (video_qscale || same_quality) {
2093
                    video_enc->flags |= CODEC_FLAG_QSCALE;
2094
                    st->quality = video_qscale;
2095
                }
2096
            
2097
                if (use_hq) {
2098
                    video_enc->flags |= CODEC_FLAG_HQ;
2099
                }
2100
            
2101
                if (use_4mv) {
2102
                    video_enc->flags |= CODEC_FLAG_HQ;
2103
                    video_enc->flags |= CODEC_FLAG_4MV;
2104
                }
2105
            
2106
                if(use_part)
2107
                    video_enc->flags |= CODEC_FLAG_PART;
2108
               
2109
            
2110
                if (b_frames) {
2111
                    if (codec_id != CODEC_ID_MPEG4) {
2112
                        fprintf(stderr, "\nB frames encoding only supported by MPEG-4.\n");
2113
                        exit(1);
2114
                    }
2115
                    video_enc->max_b_frames = b_frames;
2116
                    video_enc->b_frame_strategy = 0;
2117
                    video_enc->b_quant_factor = 2.0;
2118
                }
2119
            
2120
                video_enc->qmin = video_qmin;
2121
                video_enc->qmax = video_qmax;
2122
                video_enc->max_qdiff = video_qdiff;
2123
                video_enc->qblur = video_qblur;
2124
                video_enc->qcompress = video_qcomp;
2125
                video_enc->rc_eq = video_rc_eq;
2126
                
2127
                p= video_rc_override_string;
2128
                for(i=0; p; i++){
2129
                    int start, end, q;
2130
                    int e=sscanf(p, "%d,%d,%d", &start, &end, &q);
2131
                    if(e!=3){
2132
                        fprintf(stderr, "error parsing rc_override\n");
2133
                        exit(1);
2134
                    }
2135
                    video_enc->rc_override= 
2136
                        realloc(video_enc->rc_override, sizeof(RcOverride)*(i+1));
2137
                    video_enc->rc_override[i].start_frame= start;
2138
                    video_enc->rc_override[i].end_frame  = end;
2139
                    if(q>0){
2140
                        video_enc->rc_override[i].qscale= q;
2141
                        video_enc->rc_override[i].quality_factor= 1.0;
2142
                    }
2143
                    else{
2144
                        video_enc->rc_override[i].qscale= 0;
2145
                        video_enc->rc_override[i].quality_factor= -q/100.0;
2146
                    }
2147
                    p= strchr(p, '/');
2148
                    if(p) p++;
2149
                }
2150
                video_enc->rc_override_count=i;
2151

    
2152
                video_enc->rc_max_rate = video_rc_max_rate;
2153
                video_enc->rc_min_rate = video_rc_min_rate;
2154
                video_enc->rc_buffer_size = video_rc_buffer_size;
2155
                video_enc->rc_buffer_aggressivity= video_rc_buffer_aggressivity;
2156
                video_enc->rc_initial_cplx= video_rc_initial_cplx;
2157
                video_enc->i_quant_factor = video_i_qfactor;
2158
                video_enc->b_quant_factor = video_b_qfactor;
2159
                video_enc->i_quant_offset = video_i_qoffset;
2160
                video_enc->b_quant_offset = video_b_qoffset;
2161
                video_enc->dct_algo = dct_algo;
2162
                video_enc->idct_algo = idct_algo;
2163
                if(packet_size){
2164
                    video_enc->rtp_mode= 1;
2165
                    video_enc->rtp_payload_size= packet_size;
2166
                }
2167
            
2168
                if (do_psnr)
2169
                    video_enc->flags|= CODEC_FLAG_PSNR;
2170
            
2171
                video_enc->me_method = me_method;
2172

    
2173
                /* two pass mode */
2174
                if (do_pass) {
2175
                    if (do_pass == 1) {
2176
                        video_enc->flags |= CODEC_FLAG_PASS1;
2177
                    } else {
2178
                        video_enc->flags |= CODEC_FLAG_PASS2;
2179
                    }
2180
                }
2181
            
2182
                /* XXX: need to find a way to set codec parameters */
2183
                if (oc->oformat->flags & AVFMT_RGB24) {
2184
                    video_enc->pix_fmt = PIX_FMT_RGB24;
2185
                }
2186
            }
2187
            oc->streams[nb_streams] = st;
2188
            nb_streams++;
2189
        }
2190
    
2191
        if (use_audio) {
2192
            AVCodecContext *audio_enc;
2193

    
2194
            st = av_mallocz(sizeof(AVStream));
2195
            if (!st) {
2196
                fprintf(stderr, "Could not alloc stream\n");
2197
                exit(1);
2198
            }
2199
            avcodec_get_context_defaults(&st->codec);
2200

    
2201
            audio_enc = &st->codec;
2202
            audio_enc->codec_type = CODEC_TYPE_AUDIO;
2203
            if (audio_stream_copy) {
2204
                st->stream_copy = 1;
2205
            } else {
2206
                codec_id = file_oformat->audio_codec;
2207
                if (audio_codec_id != CODEC_ID_NONE)
2208
                    codec_id = audio_codec_id;
2209
                audio_enc->codec_id = codec_id;
2210
                
2211
                audio_enc->bit_rate = audio_bit_rate;
2212
                audio_enc->sample_rate = audio_sample_rate;
2213
                /* For audio codecs other than AC3 we limit */
2214
                /* the number of coded channels to stereo   */
2215
                if (audio_channels > 2 && codec_id != CODEC_ID_AC3) {
2216
                    audio_enc->channels = 2;
2217
                } else
2218
                    audio_enc->channels = audio_channels;
2219
            }
2220
            oc->streams[nb_streams] = st;
2221
            nb_streams++;
2222
        }
2223

    
2224
        oc->nb_streams = nb_streams;
2225

    
2226
        if (!nb_streams) {
2227
            fprintf(stderr, "No audio or video streams available\n");
2228
            exit(1);
2229
        }
2230

    
2231
        if (str_title)
2232
            pstrcpy(oc->title, sizeof(oc->title), str_title);
2233
        if (str_author)
2234
            pstrcpy(oc->author, sizeof(oc->author), str_author);
2235
        if (str_copyright)
2236
            pstrcpy(oc->copyright, sizeof(oc->copyright), str_copyright);
2237
        if (str_comment)
2238
            pstrcpy(oc->comment, sizeof(oc->comment), str_comment);
2239
    }
2240

    
2241
    output_files[nb_output_files++] = oc;
2242

    
2243
    strcpy(oc->filename, filename);
2244

    
2245
    /* check filename in case of an image number is expected */
2246
    if (oc->oformat->flags & AVFMT_NEEDNUMBER) {
2247
        if (filename_number_test(oc->filename) < 0) {
2248
            print_error(oc->filename, AVERROR_NUMEXPECTED);
2249
            exit(1);
2250
        }
2251
    }
2252

    
2253
    if (!(oc->oformat->flags & AVFMT_NOFILE)) {
2254
        /* test if it already exists to avoid loosing precious files */
2255
        if (!file_overwrite && 
2256
            (strchr(filename, ':') == NULL ||
2257
             strstart(filename, "file:", NULL))) {
2258
            if (url_exist(filename)) {
2259
                int c;
2260
                
2261
                printf("File '%s' already exists. Overwrite ? [y/N] ", filename);
2262
                fflush(stdout);
2263
                c = getchar();
2264
                if (toupper(c) != 'Y') {
2265
                    fprintf(stderr, "Not overwriting - exiting\n");
2266
                    exit(1);
2267
                }
2268
            }
2269
        }
2270
        
2271
        /* open the file */
2272
        if (url_fopen(&oc->pb, filename, URL_WRONLY) < 0) {
2273
            fprintf(stderr, "Could not open '%s'\n", filename);
2274
            exit(1);
2275
        }
2276
    }
2277

    
2278
    /* reset some options */
2279
    file_oformat = NULL;
2280
    file_iformat = NULL;
2281
    audio_disable = 0;
2282
    video_disable = 0;
2283
    audio_codec_id = CODEC_ID_NONE;
2284
    video_codec_id = CODEC_ID_NONE;
2285
    audio_stream_copy = 0;
2286
    video_stream_copy = 0;
2287
}
2288

    
2289
/* prepare dummy protocols for grab */
2290
void prepare_grab(void)
2291
{
2292
    int has_video, has_audio, i, j;
2293
    AVFormatContext *oc;
2294
    AVFormatContext *ic;
2295
    AVFormatParameters ap1, *ap = &ap1;
2296

    
2297
    /* see if audio/video inputs are needed */
2298
    has_video = 0;
2299
    has_audio = 0;
2300
    memset(ap, 0, sizeof(*ap));
2301
    for(j=0;j<nb_output_files;j++) {
2302
        oc = output_files[j];
2303
        for(i=0;i<oc->nb_streams;i++) {
2304
            AVCodecContext *enc = &oc->streams[i]->codec;
2305
            switch(enc->codec_type) {
2306
            case CODEC_TYPE_AUDIO:
2307
                if (enc->sample_rate > ap->sample_rate)
2308
                    ap->sample_rate = enc->sample_rate;
2309
                if (enc->channels > ap->channels)
2310
                    ap->channels = enc->channels;
2311
                has_audio = 1;
2312
                break;
2313
            case CODEC_TYPE_VIDEO:
2314
                if (enc->width > ap->width)
2315
                    ap->width = enc->width;
2316
                if (enc->height > ap->height)
2317
                    ap->height = enc->height;
2318
                if (enc->frame_rate > ap->frame_rate)
2319
                    ap->frame_rate = enc->frame_rate;
2320
                has_video = 1;
2321
                break;
2322
            default:
2323
                av_abort();
2324
            }
2325
        }
2326
    }
2327
    
2328
    if (has_video == 0 && has_audio == 0) {
2329
        fprintf(stderr, "Output file must have at least one audio or video stream\n");
2330
        exit(1);
2331
    }
2332
    
2333
    if (has_video) {
2334
        AVInputFormat *fmt1;
2335
        fmt1 = av_find_input_format("video_grab_device");
2336
        if (av_open_input_file(&ic, "", fmt1, 0, ap) < 0) {
2337
            fprintf(stderr, "Could not find video grab device\n");
2338
            exit(1);
2339
        }
2340
        /* by now video grab has one stream */
2341
        ic->streams[0]->r_frame_rate = ap->frame_rate;
2342
        input_files[nb_input_files] = ic;
2343
        dump_format(ic, nb_input_files, v4l_device, 0);
2344
        nb_input_files++;
2345
    }
2346
    if (has_audio) {
2347
        AVInputFormat *fmt1;
2348
        fmt1 = av_find_input_format("audio_device");
2349
        if (av_open_input_file(&ic, "", fmt1, 0, ap) < 0) {
2350
            fprintf(stderr, "Could not find audio grab device\n");
2351
            exit(1);
2352
        }
2353
        input_files[nb_input_files] = ic;
2354
        dump_format(ic, nb_input_files, audio_device, 0);
2355
        nb_input_files++;
2356
    }
2357
}
2358

    
2359
/* open the necessary output devices for playing */
2360
void prepare_play(void)
2361
{
2362
    file_iformat = NULL;
2363
    file_oformat = guess_format("audio_device", NULL, NULL);
2364
    if (!file_oformat) {
2365
        fprintf(stderr, "Could not find audio device\n");
2366
        exit(1);
2367
    }
2368
    
2369
    opt_output_file(audio_device);
2370
}
2371

    
2372
/* same option as mencoder */
2373
void opt_pass(const char *pass_str)
2374
{
2375
    int pass;
2376
    pass = atoi(pass_str);
2377
    if (pass != 1 && pass != 2) {
2378
        fprintf(stderr, "pass number can be only 1 or 2\n");
2379
        exit(1);
2380
    }
2381
    do_pass = pass;
2382
}
2383

    
2384
#ifndef CONFIG_WIN32
2385
INT64 getutime(void)
2386
{
2387
    struct rusage rusage;
2388

    
2389
    getrusage(RUSAGE_SELF, &rusage);
2390
    return (rusage.ru_utime.tv_sec * 1000000LL) + rusage.ru_utime.tv_usec;
2391
}
2392
#else
2393
INT64 getutime(void)
2394
{
2395
  return av_gettime();
2396
}
2397
#endif
2398

    
2399
extern int ffm_nopts;
2400

    
2401
void opt_bitexact(void)
2402
{
2403
    avcodec_set_bit_exact();
2404
    /* disable generate of real time pts in ffm (need to be supressed anyway) */
2405
    ffm_nopts = 1;
2406
}
2407

    
2408
void show_formats(void)
2409
{
2410
    AVInputFormat *ifmt;
2411
    AVOutputFormat *ofmt;
2412
    URLProtocol *up;
2413
    AVCodec *p;
2414
    const char **pp;
2415

    
2416
    printf("File formats:\n");
2417
    printf("  Encoding:");
2418
    for(ofmt = first_oformat; ofmt != NULL; ofmt = ofmt->next) {
2419
        printf(" %s", ofmt->name);
2420
    }
2421
    printf("\n");
2422
    printf("  Decoding:");
2423
    for(ifmt = first_iformat; ifmt != NULL; ifmt = ifmt->next) {
2424
        printf(" %s", ifmt->name);
2425
    }
2426
    printf("\n");
2427

    
2428
    printf("Codecs:\n");
2429
    printf("  Encoders:");
2430
    for(p = first_avcodec; p != NULL; p = p->next) {
2431
        if (p->encode)
2432
            printf(" %s", p->name);
2433
    }
2434
    printf("\n");
2435

    
2436
    printf("  Decoders:");
2437
    for(p = first_avcodec; p != NULL; p = p->next) {
2438
        if (p->decode)
2439
            printf(" %s", p->name);
2440
    }
2441
    printf("\n");
2442

    
2443
    printf("Supported file protocols:");
2444
    for(up = first_protocol; up != NULL; up = up->next)
2445
        printf(" %s:", up->name);
2446
    printf("\n");
2447
    
2448
    printf("Frame size abbreviations: sqcif qcif cif 4cif\n");
2449
    printf("Motion estimation methods:");
2450
    pp = motion_str;
2451
    while (*pp) {
2452
        printf(" %s", *pp);
2453
        if ((pp - motion_str + 1) == ME_ZERO) 
2454
            printf("(fastest)");
2455
        else if ((pp - motion_str + 1) == ME_FULL) 
2456
            printf("(slowest)");
2457
        else if ((pp - motion_str + 1) == ME_EPZS) 
2458
            printf("(default)");
2459
        pp++;
2460
    }
2461
    printf("\n");
2462
    exit(1);
2463
}
2464

    
2465
void show_help(void)
2466
{
2467
    const char *prog;
2468
    const OptionDef *po;
2469
    int i, expert;
2470
    
2471
    prog = do_play ? "ffplay" : "ffmpeg";
2472

    
2473
    printf("%s version " FFMPEG_VERSION ", Copyright (c) 2000, 2001, 2002 Fabrice Bellard\n",
2474
           prog);
2475
    
2476
    if (!do_play) {
2477
        printf("usage: ffmpeg [[options] -i input_file]... {[options] outfile}...\n"
2478
               "Hyper fast MPEG1/MPEG4/H263/RV and AC3/MPEG audio encoder\n");
2479
    } else {
2480
        printf("usage: ffplay [options] input_file...\n"
2481
               "Simple audio player\n");
2482
    }
2483
           
2484
    printf("\n"
2485
           "Main options are:\n");
2486
    for(i=0;i<2;i++) {
2487
        if (i == 1)
2488
            printf("\nAdvanced options are:\n");
2489
        for(po = options; po->name != NULL; po++) {
2490
            char buf[64];
2491
            expert = (po->flags & OPT_EXPERT) != 0;
2492
            if (expert == i) {
2493
                strcpy(buf, po->name);
2494
                if (po->flags & HAS_ARG) {
2495
                    strcat(buf, " ");
2496
                    strcat(buf, po->argname);
2497
                }
2498
                printf("-%-17s  %s\n", buf, po->help);
2499
            }
2500
        }
2501
    }
2502

    
2503
    exit(1);
2504
}
2505

    
2506
const OptionDef options[] = {
2507
    { "L", 0, {(void*)show_licence}, "show license" },
2508
    { "h", 0, {(void*)show_help}, "show help" },
2509
    { "formats", 0, {(void*)show_formats}, "show available formats, codecs, protocols, ..." },
2510
    { "f", HAS_ARG, {(void*)opt_format}, "force format", "fmt" },
2511
    { "i", HAS_ARG, {(void*)opt_input_file}, "input file name", "filename" },
2512
    { "y", OPT_BOOL, {(void*)&file_overwrite}, "overwrite output files" },
2513
    { "map", HAS_ARG | OPT_EXPERT, {(void*)opt_map}, "set input stream mapping", "file:stream" },
2514
    { "t", HAS_ARG, {(void*)opt_recording_time}, "set the recording time", "duration" },
2515
    { "title", HAS_ARG | OPT_STRING, {(void*)&str_title}, "set the title", "string" },
2516
    { "author", HAS_ARG | OPT_STRING, {(void*)&str_author}, "set the author", "string" },
2517
    { "copyright", HAS_ARG | OPT_STRING, {(void*)&str_copyright}, "set the copyright", "string" },
2518
    { "comment", HAS_ARG | OPT_STRING, {(void*)&str_comment}, "set the comment", "string" },
2519
    { "pass", HAS_ARG, {(void*)&opt_pass}, "select the pass number (1 or 2)", "n" },
2520
    { "passlogfile", HAS_ARG | OPT_STRING, {(void*)&pass_logfilename}, "select two pass log file name", "file" },
2521
    /* video options */
2522
    { "b", HAS_ARG, {(void*)opt_video_bitrate}, "set video bitrate (in kbit/s)", "bitrate" },
2523
    { "r", HAS_ARG, {(void*)opt_frame_rate}, "set frame rate (in Hz)", "rate" },
2524
    { "s", HAS_ARG, {(void*)opt_frame_size}, "set frame size (WxH or abbreviation)", "size" },
2525
    { "croptop", HAS_ARG, {(void*)opt_frame_crop_top}, "set top crop band size (in pixels)", "size" },
2526
    { "cropbottom", HAS_ARG, {(void*)opt_frame_crop_bottom}, "set bottom crop band size (in pixels)", "size" },
2527
    { "cropleft", HAS_ARG, {(void*)opt_frame_crop_left}, "set left crop band size (in pixels)", "size" },
2528
    { "cropright", HAS_ARG, {(void*)opt_frame_crop_right}, "set right crop band size (in pixels)", "size" },
2529
    { "g", HAS_ARG | OPT_EXPERT, {(void*)opt_gop_size}, "set the group of picture size", "gop_size" },
2530
    { "intra", OPT_BOOL | OPT_EXPERT, {(void*)&intra_only}, "use only intra frames"},
2531
    { "vn", OPT_BOOL, {(void*)&video_disable}, "disable video" },
2532
    { "qscale", HAS_ARG | OPT_EXPERT, {(void*)opt_qscale}, "use fixed video quantiser scale (VBR)", "q" },
2533
    { "qmin", HAS_ARG | OPT_EXPERT, {(void*)opt_qmin}, "min video quantiser scale (VBR)", "q" },
2534
    { "qmax", HAS_ARG | OPT_EXPERT, {(void*)opt_qmax}, "max video quantiser scale (VBR)", "q" },
2535
    { "qdiff", HAS_ARG | OPT_EXPERT, {(void*)opt_qdiff}, "max difference between the quantiser scale (VBR)", "q" },
2536
    { "qblur", HAS_ARG | OPT_EXPERT, {(void*)opt_qblur}, "video quantiser scale blur (VBR)", "blur" },
2537
    { "qcomp", HAS_ARG | OPT_EXPERT, {(void*)opt_qcomp}, "video quantiser scale compression (VBR)", "compression" },
2538
    { "rc_init_cplx", HAS_ARG | OPT_EXPERT, {(void*)opt_rc_initial_cplx}, "initial complexity for 1-pass encoding", "complexity" },
2539
    { "b_qfactor", HAS_ARG | OPT_EXPERT, {(void*)opt_b_qfactor}, "qp factor between p and b frames", "factor" },
2540
    { "i_qfactor", HAS_ARG | OPT_EXPERT, {(void*)opt_i_qfactor}, "qp factor between p and i frames", "factor" },
2541
    { "b_qoffset", HAS_ARG | OPT_EXPERT, {(void*)opt_b_qoffset}, "qp offset between p and b frames", "offset" },
2542
    { "i_qoffset", HAS_ARG | OPT_EXPERT, {(void*)opt_i_qoffset}, "qp offset between p and i frames", "offset" },
2543
    { "rc_eq", HAS_ARG | OPT_EXPERT, {(void*)opt_video_rc_eq}, "", "equation" },
2544
    { "rc_override", HAS_ARG | OPT_EXPERT, {(void*)opt_video_rc_override_string}, "Rate control override", "qualities for specific intervals" },
2545
    { "bt", HAS_ARG, {(void*)opt_video_bitrate_tolerance}, "set video bitrate tolerance (in kbit/s)", "tolerance" },
2546
    { "maxrate", HAS_ARG, {(void*)opt_video_bitrate_max}, "set max video bitrate tolerance (in kbit/s)", "bitrate" },
2547
    { "minrate", HAS_ARG, {(void*)opt_video_bitrate_min}, "set min video bitrate tolerance (in kbit/s)", "bitrate" },
2548
    { "bufsize", HAS_ARG, {(void*)opt_video_buffer_size}, "set ratecontrol buffere size (in kbit)", "size" },
2549
    { "vd", HAS_ARG | OPT_EXPERT, {(void*)opt_video_device}, "set video grab device", "device" },
2550
    { "vcodec", HAS_ARG | OPT_EXPERT, {(void*)opt_video_codec}, "force video codec ('copy' to copy stream)", "codec" },
2551
    { "me", HAS_ARG | OPT_EXPERT, {(void*)opt_motion_estimation}, "set motion estimation method", 
2552
      "method" },
2553
    { "dct_algo", HAS_ARG | OPT_EXPERT, {(void*)opt_dct_algo}, "set dct algo",  "algo" },
2554
    { "idct_algo", HAS_ARG | OPT_EXPERT, {(void*)opt_idct_algo}, "set idct algo",  "algo" },
2555
    { "er", HAS_ARG | OPT_EXPERT, {(void*)opt_error_resilience}, "set error resilience",  "" },
2556
    { "ec", HAS_ARG | OPT_EXPERT, {(void*)opt_error_resilience}, "set error concealment",  "" },
2557
    { "bf", HAS_ARG | OPT_EXPERT, {(void*)opt_b_frames}, "use 'frames' B frames (only MPEG-4)", "frames" },
2558
    { "hq", OPT_BOOL | OPT_EXPERT, {(void*)&use_hq}, "activate high quality settings" },
2559
    { "4mv", OPT_BOOL | OPT_EXPERT, {(void*)&use_4mv}, "use four motion vector by macroblock (only MPEG-4)" },
2560
    { "part", OPT_BOOL | OPT_EXPERT, {(void*)&use_part}, "use data partitioning (only MPEG-4)" },
2561
    { "bug", HAS_ARG | OPT_EXPERT, {(void*)opt_workaround_bugs}, "workaround not auto detected encoder bugs", "param" },
2562
    { "ps", HAS_ARG | OPT_EXPERT, {(void*)opt_packet_size}, "packet size", "size in bits" },
2563
    { "sameq", OPT_BOOL, {(void*)&same_quality}, 
2564
      "use same video quality as source (implies VBR)" },
2565
    /* audio options */
2566
    { "ab", HAS_ARG, {(void*)opt_audio_bitrate}, "set audio bitrate (in kbit/s)", "bitrate", },
2567
    { "ar", HAS_ARG, {(void*)opt_audio_rate}, "set audio sampling rate (in Hz)", "rate" },
2568
    { "ac", HAS_ARG, {(void*)opt_audio_channels}, "set number of audio channels", "channels" },
2569
    { "an", OPT_BOOL, {(void*)&audio_disable}, "disable audio" },
2570
    { "ad", HAS_ARG | OPT_EXPERT, {(void*)opt_audio_device}, "set audio device", "device" },
2571
    { "acodec", HAS_ARG | OPT_EXPERT, {(void*)opt_audio_codec}, "force audio codec ('copy' to copy stream)", "codec" },
2572
    { "deinterlace", OPT_BOOL | OPT_EXPERT, {(void*)&do_deinterlace}, 
2573
      "deinterlace pictures" },
2574
    { "benchmark", OPT_BOOL | OPT_EXPERT, {(void*)&do_benchmark}, 
2575
      "add timings for benchmarking" },
2576
    { "hex", OPT_BOOL | OPT_EXPERT, {(void*)&do_hex_dump}, 
2577
      "dump each input packet" },
2578
    { "psnr", OPT_BOOL | OPT_EXPERT, {(void*)&do_psnr}, "calculate PSNR of compressed frames" },
2579
    { "vstats", OPT_BOOL | OPT_EXPERT, {(void*)&do_vstats}, "dump video coding statistics to file" }, 
2580
    { "bitexact", OPT_EXPERT, {(void*)opt_bitexact}, "only use bit exact algorithms (for codec testing)" }, 
2581
    { "vhook", HAS_ARG | OPT_EXPERT, {(void*)add_frame_hooker}, "insert video processing module", "module name and parameters" },
2582
    { NULL, },
2583
};
2584

    
2585
int main(int argc, char **argv)
2586
{
2587
    int optindex, i;
2588
    const char *opt, *arg;
2589
    const OptionDef *po;
2590
    INT64 ti;
2591
    
2592
    av_register_all();
2593

    
2594
    /* detect if invoked as player */
2595
    i = strlen(argv[0]);
2596
    if (i >= 6 && !strcmp(argv[0] + i - 6, "ffplay"))
2597
        do_play = 1;
2598

    
2599
    if (argc <= 1)
2600
        show_help();
2601
    
2602
    /* parse options */
2603
    optindex = 1;
2604
    while (optindex < argc) {
2605
        opt = argv[optindex++];
2606
        
2607
        if (opt[0] == '-' && opt[1] != '\0') {
2608
            po = options;
2609
            while (po->name != NULL) {
2610
                if (!strcmp(opt + 1, po->name))
2611
                    break;
2612
                po++;
2613
            }
2614
            if (!po->name) {
2615
                fprintf(stderr, "%s: unrecognized option '%s'\n", argv[0], opt);
2616
                exit(1);
2617
            }
2618
            arg = NULL;
2619
            if (po->flags & HAS_ARG) {
2620
                arg = argv[optindex++];
2621
                if (!arg) {
2622
                    fprintf(stderr, "%s: missing argument for option '%s'\n", argv[0], opt);
2623
                    exit(1);
2624
                }
2625
            }
2626
            if (po->flags & OPT_STRING) {
2627
                char *str;
2628
                str = strdup(arg);
2629
                *po->u.str_arg = str;
2630
            } else if (po->flags & OPT_BOOL) {
2631
                *po->u.int_arg = 1;
2632
            } else {
2633
                po->u.func_arg(arg);
2634
            }
2635
        } else {
2636
            if (!do_play) {
2637
                opt_output_file(opt);
2638
            } else {
2639
                opt_input_file(opt);
2640
            }
2641
        }
2642
    }
2643

    
2644

    
2645
    if (!do_play) {
2646
        /* file converter / grab */
2647
        if (nb_output_files <= 0) {
2648
            fprintf(stderr, "Must supply at least one output file\n");
2649
            exit(1);
2650
        }
2651
        
2652
        if (nb_input_files == 0) {
2653
            prepare_grab();
2654
        }
2655
    } else {
2656
        /* player */
2657
        if (nb_input_files <= 0) {
2658
            fprintf(stderr, "Must supply at least one input file\n");
2659
            exit(1);
2660
        }
2661
        prepare_play();
2662
    }
2663

    
2664
    ti = getutime();
2665
    av_encode(output_files, nb_output_files, input_files, nb_input_files, 
2666
              stream_maps, nb_stream_maps);
2667
    ti = getutime() - ti;
2668
    if (do_benchmark) {
2669
        printf("bench: utime=%0.3fs\n", ti / 1000000.0);
2670
    }
2671

    
2672
    /* close files */
2673
    for(i=0;i<nb_output_files;i++) {
2674
        /* maybe av_close_output_file ??? */
2675
        AVFormatContext *s = output_files[i];
2676
        int j;
2677
        if (!(s->oformat->flags & AVFMT_NOFILE))
2678
            url_fclose(&s->pb);
2679
        for(j=0;j<s->nb_streams;j++)
2680
            av_free(s->streams[j]);
2681
        av_free(s);
2682
    }
2683
    for(i=0;i<nb_input_files;i++)
2684
        av_close_input_file(input_files[i]);
2685

    
2686
    av_free_static();
2687
    return 0;
2688
}