Statistics
| Branch: | Revision:

ffmpeg / ffmpeg.c @ 79a7c268

History | View | Annotate | Download (91.6 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
#ifdef CONFIG_OS2
32
#include <sys/types.h>
33
#include <sys/select.h>
34
#include <stdlib.h>
35
#endif
36
#include <time.h>
37
#include <ctype.h>
38

    
39
#if !defined(INFINITY) && defined(HUGE_VAL)
40
#define INFINITY HUGE_VAL
41
#endif
42

    
43
#define MAXINT64 INT64_C(0x7fffffffffffffff)
44

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

    
61
/* select an input stream for an output stream */
62
typedef struct AVStreamMap {
63
    int file_index;
64
    int stream_index;
65
} AVStreamMap;
66

    
67
extern const OptionDef options[];
68

    
69
void show_help(void);
70

    
71
#define MAX_FILES 20
72

    
73
static AVFormatContext *input_files[MAX_FILES];
74
static int nb_input_files = 0;
75

    
76
static AVFormatContext *output_files[MAX_FILES];
77
static int nb_output_files = 0;
78

    
79
static AVStreamMap stream_maps[MAX_FILES];
80
static int nb_stream_maps;
81

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

    
137
static int gop_size = 12;
138
static int intra_only = 0;
139
static int audio_sample_rate = 44100;
140
static int audio_bit_rate = 64000;
141
static int audio_disable = 0;
142
static int audio_channels = 1;
143
static int audio_codec_id = CODEC_ID_NONE;
144

    
145
static INT64 recording_time = 0;
146
static int file_overwrite = 0;
147
static char *str_title = NULL;
148
static char *str_author = NULL;
149
static char *str_copyright = NULL;
150
static char *str_comment = NULL;
151
static int do_benchmark = 0;
152
static int do_hex_dump = 0;
153
static int do_play = 0;
154
static int do_psnr = 0;
155
static int do_vstats = 0;
156
static int do_pass = 0;
157
static char *pass_logfilename = NULL;
158
static int audio_stream_copy = 0;
159
static int video_stream_copy = 0;
160

    
161
static char *video_grab_format = "video4linux";
162
static char *video_device = NULL;
163

    
164
static char *audio_grab_format = "audio_device";
165
static char *audio_device = NULL;
166

    
167
#define DEFAULT_PASS_LOGFILENAME "ffmpeg2pass"
168

    
169
typedef struct AVOutputStream {
170
    int file_index;          /* file index */
171
    int index;               /* stream index in the output file */
172
    int source_index;        /* AVInputStream index */
173
    AVStream *st;            /* stream in the output file */
174
    int encoding_needed;     /* true if encoding needed for this stream */
175
    int frame_number;
176
    /* input pts and corresponding output pts
177
       for A/V sync */
178
    double sync_ipts;
179
    double sync_ipts_offset;
180
    INT64 sync_opts;
181
    /* video only */
182
    int video_resample;      /* video_resample and video_crop are mutually exclusive */
183
    AVPicture pict_tmp;      /* temporary image for resampling */
184
    ImgReSampleContext *img_resample_ctx; /* for image resampling */
185

    
186
    int video_crop;          /* video_resample and video_crop are mutually exclusive */
187
    int topBand;             /* cropping area sizes */
188
    int leftBand;
189
    
190
    /* audio only */
191
    int audio_resample;
192
    ReSampleContext *resample; /* for audio resampling */
193
    FifoBuffer fifo;     /* for compression: one audio fifo per codec */
194
    FILE *logfile;
195
} AVOutputStream;
196

    
197
typedef struct AVInputStream {
198
    int file_index;
199
    int index;
200
    AVStream *st;
201
    int discard;             /* true if stream data should be discarded */
202
    int decoding_needed;     /* true if the packets must be decoded in 'raw_fifo' */
203
    INT64 sample_index;      /* current sample */
204
    int frame_decoded;       /* true if a video or audio frame has been decoded */
205
} AVInputStream;
206

    
207
typedef struct AVInputFile {
208
    int eof_reached;      /* true if eof reached */
209
    int ist_index;        /* index of first stream in ist_table */
210
    int buffer_size;      /* current total buffer size */
211
    int buffer_size_max;  /* buffer size at which we consider we can stop
212
                             buffering */
213
    int nb_streams;       /* nb streams we are aware of */
214
} AVInputFile;
215

    
216
#ifndef CONFIG_WIN32
217

    
218
/* init terminal so that we can grab keys */
219
static struct termios oldtty;
220

    
221
static void term_exit(void)
222
{
223
    tcsetattr (0, TCSANOW, &oldtty);
224
}
225

    
226
static void term_init(void)
227
{
228
    struct termios tty;
229

    
230
    tcgetattr (0, &tty);
231
    oldtty = tty;
232

    
233
    tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
234
                          |INLCR|IGNCR|ICRNL|IXON);
235
    tty.c_oflag |= OPOST;
236
    tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
237
    tty.c_cflag &= ~(CSIZE|PARENB);
238
    tty.c_cflag |= CS8;
239
    tty.c_cc[VMIN] = 1;
240
    tty.c_cc[VTIME] = 0;
241
    
242
    tcsetattr (0, TCSANOW, &tty);
243

    
244
    atexit(term_exit);
245
#ifdef CONFIG_BEOS_NETSERVER
246
    fcntl(0, F_SETFL, fcntl(0, F_GETFL) | O_NONBLOCK);
247
#endif
248
}
249

    
250
/* read a key without blocking */
251
static int read_key(void)
252
{
253
    int n = 1;
254
    unsigned char ch;
255
#ifndef CONFIG_BEOS_NETSERVER
256
    struct timeval tv;
257
    fd_set rfds;
258

    
259
    FD_ZERO(&rfds);
260
    FD_SET(0, &rfds);
261
    tv.tv_sec = 0;
262
    tv.tv_usec = 0;
263
    n = select(1, &rfds, NULL, NULL, &tv);
264
#endif
265
    if (n > 0) {
266
        n = read(0, &ch, 1);
267
        if (n == 1)
268
            return ch;
269

    
270
        return n;
271
    }
272
    return -1;
273
}
274

    
275
#else
276

    
277
/* no interactive support */
278
static void term_exit(void)
279
{
280
}
281

    
282
static void term_init(void)
283
{
284
}
285

    
286
static int read_key(void)
287
{
288
    return 0;
289
}
290

    
291
#endif
292

    
293
int read_ffserver_streams(AVFormatContext *s, const char *filename)
294
{
295
    int i, err;
296
    AVFormatContext *ic;
297

    
298
    err = av_open_input_file(&ic, filename, NULL, FFM_PACKET_SIZE, NULL);
299
    if (err < 0)
300
        return err;
301
    /* copy stream format */
302
    s->nb_streams = ic->nb_streams;
303
    for(i=0;i<ic->nb_streams;i++) {
304
        AVStream *st;
305

    
306
        st = av_mallocz(sizeof(AVFormatContext));
307
        memcpy(st, ic->streams[i], sizeof(AVStream));
308
        s->streams[i] = st;
309
    }
310

    
311
    av_close_input_file(ic);
312
    return 0;
313
}
314

    
315
#define MAX_AUDIO_PACKET_SIZE (128 * 1024)
316

    
317
static void do_audio_out(AVFormatContext *s, 
318
                         AVOutputStream *ost, 
319
                         AVInputStream *ist,
320
                         unsigned char *buf, int size)
321
{
322
    UINT8 *buftmp;
323
    UINT8 audio_buf[2*MAX_AUDIO_PACKET_SIZE]; /* XXX: allocate it */
324
    UINT8 audio_out[4*MAX_AUDIO_PACKET_SIZE]; /* XXX: allocate it - yep really WMA */
325
    int size_out, frame_bytes, ret;
326
    AVCodecContext *enc;
327

    
328
    enc = &ost->st->codec;
329

    
330
    if (ost->audio_resample) {
331
        buftmp = audio_buf;
332
        size_out = audio_resample(ost->resample, 
333
                                  (short *)buftmp, (short *)buf,
334
                                  size / (ist->st->codec.channels * 2));
335
        size_out = size_out * enc->channels * 2;
336
    } else {
337
        buftmp = buf;
338
        size_out = size;
339
    }
340

    
341
    /* now encode as many frames as possible */
342
    if (enc->frame_size > 1) {
343
        /* output resampled raw samples */
344
        fifo_write(&ost->fifo, buftmp, size_out, 
345
                   &ost->fifo.wptr);
346

    
347
        frame_bytes = enc->frame_size * 2 * enc->channels;
348
        
349
        while (fifo_read(&ost->fifo, audio_buf, frame_bytes, 
350
                     &ost->fifo.rptr) == 0) {
351
            ret = avcodec_encode_audio(enc, audio_out, sizeof(audio_out), 
352
                                       (short *)audio_buf);
353
            av_write_frame(s, ost->index, audio_out, ret);
354
        }
355
    } else {
356
        /* output a pcm frame */
357
        /* XXX: change encoding codec API to avoid this ? */
358
        switch(enc->codec->id) {
359
        case CODEC_ID_PCM_S16LE:
360
        case CODEC_ID_PCM_S16BE:
361
        case CODEC_ID_PCM_U16LE:
362
        case CODEC_ID_PCM_U16BE:
363
            break;
364
        default:
365
            size_out = size_out >> 1;
366
            break;
367
        }
368
        ret = avcodec_encode_audio(enc, audio_out, size_out, 
369
                                   (short *)buftmp);
370
        av_write_frame(s, ost->index, audio_out, ret);
371
    }
372
}
373

    
374
/* write a picture to a raw mux */
375
static void write_picture(AVFormatContext *s, int index, AVPicture *picture, 
376
                          int pix_fmt, int w, int h)
