Statistics
| Branch: | Revision:

ffmpeg / ffmpeg.c @ d66c7abc

History | View | Annotate | Download (91.5 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 "common.h"
21
#include "avformat.h"
22
#include "framehook.h"
23
/* usleep() */
24
#include "os_support.h"
25

    
26
#ifndef CONFIG_WIN32
27
#include <unistd.h>
28
#include <fcntl.h>
29
#include <sys/ioctl.h>
30
#include <sys/time.h>
31
#include <termios.h>
32
#include <sys/resource.h>
33
#endif
34
#ifdef CONFIG_OS2
35
#include <sys/types.h>
36
#include <sys/select.h>
37
#include <stdlib.h>
38
#endif
39
#include <time.h>
40
#include <ctype.h>
41

    
42
#if !defined(INFINITY) && defined(HUGE_VAL)
43
#define INFINITY HUGE_VAL
44
#endif
45

    
46
#define MAXINT64 int64_t_C(0x7fffffffffffffff)
47

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

    
64
/* select an input stream for an output stream */
65
typedef struct AVStreamMap {
66
    int file_index;
67
    int stream_index;
68
} AVStreamMap;
69

    
70
extern const OptionDef options[];
71

    
72
void show_help(void);
73

    
74
#define MAX_FILES 20
75

    
76
static AVFormatContext *input_files[MAX_FILES];
77
static int nb_input_files = 0;
78

    
79
static AVFormatContext *output_files[MAX_FILES];
80
static int nb_output_files = 0;
81

    
82
static AVStreamMap stream_maps[MAX_FILES];
83
static int nb_stream_maps;
84

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

    
145
static int gop_size = 12;
146
static int intra_only = 0;
147
static int audio_sample_rate = 44100;
148
static int audio_bit_rate = 64000;
149
static int audio_disable = 0;
150
static int audio_channels = 1;
151
static int audio_codec_id = CODEC_ID_NONE;
152

    
153
static int64_t recording_time = 0;
154
static int file_overwrite = 0;
155
static char *str_title = NULL;
156
static char *str_author = NULL;
157
static char *str_copyright = NULL;
158
static char *str_comment = NULL;
159
static int do_benchmark = 0;
160
static int do_hex_dump = 0;
161
static int do_play = 0;
162
static int do_psnr = 0;
163
static int do_vstats = 0;
164
static int do_pass = 0;
165
static int bitexact = 0;
166
static char *pass_logfilename = NULL;
167
static int audio_stream_copy = 0;
168
static int video_stream_copy = 0;
169

    
170
static int rate_emu = 0;
171

    
172
static char *video_grab_format = "video4linux";
173
static char *video_device = NULL;
174
static int  video_channel = 0;
175

    
176
static char *audio_grab_format = "audio_device";
177
static char *audio_device = NULL;
178

    
179
#define DEFAULT_PASS_LOGFILENAME "ffmpeg2pass"
180

    
181
typedef struct AVOutputStream {
182
    int file_index;          /* file index */
183
    int index;               /* stream index in the output file */
184
    int source_index;        /* AVInputStream index */
185
    AVStream *st;            /* stream in the output file */
186
    int encoding_needed;     /* true if encoding needed for this stream */
187
    int frame_number;
188
    /* input pts and corresponding output pts
189
       for A/V sync */
190
    double sync_ipts;
191
    double sync_ipts_offset;
192
    int64_t sync_opts;
193
    /* video only */
194
    int video_resample;      /* video_resample and video_crop are mutually exclusive */
195
    AVPicture pict_tmp;      /* temporary image for resampling */
196
    ImgReSampleContext *img_resample_ctx; /* for image resampling */
197

    
198
    int video_crop;          /* video_resample and video_crop are mutually exclusive */
199
    int topBand;             /* cropping area sizes */
200
    int leftBand;
201
    
202
    /* audio only */
203
    int audio_resample;
204
    ReSampleContext *resample; /* for audio resampling */
205
    FifoBuffer fifo;     /* for compression: one audio fifo per codec */
206
    FILE *logfile;
207
} AVOutputStream;
208

    
209
typedef struct AVInputStream {
210
    int file_index;
211
    int index;
212
    AVStream *st;
213
    int discard;             /* true if stream data should be discarded */
214
    int decoding_needed;     /* true if the packets must be decoded in 'raw_fifo' */
215
    int64_t sample_index;      /* current sample */
216
    int frame_decoded;       /* true if a video or audio frame has been decoded */
217

    
218
    int64_t       start;     /* time when read started */
219
    unsigned long frame;     /* current frame */
220
} AVInputStream;
221

    
222
typedef struct AVInputFile {
223
    int eof_reached;      /* true if eof reached */
224
    int ist_index;        /* index of first stream in ist_table */
225
    int buffer_size;      /* current total buffer size */
226
    int buffer_size_max;  /* buffer size at which we consider we can stop
227
                             buffering */
228
    int nb_streams;       /* nb streams we are aware of */
229
} AVInputFile;
230

    
231
#ifndef CONFIG_WIN32
232

    
233
/* init terminal so that we can grab keys */
234
static struct termios oldtty;
235

    
236
static void term_exit(void)
237
{
238
    tcsetattr (0, TCSANOW, &oldtty);
239
}
240

    
241
static void term_init(void)
242
{
243
    struct termios tty;
244

    
245
    tcgetattr (0, &tty);
246
    oldtty = tty;
247

    
248
    tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
249
                          |INLCR|IGNCR|ICRNL|IXON);
250
    tty.c_oflag |= OPOST;
251
    tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
252
    tty.c_cflag &= ~(CSIZE|PARENB);
253
    tty.c_cflag |= CS8;
254
    tty.c_cc[VMIN] = 1;
255
    tty.c_cc[VTIME] = 0;
256
    
257
    tcsetattr (0, TCSANOW, &tty);
258

    
259
    atexit(term_exit);
260
#ifdef CONFIG_BEOS_NETSERVER
261
    fcntl(0, F_SETFL, fcntl(0, F_GETFL) | O_NONBLOCK);
262
#endif
263
}
264

    
265
/* read a key without blocking */
266
static int read_key(void)
267
{
268
    int n = 1;
269
    unsigned char ch;
270
#ifndef CONFIG_BEOS_NETSERVER
271
    struct timeval tv;
272
    fd_set rfds;
273

    
274
    FD_ZERO(&rfds);
275
    FD_SET(0, &rfds);
276
    tv.tv_sec = 0;
277
    tv.tv_usec = 0;
278
    n = select(1, &rfds, NULL, NULL, &tv);
279
#endif
280
    if (n > 0) {
281
        n = read(0, &ch, 1);
282
        if (n == 1)
283
            return ch;
284

    
285
        return n;
286
    }
287
    return -1;
288
}
289

    
290
#else
291

    
292
/* no interactive support */
293
static void term_exit(void)
294
{
295
}
296

    
297
static void term_init(void)
298
{
299
}
300

    
301
static int read_key(void)
302
{
303
    return 0;
304
}
305

    
306
#endif
307

    
308
static int read_ffserver_streams(AVFormatContext *s, const char *filename)
309
{
310
    int i, err;
311
    AVFormatContext *ic;
312

    
313
    err = av_open_input_file(&ic, filename, NULL, FFM_PACKET_SIZE, NULL);
314
    if (err < 0)
315
        return err;
316
    /* copy stream format */
317
    s->nb_streams = ic->nb_streams;
318
    for(i=0;i<ic->nb_streams;i++) {
319
        AVStream *st;
320

    
321
        st = av_mallocz(sizeof(AVFormatContext));
322
        memcpy(st, ic->streams[i], sizeof(AVStream));
323
        s->streams[i] = st;
324
    }
325

    
326
    av_close_input_file(ic);
327
    return 0;
328
}
329

    
330
#define MAX_AUDIO_PACKET_SIZE (128 * 1024)
331

    
332
static void do_audio_out(AVFormatContext *s, 
333
                         AVOutputStream *ost, 
334
                         AVInputStream *ist,
335
                         unsigned char *buf, int size)
336
{
337
    uint8_t *buftmp;
338
    static uint8_t *audio_buf = NULL;
339
    static uint8_t *audio_out = NULL;
340

    
341
    int size_out, frame_bytes, ret;
342
    AVCodecContext *enc;
343

    
344
    /* SC: dynamic allocation of buffers */
345
    if (!audio_buf)
346
        audio_buf = av_malloc(2*MAX_AUDIO_PACKET_SIZE);
347
    if (!audio_out)
348
        audio_out = av_malloc(4*MAX_AUDIO_PACKET_SIZE);
349
    if (!audio_buf || !audio_out)
350
        return;               /* Should signal an error ! */
351

    
352
    
353
    enc = &ost->st->codec;
354

    
355
    if (ost->audio_resample) {
356
        buftmp = audio_buf;
357
        size_out = audio_resample(ost->resample, 
358
                                  (short *)buftmp, (short *)buf,
359
                                  size / (ist->st->codec.channels * 2));
360
        size_out = size_out * enc->channels * 2;
361
    } else {
362
        buftmp = buf;
363
        size_out = size;
364
    }
365

    
366
    /* now encode as many frames as possible */
367
    if (enc->frame_size > 1) {
368
        /* output resampled raw samples */
369
        fifo_write(&ost->fifo, buftmp, size_out, 
370
                   &ost->fifo.wptr);
371

    
372
        frame_bytes = enc->frame_size * 2 * enc->channels;
373
        
374
        while (fifo_read(&ost->fifo, audio_buf, frame_bytes, 
375
                     &ost->fifo.rptr) == 0) {
376
            ret = avcodec_encode_audio(enc, audio_out, sizeof(audio_out), 
377
                                       (short *)audio_buf);
378
            av_write_frame(s, ost->index, audio_out, ret);
379
        }
380
    } else {
381
        /* output a pcm frame */
382
        /* XXX: change encoding codec API to avoid this ? */
383
        switch(enc->codec->id) {
384
        case CODEC_ID_PCM_S16LE:
385
        case CODEC_ID_PCM_S16BE:
386
        case CODEC_ID_PCM_U16LE:
387
        case CODEC_ID_PCM_U16BE:
388
            break;
389
        default:
390
            size_out = size_out >> 1;
391
            break;
392
        }
393
        ret = avcodec_encode_audio(enc, audio_out, size_out, 
394
                                   (short *)buftmp);
395
        av_write_frame(s, ost->index, audio_out, ret);
396
    }
397
}
398

    
399
static void pre_process_video_frame(AVInputStream *ist, AVPicture *picture, void **bufp)
400
{
401
    AVCodecContext *dec;
402
    AVPicture *picture2;
403
    AVPicture picture_tmp;
404
    uint8_t *buf = 0;
405

    
406
    dec = &ist->st->codec;
407

    
408
    /* deinterlace : must be done before any resize */
409
    if (do_deinterlace) {
410
        int size;
411

    
412
        /* create temporary picture */
413
        size = avpicture_get_size(dec->pix_fmt, dec->width, dec->height);
414
        buf = av_malloc(size);
415
        if (!buf)
416
            return;
417
        
418
        picture2 = &picture_tmp;
419
        avpicture_fill(picture2, buf, dec->pix_fmt, dec->width, dec->height);
420

    
421
        if (avpicture_deinterlace(picture2, picture, 
422
                                  dec->pix_fmt, dec->width, dec->height) < 0) {
423
            /* if error, do not deinterlace */
424
            av_free(buf);
425
            buf = NULL;
426
            picture2 = picture;
427
        }
428
    } else {
429
        picture2 = picture;
430
    }
431

    
432
    frame_hook_process(picture2, dec->pix_fmt, dec->width, dec->height);
433

    
434
    if (picture != picture2)
435
        *picture = *picture2;
436
    *bufp = buf;
437
}
438

    
439
/* we begin to correct av delay at this threshold */
440
#define AV_DELAY_MAX 0.100
441

    
442
static void do_video_out(AVFormatContext *s, 
443
                         AVOutputStream *ost, 
444
                         AVInputStream *ist,
445
                         AVPicture *in_picture,
446
                         int *frame_size, AVOutputStream *audio_sync)
