Statistics
| Branch: | Revision:

ffmpeg / ffmpeg.c @ 0da71265

History | View | Annotate | Download (91.6 KB)

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
456
#define VIDEO_BUFFER_SIZE (1024*1024)
457

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

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

    
464
    *frame_size = 0;
465

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

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

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

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

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

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

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

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

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

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

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

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

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

    
695

    
696
    oc = output_files[0];
697

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1187
            ipts = AV_NOPTS_VALUE;
1188

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

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

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

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

    
1264
            ist->frame_decoded = 1;
1265

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

    
1273
                ist->frame++;
1274
            }
1275

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1546

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

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

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

    
1562

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

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

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

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

    
1585

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1858
    i = frame_hook_add(argc, argv);
1859

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
2042
    rate_emu = 0;
2043
}
2044

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
2301
        oc->nb_streams = nb_streams;
2302

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

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

    
2318
    output_files[nb_output_files++] = oc;
2319

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

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

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

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

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

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

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

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

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

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

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

    
2516
extern int ffm_nopts;
2517

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

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

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

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

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

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

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

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

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

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

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

    
2637
    exit(1);
2638
}
2639

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

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

    
2739
    av_register_all();
2740

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

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

    
2791

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

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

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

    
2833
    av_free_static();
2834

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

    
2841
    return 0;
2842
}