377
{
378
    UINT8 *buf, *src, *dest;
379
    int size, j, i;
380

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

    
470
static void pre_process_video_frame(AVInputStream *ist, AVPicture *picture, void **bufp)
471
{
472
    AVCodecContext *dec;
473
    AVPicture *picture2;
474
    AVPicture picture_tmp;
475
    UINT8 *buf = 0;
476

    
477
    dec = &ist->st->codec;
478

    
479
    /* deinterlace : must be done before any resize */
480
    if (do_deinterlace) {
481
        int size;
482

    
483
        /* create temporary picture */
484
        size = avpicture_get_size(dec->pix_fmt, dec->width, dec->height);
485
        buf = av_malloc(size);
486
        if (!buf)
487
            return;
488
        
489
        picture2 = &picture_tmp;
490
        avpicture_fill(picture2, buf, dec->pix_fmt, dec->width, dec->height);
491

    
492
        if (avpicture_deinterlace(picture2, picture, 
493
                                  dec->pix_fmt, dec->width, dec->height) < 0) {
494
            /* if error, do not deinterlace */
495
            av_free(buf);
496
            buf = NULL;
497
            picture2 = picture;
498
        }
499
    } else {
500
        picture2 = picture;
501
    }
502

    
503
    frame_hook_process(picture2, dec->pix_fmt, dec->width, dec->height);
504

    
505
    if (picture != picture2)
506
        *picture = *picture2;
507
    *bufp = buf;
508
}
509

    
510
/* we begin to correct av delay at this threshold */
511
#define AV_DELAY_MAX 0.100
512

    
513
static void do_video_out(AVFormatContext *s, 
514
                         AVOutputStream *ost, 
515
                         AVInputStream *ist,
516
                         AVPicture *in_picture,
517
                         int *frame_size, AVOutputStream *audio_sync)
518
{
519
    int nb_frames, i, ret;
520
    AVPicture *final_picture, *formatted_picture;
521
    AVPicture picture_format_temp, picture_crop_temp;
522
    static UINT8 *video_buffer;
523
    UINT8 *buf = NULL, *buf1 = NULL;
524
    AVCodecContext *enc, *dec;
525

    
526
#define VIDEO_BUFFER_SIZE (1024*1024)
527

    
528
    enc = &ost->st->codec;
529
    dec = &ist->st->codec;
530

    
531
    /* by default, we output a single frame */
532
    nb_frames = 1;
533

    
534
    *frame_size = 0;
535

    
536
    /* NOTE: the A/V sync is always done by considering the audio is
537
       the master clock. It is suffisant for transcoding or playing,
538
       but not for the general case */
539
    if (audio_sync) {
540
        /* compute the A-V delay and duplicate/remove frames if needed */
541
        double adelta, vdelta, apts, vpts, av_delay;
542
        
543
        if (audio_sync->sync_ipts != AV_NOPTS_VALUE &&
544
            ost->sync_ipts != AV_NOPTS_VALUE) {
545
            
546
            adelta = (double)(ost->st->pts.val - audio_sync->sync_opts) * 
547
                s->pts_num / s->pts_den;
548
            apts = audio_sync->sync_ipts + adelta; 
549
            
550
            vdelta = (double)(ost->st->pts.val - ost->sync_opts) *
551
                s->pts_num / s->pts_den;
552
            vpts = ost->sync_ipts + vdelta;
553
            
554
            av_delay = apts - vpts;
555
            //            printf("delay=%f\n", av_delay);
556
            if (av_delay < -AV_DELAY_MAX)
557
                nb_frames = 2;
558
            else if (av_delay > AV_DELAY_MAX)
559
                nb_frames = 0;
560
        }
561
    } else {
562
        double vdelta;
563

    
564
        if (ost->sync_ipts != AV_NOPTS_VALUE) {
565
            vdelta = (double)(ost->st->pts.val) * s->pts_num / s->pts_den - (ost->sync_ipts - ost->sync_ipts_offset);
566
            if (vdelta < 100 && vdelta > -100 && ost->sync_ipts_offset) {
567
                if (vdelta < -AV_DELAY_MAX)
568
                    nb_frames = 2;
569
                else if (vdelta > AV_DELAY_MAX)
570
                    nb_frames = 0;
571
            } else {
572
                ost->sync_ipts_offset -= vdelta;
573
                if (!ost->sync_ipts_offset)
574
                    ost->sync_ipts_offset = 0.000001; /* one microsecond */
575
            }
576

    
577
#if defined(PJSG)
578
            {
579
                static char *action[] = { "drop frame", "copy frame", "dup frame" };
580
                printf("Input PTS %12.6f, output PTS %12.6f: %s\n",
581
                    (double) ost->sync_ipts, (double) ost->st->pts.val * s->pts_num / s->pts_den,
582
                    action[nb_frames]);
583
            }
584
#endif
585
        }
586
    }
587
    if (nb_frames <= 0) 
588
        return;
589

    
590
    if (!video_buffer)
591
        video_buffer = av_malloc(VIDEO_BUFFER_SIZE);
592
    if (!video_buffer)
593
        return;
594

    
595
    /* convert pixel format if needed */
596
    if (enc->pix_fmt != dec->pix_fmt) {
597
        int size;
598

    
599
        /* create temporary picture */
600
        size = avpicture_get_size(enc->pix_fmt, dec->width, dec->height);
601
        buf = av_malloc(size);
602
        if (!buf)
603
            return;
604
        formatted_picture = &picture_format_temp;
605
        avpicture_fill(formatted_picture, buf, enc->pix_fmt, dec->width, dec->height);
606
        
607
        if (img_convert(formatted_picture, enc->pix_fmt, 
608
                        in_picture, dec->pix_fmt, 
609
                        dec->width, dec->height) < 0) {
610
            fprintf(stderr, "pixel format conversion not handled\n");
611
            goto the_end;
612
        }
613
    } else {
614
        formatted_picture = in_picture;
615
    }
616

    
617
    /* XXX: resampling could be done before raw format convertion in
618
       some cases to go faster */
619
    /* XXX: only works for YUV420P */
620
    if (ost->video_resample) {
621
        final_picture = &ost->pict_tmp;
622
        img_resample(ost->img_resample_ctx, final_picture, formatted_picture);
623
    } else if (ost->video_crop) {
624
        picture_crop_temp.data[0] = formatted_picture->data[0] +
625
                (ost->topBand * formatted_picture->linesize[0]) + ost->leftBand;
626

    
627
        picture_crop_temp.data[1] = formatted_picture->data[1] +
628
                ((ost->topBand >> 1) * formatted_picture->linesize[1]) +
629
                (ost->leftBand >> 1);
630

    
631
        picture_crop_temp.data[2] = formatted_picture->data[2] +
632
                ((ost->topBand >> 1) * formatted_picture->linesize[2]) +
633
                (ost->leftBand >> 1);
634

    
635
        picture_crop_temp.linesize[0] = formatted_picture->linesize[0];
636
        picture_crop_temp.linesize[1] = formatted_picture->linesize[1];
637
        picture_crop_temp.linesize[2] = formatted_picture->linesize[2];
638
        final_picture = &picture_crop_temp;
639
    } else {
640
        final_picture = formatted_picture;
641
    }
642
    /* duplicates frame if needed */
643
    /* XXX: pb because no interleaving */
644
    for(i=0;i<nb_frames;i++) {
645
        if (enc->codec_id != CODEC_ID_RAWVIDEO) {
646
            AVFrame big_picture;
647
            
648
            memset(&big_picture, 0, sizeof(AVFrame));
649
            *(AVPicture*)&big_picture= *final_picture;
650
                        
651
            /* handles sameq here. This is not correct because it may
652
               not be a global option */
653
            if (same_quality) {
654
                big_picture.quality = ist->st->quality;
655
            }else
656
                big_picture.quality = ost->st->quality;
657
            
658
            ret = avcodec_encode_video(enc, 
659
                                       video_buffer, VIDEO_BUFFER_SIZE,
660
                                       &big_picture);
661
            //enc->frame_number = enc->real_pict_num;
662
            av_write_frame(s, ost->index, video_buffer, ret);
663
            *frame_size = ret;
664
            //fprintf(stderr,"\nFrame: %3d %3d size: %5d type: %d",
665
            //        enc->frame_number-1, enc->real_pict_num, ret,
666
            //        enc->pict_type);
667
            /* if two pass, output log */
668
            if (ost->logfile && enc->stats_out) {
669
                fprintf(ost->logfile, "%s", enc->stats_out);
670
            }
671
        } else {
672
            if (s->oformat->flags & AVFMT_RAWPICTURE) {
673
                /* raw pictures are written as AVPicture structure to
674
                   avoid any copies. We support temorarily the older
675
                   method. */
676
                av_write_frame(s, ost->index, 
677
                               (UINT8 *)final_picture, sizeof(AVPicture));
678
            } else {
679
                write_picture(s, ost->index, final_picture, enc->pix_fmt, 
680
                              enc->width, enc->height);
681
            }
682
        }
683
        ost->frame_number++;
684
    }
685
 the_end:
686
    av_free(buf);
687
    av_free(buf1);
688
}
689

    
690
static double psnr(double d){
691
    if(d==0) return INFINITY;
692
    return -10.0*log(d)/log(10);
693
}
694

    
695
static void do_video_stats(AVFormatContext *os, AVOutputStream *ost, 
696
                           int frame_size)
697
{
698
    static FILE *fvstats=NULL;
699
    static INT64 total_size = 0;
700
    char filename[40];
701
    time_t today2;
702
    struct tm *today;
703
    AVCodecContext *enc;
704
    int frame_number;
705
    INT64 ti;
706
    double ti1, bitrate, avg_bitrate;
707
    
708
    if (!fvstats) {
709
        today2 = time(NULL);
710
        today = localtime(&today2);
711
        sprintf(filename, "vstats_%02d%02d%02d.log", today->tm_hour,
712
                                               today->tm_min,
713
                                               today->tm_sec);
714
        fvstats = fopen(filename,"w");
715
        if (!fvstats) {
716
            perror("fopen");
717
            exit(1);
718
        }
719
    }
720
    
721
    ti = MAXINT64;
722
    enc = &ost->st->codec;
723
    total_size += frame_size;
724
    if (enc->codec_type == CODEC_TYPE_VIDEO) {
725
        frame_number = ost->frame_number;
726
        fprintf(fvstats, "frame= %5d q= %2.1f ", frame_number, enc->coded_frame->quality);
727
        if (enc->flags&CODEC_FLAG_PSNR)
728
            fprintf(fvstats, "PSNR= %6.2f ", psnr(enc->coded_frame->error[0]/(enc->width*enc->height*255.0*255.0)));
729
        
730
        fprintf(fvstats,"f_size= %6d ", frame_size);
731
        /* compute pts value */
732
        ti1 = (double)ost->st->pts.val * os->pts_num / os->pts_den;
733
        if (ti1 < 0.01)
734
            ti1 = 0.01;
735
    
736
        bitrate = (double)(frame_size * 8) * enc->frame_rate / FRAME_RATE_BASE / 1000.0;
737
        avg_bitrate = (double)(total_size * 8) / ti1 / 1000.0;
738
        fprintf(fvstats, "s_size= %8.0fkB time= %0.3f br= %7.1fkbits/s avg_br= %7.1fkbits/s ",
739
            (double)total_size / 1024, ti1, bitrate, avg_bitrate);
740
        fprintf(fvstats,"type= %s\n", enc->coded_frame->key_frame == 1 ? "I" : "P");        
741
    }
742
}
743

    
744
void print_report(AVFormatContext **output_files, 
745
                  AVOutputStream **ost_table, int nb_ostreams,
746
                  int is_last_report)
747
{
748
    char buf[1024];
749
    AVOutputStream *ost;
750
    AVFormatContext *oc, *os;
751
    INT64 total_size;
752
    AVCodecContext *enc;
753
    int frame_number, vid, i;
754
    double bitrate, ti1, pts;
755
    static INT64 last_time = -1;
756
    
757
    if (!is_last_report) {
758
        INT64 cur_time;
759
        /* display the report every 0.5 seconds */
760
        cur_time = av_gettime();
761
        if (last_time == -1) {
762
            last_time = cur_time;
763
            return;
764
        } 
765
        if ((cur_time - last_time) < 500000)
766
            return;
767
        last_time = cur_time;
768
    }
769

    
770

    
771
    oc = output_files[0];
772

    
773
    total_size = url_ftell(&oc->pb);
774
    
775
    buf[0] = '\0';
776
    ti1 = 1e10;
777
    vid = 0;
778
    for(i=0;i<nb_ostreams;i++) {
779
        ost = ost_table[i];
780
        os = output_files[ost->file_index];
781
        enc = &ost->st->codec;
782
        if (vid && enc->codec_type == CODEC_TYPE_VIDEO) {
783
            sprintf(buf + strlen(buf), "q=%2.1f ",
784
                    enc->coded_frame->quality);
785
        }
786
        if (!vid && enc->codec_type == CODEC_TYPE_VIDEO) {
787
            frame_number = ost->frame_number;
788
            sprintf(buf + strlen(buf), "frame=%5d q=%2.1f ",
789
                    frame_number, enc->coded_frame ? enc->coded_frame->quality : 0);
790
            if (enc->flags&CODEC_FLAG_PSNR)
791
                sprintf(buf + strlen(buf), "PSNR= %6.2f ", psnr(enc->coded_frame->error[0]/(enc->width*enc->height*255.0*255.0)));
792
            vid = 1;
793
        }
794
        /* compute min output value */
795
        pts = (double)ost->st->pts.val * os->pts_num / os->pts_den;
796
        if ((pts < ti1) && (pts > 0))
797
            ti1 = pts;
798
    }
799
    if (ti1 < 0.01)
800
        ti1 = 0.01;
801
    bitrate = (double)(total_size * 8) / ti1 / 1000.0;
802
    
803
    sprintf(buf + strlen(buf), 
804
            "size=%8.0fkB time=%0.1f bitrate=%6.1fkbits/s",
805
            (double)total_size / 1024, ti1, bitrate);
806
    
807
    fprintf(stderr, "%s   ", buf);
808
    
809
    if (is_last_report) {
810
        fprintf(stderr, "\n");
811
    } else {
812
        fprintf(stderr, "\r");
813
        fflush(stderr);
814
    }
815
}
816

    
817
/*
818
 * The following code is the main loop of the file converter
819
 */
820
static int av_encode(AVFormatContext **output_files,
821
                     int nb_output_files,
822
                     AVFormatContext **input_files,
823
                     int nb_input_files,
824
                     AVStreamMap *stream_maps, int nb_stream_maps)
825
{
826
    int ret, i, j, k, n, nb_istreams = 0, nb_ostreams = 0, pts_set;
827
    AVFormatContext *is, *os;
828
    AVCodecContext *codec, *icodec;
829
    AVOutputStream *ost, **ost_table = NULL;
830
    AVInputStream *ist, **ist_table = NULL;
831
    AVInputFile *file_table;
832
    AVFormatContext *stream_no_data;
833
    int key;
834

    
835
    file_table= (AVInputFile*) av_mallocz(nb_input_files * sizeof(AVInputFile));
836
    if (!file_table)
837
        goto fail;
838

    
839
    /* input stream init */
840
    j = 0;
841
    for(i=0;i<nb_input_files;i++) {
842
        is = input_files[i];
843
        file_table[i].ist_index = j;
844
        file_table[i].nb_streams = is->nb_streams;
845
        j += is->nb_streams;
846
    }
847
    nb_istreams = j;
848

    
849
    ist_table = av_mallocz(nb_istreams * sizeof(AVInputStream *));
850
    if (!ist_table)
851
        goto fail;
852
    
853
    for(i=0;i<nb_istreams;i++) {
854
        ist = av_mallocz(sizeof(AVInputStream));
855
        if (!ist)
856
            goto fail;
857
        ist_table[i] = ist;
858
    }
859
    j = 0;
860
    for(i=0;i<nb_input_files;i++) {
861
        is = input_files[i];
862
        for(k=0;k<is->nb_streams;k++) {
863
            ist = ist_table[j++];
864
            ist->st = is->streams[k];
865
            ist->file_index = i;
866
            ist->index = k;
867
            ist->discard = 1; /* the stream is discarded by default
868
                                 (changed later) */
869
        }
870
    }
871

    
872
    /* output stream init */
873
    nb_ostreams = 0;
874
    for(i=0;i<nb_output_files;i++) {
875
        os = output_files[i];
876
        nb_ostreams += os->nb_streams;
877
    }
878
    if (nb_stream_maps > 0 && nb_stream_maps != nb_ostreams) {
879
        fprintf(stderr, "Number of stream maps must match number of output streams\n");
880
        exit(1);
881
    }
882

    
883
    ost_table = av_mallocz(sizeof(AVOutputStream *) * nb_ostreams);
884
    if (!ost_table)
885
        goto fail;
886
    for(i=0;i<nb_ostreams;i++) {
887
        ost = av_mallocz(sizeof(AVOutputStream));
888
        if (!ost)
889
            goto fail;
890
        ost_table[i] = ost;
891
    }
892
    
893
    n = 0;
894
    for(k=0;k<nb_output_files;k++) {
895
        os = output_files[k];
896
        for(i=0;i<os->nb_streams;i++) {
897
            int found;
898
            ost = ost_table[n++];
899
            ost->file_index = k;
900
            ost->index = i;
901
            ost->st = os->streams[i];
902
            if (nb_stream_maps > 0) {
903
                ost->source_index = file_table[stream_maps[n-1].file_index].ist_index + 
904
                    stream_maps[n-1].stream_index;
905
            } else {
906
                /* get corresponding input stream index : we select the first one with the right type */
907
                found = 0;
908
                for(j=0;j<nb_istreams;j++) {
909
                    ist = ist_table[j];
910
                    if (ist->discard && 
911
                        ist->st->codec.codec_type == ost->st->codec.codec_type) {
912
                        ost->source_index = j;
913
                        found = 1;
914
                    }
915
                }
916
                
917
                if (!found) {
918
                    /* try again and reuse existing stream */
919
                    for(j=0;j<nb_istreams;j++) {
920
                        ist = ist_table[j];
921
                        if (ist->st->codec.codec_type == ost->st->codec.codec_type) {
922
                            ost->source_index = j;
923
                            found = 1;
924
                        }
925
                    }
926
                    if (!found) {
927
                        fprintf(stderr, "Could not find input stream matching output stream #%d.%d\n",
928
                                ost->file_index, ost->index);
929
                        exit(1);
930
                    }
931
                }
932
            }
933
            ist = ist_table[ost->source_index];
934
            ist->discard = 0;
935
        }
936
    }
937

    
938
    /* for each output stream, we compute the right encoding parameters */
939
    for(i=0;i<nb_ostreams;i++) {
940
        ost = ost_table[i];
941
        ist = ist_table[ost->source_index];
942

    
943
        codec = &ost->st->codec;
944
        icodec = &ist->st->codec;
945

    
946
        if (ost->st->stream_copy) {
947
            /* if stream_copy is selected, no need to decode or encode */
948
            codec->codec_id = icodec->codec_id;
949
            codec->codec_type = icodec->codec_type;
950
            codec->codec_tag = icodec->codec_tag;
951
            codec->bit_rate = icodec->bit_rate;
952
            switch(codec->codec_type) {
953
            case CODEC_TYPE_AUDIO:
954
                codec->sample_rate = icodec->sample_rate;
955
                codec->channels = icodec->channels;
956
                break;
957
            case CODEC_TYPE_VIDEO:
958
                codec->frame_rate = icodec->frame_rate;
959
                codec->width = icodec->width;
960
                codec->height = icodec->height;
961
                break;
962
            default:
963
                av_abort();
964
            }
965
        } else {
966
            switch(codec->codec_type) {
967
            case CODEC_TYPE_AUDIO:
968
                if (fifo_init(&ost->fifo, 2 * MAX_AUDIO_PACKET_SIZE))
969
                    goto fail;
970
                
971
                if (codec->channels == icodec->channels &&
972
                    codec->sample_rate == icodec->sample_rate) {
973
                    ost->audio_resample = 0;
974
                } else {
975
                    if (codec->channels != icodec->channels &&
976
                        icodec->codec_id == CODEC_ID_AC3) {
977
                        /* Special case for 5:1 AC3 input */
978
                        /* and mono or stereo output      */
979
                        /* Request specific number of channels */
980
                        icodec->channels = codec->channels;
981
                        if (codec->sample_rate == icodec->sample_rate)
982
                            ost->audio_resample = 0;
983
                        else {
984
                            ost->audio_resample = 1;
985
                            ost->resample = audio_resample_init(codec->channels, icodec->channels,
986
                                                        codec->sample_rate, 
987
                                                        icodec->sample_rate);
988
                        }
989
                        /* Request specific number of channels */
990
                        icodec->channels = codec->channels;
991
                    } else {
992
                        ost->audio_resample = 1; 
993
                        ost->resample = audio_resample_init(codec->channels, icodec->channels,
994
                                                        codec->sample_rate, 
995
                                                        icodec->sample_rate);
996
                    }
997
                }
998
                ist->decoding_needed = 1;
999
                ost->encoding_needed = 1;
1000
                break;
1001
            case CODEC_TYPE_VIDEO:
1002
                if (codec->width == icodec->width &&
1003
                    codec->height == icodec->height &&
1004
                    frame_topBand == 0 &&
1005
                    frame_bottomBand == 0 &&
1006
                    frame_leftBand == 0 &&
1007
                    frame_rightBand == 0)
1008
                {
1009
                    ost->video_resample = 0;
1010
                    ost->video_crop = 0;
1011
                } else if ((codec->width == icodec->width -
1012
                                (frame_leftBand + frame_rightBand)) &&
1013
                        (codec->height == icodec->height -
1014
                                (frame_topBand  + frame_bottomBand)))
1015
                {
1016
                    ost->video_resample = 0;
1017
                    ost->video_crop = 1;
1018
                    ost->topBand = frame_topBand;
1019
                    ost->leftBand = frame_leftBand;
1020
                } else {
1021
                    UINT8 *buf;
1022
                    ost->video_resample = 1;
1023
                    ost->video_crop = 0; // cropping is handled as part of resample
1024
                    buf = av_malloc((codec->width * codec->height * 3) / 2);
1025
                    if (!buf)
1026
                        goto fail;
1027
                    ost->pict_tmp.data[0] = buf;
1028
                    ost->pict_tmp.data[1] = ost->pict_tmp.data[0] + (codec->width * codec->height);
1029
                    ost->pict_tmp.data[2] = ost->pict_tmp.data[1] + (codec->width * codec->height) / 4;
1030
                    ost->pict_tmp.linesize[0] = codec->width;
1031
                    ost->pict_tmp.linesize[1] = codec->width / 2;
1032
                    ost->pict_tmp.linesize[2] = codec->width / 2;
1033

    
1034
                    ost->img_resample_ctx = img_resample_full_init( 
1035
                                      ost->st->codec.width, ost->st->codec.height,
1036
                                      ist->st->codec.width, ist->st->codec.height,
1037
                                      frame_topBand, frame_bottomBand,
1038
                                      frame_leftBand, frame_rightBand);
1039
                }
1040
                ost->encoding_needed = 1;
1041
                ist->decoding_needed = 1;
1042
                break;
1043
            default:
1044
                av_abort();
1045
            }
1046
            /* two pass mode */
1047
            if (ost->encoding_needed && 
1048
                (codec->flags & (CODEC_FLAG_PASS1 | CODEC_FLAG_PASS2))) {
1049
                char logfilename[1024];
1050
                FILE *f;
1051
                int size;
1052
                char *logbuffer;
1053
                
1054
                snprintf(logfilename, sizeof(logfilename), "%s-%d.log", 
1055
                         pass_logfilename ? 
1056
                         pass_logfilename : DEFAULT_PASS_LOGFILENAME, i);
1057
                if (codec->flags & CODEC_FLAG_PASS1) {
1058
                    f = fopen(logfilename, "w");
1059
                    if (!f) {
1060
                        perror(logfilename);
1061
                        exit(1);
1062
                    }
1063
                    ost->logfile = f;
1064
                } else {
1065
                    /* read the log file */
1066
                    f = fopen(logfilename, "r");
1067
                    if (!f) {
1068
                        perror(logfilename);
1069
                        exit(1);
1070
                    }
1071
                    fseek(f, 0, SEEK_END);
1072
                    size = ftell(f);
1073
                    fseek(f, 0, SEEK_SET);
1074
                    logbuffer = av_malloc(size + 1);
1075
                    if (!logbuffer) {
1076
                        fprintf(stderr, "Could not allocate log buffer\n");
1077
                        exit(1);
1078
                    }
1079
                    fread(logbuffer, 1, size, f);
1080
                    fclose(f);
1081
                    logbuffer[size] = '\0';
1082
                    codec->stats_in = logbuffer;
1083
                }
1084
            }
1085
        }
1086
    }
1087

    
1088
    /* dump the file output parameters - cannot be done before in case
1089
       of stream copy */
1090
    for(i=0;i<nb_output_files;i++) {
1091
        dump_format(output_files[i], i, output_files[i]->filename, 1);
1092
    }
1093

    
1094
    /* dump the stream mapping */
1095
    fprintf(stderr, "Stream mapping:\n");
1096
    for(i=0;i<nb_ostreams;i++) {
1097
        ost = ost_table[i];
1098
        fprintf(stderr, "  Stream #%d.%d -> #%d.%d\n",
1099
                ist_table[ost->source_index]->file_index,
1100
                ist_table[ost->source_index]->index,
1101
                ost->file_index, 
1102
                ost->index);
1103
    }
1104

    
1105
    /* open each encoder */
1106
    for(i=0;i<nb_ostreams;i++) {
1107
        ost = ost_table[i];
1108
        if (ost->encoding_needed) {
1109
            AVCodec *codec;
1110
            codec = avcodec_find_encoder(ost->st->codec.codec_id);
1111
            if (!codec) {
1112
                fprintf(stderr, "Unsupported codec for output stream #%d.%d\n", 
1113
                        ost->file_index, ost->index);
1114
                exit(1);
1115
            }
1116
            if (avcodec_open(&ost->st->codec, codec) < 0) {
1117
                fprintf(stderr, "Error while opening codec for stream #%d.%d - maybe incorrect parameters such as bit_rate, rate, width or height\n", 
1118
                        ost->file_index, ost->index);
1119
                exit(1);
1120
            }
1121
        }
1122
    }
1123

    
1124
    /* open each decoder */
1125
    for(i=0;i<nb_istreams;i++) {
1126
        ist = ist_table[i];
1127
        if (ist->decoding_needed) {
1128
            AVCodec *codec;
1129
            codec = avcodec_find_decoder(ist->st->codec.codec_id);
1130
            if (!codec) {
1131
                fprintf(stderr, "Unsupported codec (id=%d) for input stream #%d.%d\n", 
1132
                        ist->st->codec.codec_id, ist->file_index, ist->index);
1133
                exit(1);
1134
            }
1135
            if (avcodec_open(&ist->st->codec, codec) < 0) {
1136
                fprintf(stderr, "Error while opening codec for input stream #%d.%d\n", 
1137
                        ist->file_index, ist->index);
1138
                exit(1);
1139
            }
1140
            //if (ist->st->codec.codec_type == CODEC_TYPE_VIDEO)
1141
            //    ist->st->codec.flags |= CODEC_FLAG_REPEAT_FIELD;
1142
            ist->frame_decoded = 1;
1143
        }
1144
    }
1145

    
1146
    /* init pts */
1147
    for(i=0;i<nb_istreams;i++) {
1148
        ist = ist_table[i];
1149
    }
1150
    
1151
    /* compute buffer size max (should use a complete heuristic) */
1152
    for(i=0;i<nb_input_files;i++) {
1153
        file_table[i].buffer_size_max = 2048;
1154
    }
1155

    
1156
    /* open files and write file headers */
1157
    for(i=0;i<nb_output_files;i++) {
1158
        os = output_files[i];
1159
        if (av_write_header(os) < 0) {
1160
            fprintf(stderr, "Could not write header for output file #%d (incorrect codec paramters ?)\n", i);
1161
            ret = -EINVAL;
1162
            goto fail;
1163
        }
1164
    }
1165

    
1166
#ifndef CONFIG_WIN32
1167
    if (!do_play) {
1168
        fprintf(stderr, "Press [q] to stop encoding\n");
1169
    } else {
1170
        fprintf(stderr, "Press [q] to stop playing\n");
1171
    }
1172
#endif
1173
    term_init();
1174

    
1175
    stream_no_data = 0;
1176
    key = -1;
1177

    
1178
    for(;;) {
1179
        int file_index, ist_index;
1180
        AVPacket pkt;
1181
        UINT8 *ptr;
1182
        int len;
1183
        UINT8 *data_buf;
1184
        int data_size, got_picture;
1185
        AVPicture picture;
1186
        short samples[AVCODEC_MAX_AUDIO_FRAME_SIZE / 2];
1187
        void *buffer_to_free;
1188
        double pts_min;
1189
        
1190
    redo:
1191
        /* if 'q' pressed, exits */
1192
        if (key) {
1193
            /* read_key() returns 0 on EOF */
1194
            key = read_key();
1195
            if (key == 'q')
1196
                break;
1197
        }
1198

    
1199
        /* select the stream that we must read now by looking at the
1200
           smallest output pts */
1201
        file_index = -1;
1202
        pts_min = 1e10;
1203
        for(i=0;i<nb_ostreams;i++) {
1204
            double pts;
1205
            ost = ost_table[i];
1206
            os = output_files[ost->file_index];
1207
            ist = ist_table[ost->source_index];
1208
            pts = (double)ost->st->pts.val * os->pts_num / os->pts_den;
1209
            if (!file_table[ist->file_index].eof_reached && 
1210
                pts < pts_min) {
1211
                pts_min = pts;
1212
                file_index = ist->file_index;
1213
            }
1214
        }
1215
        /* if none, if is finished */
1216
        if (file_index < 0) {
1217
            break;
1218
        }
1219

    
1220
        /* finish if recording time exhausted */
1221
        if (recording_time > 0 && pts_min >= (recording_time / 1000000.0))
1222
            break;
1223

    
1224
        /* read a packet from it and output it in the fifo */
1225
        is = input_files[file_index];
1226
        if (av_read_packet(is, &pkt) < 0) {
1227
            file_table[file_index].eof_reached = 1;
1228
            continue;
1229
        }
1230
        if (!pkt.size) {
1231
            stream_no_data = is;
1232
        } else {
1233
            stream_no_data = 0;
1234
        }
1235
        if (do_hex_dump) {
1236
            printf("stream #%d, size=%d:\n", pkt.stream_index, pkt.size);
1237
            av_hex_dump(pkt.data, pkt.size);
1238
        }
1239
        /* the following test is needed in case new streams appear
1240
           dynamically in stream : we ignore them */
1241
        if (pkt.stream_index >= file_table[file_index].nb_streams)
1242
            goto discard_packet;
1243
        ist_index = file_table[file_index].ist_index + pkt.stream_index;
1244
        ist = ist_table[ist_index];
1245
        if (ist->discard)
1246
            goto discard_packet;
1247

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

    
1250
        len = pkt.size;
1251
        ptr = pkt.data;
1252
        pts_set = 0;
1253
        while (len > 0) {
1254
            INT64 ipts;
1255

    
1256
            ipts = AV_NOPTS_VALUE;
1257

    
1258
            /* decode the packet if needed */
1259
            data_buf = NULL; /* fail safe */
1260
            data_size = 0;
1261
            if (ist->decoding_needed) {
1262
                /* NOTE1: we only take into account the PTS if a new
1263
                   frame has begun (MPEG semantics) */
1264
                /* NOTE2: even if the fraction is not initialized,
1265
                   av_frac_set can be used to set the integer part */
1266
                if (ist->frame_decoded && 
1267
                    pkt.pts != AV_NOPTS_VALUE && 
1268
                    !pts_set) {
1269
                    ipts = pkt.pts;
1270
                    ist->frame_decoded = 0;
1271
                    pts_set = 1;
1272
                }
1273

    
1274
                switch(ist->st->codec.codec_type) {
1275
                case CODEC_TYPE_AUDIO:
1276
                    /* XXX: could avoid copy if PCM 16 bits with same
1277
                       endianness as CPU */
1278
                    ret = avcodec_decode_audio(&ist->st->codec, samples, &data_size,
1279
                                               ptr, len);
1280
                    if (ret < 0)
1281
                        goto fail_decode;
1282
                    /* Some bug in mpeg audio decoder gives */
1283
                    /* data_size < 0, it seems they are overflows */
1284
                    if (data_size <= 0) {
1285
                        /* no audio frame */
1286
                        ptr += ret;
1287
                        len -= ret;
1288
                        continue;
1289
                    }
1290
                    data_buf = (UINT8 *)samples;
1291
                    break;
1292
                case CODEC_TYPE_VIDEO:
1293
                    if (ist->st->codec.codec_id == CODEC_ID_RAWVIDEO) {
1294
                        int size;
1295

    
1296
                        size = (ist->st->codec.width * ist->st->codec.height);
1297
                        avpicture_fill(&picture, ptr, 
1298
                                     ist->st->codec.pix_fmt,
1299
                                     ist->st->codec.width,
1300
                                     ist->st->codec.height);
1301
                        ret = len;
1302
                    } else {
1303
                        AVFrame big_picture;
1304

    
1305
                        data_size = (ist->st->codec.width * ist->st->codec.height * 3) / 2;
1306
                        ret = avcodec_decode_video(&ist->st->codec, 
1307
                                                   &big_picture, &got_picture, ptr, len);
1308
                        picture= *(AVPicture*)&big_picture;
1309
                        ist->st->quality= big_picture.quality;
1310
                        if (ret < 0) {
1311
                        fail_decode:
1312
                            fprintf(stderr, "Error while decoding stream #%d.%d\n",
1313
                                    ist->file_index, ist->index);
1314
                            av_free_packet(&pkt);
1315
                            goto redo;
1316
                        }
1317
                        if (!got_picture) {
1318
                            /* no picture yet */
1319
                            ptr += ret;
1320
                            len -= ret;
1321
                            continue;
1322
                        }
1323
                                  
1324
                    }
1325
                    break;
1326
                default:
1327
                    goto fail_decode;
1328
                }
1329
            } else {
1330
                data_buf = ptr;
1331
                data_size = len;
1332
                ret = len;
1333
            }
1334
            ptr += ret;
1335
            len -= ret;
1336

    
1337
            buffer_to_free = 0;
1338
            if (ist->st->codec.codec_type == CODEC_TYPE_VIDEO) {
1339
                pre_process_video_frame(ist, &picture, &buffer_to_free);
1340
            }
1341

    
1342
            ist->frame_decoded = 1;
1343

    
1344
#if 0
1345
            /* mpeg PTS deordering : if it is a P or I frame, the PTS
1346
               is the one of the next displayed one */
1347
            /* XXX: add mpeg4 too ? */
1348
            if (ist->st->codec.codec_id == CODEC_ID_MPEG1VIDEO) {
1349
                if (ist->st->codec.pict_type != B_TYPE) {
1350
                    INT64 tmp;
1351
                    tmp = ist->last_ip_pts;
1352
                    ist->last_ip_pts  = ist->frac_pts.val;
1353
                    ist->frac_pts.val = tmp;
1354
                }
1355
            }
1356
#endif
1357
            /* transcode raw format, encode packets and output them */
1358

    
1359
            for(i=0;i<nb_ostreams;i++) {
1360
                int frame_size;
1361

    
1362
                ost = ost_table[i];
1363
                if (ost->source_index == ist_index) {
1364
                    os = output_files[ost->file_index];
1365

    
1366
                    if (ipts != AV_NOPTS_VALUE) {
1367
#if 0
1368
                        printf("%d: got pts=%f %f\n", 
1369
                               i, pkt.pts / 90000.0, 
1370
                               (ipts - ost->st->pts.val) / 90000.0);
1371
#endif
1372
                        /* set the input output pts pairs */
1373
                        ost->sync_ipts = (double)ipts * is->pts_num / 
1374
                            is->pts_den;
1375
                        /* XXX: take into account the various fifos,
1376
                           in particular for audio */
1377
                        ost->sync_opts = ost->st->pts.val;
1378
                        //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); 
1379
                    } else {
1380
                        //printf("pts.val=%lld\n", ost->st->pts.val); 
1381
                        ost->sync_ipts = AV_NOPTS_VALUE;
1382
                    }
1383

    
1384
                    if (ost->encoding_needed) {
1385
                        switch(ost->st->codec.codec_type) {
1386
                        case CODEC_TYPE_AUDIO:
1387
                            do_audio_out(os, ost, ist, data_buf, data_size);
1388
                            break;
1389
                        case CODEC_TYPE_VIDEO:
1390
                            /* find an audio stream for synchro */
1391
                            {
1392
                                int i;
1393
                                AVOutputStream *audio_sync, *ost1;
1394
                                audio_sync = NULL;
1395
                                for(i=0;i<nb_ostreams;i++) {
1396
                                    ost1 = ost_table[i];
1397
                                    if (ost1->file_index == ost->file_index &&
1398
                                        ost1->st->codec.codec_type == CODEC_TYPE_AUDIO) {
1399
                                        audio_sync = ost1;
1400
                                        break;
1401
                                    }
1402
                                }
1403

    
1404
                                do_video_out(os, ost, ist, &picture, &frame_size, audio_sync);
1405
                                if (do_vstats && frame_size)
1406
                                    do_video_stats(os, ost, frame_size);
1407
                            }
1408
                            break;
1409
                        default:
1410
                            av_abort();
1411
                        }
1412
                    } else {
1413
                        AVFrame avframe;
1414
                                                
1415
                        /* no reencoding needed : output the packet directly */
1416
                        /* force the input stream PTS */
1417
                        
1418
                        //XXX/FIXME set keyframe flag from demuxer (or optionally from decoder)
1419
                        memset(&avframe, 0, sizeof(AVFrame));
1420
                        ost->st->codec.coded_frame= &avframe;
1421
                        
1422
                        av_write_frame(os, ost->index, data_buf, data_size);
1423
                        ost->st->codec.frame_number++;
1424
                        ost->frame_number++;
1425
                    }
1426
                }
1427
            }
1428
            av_free(buffer_to_free);
1429
            ipts = AV_NOPTS_VALUE;
1430
        }
1431
    discard_packet:
1432
        av_free_packet(&pkt);
1433
        
1434
        /* dump report by using the output first video and audio streams */
1435
        print_report(output_files, ost_table, nb_ostreams, 0);
1436
    }
1437
    term_exit();
1438

    
1439
    /* dump report by using the first video and audio streams */
1440
    print_report(output_files, ost_table, nb_ostreams, 1);
1441

    
1442
    /* close each encoder */
1443
    for(i=0;i<nb_ostreams;i++) {
1444
        ost = ost_table[i];
1445
        if (ost->encoding_needed) {
1446
            av_freep(&ost->st->codec.stats_in);
1447
            avcodec_close(&ost->st->codec);
1448
        }
1449
    }
1450
    
1451
    /* close each decoder */
1452
    for(i=0;i<nb_istreams;i++) {
1453
        ist = ist_table[i];
1454
        if (ist->decoding_needed) {
1455
            avcodec_close(&ist->st->codec);
1456
        }
1457
    }
1458
    
1459

    
1460
    /* write the trailer if needed and close file */
1461
    for(i=0;i<nb_output_files;i++) {
1462
        os = output_files[i];
1463
        av_write_trailer(os);
1464
    }
1465
    /* finished ! */
1466
    
1467
    ret = 0;
1468
 fail1:
1469
    av_free(file_table);
1470

    
1471
    if (ist_table) {
1472
        for(i=0;i<nb_istreams;i++) {
1473
            ist = ist_table[i];
1474
            av_free(ist);
1475
        }
1476
        av_free(ist_table);
1477
    }
1478
    if (ost_table) {
1479
        for(i=0;i<nb_ostreams;i++) {
1480
            ost = ost_table[i];
1481
            if (ost) {
1482
                if (ost->logfile) {
1483
                    fclose(ost->logfile);
1484
                    ost->logfile = NULL;
1485
                }
1486
                fifo_free(&ost->fifo); /* works even if fifo is not
1487
                                          initialized but set to zero */
1488
                av_free(ost->pict_tmp.data[0]);
1489
                if (ost->video_resample)
1490
                    img_resample_close(ost->img_resample_ctx);
1491
                if (ost->audio_resample)
1492
                    audio_resample_close(ost->resample);
1493
                av_free(ost);
1494
            }
1495
        }
1496
        av_free(ost_table);
1497
    }
1498
    return ret;
1499
 fail:
1500
    ret = -ENOMEM;
1501
    goto fail1;
1502
}
1503

    
1504
#if 0
1505
int file_read(const char *filename)
1506
{
1507
    URLContext *h;
1508
    unsigned char buffer[1024];
1509
    int len, i;
1510

1511
    if (url_open(&h, filename, O_RDONLY) < 0) {
1512
        printf("could not open '%s'\n", filename);
1513
        return -1;
1514
    }
1515
    for(;;) {
1516
        len = url_read(h, buffer, sizeof(buffer));
1517
        if (len <= 0)
1518
            break;
1519
        for(i=0;i<len;i++) putchar(buffer[i]);
1520
    }
1521
    url_close(h);
1522
    return 0;
1523
}
1524
#endif
1525

    
1526
void show_licence(void)
1527
{
1528
    printf(
1529
    "ffmpeg version " FFMPEG_VERSION "\n"
1530
    "Copyright (c) 2000, 2001, 2002 Fabrice Bellard\n"
1531
    "This library is free software; you can redistribute it and/or\n"
1532
    "modify it under the terms of the GNU Lesser General Public\n"
1533
    "License as published by the Free Software Foundation; either\n"
1534
    "version 2 of the License, or (at your option) any later version.\n"
1535
    "\n"
1536
    "This library is distributed in the hope that it will be useful,\n"
1537
    "but WITHOUT ANY WARRANTY; without even the implied warranty of\n"
1538
    "MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n"
1539
    "Lesser General Public License for more details.\n"
1540
    "\n"
1541
    "You should have received a copy of the GNU Lesser General Public\n"
1542
    "License along with this library; if not, write to the Free Software\n"
1543
    "Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA\n"
1544
    );
1545
    exit(1);
1546
}
1547

    
1548
void opt_image_format(const char *arg)
1549
{
1550
    AVImageFormat *f;
1551
    
1552
    for(f = first_image_format; f != NULL; f = f->next) {
1553
        if (!strcmp(arg, f->name))
1554
            break;
1555
    }
1556
    if (!f) {
1557
        fprintf(stderr, "Unknown image format: '%s'\n", arg);
1558
        exit(1);
1559
    }
1560
    image_format = f;
1561
}
1562

    
1563
void opt_format(const char *arg)
1564
{
1565
    /* compatibility stuff for pgmyuv */
1566
    if (!strcmp(arg, "pgmyuv")) {
1567
        opt_image_format(arg);
1568
        arg = "image";
1569
    }
1570

    
1571
    file_iformat = av_find_input_format(arg);
1572
    file_oformat = guess_format(arg, NULL, NULL);
1573
    if (!file_iformat && !file_oformat) {
1574
        fprintf(stderr, "Unknown input or output format: %s\n", arg);
1575
        exit(1);
1576
    }
1577
}
1578

    
1579
void opt_video_bitrate(const char *arg)
1580
{
1581
    video_bit_rate = atoi(arg) * 1000;
1582
}
1583

    
1584
void opt_video_bitrate_tolerance(const char *arg)
1585
{
1586
    video_bit_rate_tolerance = atoi(arg) * 1000;
1587
}
1588

    
1589
void opt_video_bitrate_max(const char *arg)
1590
{
1591
    video_rc_max_rate = atoi(arg) * 1000;
1592
}
1593

    
1594
void opt_video_bitrate_min(const char *arg)
1595
{
1596
    video_rc_min_rate = atoi(arg) * 1000;
1597
}
1598

    
1599
void opt_video_buffer_size(const char *arg)
1600
{
1601
    video_rc_buffer_size = atoi(arg) * 1000;
1602
}
1603

    
1604
void opt_video_rc_eq(char *arg)
1605
{
1606
    video_rc_eq = arg;
1607
}
1608

    
1609
void opt_video_rc_override_string(char *arg)
1610
{
1611
    video_rc_override_string = arg;
1612
}
1613

    
1614

    
1615
void opt_workaround_bugs(const char *arg)
1616
{
1617
    workaround_bugs = atoi(arg);
1618
}
1619

    
1620
void opt_dct_algo(const char *arg)
1621
{
1622
    dct_algo = atoi(arg);
1623
}
1624

    
1625
void opt_idct_algo(const char *arg)
1626
{
1627
    idct_algo = atoi(arg);
1628
}
1629

    
1630

    
1631
void opt_error_resilience(const char *arg)
1632
{
1633
    error_resilience = atoi(arg);
1634
}
1635

    
1636
void opt_error_concealment(const char *arg)
1637
{
1638
    error_concealment = atoi(arg);
1639
}
1640

    
1641
void opt_debug(const char *arg)
1642
{
1643
    debug = atoi(arg);
1644
}
1645

    
1646
void opt_frame_rate(const char *arg)
1647
{
1648
    frame_rate = (int)(strtod(arg, 0) * FRAME_RATE_BASE);
1649
}
1650

    
1651

    
1652
void opt_frame_crop_top(const char *arg)
1653
{
1654
    frame_topBand = atoi(arg); 
1655
    if (frame_topBand < 0) {
1656
        fprintf(stderr, "Incorrect top crop size\n");
1657
        exit(1);
1658
    }
1659
    if ((frame_topBand % 2) != 0) {
1660
        fprintf(stderr, "Top crop size must be a multiple of 2\n");
1661
        exit(1);
1662
    }
1663
    if ((frame_topBand) >= frame_height){
1664
            fprintf(stderr, "Vertical crop dimensions are outside the range of the original image.\nRemember to crop first and scale second.\n");
1665
        exit(1);
1666
    }
1667
    frame_height -= frame_topBand;
1668
}
1669

    
1670
void opt_frame_crop_bottom(const char *arg)
1671
{
1672
    frame_bottomBand = atoi(arg);
1673
    if (frame_bottomBand < 0) {
1674
        fprintf(stderr, "Incorrect bottom crop size\n");
1675
        exit(1);
1676
    }
1677
    if ((frame_bottomBand % 2) != 0) {
1678
        fprintf(stderr, "Bottom crop size must be a multiple of 2\n");
1679
        exit(1);        
1680
    }
1681
    if ((frame_bottomBand) >= frame_height){
1682
            fprintf(stderr, "Vertical crop dimensions are outside the range of the original image.\nRemember to crop first and scale second.\n");
1683
        exit(1);
1684
    }
1685
    frame_height -= frame_bottomBand;
1686
}
1687

    
1688
void opt_frame_crop_left(const char *arg)
1689
{
1690
    frame_leftBand = atoi(arg);
1691
    if (frame_leftBand < 0) {
1692
        fprintf(stderr, "Incorrect left crop size\n");
1693
        exit(1);
1694
    }
1695
    if ((frame_leftBand % 2) != 0) {
1696
        fprintf(stderr, "Left crop size must be a multiple of 2\n");
1697
        exit(1);
1698
    }
1699
    if ((frame_leftBand) >= frame_width){
1700
            fprintf(stderr, "Horizontal crop dimensions are outside the range of the original image.\nRemember to crop first and scale second.\n");
1701
        exit(1);
1702
    }
1703
    frame_width -= frame_leftBand;
1704
}
1705

    
1706
void opt_frame_crop_right(const char *arg)
1707
{
1708
    frame_rightBand = atoi(arg);
1709
    if (frame_rightBand < 0) {
1710
        fprintf(stderr, "Incorrect right crop size\n");
1711
        exit(1);
1712
    }
1713
    if ((frame_rightBand % 2) != 0) {
1714
        fprintf(stderr, "Right crop size must be a multiple of 2\n");
1715
        exit(1);        
1716
    }
1717
    if ((frame_rightBand) >= frame_width){
1718
            fprintf(stderr, "Horizontal crop dimensions are outside the range of the original image.\nRemember to crop first and scale second.\n");
1719
        exit(1);
1720
    }
1721
    frame_width -= frame_rightBand;
1722
}
1723

    
1724
void opt_frame_size(const char *arg)
1725
{
1726
    parse_image_size(&frame_width, &frame_height, arg);
1727
    if (frame_width <= 0 || frame_height <= 0) {
1728
        fprintf(stderr, "Incorrect frame size\n");
1729
        exit(1);
1730
    }
1731
    if ((frame_width % 2) != 0 || (frame_height % 2) != 0) {
1732
        fprintf(stderr, "Frame size must be a multiple of 2\n");
1733
        exit(1);
1734
    }
1735
}
1736

    
1737
void opt_gop_size(const char *arg)
1738
{
1739
    gop_size = atoi(arg);
1740
}
1741

    
1742
void opt_b_frames(const char *arg)
1743
{
1744
    b_frames = atoi(arg);
1745
    if (b_frames > FF_MAX_B_FRAMES) {
1746
        fprintf(stderr, "\nCannot have more than %d B frames, increase FF_MAX_B_FRAMES.\n", FF_MAX_B_FRAMES);
1747
        exit(1);
1748
    } else if (b_frames < 1) {
1749
        fprintf(stderr, "\nNumber of B frames must be higher than 0\n");
1750
        exit(1);
1751
    }
1752
}
1753

    
1754
void opt_qscale(const char *arg)
1755
{
1756
    video_qscale = atoi(arg);
1757
    if (video_qscale < 0 ||
1758
        video_qscale > 31) {
1759
        fprintf(stderr, "qscale must be >= 1 and <= 31\n");
1760
        exit(1);
1761
    }
1762
}
1763

    
1764
void opt_qmin(const char *arg)
1765
{
1766
    video_qmin = atoi(arg);
1767
    if (video_qmin < 0 ||
1768
        video_qmin > 31) {
1769
        fprintf(stderr, "qmin must be >= 1 and <= 31\n");
1770
        exit(1);
1771
    }
1772
}
1773

    
1774
void opt_qmax(const char *arg)
1775
{
1776
    video_qmax = atoi(arg);
1777
    if (video_qmax < 0 ||
1778
        video_qmax > 31) {
1779
        fprintf(stderr, "qmax must be >= 1 and <= 31\n");
1780
        exit(1);
1781
    }
1782
}
1783

    
1784
void opt_mb_qmin(const char *arg)
1785
{
1786
    video_mb_qmin = atoi(arg);
1787
    if (video_mb_qmin < 0 ||
1788
        video_mb_qmin > 31) {
1789
        fprintf(stderr, "qmin must be >= 1 and <= 31\n");
1790
        exit(1);
1791
    }
1792
}
1793

    
1794
void opt_mb_qmax(const char *arg)
1795
{
1796
    video_mb_qmax = atoi(arg);
1797
    if (video_mb_qmax < 0 ||
1798
        video_mb_qmax > 31) {
1799
        fprintf(stderr, "qmax must be >= 1 and <= 31\n");
1800
        exit(1);
1801
    }
1802
}
1803

    
1804
void opt_qdiff(const char *arg)
1805
{
1806
    video_qdiff = atoi(arg);
1807
    if (video_qdiff < 0 ||
1808
        video_qdiff > 31) {
1809
        fprintf(stderr, "qdiff must be >= 1 and <= 31\n");
1810
        exit(1);
1811
    }
1812
}
1813

    
1814
void opt_qblur(const char *arg)
1815
{
1816
    video_qblur = atof(arg);
1817
}
1818

    
1819
void opt_qcomp(const char *arg)
1820
{
1821
    video_qcomp = atof(arg);
1822
}
1823

    
1824
void opt_rc_initial_cplx(const char *arg)
1825
{
1826
    video_rc_initial_cplx = atof(arg);
1827
}
1828
void opt_b_qfactor(const char *arg)
1829
{
1830
    video_b_qfactor = atof(arg);
1831
}
1832
void opt_i_qfactor(const char *arg)
1833
{
1834
    video_i_qfactor = atof(arg);
1835
}
1836
void opt_b_qoffset(const char *arg)
1837
{
1838
    video_b_qoffset = atof(arg);
1839
}
1840
void opt_i_qoffset(const char *arg)
1841
{
1842
    video_i_qoffset = atof(arg);
1843
}
1844

    
1845
void opt_packet_size(const char *arg)
1846
{
1847
    packet_size= atoi(arg);
1848
}
1849

    
1850
void opt_strict(const char *arg)
1851
{
1852
    strict= atoi(arg);
1853
}
1854

    
1855
void opt_audio_bitrate(const char *arg)
1856
{
1857
    audio_bit_rate = atoi(arg) * 1000;
1858
}
1859

    
1860
void opt_audio_rate(const char *arg)
1861
{
1862
    audio_sample_rate = atoi(arg);
1863
}
1864

    
1865
void opt_audio_channels(const char *arg)
1866
{
1867
    audio_channels = atoi(arg);
1868
}
1869

    
1870
void opt_video_device(const char *arg)
1871
{
1872
    video_device = strdup(arg);
1873
}
1874

    
1875
void opt_audio_device(const char *arg)
1876
{
1877
    audio_device = strdup(arg);
1878
}
1879

    
1880
void opt_dv1394(const char *arg)
1881
{
1882
    video_grab_format = "dv1394";
1883
    audio_grab_format = "none";
1884
}
1885

    
1886
void opt_audio_codec(const char *arg)
1887
{
1888
    AVCodec *p;
1889

    
1890
    if (!strcmp(arg, "copy")) {
1891
        audio_stream_copy = 1;
1892
    } else {
1893
        p = first_avcodec;
1894
        while (p) {
1895
            if (!strcmp(p->name, arg) && p->type == CODEC_TYPE_AUDIO)
1896
                break;
1897
            p = p->next;
1898
        }
1899
        if (p == NULL) {
1900
            fprintf(stderr, "Unknown audio codec '%s'\n", arg);
1901
            exit(1);
1902
        } else {
1903
            audio_codec_id = p->id;
1904
        }
1905
    }
1906
}
1907

    
1908
void add_frame_hooker(const char *arg)
1909
{
1910
    int argc = 0;
1911
    char *argv[64];
1912
    int i;
1913
    char *args = strdup(arg);
1914

    
1915
    argv[0] = strtok(args, " ");
1916
    while (argc < 62 && (argv[++argc] = strtok(NULL, " "))) {
1917
    }
1918

    
1919
    i = frame_hook_add(argc, argv);
1920

    
1921
    if (i != 0) {
1922
        fprintf(stderr, "Failed to add video hook function: %s\n", arg);
1923
        exit(1);
1924
    }
1925
}
1926

    
1927
const char *motion_str[] = {
1928
    "zero",
1929
    "full",
1930
    "log",
1931
    "phods",
1932
    "epzs",
1933
    "x1",
1934
    NULL,
1935
};
1936

    
1937
void opt_motion_estimation(const char *arg)
1938
{
1939
    const char **p;
1940
    p = motion_str;
1941
    for(;;) {
1942
        if (!*p) {
1943
            fprintf(stderr, "Unknown motion estimation method '%s'\n", arg);
1944
            exit(1);
1945
        }
1946
        if (!strcmp(*p, arg))
1947
            break;
1948
        p++;
1949
    }
1950
    me_method = (p - motion_str) + 1;
1951
}
1952

    
1953
void opt_video_codec(const char *arg)
1954
{
1955
    AVCodec *p;
1956

    
1957
    if (!strcmp(arg, "copy")) {
1958
        video_stream_copy = 1;
1959
    } else {
1960
        p = first_avcodec;
1961
        while (p) {
1962
            if (!strcmp(p->name, arg) && p->type == CODEC_TYPE_VIDEO)
1963
                break;
1964
            p = p->next;
1965
        }
1966
        if (p == NULL) {
1967
            fprintf(stderr, "Unknown video codec '%s'\n", arg);
1968
            exit(1);
1969
        } else {
1970
            video_codec_id = p->id;
1971
        }
1972
    }
1973
}
1974

    
1975
void opt_map(const char *arg)
1976
{
1977
    AVStreamMap *m;
1978
    const char *p;
1979

    
1980
    p = arg;
1981
    m = &stream_maps[nb_stream_maps++];
1982

    
1983
    m->file_index = strtol(arg, (char **)&p, 0);
1984
    if (*p)
1985
        p++;
1986

    
1987
    m->stream_index = strtol(p, (char **)&p, 0);
1988
}
1989

    
1990
void opt_recording_time(const char *arg)
1991
{
1992
    recording_time = parse_date(arg, 1);
1993
}
1994

    
1995
void print_error(const char *filename, int err)
1996
{
1997
    switch(err) {
1998
    case AVERROR_NUMEXPECTED:
1999
        fprintf(stderr, "%s: Incorrect image filename syntax.\n"
2000
                "Use '%%d' to specify the image number:\n"
2001
                "  for img1.jpg, img2.jpg, ..., use 'img%%d.jpg';\n"
2002
                "  for img001.jpg, img002.jpg, ..., use 'img%%03d.jpg'.\n", 
2003
                filename);
2004
        break;
2005
    case AVERROR_INVALIDDATA:
2006
        fprintf(stderr, "%s: Error while parsing header\n", filename);
2007
        break;
2008
    case AVERROR_NOFMT:
2009
        fprintf(stderr, "%s: Unknown format\n", filename);
2010
        break;
2011
    default:
2012
        fprintf(stderr, "%s: Error while opening file\n", filename);
2013
        break;
2014
    }
2015
}
2016

    
2017
void opt_input_file(const char *filename)
2018
{
2019
    AVFormatContext *ic;
2020
    AVFormatParameters params, *ap = &params;
2021
    int err, i, ret, rfps;
2022

    
2023
    if (!strcmp(filename, "-"))
2024
        filename = "pipe:";
2025

    
2026
    /* get default parameters from command line */
2027
    memset(ap, 0, sizeof(*ap));
2028
    ap->sample_rate = audio_sample_rate;
2029
    ap->channels = audio_channels;
2030
    ap->frame_rate = frame_rate;
2031
    ap->width = frame_width;
2032
    ap->height = frame_height;
2033
    ap->image_format = image_format;
2034

    
2035
    /* open the input file with generic libav function */
2036
    err = av_open_input_file(&ic, filename, file_iformat, 0, ap);
2037
    if (err < 0) {
2038
        print_error(filename, err);
2039
        exit(1);
2040
    }
2041
    
2042
    /* If not enough info to get the stream parameters, we decode the
2043
       first frames to get it. (used in mpeg case for example) */
2044
    ret = av_find_stream_info(ic);
2045
    if (ret < 0) {
2046
        fprintf(stderr, "%s: could not find codec parameters\n", filename);
2047
        exit(1);
2048
    }
2049

    
2050
    /* update the current parameters so that they match the one of the input stream */
2051
    for(i=0;i<ic->nb_streams;i++) {
2052
        AVCodecContext *enc = &ic->streams[i]->codec;
2053
        switch(enc->codec_type) {
2054
        case CODEC_TYPE_AUDIO:
2055
            //fprintf(stderr, "\nInput Audio channels: %d", enc->channels);
2056
            audio_channels = enc->channels;
2057
            audio_sample_rate = enc->sample_rate;
2058
            break;
2059
        case CODEC_TYPE_VIDEO:
2060
            frame_height = enc->height;
2061
            frame_width = enc->width;
2062
            rfps = ic->streams[i]->r_frame_rate;
2063
            enc->workaround_bugs = workaround_bugs;
2064
            enc->error_resilience = error_resilience; 
2065
            enc->error_concealment = error_concealment; 
2066
            enc->idct_algo= idct_algo;
2067
            enc->debug= debug;
2068
/*            if(enc->codec->capabilities & CODEC_CAP_TRUNCATED)
2069
                enc->flags|= CODEC_FLAG_TRUNCATED; */
2070
            if(/*enc->codec_id==CODEC_ID_MPEG4 || */enc->codec_id==CODEC_ID_MPEG1VIDEO)
2071
                enc->flags|= CODEC_FLAG_TRUNCATED;
2072

    
2073
            if (enc->frame_rate != rfps) {
2074
                fprintf(stderr,"\nSeems that stream %d comes from film source: %2.2f->%2.2f\n",
2075
                    i, (float)enc->frame_rate / FRAME_RATE_BASE,
2076
                    (float)rfps / FRAME_RATE_BASE);
2077
            }
2078
            /* update the current frame rate to match the stream frame rate */
2079
            frame_rate = rfps;
2080
            break;
2081
        default:
2082
            av_abort();
2083
        }
2084
    }
2085
    
2086
    input_files[nb_input_files] = ic;
2087
    /* dump the file content */
2088
    dump_format(ic, nb_input_files, filename, 0);
2089
    nb_input_files++;
2090
    file_iformat = NULL;
2091
    file_oformat = NULL;
2092
    image_format = NULL;
2093
}
2094

    
2095
void check_audio_video_inputs(int *has_video_ptr, int *has_audio_ptr)
2096
{
2097
    int has_video, has_audio, i, j;
2098
    AVFormatContext *ic;
2099

    
2100
    has_video = 0;
2101
    has_audio = 0;
2102
    for(j=0;j<nb_input_files;j++) {
2103
        ic = input_files[j];
2104
        for(i=0;i<ic->nb_streams;i++) {
2105
            AVCodecContext *enc = &ic->streams[i]->codec;
2106
            switch(enc->codec_type) {
2107
            case CODEC_TYPE_AUDIO:
2108
                has_audio = 1;
2109
                break;
2110
            case CODEC_TYPE_VIDEO:
2111
                has_video = 1;
2112
                break;
2113
            default:
2114
                av_abort();
2115
            }
2116
        }
2117
    }
2118
    *has_video_ptr = has_video;
2119
    *has_audio_ptr = has_audio;
2120
}
2121

    
2122
void opt_output_file(const char *filename)
2123
{
2124
    AVStream *st;
2125
    AVFormatContext *oc;
2126
    int use_video, use_audio, nb_streams, input_has_video, input_has_audio;
2127
    int codec_id;
2128
    AVFormatParameters params, *ap = &params;
2129

    
2130
    if (!strcmp(filename, "-"))
2131
        filename = "pipe:";
2132

    
2133
    oc = av_mallocz(sizeof(AVFormatContext));
2134

    
2135
    if (!file_oformat) {
2136
        file_oformat = guess_format(NULL, filename, NULL);
2137
        if (!file_oformat) {
2138
            fprintf(stderr, "Unable for find a suitable output format for '%s'\n",
2139
                    filename);
2140
            exit(1);
2141
        }
2142
    }
2143
    
2144
    oc->oformat = file_oformat;
2145

    
2146
    if (!strcmp(file_oformat->name, "ffm") && 
2147
        strstart(filename, "http:", NULL)) {
2148
        /* special case for files sent to ffserver: we get the stream
2149
           parameters from ffserver */
2150
        if (read_ffserver_streams(oc, filename) < 0) {
2151
            fprintf(stderr, "Could not read stream parameters from '%s'\n", filename);
2152
            exit(1);
2153
        }
2154
    } else {
2155
        use_video = file_oformat->video_codec != CODEC_ID_NONE;
2156
        use_audio = file_oformat->audio_codec != CODEC_ID_NONE;
2157

    
2158
        /* disable if no corresponding type found and at least one
2159
           input file */
2160
        if (nb_input_files > 0) {
2161
            check_audio_video_inputs(&input_has_video, &input_has_audio);
2162
            if (!input_has_video)
2163
                use_video = 0;
2164
            if (!input_has_audio)
2165
                use_audio = 0;
2166
        }
2167

    
2168
        /* manual disable */
2169
        if (audio_disable) {
2170
            use_audio = 0;
2171
        }
2172
        if (video_disable) {
2173
            use_video = 0;
2174
        }
2175
        
2176
        nb_streams = 0;
2177
        if (use_video) {
2178
            AVCodecContext *video_enc;
2179
            
2180
            st = av_mallocz(sizeof(AVStream));
2181
            if (!st) {
2182
                fprintf(stderr, "Could not alloc stream\n");
2183
                exit(1);
2184
            }
2185
            avcodec_get_context_defaults(&st->codec);
2186

    
2187
            video_enc = &st->codec;
2188
            if (video_stream_copy) {
2189
                st->stream_copy = 1;
2190
                video_enc->codec_type = CODEC_TYPE_VIDEO;
2191
            } else {
2192
                char *p;
2193
                int i;
2194
            
2195
                codec_id = file_oformat->video_codec;
2196
                if (video_codec_id != CODEC_ID_NONE)
2197
                    codec_id = video_codec_id;
2198
                
2199
                video_enc->codec_id = codec_id;
2200
                
2201
                video_enc->bit_rate = video_bit_rate;
2202
                video_enc->bit_rate_tolerance = video_bit_rate_tolerance;
2203
                video_enc->frame_rate = frame_rate; 
2204
                
2205
                video_enc->width = frame_width;
2206
                video_enc->height = frame_height;
2207

    
2208
                if (!intra_only)
2209
                    video_enc->gop_size = gop_size;
2210
                else
2211
                    video_enc->gop_size = 0;
2212
                if (video_qscale || same_quality) {
2213
                    video_enc->flags |= CODEC_FLAG_QSCALE;
2214
                    st->quality = video_qscale;
2215
                }
2216
            
2217
                if (use_hq) {
2218
                    video_enc->flags |= CODEC_FLAG_HQ;
2219
                }
2220
            
2221
                if (use_4mv) {
2222
                    video_enc->flags |= CODEC_FLAG_HQ;
2223
                    video_enc->flags |= CODEC_FLAG_4MV;
2224
                }
2225
            
2226
                if(use_part)
2227
                    video_enc->flags |= CODEC_FLAG_PART;
2228
               
2229
            
2230
                if (b_frames) {
2231
                    if (codec_id != CODEC_ID_MPEG4) {
2232
                        fprintf(stderr, "\nB frames encoding only supported by MPEG-4.\n");
2233
                        exit(1);
2234
                    }
2235
                    video_enc->max_b_frames = b_frames;
2236
                    video_enc->b_frame_strategy = 0;
2237
                    video_enc->b_quant_factor = 2.0;
2238
                }
2239
            
2240
                video_enc->qmin = video_qmin;
2241
                video_enc->qmax = video_qmax;
2242
                video_enc->mb_qmin = video_mb_qmin;
2243
                video_enc->mb_qmax = video_mb_qmax;
2244
                video_enc->max_qdiff = video_qdiff;
2245
                video_enc->qblur = video_qblur;
2246
                video_enc->qcompress = video_qcomp;
2247
                video_enc->rc_eq = video_rc_eq;
2248
                video_enc->debug= debug;
2249
                
2250
                p= video_rc_override_string;
2251
                for(i=0; p; i++){
2252
                    int start, end, q;
2253
                    int e=sscanf(p, "%d,%d,%d", &start, &end, &q);
2254
                    if(e!=3){
2255
                        fprintf(stderr, "error parsing rc_override\n");
2256
                        exit(1);
2257
                    }
2258
                    video_enc->rc_override= 
2259
                        realloc(video_enc->rc_override, sizeof(RcOverride)*(i+1));
2260
                    video_enc->rc_override[i].start_frame= start;
2261
                    video_enc->rc_override[i].end_frame  = end;
2262
                    if(q>0){
2263
                        video_enc->rc_override[i].qscale= q;
2264
                        video_enc->rc_override[i].quality_factor= 1.0;
2265
                    }
2266
                    else{
2267
                        video_enc->rc_override[i].qscale= 0;
2268
                        video_enc->rc_override[i].quality_factor= -q/100.0;
2269
                    }
2270
                    p= strchr(p, '/');
2271
                    if(p) p++;
2272
                }
2273
                video_enc->rc_override_count=i;
2274

    
2275
                video_enc->rc_max_rate = video_rc_max_rate;
2276
                video_enc->rc_min_rate = video_rc_min_rate;
2277
                video_enc->rc_buffer_size = video_rc_buffer_size;
2278
                video_enc->rc_buffer_aggressivity= video_rc_buffer_aggressivity;
2279
                video_enc->rc_initial_cplx= video_rc_initial_cplx;
2280
                video_enc->i_quant_factor = video_i_qfactor;
2281
                video_enc->b_quant_factor = video_b_qfactor;
2282
                video_enc->i_quant_offset = video_i_qoffset;
2283
                video_enc->b_quant_offset = video_b_qoffset;
2284
                video_enc->dct_algo = dct_algo;
2285
                video_enc->idct_algo = idct_algo;
2286
                video_enc->strict_std_compliance = strict;
2287
                if(packet_size){
2288
                    video_enc->rtp_mode= 1;
2289
                    video_enc->rtp_payload_size= packet_size;
2290
                }
2291
            
2292
                if (do_psnr)
2293
                    video_enc->flags|= CODEC_FLAG_PSNR;
2294
            
2295
                video_enc->me_method = me_method;
2296

    
2297
                /* two pass mode */
2298
                if (do_pass) {
2299
                    if (do_pass == 1) {
2300
                        video_enc->flags |= CODEC_FLAG_PASS1;
2301
                    } else {
2302
                        video_enc->flags |= CODEC_FLAG_PASS2;
2303
                    }
2304
                }
2305
            }
2306
            oc->streams[nb_streams] = st;
2307
            nb_streams++;
2308
        }
2309
    
2310
        if (use_audio) {
2311
            AVCodecContext *audio_enc;
2312

    
2313
            st = av_mallocz(sizeof(AVStream));
2314
            if (!st) {
2315
                fprintf(stderr, "Could not alloc stream\n");
2316
                exit(1);
2317
            }
2318
            avcodec_get_context_defaults(&st->codec);
2319

    
2320
            audio_enc = &st->codec;
2321
            audio_enc->codec_type = CODEC_TYPE_AUDIO;
2322
            if (audio_stream_copy) {
2323
                st->stream_copy = 1;
2324
            } else {
2325
                codec_id = file_oformat->audio_codec;
2326
                if (audio_codec_id != CODEC_ID_NONE)
2327
                    codec_id = audio_codec_id;
2328
                audio_enc->codec_id = codec_id;
2329
                
2330
                audio_enc->bit_rate = audio_bit_rate;
2331
                audio_enc->sample_rate = audio_sample_rate;
2332
                /* For audio codecs other than AC3 we limit */
2333
                /* the number of coded channels to stereo   */
2334
                if (audio_channels > 2 && codec_id != CODEC_ID_AC3) {
2335
                    audio_enc->channels = 2;
2336
                } else
2337
                    audio_enc->channels = audio_channels;
2338
            }
2339
            oc->streams[nb_streams] = st;
2340
            nb_streams++;
2341
        }
2342

    
2343
        oc->nb_streams = nb_streams;
2344

    
2345
        if (!nb_streams) {
2346
            fprintf(stderr, "No audio or video streams available\n");
2347
            exit(1);
2348
        }
2349

    
2350
        if (str_title)
2351
            pstrcpy(oc->title, sizeof(oc->title), str_title);
2352
        if (str_author)
2353
            pstrcpy(oc->author, sizeof(oc->author), str_author);
2354
        if (str_copyright)
2355
            pstrcpy(oc->copyright, sizeof(oc->copyright), str_copyright);
2356
        if (str_comment)
2357
            pstrcpy(oc->comment, sizeof(oc->comment), str_comment);
2358
    }
2359

    
2360
    output_files[nb_output_files++] = oc;
2361

    
2362
    strcpy(oc->filename, filename);
2363

    
2364
    /* check filename in case of an image number is expected */
2365
    if (oc->oformat->flags & AVFMT_NEEDNUMBER) {
2366
        if (filename_number_test(oc->filename) < 0) {
2367
            print_error(oc->filename, AVERROR_NUMEXPECTED);
2368
            exit(1);
2369
        }
2370
    }
2371

    
2372
    if (!(oc->oformat->flags & AVFMT_NOFILE)) {
2373
        /* test if it already exists to avoid loosing precious files */
2374
        if (!file_overwrite && 
2375
            (strchr(filename, ':') == NULL ||
2376
             strstart(filename, "file:", NULL))) {
2377
            if (url_exist(filename)) {
2378
                int c;
2379
                
2380
                printf("File '%s' already exists. Overwrite ? [y/N] ", filename);
2381
                fflush(stdout);
2382
                c = getchar();
2383
                if (toupper(c) != 'Y') {
2384
                    fprintf(stderr, "Not overwriting - exiting\n");
2385
                    exit(1);
2386
                }
2387
            }
2388
        }
2389
        
2390
        /* open the file */
2391
        if (url_fopen(&oc->pb, filename, URL_WRONLY) < 0) {
2392
            fprintf(stderr, "Could not open '%s'\n", filename);
2393
            exit(1);
2394
        }
2395
    }
2396

    
2397
    memset(ap, 0, sizeof(*ap));
2398
    ap->image_format = image_format;
2399
    if (av_set_parameters(oc, ap) < 0) {
2400
        fprintf(stderr, "%s: Invalid encoding parameters\n",
2401
                oc->filename);
2402
        exit(1);
2403
    }
2404

    
2405
    /* reset some options */
2406
    file_oformat = NULL;
2407
    file_iformat = NULL;
2408
    image_format = NULL;
2409
    audio_disable = 0;
2410
    video_disable = 0;
2411
    audio_codec_id = CODEC_ID_NONE;
2412
    video_codec_id = CODEC_ID_NONE;
2413
    audio_stream_copy = 0;
2414
    video_stream_copy = 0;
2415
}
2416

    
2417
/* prepare dummy protocols for grab */
2418
void prepare_grab(void)
2419
{
2420
    int has_video, has_audio, i, j;
2421
    AVFormatContext *oc;
2422
    AVFormatContext *ic;
2423
    AVFormatParameters vp1, *vp = &vp1;
2424
    AVFormatParameters ap1, *ap = &ap1;
2425
    
2426
    /* see if audio/video inputs are needed */
2427
    has_video = 0;
2428
    has_audio = 0;
2429
    memset(ap, 0, sizeof(*ap));
2430
    memset(vp, 0, sizeof(*vp));
2431
    for(j=0;j<nb_output_files;j++) {
2432
        oc = output_files[j];
2433
        for(i=0;i<oc->nb_streams;i++) {
2434
            AVCodecContext *enc = &oc->streams[i]->codec;
2435
            switch(enc->codec_type) {
2436
            case CODEC_TYPE_AUDIO:
2437
                if (enc->sample_rate > ap->sample_rate)
2438
                    ap->sample_rate = enc->sample_rate;
2439
                if (enc->channels > ap->channels)
2440
                    ap->channels = enc->channels;
2441
                has_audio = 1;
2442
                break;
2443
            case CODEC_TYPE_VIDEO:
2444
                if (enc->width > vp->width)
2445
                    vp->width = enc->width;
2446
                if (enc->height > vp->height)
2447
                    vp->height = enc->height;
2448
                if (enc->frame_rate > vp->frame_rate)
2449
                    vp->frame_rate = enc->frame_rate;
2450
                has_video = 1;
2451
                break;
2452
            default:
2453
                av_abort();
2454
            }
2455
        }
2456
    }
2457
    
2458
    if (has_video == 0 && has_audio == 0) {
2459
        fprintf(stderr, "Output file must have at least one audio or video stream\n");
2460
        exit(1);
2461
    }
2462
    
2463
    if (has_video) {
2464
        AVInputFormat *fmt1;
2465
        fmt1 = av_find_input_format(video_grab_format);
2466
        vp->device = video_device;
2467
        /* XXX: set DV video channel ? */
2468
        if (av_open_input_file(&ic, "", fmt1, 0, vp) < 0) {
2469
            fprintf(stderr, "Could not find video grab device\n");
2470
            exit(1);
2471
        }
2472
        /* by now video grab has one stream */
2473
        ic->streams[0]->r_frame_rate = vp->frame_rate;
2474
        input_files[nb_input_files] = ic;
2475
        dump_format(ic, nb_input_files, "", 0);
2476
        nb_input_files++;
2477
    }
2478
    if (has_audio) {
2479
        AVInputFormat *fmt1;
2480
        fmt1 = av_find_input_format(audio_grab_format);
2481
        ap->device = audio_device;
2482
        if (av_open_input_file(&ic, "", fmt1, 0, ap) < 0) {
2483
            fprintf(stderr, "Could not find audio grab device\n");
2484
            exit(1);
2485
        }
2486
        input_files[nb_input_files] = ic;
2487
        dump_format(ic, nb_input_files, "", 0);
2488
        nb_input_files++;
2489
    }
2490
}
2491

    
2492
/* open the necessary output devices for playing */
2493
void prepare_play(void)
2494
{
2495
    int has_video, has_audio;
2496
    
2497
    check_audio_video_inputs(&has_video, &has_audio);
2498
        
2499
    /* manual disable */
2500
    if (audio_disable) {
2501
        has_audio = 0;
2502
    }
2503
    if (video_disable) {
2504
        has_video = 0;
2505
    }
2506
        
2507
    if (has_audio) {
2508
        file_oformat = guess_format("audio_device", NULL, NULL);
2509
        if (!file_oformat) {
2510
            fprintf(stderr, "Could not find audio device\n");
2511
            exit(1);
2512
        }
2513
        opt_output_file(audio_device);
2514
    }
2515

    
2516
    if (has_video) {
2517
        file_oformat = guess_format("framebuffer_device", NULL, NULL);
2518
        if (!file_oformat) {
2519
            fprintf(stderr, "Could not find framebuffer device\n");
2520
            exit(1);
2521
        }
2522
        opt_output_file("");
2523
    }
2524
}
2525

    
2526
/* same option as mencoder */
2527
void opt_pass(const char *pass_str)
2528
{
2529
    int pass;
2530
    pass = atoi(pass_str);
2531
    if (pass != 1 && pass != 2) {
2532
        fprintf(stderr, "pass number can be only 1 or 2\n");
2533
        exit(1);
2534
    }
2535
    do_pass = pass;
2536
}
2537

    
2538
#if defined(CONFIG_WIN32) || defined(CONFIG_OS2)
2539
INT64 getutime(void)
2540
{
2541
  return av_gettime();
2542
}
2543
#else
2544
INT64 getutime(void)
2545
{
2546
    struct rusage rusage;
2547

    
2548
    getrusage(RUSAGE_SELF, &rusage);
2549
    return (rusage.ru_utime.tv_sec * 1000000LL) + rusage.ru_utime.tv_usec;
2550
}
2551
#endif
2552

    
2553
extern int ffm_nopts;
2554

    
2555
void opt_bitexact(void)
2556
{
2557
    avcodec_set_bit_exact();
2558
    /* disable generate of real time pts in ffm (need to be supressed anyway) */
2559
    ffm_nopts = 1;
2560
}
2561

    
2562
void show_formats(void)
2563
{
2564
    AVInputFormat *ifmt;
2565
    AVOutputFormat *ofmt;
2566
    AVImageFormat *image_fmt;
2567
    URLProtocol *up;
2568
    AVCodec *p;
2569
    const char **pp;
2570

    
2571
    printf("Output audio/video file formats:");
2572
    for(ofmt = first_oformat; ofmt != NULL; ofmt = ofmt->next) {
2573
        printf(" %s", ofmt->name);
2574
    }
2575
    printf("\n");
2576

    
2577
    printf("Input audio/video file formats:");
2578
    for(ifmt = first_iformat; ifmt != NULL; ifmt = ifmt->next) {
2579
        printf(" %s", ifmt->name);
2580
    }
2581
    printf("\n");
2582

    
2583
    printf("Output image formats:");
2584
    for(image_fmt = first_image_format; image_fmt != NULL; 
2585
        image_fmt = image_fmt->next) {
2586
        if (image_fmt->img_write)
2587
            printf(" %s", image_fmt->name);
2588
    }
2589
    printf("\n");
2590

    
2591
    printf("Input image formats:");
2592
    for(image_fmt = first_image_format; image_fmt != NULL; 
2593
        image_fmt = image_fmt->next) {
2594
        if (image_fmt->img_read)
2595
            printf(" %s", image_fmt->name);
2596
    }
2597
    printf("\n");
2598

    
2599
    printf("Codecs:\n");
2600
    printf("  Encoders:");
2601
    for(p = first_avcodec; p != NULL; p = p->next) {
2602
        if (p->encode)
2603
            printf(" %s", p->name);
2604
    }
2605
    printf("\n");
2606

    
2607
    printf("  Decoders:");
2608
    for(p = first_avcodec; p != NULL; p = p->next) {
2609
        if (p->decode)
2610
            printf(" %s", p->name);
2611
    }
2612
    printf("\n");
2613

    
2614
    printf("Supported file protocols:");
2615
    for(up = first_protocol; up != NULL; up = up->next)
2616
        printf(" %s:", up->name);
2617
    printf("\n");
2618
    
2619
    printf("Frame size abbreviations: sqcif qcif cif 4cif\n");
2620
    printf("Motion estimation methods:");
2621
    pp = motion_str;
2622
    while (*pp) {
2623
        printf(" %s", *pp);
2624
        if ((pp - motion_str + 1) == ME_ZERO) 
2625
            printf("(fastest)");
2626
        else if ((pp - motion_str + 1) == ME_FULL) 
2627
            printf("(slowest)");
2628
        else if ((pp - motion_str + 1) == ME_EPZS) 
2629
            printf("(default)");
2630
        pp++;
2631
    }
2632
    printf("\n");
2633
    exit(1);
2634
}
2635

    
2636
void show_help(void)
2637
{
2638
    const char *prog;
2639
    const OptionDef *po;
2640
    int i, expert;
2641
    
2642
    prog = do_play ? "ffplay" : "ffmpeg";
2643

    
2644
    printf("%s version " FFMPEG_VERSION ", Copyright (c) 2000, 2001, 2002 Fabrice Bellard\n",
2645
           prog);
2646
    
2647
    if (!do_play) {
2648
        printf("usage: ffmpeg [[options] -i input_file]... {[options] outfile}...\n"
2649
               "Hyper fast MPEG1/MPEG4/H263/RV and AC3/MPEG audio encoder\n");
2650
    } else {
2651
        printf("usage: ffplay [options] input_file...\n"
2652
               "Simple audio player\n");
2653
    }
2654
           
2655
    printf("\n"
2656
           "Main options are:\n");
2657
    for(i=0;i<2;i++) {
2658
        if (i == 1)
2659
            printf("\nAdvanced options are:\n");
2660
        for(po = options; po->name != NULL; po++) {
2661
            char buf[64];
2662
            expert = (po->flags & OPT_EXPERT) != 0;
2663
            if (expert == i) {
2664
                strcpy(buf, po->name);
2665
                if (po->flags & HAS_ARG) {
2666
                    strcat(buf, " ");
2667
                    strcat(buf, po->argname);
2668
                }
2669
                printf("-%-17s  %s\n", buf, po->help);
2670
            }
2671
        }
2672
    }
2673

    
2674
    exit(1);
2675
}
2676

    
2677
const OptionDef options[] = {
2678
    { "L", 0, {(void*)show_licence}, "show license" },
2679
    { "h", 0, {(void*)show_help}, "show help" },
2680
    { "formats", 0, {(void*)show_formats}, "show available formats, codecs, protocols, ..." },
2681
    { "f", HAS_ARG, {(void*)opt_format}, "force format", "fmt" },
2682
    { "img", HAS_ARG, {(void*)opt_image_format}, "force image format", "img_fmt" },
2683
    { "i", HAS_ARG, {(void*)opt_input_file}, "input file name", "filename" },
2684
    { "y", OPT_BOOL, {(void*)&file_overwrite}, "overwrite output files" },
2685
    { "map", HAS_ARG | OPT_EXPERT, {(void*)opt_map}, "set input stream mapping", "file:stream" },
2686
    { "t", HAS_ARG, {(void*)opt_recording_time}, "set the recording time", "duration" },
2687
    { "title", HAS_ARG | OPT_STRING, {(void*)&str_title}, "set the title", "string" },
2688
    { "author", HAS_ARG | OPT_STRING, {(void*)&str_author}, "set the author", "string" },
2689
    { "copyright", HAS_ARG | OPT_STRING, {(void*)&str_copyright}, "set the copyright", "string" },
2690
    { "comment", HAS_ARG | OPT_STRING, {(void*)&str_comment}, "set the comment", "string" },
2691
    { "pass", HAS_ARG, {(void*)&opt_pass}, "select the pass number (1 or 2)", "n" },
2692
    { "passlogfile", HAS_ARG | OPT_STRING, {(void*)&pass_logfilename}, "select two pass log file name", "file" },
2693
    /* video options */
2694
    { "b", HAS_ARG, {(void*)opt_video_bitrate}, "set video bitrate (in kbit/s)", "bitrate" },
2695
    { "r", HAS_ARG, {(void*)opt_frame_rate}, "set frame rate (in Hz)", "rate" },
2696
    { "em_rate", OPT_BOOL|OPT_EXPERT, {(void*)&emulate_frame_rate}, "makes img reading happen at nominal frame rate" },
2697
    { "s", HAS_ARG, {(void*)opt_frame_size}, "set frame size (WxH or abbreviation)", "size" },
2698
    { "croptop", HAS_ARG, {(void*)opt_frame_crop_top}, "set top crop band size (in pixels)", "size" },
2699
    { "cropbottom", HAS_ARG, {(void*)opt_frame_crop_bottom}, "set bottom crop band size (in pixels)", "size" },
2700
    { "cropleft", HAS_ARG, {(void*)opt_frame_crop_left}, "set left crop band size (in pixels)", "size" },
2701
    { "cropright", HAS_ARG, {(void*)opt_frame_crop_right}, "set right crop band size (in pixels)", "size" },
2702
    { "g", HAS_ARG | OPT_EXPERT, {(void*)opt_gop_size}, "set the group of picture size", "gop_size" },
2703
    { "intra", OPT_BOOL | OPT_EXPERT, {(void*)&intra_only}, "use only intra frames"},
2704
    { "vn", OPT_BOOL, {(void*)&video_disable}, "disable video" },
2705
    { "qscale", HAS_ARG | OPT_EXPERT, {(void*)opt_qscale}, "use fixed video quantiser scale (VBR)", "q" },
2706
    { "qmin", HAS_ARG | OPT_EXPERT, {(void*)opt_qmin}, "min video quantiser scale (VBR)", "q" },
2707
    { "qmax", HAS_ARG | OPT_EXPERT, {(void*)opt_qmax}, "max video quantiser scale (VBR)", "q" },
2708
    { "mbqmin", HAS_ARG | OPT_EXPERT, {(void*)opt_mb_qmin}, "min macroblock quantiser scale (VBR)", "q" },
2709
    { "mbqmax", HAS_ARG | OPT_EXPERT, {(void*)opt_mb_qmax}, "max macroblock quantiser scale (VBR)", "q" },
2710
    { "qdiff", HAS_ARG | OPT_EXPERT, {(void*)opt_qdiff}, "max difference between the quantiser scale (VBR)", "q" },
2711
    { "qblur", HAS_ARG | OPT_EXPERT, {(void*)opt_qblur}, "video quantiser scale blur (VBR)", "blur" },
2712
    { "qcomp", HAS_ARG | OPT_EXPERT, {(void*)opt_qcomp}, "video quantiser scale compression (VBR)", "compression" },
2713
    { "rc_init_cplx", HAS_ARG | OPT_EXPERT, {(void*)opt_rc_initial_cplx}, "initial complexity for 1-pass encoding", "complexity" },
2714
    { "b_qfactor", HAS_ARG | OPT_EXPERT, {(void*)opt_b_qfactor}, "qp factor between p and b frames", "factor" },
2715
    { "i_qfactor", HAS_ARG | OPT_EXPERT, {(void*)opt_i_qfactor}, "qp factor between p and i frames", "factor" },
2716
    { "b_qoffset", HAS_ARG | OPT_EXPERT, {(void*)opt_b_qoffset}, "qp offset between p and b frames", "offset" },
2717
    { "i_qoffset", HAS_ARG | OPT_EXPERT, {(void*)opt_i_qoffset}, "qp offset between p and i frames", "offset" },
2718
//    { "b_strategy", HAS_ARG | OPT_EXPERT, {(void*)opt_b_strategy}, "dynamic b frame selection strategy", "strategy" },
2719
    { "rc_eq", HAS_ARG | OPT_EXPERT, {(void*)opt_video_rc_eq}, "", "equation" },
2720
    { "rc_override", HAS_ARG | OPT_EXPERT, {(void*)opt_video_rc_override_string}, "Rate control override", "qualities for specific intervals" },
2721
    { "bt", HAS_ARG, {(void*)opt_video_bitrate_tolerance}, "set video bitrate tolerance (in kbit/s)", "tolerance" },
2722
    { "maxrate", HAS_ARG, {(void*)opt_video_bitrate_max}, "set max video bitrate tolerance (in kbit/s)", "bitrate" },
2723
    { "minrate", HAS_ARG, {(void*)opt_video_bitrate_min}, "set min video bitrate tolerance (in kbit/s)", "bitrate" },
2724
    { "bufsize", HAS_ARG, {(void*)opt_video_buffer_size}, "set ratecontrol buffere size (in kbit)", "size" },
2725
    { "vd", HAS_ARG | OPT_EXPERT, {(void*)opt_video_device}, "set video grab device", "device" },
2726
    { "dv1394", OPT_EXPERT, {(void*)opt_dv1394}, "set DV1394 grab", "" },
2727
    { "vcodec", HAS_ARG | OPT_EXPERT, {(void*)opt_video_codec}, "force video codec ('copy' to copy stream)", "codec" },
2728
    { "me", HAS_ARG | OPT_EXPERT, {(void*)opt_motion_estimation}, "set motion estimation method", 
2729
      "method" },
2730
    { "dct_algo", HAS_ARG | OPT_EXPERT, {(void*)opt_dct_algo}, "set dct algo",  "algo" },
2731
    { "idct_algo", HAS_ARG | OPT_EXPERT, {(void*)opt_idct_algo}, "set idct algo",  "algo" },
2732
    { "er", HAS_ARG | OPT_EXPERT, {(void*)opt_error_resilience}, "set error resilience",  "" },
2733
    { "ec", HAS_ARG | OPT_EXPERT, {(void*)opt_error_concealment}, "set error concealment",  "" },
2734
    { "bf", HAS_ARG | OPT_EXPERT, {(void*)opt_b_frames}, "use 'frames' B frames (only MPEG-4)", "frames" },
2735
    { "hq", OPT_BOOL | OPT_EXPERT, {(void*)&use_hq}, "activate high quality settings" },
2736
    { "4mv", OPT_BOOL | OPT_EXPERT, {(void*)&use_4mv}, "use four motion vector by macroblock (only MPEG-4)" },
2737
    { "part", OPT_BOOL | OPT_EXPERT, {(void*)&use_part}, "use data partitioning (only MPEG-4)" },
2738
    { "bug", HAS_ARG | OPT_EXPERT, {(void*)opt_workaround_bugs}, "workaround not auto detected encoder bugs", "param" },
2739
    { "ps", HAS_ARG | OPT_EXPERT, {(void*)opt_packet_size}, "packet size", "size in bits" },
2740
    { "strict", HAS_ARG | OPT_EXPERT, {(void*)opt_strict}, "strictness", "how strictly to follow the standarts" },
2741
    { "sameq", OPT_BOOL, {(void*)&same_quality}, 
2742
      "use same video quality as source (implies VBR)" },
2743
    { "debug", HAS_ARG | OPT_EXPERT, {(void*)opt_debug}, "print specific debug info", "" },
2744
    /* audio options */
2745
    { "ab", HAS_ARG, {(void*)opt_audio_bitrate}, "set audio bitrate (in kbit/s)", "bitrate", },
2746
    { "ar", HAS_ARG, {(void*)opt_audio_rate}, "set audio sampling rate (in Hz)", "rate" },
2747
    { "ac", HAS_ARG, {(void*)opt_audio_channels}, "set number of audio channels", "channels" },
2748
    { "an", OPT_BOOL, {(void*)&audio_disable}, "disable audio" },
2749
    { "ad", HAS_ARG | OPT_EXPERT, {(void*)opt_audio_device}, "set audio device", "device" },
2750
    { "acodec", HAS_ARG | OPT_EXPERT, {(void*)opt_audio_codec}, "force audio codec ('copy' to copy stream)", "codec" },
2751
    { "deinterlace", OPT_BOOL | OPT_EXPERT, {(void*)&do_deinterlace}, 
2752
      "deinterlace pictures" },
2753
    { "benchmark", OPT_BOOL | OPT_EXPERT, {(void*)&do_benchmark}, 
2754
      "add timings for benchmarking" },
2755
    { "hex", OPT_BOOL | OPT_EXPERT, {(void*)&do_hex_dump}, 
2756
      "dump each input packet" },
2757
    { "psnr", OPT_BOOL | OPT_EXPERT, {(void*)&do_psnr}, "calculate PSNR of compressed frames" },
2758
    { "vstats", OPT_BOOL | OPT_EXPERT, {(void*)&do_vstats}, "dump video coding statistics to file" }, 
2759
    { "bitexact", OPT_EXPERT, {(void*)opt_bitexact}, "only use bit exact algorithms (for codec testing)" }, 
2760
    { "vhook", HAS_ARG | OPT_EXPERT, {(void*)add_frame_hooker}, "insert video processing module", "module name and parameters" },
2761
    { NULL, },
2762
};
2763

    
2764
int main(int argc, char **argv)
2765
{
2766
    int optindex, i;
2767
    const char *opt, *arg;
2768
    const OptionDef *po;
2769
    INT64 ti;
2770
    
2771
    av_register_all();
2772

    
2773
    /* detect if invoked as player */
2774
    i = strlen(argv[0]);
2775
    if (i >= 6 && !strcmp(argv[0] + i - 6, "ffplay"))
2776
        do_play = 1;
2777

    
2778
    if (argc <= 1)
2779
        show_help();
2780
    
2781
    /* parse options */
2782
    optindex = 1;
2783
    while (optindex < argc) {
2784
        opt = argv[optindex++];
2785
        
2786
        if (opt[0] == '-' && opt[1] != '\0') {
2787
            po = options;
2788
            while (po->name != NULL) {
2789
                if (!strcmp(opt + 1, po->name))
2790
                    break;
2791
                po++;
2792
            }
2793
            if (!po->name) {
2794
                fprintf(stderr, "%s: unrecognized option '%s'\n", argv[0], opt);
2795
                exit(1);
2796
            }
2797
            arg = NULL;
2798
            if (po->flags & HAS_ARG) {
2799
                arg = argv[optindex++];
2800
                if (!arg) {
2801
                    fprintf(stderr, "%s: missing argument for option '%s'\n", argv[0], opt);
2802
                    exit(1);
2803
                }
2804
            }
2805
            if (po->flags & OPT_STRING) {
2806
                char *str;
2807
                str = strdup(arg);
2808
                *po->u.str_arg = str;
2809
            } else if (po->flags & OPT_BOOL) {
2810
                *po->u.int_arg = 1;
2811
            } else {
2812
                po->u.func_arg(arg);
2813
            }
2814
        } else {
2815
            if (!do_play) {
2816
                opt_output_file(opt);
2817
            } else {
2818
                opt_input_file(opt);
2819
            }
2820
        }
2821
    }
2822

    
2823

    
2824
    if (!do_play) {
2825
        /* file converter / grab */
2826
        if (nb_output_files <= 0) {
2827
            fprintf(stderr, "Must supply at least one output file\n");
2828
            exit(1);
2829
        }
2830
        
2831
        if (nb_input_files == 0) {
2832
            prepare_grab();
2833
        }
2834
    } else {
2835
        /* player */
2836
        if (nb_input_files <= 0) {
2837
            fprintf(stderr, "Must supply at least one input file\n");
2838
            exit(1);
2839
        }
2840
        prepare_play();
2841
    }
2842

    
2843
    ti = getutime();
2844
    av_encode(output_files, nb_output_files, input_files, nb_input_files, 
2845
              stream_maps, nb_stream_maps);
2846
    ti = getutime() - ti;
2847
    if (do_benchmark) {
2848
        printf("bench: utime=%0.3fs\n", ti / 1000000.0);
2849
    }
2850

    
2851
    /* close files */
2852
    for(i=0;i<nb_output_files;i++) {
2853
        /* maybe av_close_output_file ??? */
2854
        AVFormatContext *s = output_files[i];
2855
        int j;
2856
        if (!(s->oformat->flags & AVFMT_NOFILE))
2857
            url_fclose(&s->pb);
2858
        for(j=0;j<s->nb_streams;j++)
2859
            av_free(s->streams[j]);
2860
        av_free(s);
2861
    }
2862
    for(i=0;i<nb_input_files;i++)
2863
        av_close_input_file(input_files[i]);
2864

    
2865
    av_free_static();
2866

    
2867
    
2868
#ifdef POWERPC_TBL_PERFORMANCE_REPORT
2869
    extern void powerpc_display_perf_report(void);
2870
    powerpc_display_perf_report();
2871
#endif /* POWERPC_TBL_PERFORMANCE_REPORT */
2872

    
2873
    return 0;
2874
}