447
{
448
    int nb_frames, i, ret;
449
    AVPicture *final_picture, *formatted_picture;
450
    AVPicture picture_format_temp, picture_crop_temp;
451
    static uint8_t *video_buffer;
452
    uint8_t *buf = NULL, *buf1 = NULL;
453
    AVCodecContext *enc, *dec;
454

    
455
#define VIDEO_BUFFER_SIZE (1024*1024)
456

    
457
    enc = &ost->st->codec;
458
    dec = &ist->st->codec;
459

    
460
    /* by default, we output a single frame */
461
    nb_frames = 1;
462

    
463
    *frame_size = 0;
464

    
465
    /* NOTE: the A/V sync is always done by considering the audio is
466
       the master clock. It is suffisant for transcoding or playing,
467
       but not for the general case */
468
    if (audio_sync) {
469
        /* compute the A-V delay and duplicate/remove frames if needed */
470
        double adelta, vdelta, apts, vpts, av_delay;
471
        
472
        if (audio_sync->sync_ipts != AV_NOPTS_VALUE &&
473
            ost->sync_ipts != AV_NOPTS_VALUE) {
474
            
475
            adelta = (double)(ost->st->pts.val - audio_sync->sync_opts) * 
476
                s->pts_num / s->pts_den;
477
            apts = audio_sync->sync_ipts + adelta; 
478
            
479
            vdelta = (double)(ost->st->pts.val - ost->sync_opts) *
480
                s->pts_num / s->pts_den;
481
            vpts = ost->sync_ipts + vdelta;
482
            
483
            av_delay = apts - vpts;
484
            //            printf("delay=%f\n", av_delay);
485
            if (av_delay < -AV_DELAY_MAX)
486
                nb_frames = 2;
487
            else if (av_delay > AV_DELAY_MAX)
488
                nb_frames = 0;
489
        }
490
    } else {
491
        double vdelta;
492

    
493
        if (ost->sync_ipts != AV_NOPTS_VALUE) {
494
            vdelta = (double)(ost->st->pts.val) * s->pts_num / s->pts_den - (ost->sync_ipts - ost->sync_ipts_offset);
495
            if (vdelta < 100 && vdelta > -100 && ost->sync_ipts_offset) {
496
                if (vdelta < -AV_DELAY_MAX)
497
                    nb_frames = 2;
498
                else if (vdelta > AV_DELAY_MAX)
499
                    nb_frames = 0;
500
            } else {
501
                ost->sync_ipts_offset -= vdelta;
502
                if (!ost->sync_ipts_offset)
503
                    ost->sync_ipts_offset = 0.000001; /* one microsecond */
504
            }
505

    
506
#if defined(PJSG)
507
            {
508
                static char *action[] = { "drop frame", "copy frame", "dup frame" };
509
                printf("Input PTS %12.6f, output PTS %12.6f: %s\n",
510
                    (double) ost->sync_ipts, (double) ost->st->pts.val * s->pts_num / s->pts_den,
511
                    action[nb_frames]);
512
            }
513
#endif
514
        }
515
    }
516
    if (nb_frames <= 0) 
517
        return;
518

    
519
    if (!video_buffer)
520
        video_buffer = av_malloc(VIDEO_BUFFER_SIZE);
521
    if (!video_buffer)
522
        return;
523

    
524
    /* convert pixel format if needed */
525
    if (enc->pix_fmt != dec->pix_fmt) {
526
        int size;
527

    
528
        /* create temporary picture */
529
        size = avpicture_get_size(enc->pix_fmt, dec->width, dec->height);
530
        buf = av_malloc(size);
531
        if (!buf)
532
            return;
533
        formatted_picture = &picture_format_temp;
534
        avpicture_fill(formatted_picture, buf, enc->pix_fmt, dec->width, dec->height);
535
        
536
        if (img_convert(formatted_picture, enc->pix_fmt, 
537
                        in_picture, dec->pix_fmt, 
538
                        dec->width, dec->height) < 0) {
539
            fprintf(stderr, "pixel format conversion not handled\n");
540
            goto the_end;
541
        }
542
    } else {
543
        formatted_picture = in_picture;
544
    }
545

    
546
    /* XXX: resampling could be done before raw format convertion in
547
       some cases to go faster */
548
    /* XXX: only works for YUV420P */
549
    if (ost->video_resample) {
550
        final_picture = &ost->pict_tmp;
551
        img_resample(ost->img_resample_ctx, final_picture, formatted_picture);
552
    } else if (ost->video_crop) {
553
        picture_crop_temp.data[0] = formatted_picture->data[0] +
554
                (ost->topBand * formatted_picture->linesize[0]) + ost->leftBand;
555

    
556
        picture_crop_temp.data[1] = formatted_picture->data[1] +
557
                ((ost->topBand >> 1) * formatted_picture->linesize[1]) +
558
                (ost->leftBand >> 1);
559

    
560
        picture_crop_temp.data[2] = formatted_picture->data[2] +
561
                ((ost->topBand >> 1) * formatted_picture->linesize[2]) +
562
                (ost->leftBand >> 1);
563

    
564
        picture_crop_temp.linesize[0] = formatted_picture->linesize[0];
565
        picture_crop_temp.linesize[1] = formatted_picture->linesize[1];
566
        picture_crop_temp.linesize[2] = formatted_picture->linesize[2];
567
        final_picture = &picture_crop_temp;
568
    } else {
569
        final_picture = formatted_picture;
570
    }
571
    /* duplicates frame if needed */
572
    /* XXX: pb because no interleaving */
573
    for(i=0;i<nb_frames;i++) {
574
        if (s->oformat->flags & AVFMT_RAWPICTURE) {
575
            /* raw pictures are written as AVPicture structure to
576
               avoid any copies. We support temorarily the older
577
               method. */
578
            av_write_frame(s, ost->index, 
579
                           (uint8_t *)final_picture, sizeof(AVPicture));
580
        } else {
581
            AVFrame big_picture;
582
            
583
            memset(&big_picture, 0, sizeof(AVFrame));
584
            *(AVPicture*)&big_picture= *final_picture;
585
                        
586
            /* handles sameq here. This is not correct because it may
587
               not be a global option */
588
            if (same_quality) {
589
                big_picture.quality = ist->st->quality;
590
            }else
591
                big_picture.quality = ost->st->quality;
592
            
593
            ret = avcodec_encode_video(enc, 
594
                                       video_buffer, VIDEO_BUFFER_SIZE,
595
                                       &big_picture);
596
            //enc->frame_number = enc->real_pict_num;
597
            av_write_frame(s, ost->index, video_buffer, ret);
598
            *frame_size = ret;
599
            //fprintf(stderr,"\nFrame: %3d %3d size: %5d type: %d",
600
            //        enc->frame_number-1, enc->real_pict_num, ret,
601
            //        enc->pict_type);
602
            /* if two pass, output log */
603
            if (ost->logfile && enc->stats_out) {
604
                fprintf(ost->logfile, "%s", enc->stats_out);
605
            }
606
        }
607
        ost->frame_number++;
608
    }
609
 the_end:
610
    av_free(buf);
611
    av_free(buf1);
612
}
613

    
614
static double psnr(double d){
615
    if(d==0) return INFINITY;
616
    return -10.0*log(d)/log(10.0);
617
}
618

    
619
static void do_video_stats(AVFormatContext *os, AVOutputStream *ost, 
620
                           int frame_size)
621
{
622
    static FILE *fvstats=NULL;
623
    static int64_t total_size = 0;
624
    char filename[40];
625
    time_t today2;
626
    struct tm *today;
627
    AVCodecContext *enc;
628
    int frame_number;
629
    int64_t ti;
630
    double ti1, bitrate, avg_bitrate;
631
    
632
    if (!fvstats) {
633
        today2 = time(NULL);
634
        today = localtime(&today2);
635
        sprintf(filename, "vstats_%02d%02d%02d.log", today->tm_hour,
636
                                               today->tm_min,
637
                                               today->tm_sec);
638
        fvstats = fopen(filename,"w");
639
        if (!fvstats) {
640
            perror("fopen");
641
            exit(1);
642
        }
643
    }
644
    
645
    ti = MAXINT64;
646
    enc = &ost->st->codec;
647
    total_size += frame_size;
648
    if (enc->codec_type == CODEC_TYPE_VIDEO) {
649
        frame_number = ost->frame_number;
650
        fprintf(fvstats, "frame= %5d q= %2.1f ", frame_number, enc->coded_frame->quality);
651
        if (enc->flags&CODEC_FLAG_PSNR)
652
            fprintf(fvstats, "PSNR= %6.2f ", psnr(enc->coded_frame->error[0]/(enc->width*enc->height*255.0*255.0)));
653
        
654
        fprintf(fvstats,"f_size= %6d ", frame_size);
655
        /* compute pts value */
656
        ti1 = (double)ost->st->pts.val * os->pts_num / os->pts_den;
657
        if (ti1 < 0.01)
658
            ti1 = 0.01;
659
    
660
        bitrate = (double)(frame_size * 8) * enc->frame_rate / enc->frame_rate_base / 1000.0;
661
        avg_bitrate = (double)(total_size * 8) / ti1 / 1000.0;
662
        fprintf(fvstats, "s_size= %8.0fkB time= %0.3f br= %7.1fkbits/s avg_br= %7.1fkbits/s ",
663
            (double)total_size / 1024, ti1, bitrate, avg_bitrate);
664
        fprintf(fvstats,"type= %s\n", enc->coded_frame->key_frame == 1 ? "I" : "P");        
665
    }
666
}
667

    
668
static void print_report(AVFormatContext **output_files,
669
                         AVOutputStream **ost_table, int nb_ostreams,
670
                         int is_last_report)
671
{
672
    char buf[1024];
673
    AVOutputStream *ost;
674
    AVFormatContext *oc, *os;
675
    int64_t total_size;
676
    AVCodecContext *enc;
677
    int frame_number, vid, i;
678
    double bitrate, ti1, pts;
679
    static int64_t last_time = -1;
680
    
681
    if (!is_last_report) {
682
        int64_t cur_time;
683
        /* display the report every 0.5 seconds */
684
        cur_time = av_gettime();
685
        if (last_time == -1) {
686
            last_time = cur_time;
687
            return;
688
        } 
689
        if ((cur_time - last_time) < 500000)
690
            return;
691
        last_time = cur_time;
692
    }
693

    
694

    
695
    oc = output_files[0];
696

    
697
    total_size = url_ftell(&oc->pb);
698
    
699
    buf[0] = '\0';
700
    ti1 = 1e10;
701
    vid = 0;
702
    for(i=0;i<nb_ostreams;i++) {
703
        ost = ost_table[i];
704
        os = output_files[ost->file_index];
705
        enc = &ost->st->codec;
706
        if (vid && enc->codec_type == CODEC_TYPE_VIDEO) {
707
            sprintf(buf + strlen(buf), "q=%2.1f ",
708
                    enc->coded_frame->quality);
709
        }
710
        if (!vid && enc->codec_type == CODEC_TYPE_VIDEO) {
711
            frame_number = ost->frame_number;
712
            sprintf(buf + strlen(buf), "frame=%5d q=%2.1f ",
713
                    frame_number, enc->coded_frame ? enc->coded_frame->quality : 0);
714
            if (enc->flags&CODEC_FLAG_PSNR)
715
                sprintf(buf + strlen(buf), "PSNR= %6.2f ", psnr(enc->coded_frame->error[0]/(enc->width*enc->height*255.0*255.0)));
716
            vid = 1;
717
        }
718
        /* compute min output value */
719
        pts = (double)ost->st->pts.val * os->pts_num / os->pts_den;
720
        if ((pts < ti1) && (pts > 0))
721
            ti1 = pts;
722
    }
723
    if (ti1 < 0.01)
724
        ti1 = 0.01;
725
    bitrate = (double)(total_size * 8) / ti1 / 1000.0;
726
    
727
    sprintf(buf + strlen(buf), 
728
            "size=%8.0fkB time=%0.1f bitrate=%6.1fkbits/s",
729
            (double)total_size / 1024, ti1, bitrate);
730
    
731
    fprintf(stderr, "%s   ", buf);
732
    
733
    if (is_last_report) {
734
        fprintf(stderr, "\n");
735
    } else {
736
        fprintf(stderr, "\r");
737
        fflush(stderr);
738
    }
739
}
740

    
741
/*
742
 * The following code is the main loop of the file converter
743
 */
744
static int av_encode(AVFormatContext **output_files,
745
                     int nb_output_files,
746
                     AVFormatContext **input_files,
747
                     int nb_input_files,
748
                     AVStreamMap *stream_maps, int nb_stream_maps)
749
{
750
    int ret, i, j, k, n, nb_istreams = 0, nb_ostreams = 0, pts_set;
751
    AVFormatContext *is, *os;
752
    AVCodecContext *codec, *icodec;
753
    AVOutputStream *ost, **ost_table = NULL;
754
    AVInputStream *ist, **ist_table = NULL;
755
    AVInputFile *file_table;
756
    AVFormatContext *stream_no_data;
757
    int key;
758

    
759
    file_table= (AVInputFile*) av_mallocz(nb_input_files * sizeof(AVInputFile));
760
    if (!file_table)
761
        goto fail;
762

    
763
    /* input stream init */
764
    j = 0;
765
    for(i=0;i<nb_input_files;i++) {
766
        is = input_files[i];
767
        file_table[i].ist_index = j;
768
        file_table[i].nb_streams = is->nb_streams;
769
        j += is->nb_streams;
770
    }
771
    nb_istreams = j;
772

    
773
    ist_table = av_mallocz(nb_istreams * sizeof(AVInputStream *));
774
    if (!ist_table)
775
        goto fail;
776
    
777
    for(i=0;i<nb_istreams;i++) {
778
        ist = av_mallocz(sizeof(AVInputStream));
779
        if (!ist)
780
            goto fail;
781
        ist_table[i] = ist;
782
    }
783
    j = 0;
784
    for(i=0;i<nb_input_files;i++) {
785
        is = input_files[i];
786
        for(k=0;k<is->nb_streams;k++) {
787
            ist = ist_table[j++];
788
            ist->st = is->streams[k];
789
            ist->file_index = i;
790
            ist->index = k;
791
            ist->discard = 1; /* the stream is discarded by default
792
                                 (changed later) */
793

    
794
            if (ist->st->codec.rate_emu) {
795
                ist->start = av_gettime();
796
                ist->frame = 0;
797
            }
798
        }
799
    }
800

    
801
    /* output stream init */
802
    nb_ostreams = 0;
803
    for(i=0;i<nb_output_files;i++) {
804
        os = output_files[i];
805
        nb_ostreams += os->nb_streams;
806
    }
807
    if (nb_stream_maps > 0 && nb_stream_maps != nb_ostreams) {
808
        fprintf(stderr, "Number of stream maps must match number of output streams\n");
809
        exit(1);
810
    }
811

    
812
    ost_table = av_mallocz(sizeof(AVOutputStream *) * nb_ostreams);
813
    if (!ost_table)
814
        goto fail;
815
    for(i=0;i<nb_ostreams;i++) {
816
        ost = av_mallocz(sizeof(AVOutputStream));
817
        if (!ost)
818
            goto fail;
819
        ost_table[i] = ost;
820
    }
821
    
822
    n = 0;
823
    for(k=0;k<nb_output_files;k++) {
824
        os = output_files[k];
825
        for(i=0;i<os->nb_streams;i++) {
826
            int found;
827
            ost = ost_table[n++];
828
            ost->file_index = k;
829
            ost->index = i;
830
            ost->st = os->streams[i];
831
            if (nb_stream_maps > 0) {
832
                ost->source_index = file_table[stream_maps[n-1].file_index].ist_index + 
833
                    stream_maps[n-1].stream_index;
834
            } else {
835
                /* get corresponding input stream index : we select the first one with the right type */
836
                found = 0;
837
                for(j=0;j<nb_istreams;j++) {
838
                    ist = ist_table[j];
839
                    if (ist->discard && 
840
                        ist->st->codec.codec_type == ost->st->codec.codec_type) {
841
                        ost->source_index = j;
842
                        found = 1;
843
                    }
844
                }
845
                
846
                if (!found) {
847
                    /* try again and reuse existing stream */
848
                    for(j=0;j<nb_istreams;j++) {
849
                        ist = ist_table[j];
850
                        if (ist->st->codec.codec_type == ost->st->codec.codec_type) {
851
                            ost->source_index = j;
852
                            found = 1;
853
                        }
854
                    }
855
                    if (!found) {
856
                        fprintf(stderr, "Could not find input stream matching output stream #%d.%d\n",
857
                                ost->file_index, ost->index);
858
                        exit(1);
859
                    }
860
                }
861
            }
862
            ist = ist_table[ost->source_index];
863
            ist->discard = 0;
864
        }
865
    }
866

    
867
    /* for each output stream, we compute the right encoding parameters */
868
    for(i=0;i<nb_ostreams;i++) {
869
        ost = ost_table[i];
870
        ist = ist_table[ost->source_index];
871

    
872
        codec = &ost->st->codec;
873
        icodec = &ist->st->codec;
874

    
875
        if (ost->st->stream_copy) {
876
            /* if stream_copy is selected, no need to decode or encode */
877
            codec->codec_id = icodec->codec_id;
878
            codec->codec_type = icodec->codec_type;
879
            codec->codec_tag = icodec->codec_tag;
880
            codec->bit_rate = icodec->bit_rate;
881
            switch(codec->codec_type) {
882
            case CODEC_TYPE_AUDIO:
883
                codec->sample_rate = icodec->sample_rate;
884
                codec->channels = icodec->channels;
885
                break;
886
            case CODEC_TYPE_VIDEO:
887
                codec->frame_rate = icodec->frame_rate;
888
                codec->frame_rate_base = icodec->frame_rate_base;
889
                codec->width = icodec->width;
890
                codec->height = icodec->height;
891
                break;
892
            default:
893
                av_abort();
894
            }
895
        } else {
896
            switch(codec->codec_type) {
897
            case CODEC_TYPE_AUDIO:
898
                if (fifo_init(&ost->fifo, 2 * MAX_AUDIO_PACKET_SIZE))
899
                    goto fail;
900
                
901
                if (codec->channels == icodec->channels &&
902
                    codec->sample_rate == icodec->sample_rate) {
903
                    ost->audio_resample = 0;
904
                } else {
905
                    if (codec->channels != icodec->channels &&
906
                        icodec->codec_id == CODEC_ID_AC3) {
907
                        /* Special case for 5:1 AC3 input */
908
                        /* and mono or stereo output      */
909
                        /* Request specific number of channels */
910
                        icodec->channels = codec->channels;
911
                        if (codec->sample_rate == icodec->sample_rate)
912
                            ost->audio_resample = 0;
913
                        else {
914
                            ost->audio_resample = 1;
915
                            ost->resample = audio_resample_init(codec->channels, icodec->channels,
916
                                                        codec->sample_rate, 
917
                                                        icodec->sample_rate);
918
                        }
919
                        /* Request specific number of channels */
920
                        icodec->channels = codec->channels;
921
                    } else {
922
                        ost->audio_resample = 1; 
923
                        ost->resample = audio_resample_init(codec->channels, icodec->channels,
924
                                                        codec->sample_rate, 
925
                                                        icodec->sample_rate);
926
                    }
927
                }
928
                ist->decoding_needed = 1;
929
                ost->encoding_needed = 1;
930
                break;
931
            case CODEC_TYPE_VIDEO:
932
                if (codec->width == icodec->width &&
933
                    codec->height == icodec->height &&
934
                    frame_topBand == 0 &&
935
                    frame_bottomBand == 0 &&
936
                    frame_leftBand == 0 &&
937
                    frame_rightBand == 0)
938
                {
939
                    ost->video_resample = 0;
940
                    ost->video_crop = 0;
941
                } else if ((codec->width == icodec->width -
942
                                (frame_leftBand + frame_rightBand)) &&
943
                        (codec->height == icodec->height -
944
                                (frame_topBand  + frame_bottomBand)))
945
                {
946
                    ost->video_resample = 0;
947
                    ost->video_crop = 1;
948
                    ost->topBand = frame_topBand;
949
                    ost->leftBand = frame_leftBand;
950
                } else {
951
                    uint8_t *buf;
952
                    ost->video_resample = 1;
953
                    ost->video_crop = 0; // cropping is handled as part of resample
954
                    buf = av_malloc((codec->width * codec->height * 3) / 2);
955
                    if (!buf)
956
                        goto fail;
957
                    ost->pict_tmp.data[0] = buf;
958
                    ost->pict_tmp.data[1] = ost->pict_tmp.data[0] + (codec->width * codec->height);
959
                    ost->pict_tmp.data[2] = ost->pict_tmp.data[1] + (codec->width * codec->height) / 4;
960
                    ost->pict_tmp.linesize[0] = codec->width;
961
                    ost->pict_tmp.linesize[1] = codec->width / 2;
962
                    ost->pict_tmp.linesize[2] = codec->width / 2;
963

    
964
                    ost->img_resample_ctx = img_resample_full_init( 
965
                                      ost->st->codec.width, ost->st->codec.height,
966
                                      ist->st->codec.width, ist->st->codec.height,
967
                                      frame_topBand, frame_bottomBand,
968
                                      frame_leftBand, frame_rightBand);
969
                }
970
                ost->encoding_needed = 1;
971
                ist->decoding_needed = 1;
972
                break;
973
            default:
974
                av_abort();
975
            }
976
            /* two pass mode */
977
            if (ost->encoding_needed && 
978
                (codec->flags & (CODEC_FLAG_PASS1 | CODEC_FLAG_PASS2))) {
979
                char logfilename[1024];
980
                FILE *f;
981
                int size;
982
                char *logbuffer;
983
                
984
                snprintf(logfilename, sizeof(logfilename), "%s-%d.log", 
985
                         pass_logfilename ? 
986
                         pass_logfilename : DEFAULT_PASS_LOGFILENAME, i);
987
                if (codec->flags & CODEC_FLAG_PASS1) {
988
                    f = fopen(logfilename, "w");
989
                    if (!f) {
990
                        perror(logfilename);
991
                        exit(1);
992
                    }
993
                    ost->logfile = f;
994
                } else {
995
                    /* read the log file */
996
                    f = fopen(logfilename, "r");
997
                    if (!f) {
998
                        perror(logfilename);
999
                        exit(1);
1000
                    }
1001
                    fseek(f, 0, SEEK_END);
1002
                    size = ftell(f);
1003
                    fseek(f, 0, SEEK_SET);
1004
                    logbuffer = av_malloc(size + 1);
1005
                    if (!logbuffer) {
1006
                        fprintf(stderr, "Could not allocate log buffer\n");
1007
                        exit(1);
1008
                    }
1009
                    fread(logbuffer, 1, size, f);
1010
                    fclose(f);
1011
                    logbuffer[size] = '\0';
1012
                    codec->stats_in = logbuffer;
1013
                }
1014
            }
1015
        }
1016
    }
1017

    
1018
    /* dump the file output parameters - cannot be done before in case
1019
       of stream copy */
1020
    for(i=0;i<nb_output_files;i++) {
1021
        dump_format(output_files[i], i, output_files[i]->filename, 1);
1022
    }
1023

    
1024
    /* dump the stream mapping */
1025
    fprintf(stderr, "Stream mapping:\n");
1026
    for(i=0;i<nb_ostreams;i++) {
1027
        ost = ost_table[i];
1028
        fprintf(stderr, "  Stream #%d.%d -> #%d.%d\n",
1029
                ist_table[ost->source_index]->file_index,
1030
                ist_table[ost->source_index]->index,
1031
                ost->file_index, 
1032
                ost->index);
1033
    }
1034

    
1035
    /* open each encoder */
1036
    for(i=0;i<nb_ostreams;i++) {
1037
        ost = ost_table[i];
1038
        if (ost->encoding_needed) {
1039
            AVCodec *codec;
1040
            codec = avcodec_find_encoder(ost->st->codec.codec_id);
1041
            if (!codec) {
1042
                fprintf(stderr, "Unsupported codec for output stream #%d.%d\n", 
1043
                        ost->file_index, ost->index);
1044
                exit(1);
1045
            }
1046
            if (avcodec_open(&ost->st->codec, codec) < 0) {
1047
                fprintf(stderr, "Error while opening codec for stream #%d.%d - maybe incorrect parameters such as bit_rate, rate, width or height\n", 
1048
                        ost->file_index, ost->index);
1049
                exit(1);
1050
            }
1051
        }
1052
    }
1053

    
1054
    /* open each decoder */
1055
    for(i=0;i<nb_istreams;i++) {
1056
        ist = ist_table[i];
1057
        if (ist->decoding_needed) {
1058
            AVCodec *codec;
1059
            codec = avcodec_find_decoder(ist->st->codec.codec_id);
1060
            if (!codec) {
1061
                fprintf(stderr, "Unsupported codec (id=%d) for input stream #%d.%d\n", 
1062
                        ist->st->codec.codec_id, ist->file_index, ist->index);
1063
                exit(1);
1064
            }
1065
            if (avcodec_open(&ist->st->codec, codec) < 0) {
1066
                fprintf(stderr, "Error while opening codec for input stream #%d.%d\n", 
1067
                        ist->file_index, ist->index);
1068
                exit(1);
1069
            }
1070
            //if (ist->st->codec.codec_type == CODEC_TYPE_VIDEO)
1071
            //    ist->st->codec.flags |= CODEC_FLAG_REPEAT_FIELD;
1072
            ist->frame_decoded = 1;
1073
        }
1074
    }
1075

    
1076
    /* init pts */
1077
    for(i=0;i<nb_istreams;i++) {
1078
        ist = ist_table[i];
1079
    }
1080
    
1081
    /* compute buffer size max (should use a complete heuristic) */
1082
    for(i=0;i<nb_input_files;i++) {
1083
        file_table[i].buffer_size_max = 2048;
1084
    }
1085

    
1086
    /* open files and write file headers */
1087
    for(i=0;i<nb_output_files;i++) {
1088
        os = output_files[i];
1089
        if (av_write_header(os) < 0) {
1090
            fprintf(stderr, "Could not write header for output file #%d (incorrect codec paramters ?)\n", i);
1091
            ret = -EINVAL;
1092
            goto fail;
1093
        }
1094
    }
1095

    
1096
#ifndef CONFIG_WIN32
1097
    if (!do_play) {
1098
        fprintf(stderr, "Press [q] to stop encoding\n");
1099
    } else {
1100
        fprintf(stderr, "Press [q] to stop playing\n");
1101
    }
1102
#endif
1103
    term_init();
1104

    
1105
    stream_no_data = 0;
1106
    key = -1;
1107

    
1108
    for(;;) {
1109
        int file_index, ist_index;
1110
        AVPacket pkt;
1111
        uint8_t *ptr;
1112
        int len;
1113
        uint8_t *data_buf;
1114
        int data_size, got_picture;
1115
        AVPicture picture;
1116
        short samples[AVCODEC_MAX_AUDIO_FRAME_SIZE / 2];
1117
        void *buffer_to_free;
1118
        double pts_min;
1119
        
1120
    redo:
1121
        /* if 'q' pressed, exits */
1122
        if (key) {
1123
            /* read_key() returns 0 on EOF */
1124
            key = read_key();
1125
            if (key == 'q')
1126
                break;
1127
        }
1128

    
1129
        /* select the stream that we must read now by looking at the
1130
           smallest output pts */
1131
        file_index = -1;
1132
        pts_min = 1e10;
1133
        for(i=0;i<nb_ostreams;i++) {
1134
            double pts;
1135
            ost = ost_table[i];
1136
            os = output_files[ost->file_index];
1137
            ist = ist_table[ost->source_index];
1138
            pts = (double)ost->st->pts.val * os->pts_num / os->pts_den;
1139
            if (!file_table[ist->file_index].eof_reached && 
1140
                pts < pts_min) {
1141
                pts_min = pts;
1142
                file_index = ist->file_index;
1143
            }
1144
        }
1145
        /* if none, if is finished */
1146
        if (file_index < 0) {
1147
            break;
1148
        }
1149

    
1150
        /* finish if recording time exhausted */
1151
        if (recording_time > 0 && pts_min >= (recording_time / 1000000.0))
1152
            break;
1153

    
1154
        /* read a packet from it and output it in the fifo */
1155
        is = input_files[file_index];
1156
        if (av_read_packet(is, &pkt) < 0) {
1157
            file_table[file_index].eof_reached = 1;
1158
            continue;
1159
        }
1160
        if (!pkt.size) {
1161
            stream_no_data = is;
1162
        } else {
1163
            stream_no_data = 0;
1164
        }
1165
        if (do_hex_dump) {
1166
            printf("stream #%d, size=%d:\n", pkt.stream_index, pkt.size);
1167
            av_hex_dump(pkt.data, pkt.size);
1168
        }
1169
        /* the following test is needed in case new streams appear
1170
           dynamically in stream : we ignore them */
1171
        if (pkt.stream_index >= file_table[file_index].nb_streams)
1172
            goto discard_packet;
1173
        ist_index = file_table[file_index].ist_index + pkt.stream_index;
1174
        ist = ist_table[ist_index];
1175
        if (ist->discard)
1176
            goto discard_packet;
1177

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

    
1180
        len = pkt.size;
1181
        ptr = pkt.data;
1182
        pts_set = 0;
1183
        while (len > 0) {
1184
            int64_t ipts;
1185

    
1186
            ipts = AV_NOPTS_VALUE;
1187

    
1188
            /* decode the packet if needed */
1189
            data_buf = NULL; /* fail safe */
1190
            data_size = 0;
1191
            if (ist->decoding_needed) {
1192
                /* NOTE1: we only take into account the PTS if a new
1193
                   frame has begun (MPEG semantics) */
1194
                /* NOTE2: even if the fraction is not initialized,
1195
                   av_frac_set can be used to set the integer part */
1196
                if (ist->frame_decoded && 
1197
                    pkt.pts != AV_NOPTS_VALUE && 
1198
                    !pts_set) {
1199
                    ipts = pkt.pts;
1200
                    ist->frame_decoded = 0;
1201
                    pts_set = 1;
1202
                }
1203

    
1204
                switch(ist->st->codec.codec_type) {
1205
                case CODEC_TYPE_AUDIO:
1206
                    /* XXX: could avoid copy if PCM 16 bits with same
1207
                       endianness as CPU */
1208
                    ret = avcodec_decode_audio(&ist->st->codec, samples, &data_size,
1209
                                               ptr, len);
1210
                    if (ret < 0)
1211
                        goto fail_decode;
1212
                    /* Some bug in mpeg audio decoder gives */
1213
                    /* data_size < 0, it seems they are overflows */
1214
                    if (data_size <= 0) {
1215
                        /* no audio frame */
1216
                        ptr += ret;
1217
                        len -= ret;
1218
                        continue;
1219
                    }
1220
                    data_buf = (uint8_t *)samples;
1221
                    break;
1222
                case CODEC_TYPE_VIDEO:
1223
                    {
1224
                        AVFrame big_picture;
1225

    
1226
                        data_size = (ist->st->codec.width * ist->st->codec.height * 3) / 2;
1227
                        ret = avcodec_decode_video(&ist->st->codec, 
1228
                                                   &big_picture, &got_picture, ptr, len);
1229
                        picture= *(AVPicture*)&big_picture;
1230
                        ist->st->quality= big_picture.quality;
1231
                        if (ret < 0) {
1232
                        fail_decode:
1233
                            fprintf(stderr, "Error while decoding stream #%d.%d\n",
1234
                                    ist->file_index, ist->index);
1235
                            av_free_packet(&pkt);
1236
                            goto redo;
1237
                        }
1238
                        if (!got_picture) {
1239
                            /* no picture yet */
1240
                            ptr += ret;
1241
                            len -= ret;
1242
                            continue;
1243
                        }
1244
                                  
1245
                    }
1246
                    break;
1247
                default:
1248
                    goto fail_decode;
1249
                }
1250
            } else {
1251
                data_buf = ptr;
1252
                data_size = len;
1253
                ret = len;
1254
            }
1255
            ptr += ret;
1256
            len -= ret;
1257

    
1258
            buffer_to_free = 0;
1259
            if (ist->st->codec.codec_type == CODEC_TYPE_VIDEO) {
1260
                pre_process_video_frame(ist, &picture, &buffer_to_free);
1261
            }
1262

    
1263
            ist->frame_decoded = 1;
1264

    
1265
            /* frame rate emulation */
1266
            if (ist->st->codec.rate_emu) {
1267
                int64_t pts = av_rescale((int64_t) ist->frame * ist->st->codec.frame_rate_base, 1000000, ist->st->codec.frame_rate);
1268
                int64_t now = av_gettime() - ist->start;
1269
                if (pts > now)
1270
                    usleep(pts - now);
1271

    
1272
                ist->frame++;
1273
            }
1274

    
1275
#if 0
1276
            /* mpeg PTS deordering : if it is a P or I frame, the PTS
1277
               is the one of the next displayed one */
1278
            /* XXX: add mpeg4 too ? */
1279
            if (ist->st->codec.codec_id == CODEC_ID_MPEG1VIDEO) {
1280
                if (ist->st->codec.pict_type != B_TYPE) {
1281
                    int64_t tmp;
1282
                    tmp = ist->last_ip_pts;
1283
                    ist->last_ip_pts  = ist->frac_pts.val;
1284
                    ist->frac_pts.val = tmp;
1285
                }
1286
            }
1287
#endif
1288
            /* transcode raw format, encode packets and output them */
1289

    
1290
            for(i=0;i<nb_ostreams;i++) {
1291
                int frame_size;
1292

    
1293
                ost = ost_table[i];
1294
                if (ost->source_index == ist_index) {
1295
                    os = output_files[ost->file_index];
1296

    
1297
                    if (ipts != AV_NOPTS_VALUE) {
1298
#if 0
1299
                        printf("%d: got pts=%f %f\n", 
1300
                               i, pkt.pts / 90000.0, 
1301
                               (ipts - ost->st->pts.val) / 90000.0);
1302
#endif
1303
                        /* set the input output pts pairs */
1304
                        ost->sync_ipts = (double)ipts * is->pts_num / 
1305
                            is->pts_den;
1306
                        /* XXX: take into account the various fifos,
1307
                           in particular for audio */
1308
                        ost->sync_opts = ost->st->pts.val;
1309
                        //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); 
1310
                    } else {
1311
                        //printf("pts.val=%lld\n", ost->st->pts.val); 
1312
                        ost->sync_ipts = AV_NOPTS_VALUE;
1313
                    }
1314

    
1315
                    if (ost->encoding_needed) {
1316
                        switch(ost->st->codec.codec_type) {
1317
                        case CODEC_TYPE_AUDIO:
1318
                            do_audio_out(os, ost, ist, data_buf, data_size);
1319
                            break;
1320
                        case CODEC_TYPE_VIDEO:
1321
                            /* find an audio stream for synchro */
1322
                            {
1323
                                int i;
1324
                                AVOutputStream *audio_sync, *ost1;
1325
                                audio_sync = NULL;
1326
                                for(i=0;i<nb_ostreams;i++) {
1327
                                    ost1 = ost_table[i];
1328
                                    if (ost1->file_index == ost->file_index &&
1329
                                        ost1->st->codec.codec_type == CODEC_TYPE_AUDIO) {
1330
                                        audio_sync = ost1;
1331
                                        break;
1332
                                    }
1333
                                }
1334

    
1335
                                do_video_out(os, ost, ist, &picture, &frame_size, audio_sync);
1336
                                if (do_vstats && frame_size)
1337
                                    do_video_stats(os, ost, frame_size);
1338
                            }
1339
                            break;
1340
                        default:
1341
                            av_abort();
1342
                        }
1343
                    } else {
1344
                        AVFrame avframe;
1345
                                                
1346
                        /* no reencoding needed : output the packet directly */
1347
                        /* force the input stream PTS */
1348
                        
1349
                        //XXX/FIXME set keyframe flag from demuxer (or optionally from decoder)
1350
                        memset(&avframe, 0, sizeof(AVFrame));
1351
                        ost->st->codec.coded_frame= &avframe;
1352
                        
1353
                        av_write_frame(os, ost->index, data_buf, data_size);
1354
                        ost->st->codec.frame_number++;
1355
                        ost->frame_number++;
1356
                    }
1357
                }
1358
            }
1359
            av_free(buffer_to_free);
1360
            ipts = AV_NOPTS_VALUE;
1361
        }
1362
    discard_packet:
1363
        av_free_packet(&pkt);
1364
        
1365
        /* dump report by using the output first video and audio streams */
1366
        print_report(output_files, ost_table, nb_ostreams, 0);
1367
    }
1368
    term_exit();
1369

    
1370
    /* dump report by using the first video and audio streams */
1371
    print_report(output_files, ost_table, nb_ostreams, 1);
1372

    
1373
    /* close each encoder */
1374
    for(i=0;i<nb_ostreams;i++) {
1375
        ost = ost_table[i];
1376
        if (ost->encoding_needed) {
1377
            av_freep(&ost->st->codec.stats_in);
1378
            avcodec_close(&ost->st->codec);
1379
        }
1380
    }
1381
    
1382
    /* close each decoder */
1383
    for(i=0;i<nb_istreams;i++) {
1384
        ist = ist_table[i];
1385
        if (ist->decoding_needed) {
1386
            avcodec_close(&ist->st->codec);
1387
        }
1388
    }
1389
    
1390

    
1391
    /* write the trailer if needed and close file */
1392
    for(i=0;i<nb_output_files;i++) {
1393
        os = output_files[i];
1394
        av_write_trailer(os);
1395
    }
1396
    /* finished ! */
1397
    
1398
    ret = 0;
1399
 fail1:
1400
    av_free(file_table);
1401

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

    
1435
#if 0
1436
int file_read(const char *filename)
1437
{
1438
    URLContext *h;
1439
    unsigned char buffer[1024];
1440
    int len, i;
1441

1442
    if (url_open(&h, filename, O_RDONLY) < 0) {
1443
        printf("could not open '%s'\n", filename);
1444
        return -1;
1445
    }
1446
    for(;;) {
1447
        len = url_read(h, buffer, sizeof(buffer));
1448
        if (len <= 0)
1449
            break;
1450
        for(i=0;i<len;i++) putchar(buffer[i]);
1451
    }
1452
    url_close(h);
1453
    return 0;
1454
}
1455
#endif
1456

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

    
1479
static void opt_image_format(const char *arg)
1480
{
1481
    AVImageFormat *f;
1482
    
1483
    for(f = first_image_format; f != NULL; f = f->next) {
1484
        if (!strcmp(arg, f->name))
1485
            break;
1486
    }
1487
    if (!f) {
1488
        fprintf(stderr, "Unknown image format: '%s'\n", arg);
1489
        exit(1);
1490
    }
1491
    image_format = f;
1492
}
1493

    
1494
static void opt_format(const char *arg)
1495
{
1496
    /* compatibility stuff for pgmyuv */
1497
    if (!strcmp(arg, "pgmyuv")) {
1498
        opt_image_format(arg);
1499
        arg = "image";
1500
    }
1501

    
1502
    file_iformat = av_find_input_format(arg);
1503
    file_oformat = guess_format(arg, NULL, NULL);
1504
    if (!file_iformat && !file_oformat) {
1505
        fprintf(stderr, "Unknown input or output format: %s\n", arg);
1506
        exit(1);
1507
    }
1508
}
1509

    
1510
static void opt_video_bitrate(const char *arg)
1511
{
1512
    video_bit_rate = atoi(arg) * 1000;
1513
}
1514

    
1515
static void opt_video_bitrate_tolerance(const char *arg)
1516
{
1517
    video_bit_rate_tolerance = atoi(arg) * 1000;
1518
}
1519

    
1520
static void opt_video_bitrate_max(const char *arg)
1521
{
1522
    video_rc_max_rate = atoi(arg) * 1000;
1523
}
1524

    
1525
static void opt_video_bitrate_min(const char *arg)
1526
{
1527
    video_rc_min_rate = atoi(arg) * 1000;
1528
}
1529

    
1530
static void opt_video_buffer_size(const char *arg)
1531
{
1532
    video_rc_buffer_size = atoi(arg) * 1000;
1533
}
1534

    
1535
static void opt_video_rc_eq(char *arg)
1536
{
1537
    video_rc_eq = arg;
1538
}
1539

    
1540
static void opt_video_rc_override_string(char *arg)
1541
{
1542
    video_rc_override_string = arg;
1543
}
1544

    
1545

    
1546
static void opt_workaround_bugs(const char *arg)
1547
{
1548
    workaround_bugs = atoi(arg);
1549
}
1550

    
1551
static void opt_dct_algo(const char *arg)
1552
{
1553
    dct_algo = atoi(arg);
1554
}
1555

    
1556
static void opt_idct_algo(const char *arg)
1557
{
1558
    idct_algo = atoi(arg);
1559
}
1560

    
1561

    
1562
static void opt_error_resilience(const char *arg)
1563
{
1564
    error_resilience = atoi(arg);
1565
}
1566

    
1567
static void opt_error_concealment(const char *arg)
1568
{
1569
    error_concealment = atoi(arg);
1570
}
1571

    
1572
static void opt_debug(const char *arg)
1573
{
1574
    debug = atoi(arg);
1575
}
1576

    
1577
static void opt_frame_rate(const char *arg)
1578
{
1579
    frame_rate_base = DEFAULT_FRAME_RATE_BASE; //FIXME not optimal
1580
    frame_rate = (int)(strtod(arg, 0) * frame_rate_base + 0.5);
1581
    //FIXME parse fractions 
1582
}
1583

    
1584

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

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

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

    
1639
static void opt_frame_crop_right(const char *arg)
1640
{
1641
    frame_rightBand = atoi(arg);
1642
    if (frame_rightBand < 0) {
1643
        fprintf(stderr, "Incorrect right crop size\n");
1644
        exit(1);
1645
    }
1646
    if ((frame_rightBand % 2) != 0) {
1647
        fprintf(stderr, "Right crop size must be a multiple of 2\n");
1648
        exit(1);        
1649
    }
1650
    if ((frame_rightBand) >= frame_width){
1651
            fprintf(stderr, "Horizontal crop dimensions are outside the range of the original image.\nRemember to crop first and scale second.\n");
1652
        exit(1);
1653
    }
1654
    frame_width -= frame_rightBand;
1655
}
1656

    
1657
static void opt_frame_size(const char *arg)
1658
{
1659
    parse_image_size(&frame_width, &frame_height, arg);
1660
    if (frame_width <= 0 || frame_height <= 0) {
1661
        fprintf(stderr, "Incorrect frame size\n");
1662
        exit(1);
1663
    }
1664
    if ((frame_width % 2) != 0 || (frame_height % 2) != 0) {
1665
        fprintf(stderr, "Frame size must be a multiple of 2\n");
1666
        exit(1);
1667
    }
1668
}
1669

    
1670
static void opt_gop_size(const char *arg)
1671
{
1672
    gop_size = atoi(arg);
1673
}
1674

    
1675
static void opt_b_frames(const char *arg)
1676
{
1677
    b_frames = atoi(arg);
1678
    if (b_frames > FF_MAX_B_FRAMES) {
1679
        fprintf(stderr, "\nCannot have more than %d B frames, increase FF_MAX_B_FRAMES.\n", FF_MAX_B_FRAMES);
1680
        exit(1);
1681
    } else if (b_frames < 1) {
1682
        fprintf(stderr, "\nNumber of B frames must be higher than 0\n");
1683
        exit(1);
1684
    }
1685
}
1686

    
1687
static void opt_qscale(const char *arg)
1688
{
1689
    video_qscale = atoi(arg);
1690
    if (video_qscale < 0 ||
1691
        video_qscale > 31) {
1692
        fprintf(stderr, "qscale must be >= 1 and <= 31\n");
1693
        exit(1);
1694
    }
1695
}
1696

    
1697
static void opt_qmin(const char *arg)
1698
{
1699
    video_qmin = atoi(arg);
1700
    if (video_qmin < 0 ||
1701
        video_qmin > 31) {
1702
        fprintf(stderr, "qmin must be >= 1 and <= 31\n");
1703
        exit(1);
1704
    }
1705
}
1706

    
1707
static void opt_qmax(const char *arg)
1708
{
1709
    video_qmax = atoi(arg);
1710
    if (video_qmax < 0 ||
1711
        video_qmax > 31) {
1712
        fprintf(stderr, "qmax must be >= 1 and <= 31\n");
1713
        exit(1);
1714
    }
1715
}
1716

    
1717
static void opt_mb_qmin(const char *arg)
1718
{
1719
    video_mb_qmin = atoi(arg);
1720
    if (video_mb_qmin < 0 ||
1721
        video_mb_qmin > 31) {
1722
        fprintf(stderr, "qmin must be >= 1 and <= 31\n");
1723
        exit(1);
1724
    }
1725
}
1726

    
1727
static void opt_mb_qmax(const char *arg)
1728
{
1729
    video_mb_qmax = atoi(arg);
1730
    if (video_mb_qmax < 0 ||
1731
        video_mb_qmax > 31) {
1732
        fprintf(stderr, "qmax must be >= 1 and <= 31\n");
1733
        exit(1);
1734
    }
1735
}
1736

    
1737
static void opt_qdiff(const char *arg)
1738
{
1739
    video_qdiff = atoi(arg);
1740
    if (video_qdiff < 0 ||
1741
        video_qdiff > 31) {
1742
        fprintf(stderr, "qdiff must be >= 1 and <= 31\n");
1743
        exit(1);
1744
    }
1745
}
1746

    
1747
static void opt_qblur(const char *arg)
1748
{
1749
    video_qblur = atof(arg);
1750
}
1751

    
1752
static void opt_qcomp(const char *arg)
1753
{
1754
    video_qcomp = atof(arg);
1755
}
1756

    
1757
static void opt_rc_initial_cplx(const char *arg)
1758
{
1759
    video_rc_initial_cplx = atof(arg);
1760
}
1761
static void opt_b_qfactor(const char *arg)
1762
{
1763
    video_b_qfactor = atof(arg);
1764
}
1765
static void opt_i_qfactor(const char *arg)
1766
{
1767
    video_i_qfactor = atof(arg);
1768
}
1769
static void opt_b_qoffset(const char *arg)
1770
{
1771
    video_b_qoffset = atof(arg);
1772
}
1773
static void opt_i_qoffset(const char *arg)
1774
{
1775
    video_i_qoffset = atof(arg);
1776
}
1777

    
1778
static void opt_packet_size(const char *arg)
1779
{
1780
    packet_size= atoi(arg);
1781
}
1782

    
1783
static void opt_strict(const char *arg)
1784
{
1785
    strict= atoi(arg);
1786
}
1787

    
1788
static void opt_audio_bitrate(const char *arg)
1789
{
1790
    audio_bit_rate = atoi(arg) * 1000;
1791
}
1792

    
1793
static void opt_audio_rate(const char *arg)
1794
{
1795
    audio_sample_rate = atoi(arg);
1796
}
1797

    
1798
static void opt_audio_channels(const char *arg)
1799
{
1800
    audio_channels = atoi(arg);
1801
}
1802

    
1803
static void opt_video_device(const char *arg)
1804
{
1805
    video_device = av_strdup(arg);
1806
}
1807

    
1808
static void opt_video_channel(const char *arg)
1809
{
1810
    video_channel = strtol(arg, NULL, 0);
1811
}
1812

    
1813
static void opt_audio_device(const char *arg)
1814
{
1815
    audio_device = av_strdup(arg);
1816
}
1817

    
1818
static void opt_dv1394(const char *arg)
1819
{
1820
    video_grab_format = "dv1394";
1821
    audio_grab_format = NULL;
1822
}
1823

    
1824
static void opt_audio_codec(const char *arg)
1825
{
1826
    AVCodec *p;
1827

    
1828
    if (!strcmp(arg, "copy")) {
1829
        audio_stream_copy = 1;
1830
    } else {
1831
        p = first_avcodec;
1832
        while (p) {
1833
            if (!strcmp(p->name, arg) && p->type == CODEC_TYPE_AUDIO)
1834
                break;
1835
            p = p->next;
1836
        }
1837
        if (p == NULL) {
1838
            fprintf(stderr, "Unknown audio codec '%s'\n", arg);
1839
            exit(1);
1840
        } else {
1841
            audio_codec_id = p->id;
1842
        }
1843
    }
1844
}
1845

    
1846
static void add_frame_hooker(const char *arg)
1847
{
1848
    int argc = 0;
1849
    char *argv[64];
1850
    int i;
1851
    char *args = av_strdup(arg);
1852

    
1853
    argv[0] = strtok(args, " ");
1854
    while (argc < 62 && (argv[++argc] = strtok(NULL, " "))) {
1855
    }
1856

    
1857
    i = frame_hook_add(argc, argv);
1858

    
1859
    if (i != 0) {
1860
        fprintf(stderr, "Failed to add video hook function: %s\n", arg);
1861
        exit(1);
1862
    }
1863
}
1864

    
1865
const char *motion_str[] = {
1866
    "zero",
1867
    "full",
1868
    "log",
1869
    "phods",
1870
    "epzs",
1871
    "x1",
1872
    NULL,
1873
};
1874

    
1875
static void opt_motion_estimation(const char *arg)
1876
{
1877
    const char **p;
1878
    p = motion_str;
1879
    for(;;) {
1880
        if (!*p) {
1881
            fprintf(stderr, "Unknown motion estimation method '%s'\n", arg);
1882
            exit(1);
1883
        }
1884
        if (!strcmp(*p, arg))
1885
            break;
1886
        p++;
1887
    }
1888
    me_method = (p - motion_str) + 1;
1889
}
1890

    
1891
static void opt_video_codec(const char *arg)
1892
{
1893
    AVCodec *p;
1894

    
1895
    if (!strcmp(arg, "copy")) {
1896
        video_stream_copy = 1;
1897
    } else {
1898
        p = first_avcodec;
1899
        while (p) {
1900
            if (!strcmp(p->name, arg) && p->type == CODEC_TYPE_VIDEO)
1901
                break;
1902
            p = p->next;
1903
        }
1904
        if (p == NULL) {
1905
            fprintf(stderr, "Unknown video codec '%s'\n", arg);
1906
            exit(1);
1907
        } else {
1908
            video_codec_id = p->id;
1909
        }
1910
    }
1911
}
1912

    
1913
static void opt_map(const char *arg)
1914
{
1915
    AVStreamMap *m;
1916
    const char *p;
1917

    
1918
    p = arg;
1919
    m = &stream_maps[nb_stream_maps++];
1920

    
1921
    m->file_index = strtol(arg, (char **)&p, 0);
1922
    if (*p)
1923
        p++;
1924

    
1925
    m->stream_index = strtol(p, (char **)&p, 0);
1926
}
1927

    
1928
static void opt_recording_time(const char *arg)
1929
{
1930
    recording_time = parse_date(arg, 1);
1931
}
1932

    
1933
static void print_error(const char *filename, int err)
1934
{
1935
    switch(err) {
1936
    case AVERROR_NUMEXPECTED:
1937
        fprintf(stderr, "%s: Incorrect image filename syntax.\n"
1938
                "Use '%%d' to specify the image number:\n"
1939
                "  for img1.jpg, img2.jpg, ..., use 'img%%d.jpg';\n"
1940
                "  for img001.jpg, img002.jpg, ..., use 'img%%03d.jpg'.\n", 
1941
                filename);
1942
        break;
1943
    case AVERROR_INVALIDDATA:
1944
        fprintf(stderr, "%s: Error while parsing header\n", filename);
1945
        break;
1946
    case AVERROR_NOFMT:
1947
        fprintf(stderr, "%s: Unknown format\n", filename);
1948
        break;
1949
    default:
1950
        fprintf(stderr, "%s: Error while opening file\n", filename);
1951
        break;
1952
    }
1953
}
1954

    
1955
static void opt_input_file(const char *filename)
1956
{
1957
    AVFormatContext *ic;
1958
    AVFormatParameters params, *ap = &params;
1959
    int err, i, ret, rfps, rfps_base;
1960

    
1961
    if (!strcmp(filename, "-"))
1962
        filename = "pipe:";
1963

    
1964
    /* get default parameters from command line */
1965
    memset(ap, 0, sizeof(*ap));
1966
    ap->sample_rate = audio_sample_rate;
1967
    ap->channels = audio_channels;
1968
    ap->frame_rate = frame_rate;
1969
    ap->frame_rate_base = frame_rate_base;
1970
    ap->width = frame_width;
1971
    ap->height = frame_height;
1972
    ap->image_format = image_format;
1973

    
1974
    /* open the input file with generic libav function */
1975
    err = av_open_input_file(&ic, filename, file_iformat, 0, ap);
1976
    if (err < 0) {
1977
        print_error(filename, err);
1978
        exit(1);
1979
    }
1980
    
1981
    /* If not enough info to get the stream parameters, we decode the
1982
       first frames to get it. (used in mpeg case for example) */
1983
    ret = av_find_stream_info(ic);
1984
    if (ret < 0) {
1985
        fprintf(stderr, "%s: could not find codec parameters\n", filename);
1986
        exit(1);
1987
    }
1988

    
1989
    /* update the current parameters so that they match the one of the input stream */
1990
    for(i=0;i<ic->nb_streams;i++) {
1991
        AVCodecContext *enc = &ic->streams[i]->codec;
1992
        switch(enc->codec_type) {
1993
        case CODEC_TYPE_AUDIO:
1994
            //fprintf(stderr, "\nInput Audio channels: %d", enc->channels);
1995
            audio_channels = enc->channels;
1996
            audio_sample_rate = enc->sample_rate;
1997
            break;
1998
        case CODEC_TYPE_VIDEO:
1999
            frame_height = enc->height;
2000
            frame_width = enc->width;
2001
            rfps      = ic->streams[i]->r_frame_rate;
2002
            rfps_base = ic->streams[i]->r_frame_rate_base;
2003
            enc->workaround_bugs = workaround_bugs;
2004
            enc->error_resilience = error_resilience; 
2005
            enc->error_concealment = error_concealment; 
2006
            enc->idct_algo= idct_algo;
2007
            enc->debug= debug;
2008
/*            if(enc->codec->capabilities & CODEC_CAP_TRUNCATED)
2009
                enc->flags|= CODEC_FLAG_TRUNCATED; */
2010
            if(/*enc->codec_id==CODEC_ID_MPEG4 || */enc->codec_id==CODEC_ID_MPEG1VIDEO)
2011
                enc->flags|= CODEC_FLAG_TRUNCATED;
2012
            
2013
            if(bitexact)
2014
                enc->flags|= CODEC_FLAG_BITEXACT;
2015

    
2016
            assert(enc->frame_rate_base == rfps_base); // should be true for now
2017
            if (enc->frame_rate != rfps) { 
2018
                fprintf(stderr,"\nSeems that stream %d comes from film source: %2.2f->%2.2f\n",
2019
                    i, (float)enc->frame_rate / enc->frame_rate_base,
2020
                    (float)rfps / rfps_base);
2021
            }
2022
            /* update the current frame rate to match the stream frame rate */
2023
            frame_rate      = rfps;
2024
            frame_rate_base = rfps_base;
2025

    
2026
            enc->rate_emu = rate_emu;
2027
            break;
2028
        default:
2029
            av_abort();
2030
        }
2031
    }
2032
    
2033
    input_files[nb_input_files] = ic;
2034
    /* dump the file content */
2035
    dump_format(ic, nb_input_files, filename, 0);
2036
    nb_input_files++;
2037
    file_iformat = NULL;
2038
    file_oformat = NULL;
2039
    image_format = NULL;
2040

    
2041
    rate_emu = 0;
2042
}
2043

    
2044
static void check_audio_video_inputs(int *has_video_ptr, int *has_audio_ptr)
2045
{
2046
    int has_video, has_audio, i, j;
2047
    AVFormatContext *ic;
2048

    
2049
    has_video = 0;
2050
    has_audio = 0;
2051
    for(j=0;j<nb_input_files;j++) {
2052
        ic = input_files[j];
2053
        for(i=0;i<ic->nb_streams;i++) {
2054
            AVCodecContext *enc = &ic->streams[i]->codec;
2055
            switch(enc->codec_type) {
2056
            case CODEC_TYPE_AUDIO:
2057
                has_audio = 1;
2058
                break;
2059
            case CODEC_TYPE_VIDEO:
2060
                has_video = 1;
2061
                break;
2062
            default:
2063
                av_abort();
2064
            }
2065
        }
2066
    }
2067
    *has_video_ptr = has_video;
2068
    *has_audio_ptr = has_audio;
2069
}
2070

    
2071
static void opt_output_file(const char *filename)
2072
{
2073
    AVStream *st;
2074
    AVFormatContext *oc;
2075
    int use_video, use_audio, nb_streams, input_has_video, input_has_audio;
2076
    int codec_id;
2077
    AVFormatParameters params, *ap = &params;
2078

    
2079
    if (!strcmp(filename, "-"))
2080
        filename = "pipe:";
2081

    
2082
    oc = av_mallocz(sizeof(AVFormatContext));
2083

    
2084
    if (!file_oformat) {
2085
        file_oformat = guess_format(NULL, filename, NULL);
2086
        if (!file_oformat) {
2087
            fprintf(stderr, "Unable for find a suitable output format for '%s'\n",
2088
                    filename);
2089
            exit(1);
2090
        }
2091
    }
2092
    
2093
    oc->oformat = file_oformat;
2094

    
2095
    if (!strcmp(file_oformat->name, "ffm") && 
2096
        strstart(filename, "http:", NULL)) {
2097
        /* special case for files sent to ffserver: we get the stream
2098
           parameters from ffserver */
2099
        if (read_ffserver_streams(oc, filename) < 0) {
2100
            fprintf(stderr, "Could not read stream parameters from '%s'\n", filename);
2101
            exit(1);
2102
        }
2103
    } else {
2104
        use_video = file_oformat->video_codec != CODEC_ID_NONE;
2105
        use_audio = file_oformat->audio_codec != CODEC_ID_NONE;
2106

    
2107
        /* disable if no corresponding type found and at least one
2108
           input file */
2109
        if (nb_input_files > 0) {
2110
            check_audio_video_inputs(&input_has_video, &input_has_audio);
2111
            if (!input_has_video)
2112
                use_video = 0;
2113
            if (!input_has_audio)
2114
                use_audio = 0;
2115
        }
2116

    
2117
        /* manual disable */
2118
        if (audio_disable) {
2119
            use_audio = 0;
2120
        }
2121
        if (video_disable) {
2122
            use_video = 0;
2123
        }
2124
        
2125
        nb_streams = 0;
2126
        if (use_video) {
2127
            AVCodecContext *video_enc;
2128
            
2129
            st = av_mallocz(sizeof(AVStream));
2130
            if (!st) {
2131
                fprintf(stderr, "Could not alloc stream\n");
2132
                exit(1);
2133
            }
2134
            avcodec_get_context_defaults(&st->codec);
2135

    
2136
            video_enc = &st->codec;
2137
            if (video_stream_copy) {
2138
                st->stream_copy = 1;
2139
                video_enc->codec_type = CODEC_TYPE_VIDEO;
2140
            } else {
2141
                char *p;
2142
                int i;
2143
            
2144
                codec_id = file_oformat->video_codec;
2145
                if (video_codec_id != CODEC_ID_NONE)
2146
                    codec_id = video_codec_id;
2147
                
2148
                video_enc->codec_id = codec_id;
2149
                
2150
                video_enc->bit_rate = video_bit_rate;
2151
                video_enc->bit_rate_tolerance = video_bit_rate_tolerance;
2152
                video_enc->frame_rate = frame_rate; 
2153
                video_enc->frame_rate_base = frame_rate_base; 
2154
                
2155
                video_enc->width = frame_width;
2156
                video_enc->height = frame_height;
2157

    
2158
                if (!intra_only)
2159
                    video_enc->gop_size = gop_size;
2160
                else
2161
                    video_enc->gop_size = 0;
2162
                if (video_qscale || same_quality) {
2163
                    video_enc->flags |= CODEC_FLAG_QSCALE;
2164
                    st->quality = video_qscale;
2165
                }
2166
                
2167
                if(bitexact)
2168
                    video_enc->flags |= CODEC_FLAG_BITEXACT;
2169

    
2170
                if (use_hq) {
2171
                    video_enc->flags |= CODEC_FLAG_HQ;
2172
                }
2173
                   /* Fx */ 
2174
                if (use_umv) {
2175
                    video_enc->flags |= CODEC_FLAG_H263P_UMV;
2176
                }
2177
                   if (use_aic) {
2178
                    video_enc->flags |= CODEC_FLAG_H263P_AIC;
2179
                }
2180
                   /* /Fx */ 
2181
                if (use_4mv) {
2182
                    video_enc->flags |= CODEC_FLAG_HQ;
2183
                    video_enc->flags |= CODEC_FLAG_4MV;
2184
                }
2185
            
2186
                if(use_part)
2187
                    video_enc->flags |= CODEC_FLAG_PART;
2188
               
2189
            
2190
                if (b_frames) {
2191
                    video_enc->max_b_frames = b_frames;
2192
                    video_enc->b_frame_strategy = 0;
2193
                    video_enc->b_quant_factor = 2.0;
2194
                }
2195
            
2196
                video_enc->qmin = video_qmin;
2197
                video_enc->qmax = video_qmax;
2198
                video_enc->mb_qmin = video_mb_qmin;
2199
                video_enc->mb_qmax = video_mb_qmax;
2200
                video_enc->max_qdiff = video_qdiff;
2201
                video_enc->qblur = video_qblur;
2202
                video_enc->qcompress = video_qcomp;
2203
                video_enc->rc_eq = video_rc_eq;
2204
                video_enc->debug= debug;
2205
                
2206
                p= video_rc_override_string;
2207
                for(i=0; p; i++){
2208
                    int start, end, q;
2209
                    int e=sscanf(p, "%d,%d,%d", &start, &end, &q);
2210
                    if(e!=3){
2211
                        fprintf(stderr, "error parsing rc_override\n");
2212
                        exit(1);
2213
                    }
2214
                    video_enc->rc_override= 
2215
                        av_realloc(video_enc->rc_override, 
2216
                                   sizeof(RcOverride)*(i+1));
2217
                    video_enc->rc_override[i].start_frame= start;
2218
                    video_enc->rc_override[i].end_frame  = end;
2219
                    if(q>0){
2220
                        video_enc->rc_override[i].qscale= q;
2221
                        video_enc->rc_override[i].quality_factor= 1.0;
2222
                    }
2223
                    else{
2224
                        video_enc->rc_override[i].qscale= 0;
2225
                        video_enc->rc_override[i].quality_factor= -q/100.0;
2226
                    }
2227
                    p= strchr(p, '/');
2228
                    if(p) p++;
2229
                }
2230
                video_enc->rc_override_count=i;
2231

    
2232
                video_enc->rc_max_rate = video_rc_max_rate;
2233
                video_enc->rc_min_rate = video_rc_min_rate;
2234
                video_enc->rc_buffer_size = video_rc_buffer_size;
2235
                video_enc->rc_buffer_aggressivity= video_rc_buffer_aggressivity;
2236
                video_enc->rc_initial_cplx= video_rc_initial_cplx;
2237
                video_enc->i_quant_factor = video_i_qfactor;
2238
                video_enc->b_quant_factor = video_b_qfactor;
2239
                video_enc->i_quant_offset = video_i_qoffset;
2240
                video_enc->b_quant_offset = video_b_qoffset;
2241
                video_enc->dct_algo = dct_algo;
2242
                video_enc->idct_algo = idct_algo;
2243
                video_enc->strict_std_compliance = strict;
2244
                if(packet_size){
2245
                    video_enc->rtp_mode= 1;
2246
                    video_enc->rtp_payload_size= packet_size;
2247
                }
2248
            
2249
                if (do_psnr)
2250
                    video_enc->flags|= CODEC_FLAG_PSNR;
2251
            
2252
                video_enc->me_method = me_method;
2253

    
2254
                /* two pass mode */
2255
                if (do_pass) {
2256
                    if (do_pass == 1) {
2257
                        video_enc->flags |= CODEC_FLAG_PASS1;
2258
                    } else {
2259
                        video_enc->flags |= CODEC_FLAG_PASS2;
2260
                    }
2261
                }
2262
            }
2263
            oc->streams[nb_streams] = st;
2264
            nb_streams++;
2265
        }
2266
    
2267
        if (use_audio) {
2268
            AVCodecContext *audio_enc;
2269

    
2270
            st = av_mallocz(sizeof(AVStream));
2271
            if (!st) {
2272
                fprintf(stderr, "Could not alloc stream\n");
2273
                exit(1);
2274
            }
2275
            avcodec_get_context_defaults(&st->codec);
2276

    
2277
            audio_enc = &st->codec;
2278
            audio_enc->codec_type = CODEC_TYPE_AUDIO;
2279
            if (audio_stream_copy) {
2280
                st->stream_copy = 1;
2281
            } else {
2282
                codec_id = file_oformat->audio_codec;
2283
                if (audio_codec_id != CODEC_ID_NONE)
2284
                    codec_id = audio_codec_id;
2285
                audio_enc->codec_id = codec_id;
2286
                
2287
                audio_enc->bit_rate = audio_bit_rate;
2288
                audio_enc->sample_rate = audio_sample_rate;
2289
                /* For audio codecs other than AC3 we limit */
2290
                /* the number of coded channels to stereo   */
2291
                if (audio_channels > 2 && codec_id != CODEC_ID_AC3) {
2292
                    audio_enc->channels = 2;
2293
                } else
2294
                    audio_enc->channels = audio_channels;
2295
            }
2296
            oc->streams[nb_streams] = st;
2297
            nb_streams++;
2298
        }
2299

    
2300
        oc->nb_streams = nb_streams;
2301

    
2302
        if (!nb_streams) {
2303
            fprintf(stderr, "No audio or video streams available\n");
2304
            exit(1);
2305
        }
2306

    
2307
        if (str_title)
2308
            pstrcpy(oc->title, sizeof(oc->title), str_title);
2309
        if (str_author)
2310
            pstrcpy(oc->author, sizeof(oc->author), str_author);
2311
        if (str_copyright)
2312
            pstrcpy(oc->copyright, sizeof(oc->copyright), str_copyright);
2313
        if (str_comment)
2314
            pstrcpy(oc->comment, sizeof(oc->comment), str_comment);
2315
    }
2316

    
2317
    output_files[nb_output_files++] = oc;
2318

    
2319
    strcpy(oc->filename, filename);
2320

    
2321
    /* check filename in case of an image number is expected */
2322
    if (oc->oformat->flags & AVFMT_NEEDNUMBER) {
2323
        if (filename_number_test(oc->filename) < 0) {
2324
            print_error(oc->filename, AVERROR_NUMEXPECTED);
2325
            exit(1);
2326
        }
2327
    }
2328

    
2329
    if (!(oc->oformat->flags & AVFMT_NOFILE)) {
2330
        /* test if it already exists to avoid loosing precious files */
2331
        if (!file_overwrite && 
2332
            (strchr(filename, ':') == NULL ||
2333
             strstart(filename, "file:", NULL))) {
2334
            if (url_exist(filename)) {
2335
                int c;
2336
                
2337
                printf("File '%s' already exists. Overwrite ? [y/N] ", filename);
2338
                fflush(stdout);
2339
                c = getchar();
2340
                if (toupper(c) != 'Y') {
2341
                    fprintf(stderr, "Not overwriting - exiting\n");
2342
                    exit(1);
2343
                }
2344
            }
2345
        }
2346
        
2347
        /* open the file */
2348
        if (url_fopen(&oc->pb, filename, URL_WRONLY) < 0) {
2349
            fprintf(stderr, "Could not open '%s'\n", filename);
2350
            exit(1);
2351
        }
2352
    }
2353

    
2354
    memset(ap, 0, sizeof(*ap));
2355
    ap->image_format = image_format;
2356
    if (av_set_parameters(oc, ap) < 0) {
2357
        fprintf(stderr, "%s: Invalid encoding parameters\n",
2358
                oc->filename);
2359
        exit(1);
2360
    }
2361

    
2362
    /* reset some options */
2363
    file_oformat = NULL;
2364
    file_iformat = NULL;
2365
    image_format = NULL;
2366
    audio_disable = 0;
2367
    video_disable = 0;
2368
    audio_codec_id = CODEC_ID_NONE;
2369
    video_codec_id = CODEC_ID_NONE;
2370
    audio_stream_copy = 0;
2371
    video_stream_copy = 0;
2372
}
2373

    
2374
/* prepare dummy protocols for grab */
2375
static void prepare_grab(void)
2376
{
2377
    int has_video, has_audio, i, j;
2378
    AVFormatContext *oc;
2379
    AVFormatContext *ic;
2380
    AVFormatParameters vp1, *vp = &vp1;
2381
    AVFormatParameters ap1, *ap = &ap1;
2382
    
2383
    /* see if audio/video inputs are needed */
2384
    has_video = 0;
2385
    has_audio = 0;
2386
    memset(ap, 0, sizeof(*ap));
2387
    memset(vp, 0, sizeof(*vp));
2388
    for(j=0;j<nb_output_files;j++) {
2389
        oc = output_files[j];
2390
        for(i=0;i<oc->nb_streams;i++) {
2391
            AVCodecContext *enc = &oc->streams[i]->codec;
2392
            switch(enc->codec_type) {
2393
            case CODEC_TYPE_AUDIO:
2394
                if (enc->sample_rate > ap->sample_rate)
2395
                    ap->sample_rate = enc->sample_rate;
2396
                if (enc->channels > ap->channels)
2397
                    ap->channels = enc->channels;
2398
                has_audio = 1;
2399
                break;
2400
            case CODEC_TYPE_VIDEO:
2401
                if (enc->width > vp->width)
2402
                    vp->width = enc->width;
2403
                if (enc->height > vp->height)
2404
                    vp->height = enc->height;
2405
                
2406
                assert(enc->frame_rate_base == DEFAULT_FRAME_RATE_BASE);
2407
                if (enc->frame_rate > vp->frame_rate){
2408
                    vp->frame_rate      = enc->frame_rate;
2409
                    vp->frame_rate_base = enc->frame_rate_base;
2410
                }
2411
                has_video = 1;
2412
                break;
2413
            default:
2414
                av_abort();
2415
            }
2416
        }
2417
    }
2418
    
2419
    if (has_video == 0 && has_audio == 0) {
2420
        fprintf(stderr, "Output file must have at least one audio or video stream\n");
2421
        exit(1);
2422
    }
2423
    
2424
    if (has_video) {
2425
        AVInputFormat *fmt1;
2426
        fmt1 = av_find_input_format(video_grab_format);
2427
        vp->device  = video_device;
2428
        vp->channel = video_channel;
2429
        if (av_open_input_file(&ic, "", fmt1, 0, vp) < 0) {
2430
            fprintf(stderr, "Could not find video grab device\n");
2431
            exit(1);
2432
        }
2433
        /* by now video grab has one stream */
2434
        ic->streams[0]->r_frame_rate      = vp->frame_rate;
2435
        ic->streams[0]->r_frame_rate_base = vp->frame_rate_base;
2436
        input_files[nb_input_files] = ic;
2437
        dump_format(ic, nb_input_files, "", 0);
2438
        nb_input_files++;
2439
    }
2440
    if (has_audio && audio_grab_format) {
2441
        AVInputFormat *fmt1;
2442
        fmt1 = av_find_input_format(audio_grab_format);
2443
        ap->device = audio_device;
2444
        if (av_open_input_file(&ic, "", fmt1, 0, ap) < 0) {
2445
            fprintf(stderr, "Could not find audio grab device\n");
2446
            exit(1);
2447
        }
2448
        input_files[nb_input_files] = ic;
2449
        dump_format(ic, nb_input_files, "", 0);
2450
        nb_input_files++;
2451
    }
2452
}
2453

    
2454
/* open the necessary output devices for playing */
2455
static void prepare_play(void)
2456
{
2457
    int has_video, has_audio;
2458
    
2459
    check_audio_video_inputs(&has_video, &has_audio);
2460
        
2461
    /* manual disable */
2462
    if (audio_disable) {
2463
        has_audio = 0;
2464
    }
2465
    if (video_disable) {
2466
        has_video = 0;
2467
    }
2468
        
2469
    if (has_audio) {
2470
        file_oformat = guess_format("audio_device", NULL, NULL);
2471
        if (!file_oformat) {
2472
            fprintf(stderr, "Could not find audio device\n");
2473
            exit(1);
2474
        }
2475
        opt_output_file(audio_device?audio_device:"/dev/dsp");
2476
    }
2477

    
2478
    if (has_video) {
2479
        file_oformat = guess_format("framebuffer_device", NULL, NULL);
2480
        if (!file_oformat) {
2481
            fprintf(stderr, "Could not find framebuffer device\n");
2482
            exit(1);
2483
        }
2484
        opt_output_file("");
2485
    }
2486
}
2487

    
2488
/* same option as mencoder */
2489
static void opt_pass(const char *pass_str)
2490
{
2491
    int pass;
2492
    pass = atoi(pass_str);
2493
    if (pass != 1 && pass != 2) {
2494
        fprintf(stderr, "pass number can be only 1 or 2\n");
2495
        exit(1);
2496
    }
2497
    do_pass = pass;
2498
}
2499

    
2500
#if defined(CONFIG_WIN32) || defined(CONFIG_OS2)
2501
static int64_t getutime(void)
2502
{
2503
  return av_gettime();
2504
}
2505
#else
2506
static int64_t getutime(void)
2507
{
2508
    struct rusage rusage;
2509

    
2510
    getrusage(RUSAGE_SELF, &rusage);
2511
    return (rusage.ru_utime.tv_sec * 1000000LL) + rusage.ru_utime.tv_usec;
2512
}
2513
#endif
2514

    
2515
extern int ffm_nopts;
2516

    
2517
static void opt_bitexact(void)
2518
{
2519
    bitexact=1;
2520
    /* disable generate of real time pts in ffm (need to be supressed anyway) */
2521
    ffm_nopts = 1;
2522
}
2523

    
2524
static void show_formats(void)
2525
{
2526
    AVInputFormat *ifmt;
2527
    AVOutputFormat *ofmt;
2528
    AVImageFormat *image_fmt;
2529
    URLProtocol *up;
2530
    AVCodec *p;
2531
    const char **pp;
2532

    
2533
    printf("Output audio/video file formats:");
2534
    for(ofmt = first_oformat; ofmt != NULL; ofmt = ofmt->next) {
2535
        printf(" %s", ofmt->name);
2536
    }
2537
    printf("\n");
2538

    
2539
    printf("Input audio/video file formats:");
2540
    for(ifmt = first_iformat; ifmt != NULL; ifmt = ifmt->next) {
2541
        printf(" %s", ifmt->name);
2542
    }
2543
    printf("\n");
2544

    
2545
    printf("Output image formats:");
2546
    for(image_fmt = first_image_format; image_fmt != NULL; 
2547
        image_fmt = image_fmt->next) {
2548
        if (image_fmt->img_write)
2549
            printf(" %s", image_fmt->name);
2550
    }
2551
    printf("\n");
2552

    
2553
    printf("Input image formats:");
2554
    for(image_fmt = first_image_format; image_fmt != NULL; 
2555
        image_fmt = image_fmt->next) {
2556
        if (image_fmt->img_read)
2557
            printf(" %s", image_fmt->name);
2558
    }
2559
    printf("\n");
2560

    
2561
    printf("Codecs:\n");
2562
    printf("  Encoders:");
2563
    for(p = first_avcodec; p != NULL; p = p->next) {
2564
        if (p->encode)
2565
            printf(" %s", p->name);
2566
    }
2567
    printf("\n");
2568

    
2569
    printf("  Decoders:");
2570
    for(p = first_avcodec; p != NULL; p = p->next) {
2571
        if (p->decode)
2572
            printf(" %s", p->name);
2573
    }
2574
    printf("\n");
2575

    
2576
    printf("Supported file protocols:");
2577
    for(up = first_protocol; up != NULL; up = up->next)
2578
        printf(" %s:", up->name);
2579
    printf("\n");
2580
    
2581
    printf("Frame size abbreviations: sqcif qcif cif 4cif\n");
2582
    printf("Motion estimation methods:");
2583
    pp = motion_str;
2584
    while (*pp) {
2585
        printf(" %s", *pp);
2586
        if ((pp - motion_str + 1) == ME_ZERO) 
2587
            printf("(fastest)");
2588
        else if ((pp - motion_str + 1) == ME_FULL) 
2589
            printf("(slowest)");
2590
        else if ((pp - motion_str + 1) == ME_EPZS) 
2591
            printf("(default)");
2592
        pp++;
2593
    }
2594
    printf("\n");
2595
    exit(1);
2596
}
2597

    
2598
void show_help(void)
2599
{
2600
    const char *prog;
2601
    const OptionDef *po;
2602
    int i, expert;
2603
    
2604
    prog = do_play ? "ffplay" : "ffmpeg";
2605

    
2606
    printf("%s version " FFMPEG_VERSION ", Copyright (c) 2000, 2001, 2002 Fabrice Bellard\n",
2607
           prog);
2608
    
2609
    if (!do_play) {
2610
        printf("usage: ffmpeg [[options] -i input_file]... {[options] outfile}...\n"
2611
               "Hyper fast MPEG1/MPEG4/H263/RV and AC3/MPEG audio encoder\n");
2612
    } else {
2613
        printf("usage: ffplay [options] input_file...\n"
2614
               "Simple audio player\n");
2615
    }
2616
           
2617
    printf("\n"
2618
           "Main options are:\n");
2619
    for(i=0;i<2;i++) {
2620
        if (i == 1)
2621
            printf("\nAdvanced options are:\n");
2622
        for(po = options; po->name != NULL; po++) {
2623
            char buf[64];
2624
            expert = (po->flags & OPT_EXPERT) != 0;
2625
            if (expert == i) {
2626
                strcpy(buf, po->name);
2627
                if (po->flags & HAS_ARG) {
2628
                    strcat(buf, " ");
2629
                    strcat(buf, po->argname);
2630
                }
2631
                printf("-%-17s  %s\n", buf, po->help);
2632
            }
2633
        }
2634
    }
2635

    
2636
    exit(1);
2637
}
2638

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

    
2731
int main(int argc, char **argv)
2732
{
2733
    int optindex, i;
2734
    const char *opt, *arg;
2735
    const OptionDef *po;
2736
    int64_t ti;
2737

    
2738
    av_register_all();
2739

    
2740
    /* detect if invoked as player */
2741
    i = strlen(argv[0]);
2742
    if (i >= 6 && !strcmp(argv[0] + i - 6, "ffplay"))
2743
        do_play = 1;
2744

    
2745
    if (argc <= 1)
2746
        show_help();
2747
    
2748
    /* parse options */
2749
    optindex = 1;
2750
    while (optindex < argc) {
2751
        opt = argv[optindex++];
2752
        
2753
        if (opt[0] == '-' && opt[1] != '\0') {
2754
            po = options;
2755
            while (po->name != NULL) {
2756
                if (!strcmp(opt + 1, po->name))
2757
                    break;
2758
                po++;
2759
            }
2760
            if (!po->name) {
2761
                fprintf(stderr, "%s: unrecognized option '%s'\n", argv[0], opt);
2762
                exit(1);
2763
            }
2764
            arg = NULL;
2765
            if (po->flags & HAS_ARG) {
2766
                arg = argv[optindex++];
2767
                if (!arg) {
2768
                    fprintf(stderr, "%s: missing argument for option '%s'\n", argv[0], opt);
2769
                    exit(1);
2770
                }
2771
            }
2772
            if (po->flags & OPT_STRING) {
2773
                char *str;
2774
                str = av_strdup(arg);
2775
                *po->u.str_arg = str;
2776
            } else if (po->flags & OPT_BOOL) {
2777
                *po->u.int_arg = 1;
2778
            } else {
2779
                po->u.func_arg(arg);
2780
            }
2781
        } else {
2782
            if (!do_play) {
2783
                opt_output_file(opt);
2784
            } else {
2785
                opt_input_file(opt);
2786
            }
2787
        }
2788
    }
2789

    
2790

    
2791
    if (!do_play) {
2792
        /* file converter / grab */
2793
        if (nb_output_files <= 0) {
2794
            fprintf(stderr, "Must supply at least one output file\n");
2795
            exit(1);
2796
        }
2797
        
2798
        if (nb_input_files == 0) {
2799
            prepare_grab();
2800
        }
2801
    } else {
2802
        /* player */
2803
        if (nb_input_files <= 0) {
2804
            fprintf(stderr, "Must supply at least one input file\n");
2805
            exit(1);
2806
        }
2807
        prepare_play();
2808
    }
2809

    
2810
    ti = getutime();
2811
    av_encode(output_files, nb_output_files, input_files, nb_input_files, 
2812
              stream_maps, nb_stream_maps);
2813
    ti = getutime() - ti;
2814
    if (do_benchmark) {
2815
        printf("bench: utime=%0.3fs\n", ti / 1000000.0);
2816
    }
2817

    
2818
    /* close files */
2819
    for(i=0;i<nb_output_files;i++) {
2820
        /* maybe av_close_output_file ??? */
2821
        AVFormatContext *s = output_files[i];
2822
        int j;
2823
        if (!(s->oformat->flags & AVFMT_NOFILE))
2824
            url_fclose(&s->pb);
2825
        for(j=0;j<s->nb_streams;j++)
2826
            av_free(s->streams[j]);
2827
        av_free(s);
2828
    }
2829
    for(i=0;i<nb_input_files;i++)
2830
        av_close_input_file(input_files[i]);
2831

    
2832
    av_free_static();
2833

    
2834
    
2835
#ifdef POWERPC_TBL_PERFORMANCE_REPORT
2836
    extern void powerpc_display_perf_report(void);
2837
    powerpc_display_perf_report();
2838
#endif /* POWERPC_TBL_PERFORMANCE_REPORT */
2839

    
2840
    return 0;
2841
}