Statistics
| Branch: | Revision:

ffmpeg / ffmpeg.c @ daed32f7

History | View | Annotate | Download (140 KB)

1
/*
2
 * FFmpeg main 
3
 * Copyright (c) 2000-2003 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 <limits.h>
21
#include "avformat.h"
22
#include "framehook.h"
23
#include "dsputil.h"
24

    
25
#ifndef CONFIG_WIN32
26
#include <unistd.h>
27
#include <fcntl.h>
28
#include <sys/ioctl.h>
29
#include <sys/time.h>
30
#include <termios.h>
31
#include <sys/resource.h>
32
#include <signal.h>
33
#endif
34
#ifdef CONFIG_OS2
35
#include <sys/types.h>
36
#include <sys/select.h>
37
#include <stdlib.h>
38
#endif
39
#undef time //needed because HAVE_AV_CONFIG_H is defined on top
40
#include <time.h>
41

    
42
#include "cmdutils.h"
43

    
44
#undef NDEBUG
45
#include <assert.h>
46

    
47
#if !defined(INFINITY) && defined(HUGE_VAL)
48
#define INFINITY HUGE_VAL
49
#endif
50

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

    
57
/** select an input file for an output file */
58
typedef struct AVMetaDataMap {
59
    int out_file;
60
    int in_file;
61
} AVMetaDataMap;
62

    
63
extern const OptionDef options[];
64

    
65
static void show_help(void);
66
static void show_license(void);
67

    
68
#define MAX_FILES 20
69

    
70
static AVFormatContext *input_files[MAX_FILES];
71
static int64_t input_files_ts_offset[MAX_FILES];
72
static int nb_input_files = 0;
73

    
74
static AVFormatContext *output_files[MAX_FILES];
75
static int nb_output_files = 0;
76

    
77
static AVStreamMap stream_maps[MAX_FILES];
78
static int nb_stream_maps;
79

    
80
static AVMetaDataMap meta_data_maps[MAX_FILES];
81
static int nb_meta_data_maps;
82

    
83
static AVInputFormat *file_iformat;
84
static AVOutputFormat *file_oformat;
85
static AVImageFormat *image_format;
86
static int frame_width  = 160;
87
static int frame_height = 128;
88
static float frame_aspect_ratio = 0;
89
static enum PixelFormat frame_pix_fmt = PIX_FMT_YUV420P;
90
static int frame_padtop  = 0;
91
static int frame_padbottom = 0;
92
static int frame_padleft  = 0;
93
static int frame_padright = 0;
94
static int padcolor[3] = {16,128,128}; /* default to black */
95
static int frame_topBand  = 0;
96
static int frame_bottomBand = 0;
97
static int frame_leftBand  = 0;
98
static int frame_rightBand = 0;
99
static int frame_rate = 25;
100
static int frame_rate_base = 1;
101
static int video_bit_rate = 200*1000;
102
static int video_bit_rate_tolerance = 4000*1000;
103
static float video_qscale = 0;
104
static int video_qmin = 2;
105
static int video_qmax = 31;
106
static int video_lmin = 2*FF_QP2LAMBDA;
107
static int video_lmax = 31*FF_QP2LAMBDA;
108
static int video_mb_qmin = 2;
109
static int video_mb_qmax = 31;
110
static int video_qdiff = 3;
111
static float video_qblur = 0.5;
112
static float video_qcomp = 0.5;
113
static uint16_t *intra_matrix = NULL;
114
static uint16_t *inter_matrix = NULL;
115
#if 0 //experimental, (can be removed)
116
static float video_rc_qsquish=1.0;
117
static float video_rc_qmod_amp=0;
118
static int video_rc_qmod_freq=0;
119
#endif
120
static char *video_rc_override_string=NULL;
121
static char *video_rc_eq="tex^qComp";
122
static int video_rc_buffer_size=0;
123
static float video_rc_buffer_aggressivity=1.0;
124
static int video_rc_max_rate=0;
125
static int video_rc_min_rate=0;
126
static float video_rc_initial_cplx=0;
127
static float video_b_qfactor = 1.25;
128
static float video_b_qoffset = 1.25;
129
static float video_i_qfactor = -0.8;
130
static float video_i_qoffset = 0.0;
131
static int video_intra_quant_bias= FF_DEFAULT_QUANT_BIAS;
132
static int video_inter_quant_bias= FF_DEFAULT_QUANT_BIAS;
133
static int me_method = ME_EPZS;
134
static int video_disable = 0;
135
static int video_codec_id = CODEC_ID_NONE;
136
static int video_codec_tag = 0;
137
static int same_quality = 0;
138
static int b_frames = 0;
139
static int mb_decision = FF_MB_DECISION_SIMPLE;
140
static int ildct_cmp = FF_CMP_VSAD;
141
static int mb_cmp = FF_CMP_SAD;
142
static int sub_cmp = FF_CMP_SAD;
143
static int cmp = FF_CMP_SAD;
144
static int pre_cmp = FF_CMP_SAD;
145
static int pre_me = 0;
146
static float lumi_mask = 0;
147
static float dark_mask = 0;
148
static float scplx_mask = 0;
149
static float tcplx_mask = 0;
150
static float p_mask = 0;
151
static int use_4mv = 0;
152
static int use_obmc = 0;
153
static int use_loop = 0;
154
static int use_aic = 0;
155
static int use_aiv = 0;
156
static int use_umv = 0;
157
static int use_ss = 0;
158
static int use_alt_scan = 0;
159
static int use_trell = 0;
160
static int use_scan_offset = 0;
161
static int use_qpel = 0;
162
static int use_qprd = 0;
163
static int use_cbprd = 0;
164
static int qns = 0;
165
static int closed_gop = 0;
166
static int strict_gop = 0;
167
static int do_deinterlace = 0;
168
static int do_interlace_dct = 0;
169
static int do_interlace_me = 0;
170
static int workaround_bugs = FF_BUG_AUTODETECT;
171
static int error_resilience = 2;
172
static int error_concealment = 3;
173
static int dct_algo = 0;
174
static int idct_algo = 0;
175
static int use_part = 0;
176
static int packet_size = 0;
177
static int error_rate = 0;
178
static int strict = 0;
179
static int top_field_first = -1;
180
static int noise_reduction = 0;
181
static int sc_threshold = 0;
182
static int debug = 0;
183
static int debug_mv = 0;
184
static int me_threshold = 0;
185
static int mb_threshold = 0;
186
static int intra_dc_precision = 8;
187
static int coder = 0;
188
static int context = 0;
189
static int predictor = 0;
190
static int video_profile = FF_PROFILE_UNKNOWN;
191
static int video_level = FF_LEVEL_UNKNOWN;
192
static int nsse_weight = 8;
193
static int subpel_quality= 8;
194
static int lowres= 0;
195
extern int loop_input; /* currently a hack */
196

    
197
static int gop_size = 12;
198
static int intra_only = 0;
199
static int audio_sample_rate = 44100;
200
static int audio_bit_rate = 64000;
201
static int audio_disable = 0;
202
static int audio_channels = 1;
203
static int audio_codec_id = CODEC_ID_NONE;
204
static int audio_codec_tag = 0;
205

    
206
static int mux_rate= 0;
207
static int mux_packet_size= 0;
208
static float mux_preload= 0.5;
209
static float mux_max_delay= 0.7;
210

    
211
static int64_t recording_time = 0;
212
static int64_t start_time = 0;
213
static int64_t rec_timestamp = 0;
214
static int64_t input_ts_offset = 0;
215
static int file_overwrite = 0;
216
static char *str_title = NULL;
217
static char *str_author = NULL;
218
static char *str_copyright = NULL;
219
static char *str_comment = NULL;
220
static int do_benchmark = 0;
221
static int do_hex_dump = 0;
222
static int do_pkt_dump = 0;
223
static int do_psnr = 0;
224
static int do_vstats = 0;
225
static int do_pass = 0;
226
static int bitexact = 0;
227
static char *pass_logfilename = NULL;
228
static int audio_stream_copy = 0;
229
static int video_stream_copy = 0;
230
static int video_sync_method= 1;
231
static int audio_sync_method= 0;
232
static int copy_ts= 0;
233

    
234
static int rate_emu = 0;
235

    
236
static char *video_grab_format = "video4linux";
237
static char *video_device = NULL;
238
static int  video_channel = 0;
239
static char *video_standard = "ntsc";
240

    
241
static char *audio_grab_format = "audio_device";
242
static char *audio_device = NULL;
243

    
244
static int using_stdin = 0;
245
static int using_vhook = 0;
246
static int verbose = 1;
247
static int thread_count= 1;
248
static int q_pressed = 0;
249
static int me_range = 0;
250
static int64_t video_size = 0;
251
static int64_t audio_size = 0;
252
static int64_t extra_size = 0;
253
static int nb_frames_dup = 0;
254
static int nb_frames_drop = 0;
255
static int input_sync;
256

    
257
#define DEFAULT_PASS_LOGFILENAME "ffmpeg2pass"
258

    
259
typedef struct AVOutputStream {
260
    int file_index;          /* file index */
261
    int index;               /* stream index in the output file */
262
    int source_index;        /* AVInputStream index */
263
    AVStream *st;            /* stream in the output file */
264
    int encoding_needed;     /* true if encoding needed for this stream */
265
    int frame_number;
266
    /* input pts and corresponding output pts
267
       for A/V sync */
268
    double sync_ipts;        /* dts from the AVPacket of the demuxer in second units */
269
    int64_t sync_opts;       /* output frame counter, could be changed to some true timestamp */ //FIXME look at frame_number
270
    /* video only */
271
    int video_resample;      /* video_resample and video_crop are mutually exclusive */
272
    AVFrame pict_tmp;      /* temporary image for resampling */
273
    ImgReSampleContext *img_resample_ctx; /* for image resampling */
274

    
275
    int video_crop;          /* video_resample and video_crop are mutually exclusive */
276
    int topBand;             /* cropping area sizes */
277
    int leftBand;
278
    
279
    int video_pad;           /* video_resample and video_pad are mutually exclusive */
280
    int padtop;              /* padding area sizes */
281
    int padbottom;
282
    int padleft;
283
    int padright;
284
    
285
    /* audio only */
286
    int audio_resample;
287
    ReSampleContext *resample; /* for audio resampling */
288
    FifoBuffer fifo;     /* for compression: one audio fifo per codec */
289
    FILE *logfile;
290
} AVOutputStream;
291

    
292
typedef struct AVInputStream {
293
    int file_index;
294
    int index;
295
    AVStream *st;
296
    int discard;             /* true if stream data should be discarded */
297
    int decoding_needed;     /* true if the packets must be decoded in 'raw_fifo' */
298
    int64_t sample_index;      /* current sample */
299

    
300
    int64_t       start;     /* time when read started */
301
    unsigned long frame;     /* current frame */
302
    int64_t       next_pts;  /* synthetic pts for cases where pkt.pts
303
                                is not defined */
304
    int64_t       pts;       /* current pts */
305
    int is_start;            /* is 1 at the start and after a discontinuity */
306
} AVInputStream;
307

    
308
typedef struct AVInputFile {
309
    int eof_reached;      /* true if eof reached */
310
    int ist_index;        /* index of first stream in ist_table */
311
    int buffer_size;      /* current total buffer size */
312
    int buffer_size_max;  /* buffer size at which we consider we can stop
313
                             buffering */
314
    int nb_streams;       /* nb streams we are aware of */
315
} AVInputFile;
316

    
317
#ifndef CONFIG_WIN32
318

    
319
/* init terminal so that we can grab keys */
320
static struct termios oldtty;
321

    
322
static void term_exit(void)
323
{
324
    tcsetattr (0, TCSANOW, &oldtty);
325
}
326

    
327
static volatile sig_atomic_t received_sigterm = 0;
328

    
329
static void
330
sigterm_handler(int sig)
331
{
332
    received_sigterm = sig;
333
    term_exit();
334
}
335

    
336
static void term_init(void)
337
{
338
    struct termios tty;
339

    
340
    tcgetattr (0, &tty);
341
    oldtty = tty;
342

    
343
    tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
344
                          |INLCR|IGNCR|ICRNL|IXON);
345
    tty.c_oflag |= OPOST;
346
    tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
347
    tty.c_cflag &= ~(CSIZE|PARENB);
348
    tty.c_cflag |= CS8;
349
    tty.c_cc[VMIN] = 1;
350
    tty.c_cc[VTIME] = 0;
351
    
352
    tcsetattr (0, TCSANOW, &tty);
353

    
354
    signal(SIGINT , sigterm_handler); /* Interrupt (ANSI).  */
355
    signal(SIGQUIT, sigterm_handler); /* Quit (POSIX).  */
356
    signal(SIGTERM, sigterm_handler); /* Termination (ANSI).  */
357
    /*
358
    register a function to be called at normal program termination
359
    */
360
    atexit(term_exit);
361
#ifdef CONFIG_BEOS_NETSERVER
362
    fcntl(0, F_SETFL, fcntl(0, F_GETFL) | O_NONBLOCK);
363
#endif
364
}
365

    
366
/* read a key without blocking */
367
static int read_key(void)
368
{
369
    int n = 1;
370
    unsigned char ch;
371
#ifndef CONFIG_BEOS_NETSERVER
372
    struct timeval tv;
373
    fd_set rfds;
374

    
375
    FD_ZERO(&rfds);
376
    FD_SET(0, &rfds);
377
    tv.tv_sec = 0;
378
    tv.tv_usec = 0;
379
    n = select(1, &rfds, NULL, NULL, &tv);
380
#endif
381
    if (n > 0) {
382
        n = read(0, &ch, 1);
383
        if (n == 1)
384
            return ch;
385

    
386
        return n;
387
    }
388
    return -1;
389
}
390

    
391
static int decode_interrupt_cb(void)
392
{
393
    return q_pressed || (q_pressed = read_key() == 'q');
394
}
395

    
396
#else
397

    
398
static volatile int received_sigterm = 0;
399

    
400
/* no interactive support */
401
static void term_exit(void)
402
{
403
}
404

    
405
static void term_init(void)
406
{
407
}
408

    
409
static int read_key(void)
410
{
411
    return 0;
412
}
413

    
414
#endif
415

    
416
static int read_ffserver_streams(AVFormatContext *s, const char *filename)
417
{
418
    int i, err;
419
    AVFormatContext *ic;
420

    
421
    err = av_open_input_file(&ic, filename, NULL, FFM_PACKET_SIZE, NULL);
422
    if (err < 0)
423
        return err;
424
    /* copy stream format */
425
    s->nb_streams = ic->nb_streams;
426
    for(i=0;i<ic->nb_streams;i++) {
427
        AVStream *st;
428

    
429
        st = av_mallocz(sizeof(AVStream));
430
        memcpy(st, ic->streams[i], sizeof(AVStream));
431
        s->streams[i] = st;
432
    }
433

    
434
    av_close_input_file(ic);
435
    return 0;
436
}
437

    
438
#define MAX_AUDIO_PACKET_SIZE (128 * 1024)
439

    
440
static void do_audio_out(AVFormatContext *s, 
441
                         AVOutputStream *ost, 
442
                         AVInputStream *ist,
443
                         unsigned char *buf, int size)
444
{
445
    uint8_t *buftmp;
446
    static uint8_t *audio_buf = NULL;
447
    static uint8_t *audio_out = NULL;
448
    const int audio_out_size= 4*MAX_AUDIO_PACKET_SIZE;
449

    
450
    int size_out, frame_bytes, ret;
451
    AVCodecContext *enc= &ost->st->codec;
452

    
453
    /* SC: dynamic allocation of buffers */
454
    if (!audio_buf)
455
        audio_buf = av_malloc(2*MAX_AUDIO_PACKET_SIZE);
456
    if (!audio_out)
457
        audio_out = av_malloc(audio_out_size);
458
    if (!audio_buf || !audio_out)
459
        return;               /* Should signal an error ! */
460

    
461
    if(audio_sync_method){
462
        double delta = ost->sync_ipts * enc->sample_rate - ost->sync_opts 
463
                - fifo_size(&ost->fifo, ost->fifo.rptr)/(ost->st->codec.channels * 2);
464
        double idelta= delta*ist->st->codec.sample_rate / enc->sample_rate;
465
        int byte_delta= ((int)idelta)*2*ist->st->codec.channels;
466

    
467
        //FIXME resample delay
468
        if(fabs(delta) > 50){
469
            if(ist->is_start){
470
                if(byte_delta < 0){
471
                    byte_delta= FFMAX(byte_delta, -size);
472
                    size += byte_delta;
473
                    buf  -= byte_delta;
474
                    if(verbose > 2)
475
                        fprintf(stderr, "discarding %d audio samples\n", (int)-delta);
476
                    if(!size)
477
                        return;
478
                    ist->is_start=0;
479
                }else{
480
                    static uint8_t *input_tmp= NULL;
481
                    input_tmp= av_realloc(input_tmp, byte_delta + size);
482

    
483
                    if(byte_delta + size <= MAX_AUDIO_PACKET_SIZE)
484
                        ist->is_start=0;
485
                    else
486
                        byte_delta= MAX_AUDIO_PACKET_SIZE - size;
487

    
488
                    memset(input_tmp, 0, byte_delta);
489
                    memcpy(input_tmp + byte_delta, buf, size);
490
                    buf= input_tmp;
491
                    size += byte_delta;
492
                    if(verbose > 2)
493
                        fprintf(stderr, "adding %d audio samples of silence\n", (int)delta);
494
                }
495
            }else if(audio_sync_method>1){
496
                int comp= clip(delta, -audio_sync_method, audio_sync_method);
497
                assert(ost->audio_resample);
498
                if(verbose > 2)
499
                    fprintf(stderr, "compensating audio timestamp drift:%f compensation:%d in:%d\n", delta, comp, enc->sample_rate);
500
//                fprintf(stderr, "drift:%f len:%d opts:%lld ipts:%lld fifo:%d\n", delta, -1, ost->sync_opts, (int64_t)(ost->sync_ipts * enc->sample_rate), fifo_size(&ost->fifo, ost->fifo.rptr)/(ost->st->codec.channels * 2));
501
                av_resample_compensate(*(struct AVResampleContext**)ost->resample, comp, enc->sample_rate);
502
            }
503
        } 
504
    }else
505
        ost->sync_opts= lrintf(ost->sync_ipts * enc->sample_rate)
506
                        - fifo_size(&ost->fifo, ost->fifo.rptr)/(ost->st->codec.channels * 2); //FIXME wrong
507

    
508
    if (ost->audio_resample) {
509
        buftmp = audio_buf;
510
        size_out = audio_resample(ost->resample, 
511
                                  (short *)buftmp, (short *)buf,
512
                                  size / (ist->st->codec.channels * 2));
513
        size_out = size_out * enc->channels * 2;
514
    } else {
515
        buftmp = buf;
516
        size_out = size;
517
    }
518

    
519
    /* now encode as many frames as possible */
520
    if (enc->frame_size > 1) {
521
        /* output resampled raw samples */
522
        fifo_write(&ost->fifo, buftmp, size_out, 
523
                   &ost->fifo.wptr);
524

    
525
        frame_bytes = enc->frame_size * 2 * enc->channels;
526
        
527
        while (fifo_read(&ost->fifo, audio_buf, frame_bytes, 
528
                     &ost->fifo.rptr) == 0) {
529
            AVPacket pkt;
530
            av_init_packet(&pkt);
531

    
532
            ret = avcodec_encode_audio(enc, audio_out, audio_out_size, 
533
                                       (short *)audio_buf);
534
            audio_size += ret;
535
            pkt.stream_index= ost->index;
536
            pkt.data= audio_out;
537
            pkt.size= ret;
538
            if(enc->coded_frame)
539
                pkt.pts= enc->coded_frame->pts;
540
            pkt.flags |= PKT_FLAG_KEY;
541
            av_interleaved_write_frame(s, &pkt);
542
            
543
            ost->sync_opts += enc->frame_size;
544
        }
545
    } else {
546
        AVPacket pkt;
547
        av_init_packet(&pkt);
548

    
549
        ost->sync_opts += size_out / (2 * enc->channels);
550

    
551
        /* output a pcm frame */
552
        /* XXX: change encoding codec API to avoid this ? */
553
        switch(enc->codec->id) {
554
        case CODEC_ID_PCM_S16LE:
555
        case CODEC_ID_PCM_S16BE:
556
        case CODEC_ID_PCM_U16LE:
557
        case CODEC_ID_PCM_U16BE:
558
            break;
559
        default:
560
            size_out = size_out >> 1;
561
            break;
562
        }
563
        ret = avcodec_encode_audio(enc, audio_out, size_out, 
564
                                   (short *)buftmp);
565
        audio_size += ret;
566
        pkt.stream_index= ost->index;
567
        pkt.data= audio_out;
568
        pkt.size= ret;
569
        if(enc->coded_frame)
570
            pkt.pts= enc->coded_frame->pts;
571
        pkt.flags |= PKT_FLAG_KEY;
572
        av_interleaved_write_frame(s, &pkt);
573
    }
574
}
575

    
576
static void pre_process_video_frame(AVInputStream *ist, AVPicture *picture, void **bufp)
577
{
578
    AVCodecContext *dec;
579
    AVPicture *picture2;
580
    AVPicture picture_tmp;
581
    uint8_t *buf = 0;
582

    
583
    dec = &ist->st->codec;
584

    
585
    /* deinterlace : must be done before any resize */
586
    if (do_deinterlace || using_vhook) {
587
        int size;
588

    
589
        /* create temporary picture */
590
        size = avpicture_get_size(dec->pix_fmt, dec->width, dec->height);
591
        buf = av_malloc(size);
592
        if (!buf)
593
            return;
594
        
595
        picture2 = &picture_tmp;
596
        avpicture_fill(picture2, buf, dec->pix_fmt, dec->width, dec->height);
597

    
598
        if (do_deinterlace){
599
            if(avpicture_deinterlace(picture2, picture, 
600
                                     dec->pix_fmt, dec->width, dec->height) < 0) {
601
                /* if error, do not deinterlace */
602
                av_free(buf);
603
                buf = NULL;
604
                picture2 = picture;
605
            }
606
        } else {
607
            if (img_convert(picture2, dec->pix_fmt, picture, 
608
                            dec->pix_fmt, dec->width, dec->height) < 0) {
609
                /* if error, do not copy */
610
                av_free(buf);
611
                buf = NULL;
612
                picture2 = picture;
613
            }
614
        }
615
    } else {
616
        picture2 = picture;
617
    }
618

    
619
    frame_hook_process(picture2, dec->pix_fmt, dec->width, dec->height);
620

    
621
    if (picture != picture2)
622
        *picture = *picture2;
623
    *bufp = buf;
624
}
625

    
626
/* we begin to correct av delay at this threshold */
627
#define AV_DELAY_MAX 0.100
628

    
629

    
630
/* Expects img to be yuv420 */
631
static void fill_pad_region(AVPicture* img, int height, int width,
632
        int padtop, int padbottom, int padleft, int padright, int *color) {
633
  
634
    int i, y, shift;
635
    uint8_t *optr;
636
    
637
    for (i = 0; i < 3; i++) {
638
        shift = (i == 0) ? 0 : 1;
639
        
640
        if (padtop || padleft) {
641
            memset(img->data[i], color[i], (((img->linesize[i] * padtop) + 
642
                            padleft) >> shift));
643
        }
644

    
645
        if (padleft || padright) {
646
            optr = img->data[i] + (img->linesize[i] * (padtop >> shift)) +
647
                (img->linesize[i] - (padright >> shift));
648

    
649
            for (y = 0; y < ((height - (padtop + padbottom)) >> shift); y++) {
650
                memset(optr, color[i], (padleft + padright) >> shift);
651
                optr += img->linesize[i];
652
            }
653
        }
654
      
655
        if (padbottom) {
656
            optr = img->data[i] + (img->linesize[i] * ((height - padbottom) >> shift));
657
            memset(optr, color[i], ((img->linesize[i] * padbottom) >> shift));
658
        }
659
    }
660
}
661

    
662
static uint8_t *bit_buffer= NULL;
663

    
664
static void do_video_out(AVFormatContext *s, 
665
                         AVOutputStream *ost, 
666
                         AVInputStream *ist,
667
                         AVFrame *in_picture,
668
                         int *frame_size)
669
{
670
    int nb_frames, i, ret;
671
    AVFrame *final_picture, *formatted_picture;
672
    AVFrame picture_format_temp, picture_crop_temp;
673
    uint8_t *buf = NULL, *buf1 = NULL;
674
    AVCodecContext *enc, *dec;
675
    enum PixelFormat target_pixfmt;
676
    
677
#define VIDEO_BUFFER_SIZE (1024*1024)
678

    
679
    avcodec_get_frame_defaults(&picture_format_temp);
680
    avcodec_get_frame_defaults(&picture_crop_temp);
681

    
682
    enc = &ost->st->codec;
683
    dec = &ist->st->codec;
684

    
685
    /* by default, we output a single frame */
686
    nb_frames = 1;
687

    
688
    *frame_size = 0;
689

    
690
    if(video_sync_method){
691
        double vdelta;
692
        vdelta = ost->sync_ipts * enc->frame_rate / enc->frame_rate_base - ost->sync_opts;
693
        //FIXME set to 0.5 after we fix some dts/pts bugs like in avidec.c
694
        if (vdelta < -1.1)
695
            nb_frames = 0;
696
        else if (vdelta > 1.1)
697
            nb_frames = lrintf(vdelta - 1.1 + 0.5);
698
//fprintf(stderr, "vdelta:%f, ost->sync_opts:%lld, ost->sync_ipts:%f nb_frames:%d\n", vdelta, ost->sync_opts, ost->sync_ipts, nb_frames);
699
        if (nb_frames == 0){
700
            ++nb_frames_drop;
701
            if (verbose>2)
702
                fprintf(stderr, "*** drop!\n");
703
        }else if (nb_frames > 1) {
704
            nb_frames_dup += nb_frames;
705
            if (verbose>2)
706
                fprintf(stderr, "*** %d dup!\n", nb_frames-1);
707
        }
708
    }else
709
        ost->sync_opts= lrintf(ost->sync_ipts * enc->frame_rate / enc->frame_rate_base);
710

    
711
    if (nb_frames <= 0) 
712
        return;
713

    
714
    /* convert pixel format if needed */
715
    target_pixfmt = ost->video_resample || ost->video_pad
716
        ? PIX_FMT_YUV420P : enc->pix_fmt;
717
    if (dec->pix_fmt != target_pixfmt) {
718
        int size;
719

    
720
        /* create temporary picture */
721
        size = avpicture_get_size(target_pixfmt, dec->width, dec->height);
722
        buf = av_malloc(size);
723
        if (!buf)
724
            return;
725
        formatted_picture = &picture_format_temp;
726
        avpicture_fill((AVPicture*)formatted_picture, buf, target_pixfmt, dec->width, dec->height);
727
        
728
        if (img_convert((AVPicture*)formatted_picture, target_pixfmt, 
729
                        (AVPicture *)in_picture, dec->pix_fmt, 
730
                        dec->width, dec->height) < 0) {
731

    
732
            if (verbose >= 0)
733
                fprintf(stderr, "pixel format conversion not handled\n");
734

    
735
            goto the_end;
736
        }
737
    } else {
738
        formatted_picture = in_picture;
739
    }
740

    
741
    /* XXX: resampling could be done before raw format conversion in
742
       some cases to go faster */
743
    /* XXX: only works for YUV420P */
744
    if (ost->video_resample) {
745
        final_picture = &ost->pict_tmp;
746
        img_resample(ost->img_resample_ctx, (AVPicture*)final_picture, (AVPicture*)formatted_picture);
747
       
748
        if (ost->padtop || ost->padbottom || ost->padleft || ost->padright) {
749
            fill_pad_region((AVPicture*)final_picture, enc->height, enc->width,
750
                    ost->padtop, ost->padbottom, ost->padleft, ost->padright,
751
                    padcolor);
752
        }
753
        
754
        if (enc->pix_fmt != PIX_FMT_YUV420P) {
755
            int size;
756
            
757
            av_free(buf);
758
            /* create temporary picture */
759
            size = avpicture_get_size(enc->pix_fmt, enc->width, enc->height);
760
            buf = av_malloc(size);
761
            if (!buf)
762
                return;
763
            final_picture = &picture_format_temp;
764
            avpicture_fill((AVPicture*)final_picture, buf, enc->pix_fmt, enc->width, enc->height);
765
        
766
            if (img_convert((AVPicture*)final_picture, enc->pix_fmt, 
767
                            (AVPicture*)&ost->pict_tmp, PIX_FMT_YUV420P, 
768
                            enc->width, enc->height) < 0) {
769

    
770
                if (verbose >= 0)
771
                    fprintf(stderr, "pixel format conversion not handled\n");
772

    
773
                goto the_end;
774
            }
775
        }
776
    } else if (ost->video_crop) {
777
        picture_crop_temp.data[0] = formatted_picture->data[0] +
778
                (ost->topBand * formatted_picture->linesize[0]) + ost->leftBand;
779

    
780
        picture_crop_temp.data[1] = formatted_picture->data[1] +
781
                ((ost->topBand >> 1) * formatted_picture->linesize[1]) +
782
                (ost->leftBand >> 1);
783

    
784
        picture_crop_temp.data[2] = formatted_picture->data[2] +
785
                ((ost->topBand >> 1) * formatted_picture->linesize[2]) +
786
                (ost->leftBand >> 1);
787

    
788
        picture_crop_temp.linesize[0] = formatted_picture->linesize[0];
789
        picture_crop_temp.linesize[1] = formatted_picture->linesize[1];
790
        picture_crop_temp.linesize[2] = formatted_picture->linesize[2];
791
        final_picture = &picture_crop_temp;
792
    } else if (ost->video_pad) {
793
        final_picture = &ost->pict_tmp;
794

    
795
        for (i = 0; i < 3; i++) {
796
            uint8_t *optr, *iptr;
797
            int shift = (i == 0) ? 0 : 1;
798
            int y, yheight;
799
            
800
            /* set offset to start writing image into */
801
            optr = final_picture->data[i] + (((final_picture->linesize[i] * 
802
                            ost->padtop) + ost->padleft) >> shift);
803
            iptr = formatted_picture->data[i];
804

    
805
            yheight = (enc->height - ost->padtop - ost->padbottom) >> shift;
806
            for (y = 0; y < yheight; y++) {
807
                /* copy unpadded image row into padded image row */
808
                memcpy(optr, iptr, formatted_picture->linesize[i]);
809
                optr += final_picture->linesize[i];
810
                iptr += formatted_picture->linesize[i];
811
            }
812
        }
813

    
814
        fill_pad_region((AVPicture*)final_picture, enc->height, enc->width,
815
                ost->padtop, ost->padbottom, ost->padleft, ost->padright,
816
                padcolor);
817
        
818
        if (enc->pix_fmt != PIX_FMT_YUV420P) {
819
            int size;
820

    
821
            av_free(buf);
822
            /* create temporary picture */
823
            size = avpicture_get_size(enc->pix_fmt, enc->width, enc->height);
824
            buf = av_malloc(size);
825
            if (!buf)
826
                return;
827
            final_picture = &picture_format_temp;
828
            avpicture_fill((AVPicture*)final_picture, buf, enc->pix_fmt, enc->width, enc->height);
829

    
830
            if (img_convert((AVPicture*)final_picture, enc->pix_fmt, 
831
                        (AVPicture*)&ost->pict_tmp, PIX_FMT_YUV420P, 
832
                        enc->width, enc->height) < 0) {
833

    
834
                if (verbose >= 0)
835
                    fprintf(stderr, "pixel format conversion not handled\n");
836

    
837
                goto the_end;
838
            }
839
        }
840
    } else {
841
        final_picture = formatted_picture;
842
    }
843
    /* duplicates frame if needed */
844
    for(i=0;i<nb_frames;i++) {
845
        AVPacket pkt;
846
        av_init_packet(&pkt);
847
        pkt.stream_index= ost->index;
848

    
849
        if (s->oformat->flags & AVFMT_RAWPICTURE) {
850
            /* raw pictures are written as AVPicture structure to
851
               avoid any copies. We support temorarily the older
852
               method. */
853
            AVFrame* old_frame = enc->coded_frame;
854
            enc->coded_frame = dec->coded_frame; //FIXME/XXX remove this hack
855
            pkt.data= (uint8_t *)final_picture;
856
            pkt.size=  sizeof(AVPicture);
857
            if(dec->coded_frame)
858
                pkt.pts= dec->coded_frame->pts;
859
            if(dec->coded_frame && dec->coded_frame->key_frame)
860
                pkt.flags |= PKT_FLAG_KEY;
861

    
862
            av_interleaved_write_frame(s, &pkt);
863
            enc->coded_frame = old_frame;
864
        } else {
865
            AVFrame big_picture;
866

    
867
            big_picture= *final_picture;
868
            /* better than nothing: use input picture interlaced
869
               settings */
870
            big_picture.interlaced_frame = in_picture->interlaced_frame;
871
            if(do_interlace_me || do_interlace_dct){
872
                if(top_field_first == -1)
873
                    big_picture.top_field_first = in_picture->top_field_first;
874
                else
875
                    big_picture.top_field_first = top_field_first;
876
            }
877

    
878
            /* handles sameq here. This is not correct because it may
879
               not be a global option */
880
            if (same_quality) {
881
                big_picture.quality = ist->st->quality;
882
            }else
883
                big_picture.quality = ost->st->quality;
884
            if(!me_threshold)
885
                big_picture.pict_type = 0;
886
//            big_picture.pts = AV_NOPTS_VALUE;
887
            big_picture.pts= av_rescale(ost->sync_opts, AV_TIME_BASE*(int64_t)enc->frame_rate_base, enc->frame_rate);
888
//av_log(NULL, AV_LOG_DEBUG, "%lld -> encoder\n", ost->sync_opts);
889
            ret = avcodec_encode_video(enc, 
890
                                       bit_buffer, VIDEO_BUFFER_SIZE,
891
                                       &big_picture);
892
            //enc->frame_number = enc->real_pict_num;
893
            if(ret){
894
                pkt.data= bit_buffer;
895
                pkt.size= ret;
896
                if(enc->coded_frame)
897
                    pkt.pts= enc->coded_frame->pts;
898
/*av_log(NULL, AV_LOG_DEBUG, "encoder -> %lld/%lld\n", 
899
   pkt.pts != AV_NOPTS_VALUE ? av_rescale(pkt.pts, enc->frame_rate, AV_TIME_BASE*(int64_t)enc->frame_rate_base) : -1,
900
   pkt.dts != AV_NOPTS_VALUE ? av_rescale(pkt.dts, enc->frame_rate, AV_TIME_BASE*(int64_t)enc->frame_rate_base) : -1);*/
901

    
902
                if(enc->coded_frame && enc->coded_frame->key_frame)
903
                    pkt.flags |= PKT_FLAG_KEY;
904
                av_interleaved_write_frame(s, &pkt);
905
                *frame_size = ret;
906
                //fprintf(stderr,"\nFrame: %3d %3d size: %5d type: %d",
907
                //        enc->frame_number-1, enc->real_pict_num, ret,
908
                //        enc->pict_type);
909
                /* if two pass, output log */
910
                if (ost->logfile && enc->stats_out) {
911
                    fprintf(ost->logfile, "%s", enc->stats_out);
912
                }
913
            }
914
        }
915
        ost->sync_opts++;
916
        ost->frame_number++;
917
    }
918
 the_end:
919
    av_free(buf);
920
    av_free(buf1);
921
}
922

    
923
static double psnr(double d){
924
    if(d==0) return INFINITY;
925
    return -10.0*log(d)/log(10.0);
926
}
927

    
928
static void do_video_stats(AVFormatContext *os, AVOutputStream *ost, 
929
                           int frame_size)
930
{
931
    static FILE *fvstats=NULL;
932
    char filename[40];
933
    time_t today2;
934
    struct tm *today;
935
    AVCodecContext *enc;
936
    int frame_number;
937
    int64_t ti;
938
    double ti1, bitrate, avg_bitrate;
939
    
940
    if (!fvstats) {
941
        today2 = time(NULL);
942
        today = localtime(&today2);
943
        sprintf(filename, "vstats_%02d%02d%02d.log", today->tm_hour,
944
                                               today->tm_min,
945
                                               today->tm_sec);
946
        fvstats = fopen(filename,"w");
947
        if (!fvstats) {
948
            perror("fopen");
949
            exit(1);
950
        }
951
    }
952
    
953
    ti = MAXINT64;
954
    enc = &ost->st->codec;
955
    if (enc->codec_type == CODEC_TYPE_VIDEO) {
956
        frame_number = ost->frame_number;
957
        fprintf(fvstats, "frame= %5d q= %2.1f ", frame_number, enc->coded_frame->quality/(float)FF_QP2LAMBDA);
958
        if (enc->flags&CODEC_FLAG_PSNR)
959
            fprintf(fvstats, "PSNR= %6.2f ", psnr(enc->coded_frame->error[0]/(enc->width*enc->height*255.0*255.0)));
960
        
961
        fprintf(fvstats,"f_size= %6d ", frame_size);
962
        /* compute pts value */
963
        ti1 = (double)ost->sync_opts *enc->frame_rate_base / enc->frame_rate;
964
        if (ti1 < 0.01)
965
            ti1 = 0.01;
966
    
967
        bitrate = (double)(frame_size * 8) * enc->frame_rate / enc->frame_rate_base / 1000.0;
968
        avg_bitrate = (double)(video_size * 8) / ti1 / 1000.0;
969
        fprintf(fvstats, "s_size= %8.0fkB time= %0.3f br= %7.1fkbits/s avg_br= %7.1fkbits/s ",
970
            (double)video_size / 1024, ti1, bitrate, avg_bitrate);
971
        fprintf(fvstats,"type= %c\n", av_get_pict_type_char(enc->coded_frame->pict_type));        
972
    }
973
}
974

    
975
static void print_report(AVFormatContext **output_files,
976
                         AVOutputStream **ost_table, int nb_ostreams,
977
                         int is_last_report)
978
{
979
    char buf[1024];
980
    AVOutputStream *ost;
981
    AVFormatContext *oc, *os;
982
    int64_t total_size;
983
    AVCodecContext *enc;
984
    int frame_number, vid, i;
985
    double bitrate, ti1, pts;
986
    static int64_t last_time = -1;
987
    
988
    if (!is_last_report) {
989
        int64_t cur_time;
990
        /* display the report every 0.5 seconds */
991
        cur_time = av_gettime();
992
        if (last_time == -1) {
993
            last_time = cur_time;
994
            return;
995
        } 
996
        if ((cur_time - last_time) < 500000)
997
            return;
998
        last_time = cur_time;
999
    }
1000

    
1001

    
1002
    oc = output_files[0];
1003

    
1004
    total_size = url_ftell(&oc->pb);
1005
    
1006
    buf[0] = '\0';
1007
    ti1 = 1e10;
1008
    vid = 0;
1009
    for(i=0;i<nb_ostreams;i++) {
1010
        ost = ost_table[i];
1011
        os = output_files[ost->file_index];
1012
        enc = &ost->st->codec;
1013
        if (vid && enc->codec_type == CODEC_TYPE_VIDEO) {
1014
            sprintf(buf + strlen(buf), "q=%2.1f ",
1015
                    enc->coded_frame->quality/(float)FF_QP2LAMBDA);
1016
        }
1017
        if (!vid && enc->codec_type == CODEC_TYPE_VIDEO) {
1018
            frame_number = ost->frame_number;
1019
            sprintf(buf + strlen(buf), "frame=%5d q=%2.1f ",
1020
                    frame_number, enc->coded_frame ? enc->coded_frame->quality/(float)FF_QP2LAMBDA : 0);
1021
            if(is_last_report)
1022
                sprintf(buf + strlen(buf), "L");
1023
            if (enc->flags&CODEC_FLAG_PSNR){
1024
                int j;
1025
                double error, error_sum=0;
1026
                double scale, scale_sum=0;
1027
                char type[3]= {'Y','U','V'};
1028
                sprintf(buf + strlen(buf), "PSNR=");
1029
                for(j=0; j<3; j++){
1030
                    if(is_last_report){
1031
                        error= enc->error[j];
1032
                        scale= enc->width*enc->height*255.0*255.0*frame_number;
1033
                    }else{
1034
                        error= enc->coded_frame->error[j];
1035
                        scale= enc->width*enc->height*255.0*255.0;
1036
                    }
1037
                    if(j) scale/=4;
1038
                    error_sum += error;
1039
                    scale_sum += scale;
1040
                    sprintf(buf + strlen(buf), "%c:%2.2f ", type[j], psnr(error/scale));
1041
                }
1042
                sprintf(buf + strlen(buf), "*:%2.2f ", psnr(error_sum/scale_sum));
1043
            }
1044
            vid = 1;
1045
        }
1046
        /* compute min output value */
1047
        pts = (double)ost->st->pts.val * ost->st->time_base.num / ost->st->time_base.den;
1048
        if ((pts < ti1) && (pts > 0))
1049
            ti1 = pts;
1050
    }
1051
    if (ti1 < 0.01)
1052
        ti1 = 0.01;
1053
    
1054
    if (verbose || is_last_report) {
1055
        bitrate = (double)(total_size * 8) / ti1 / 1000.0;
1056
        
1057
        sprintf(buf + strlen(buf), 
1058
            "size=%8.0fkB time=%0.1f bitrate=%6.1fkbits/s",
1059
            (double)total_size / 1024, ti1, bitrate);
1060

    
1061
        if (verbose > 1)
1062
          sprintf(buf + strlen(buf), " dup=%d drop=%d",
1063
                  nb_frames_dup, nb_frames_drop);
1064
        
1065
        if (verbose >= 0)
1066
            fprintf(stderr, "%s    \r", buf);
1067

    
1068
        fflush(stderr);
1069
    }
1070
        
1071
    if (is_last_report && verbose >= 0){
1072
        int64_t raw= audio_size + video_size + extra_size;
1073
        fprintf(stderr, "\n");
1074
        fprintf(stderr, "video:%1.0fkB audio:%1.0fkB global headers:%1.0fkB muxing overhead %f%%\n",
1075
                video_size/1024.0,
1076
                audio_size/1024.0,
1077
                extra_size/1024.0,
1078
                100.0*(total_size - raw)/raw
1079
        );
1080
    }
1081
}
1082

    
1083
/* pkt = NULL means EOF (needed to flush decoder buffers) */
1084
static int output_packet(AVInputStream *ist, int ist_index,
1085
                         AVOutputStream **ost_table, int nb_ostreams,
1086
                         const AVPacket *pkt)
1087
{
1088
    AVFormatContext *os;
1089
    AVOutputStream *ost;
1090
    uint8_t *ptr;
1091
    int len, ret, i;
1092
    uint8_t *data_buf;
1093
    int data_size, got_picture;
1094
    AVFrame picture;
1095
    void *buffer_to_free;
1096
    static int samples_size= 0;
1097
    static short *samples= NULL;
1098
    
1099
    if(!pkt){
1100
        ist->pts= ist->next_pts; // needed for last packet if vsync=0
1101
    } else if (pkt->dts != AV_NOPTS_VALUE) { //FIXME seems redundant, as libavformat does this too
1102
        ist->next_pts = ist->pts = pkt->dts;
1103
    } else {
1104
        assert(ist->pts == ist->next_pts);
1105
    }
1106
    
1107
    if (pkt == NULL) {
1108
        /* EOF handling */
1109
        ptr = NULL;
1110
        len = 0;
1111
        goto handle_eof;
1112
    }
1113

    
1114
    len = pkt->size;
1115
    ptr = pkt->data;
1116
    while (len > 0) {
1117
    handle_eof:
1118
        /* decode the packet if needed */
1119
        data_buf = NULL; /* fail safe */
1120
        data_size = 0;
1121
        if (ist->decoding_needed) {
1122
            switch(ist->st->codec.codec_type) {
1123
            case CODEC_TYPE_AUDIO:{
1124
                if(pkt) 
1125
                    samples= av_fast_realloc(samples, &samples_size, FFMAX(pkt->size, AVCODEC_MAX_AUDIO_FRAME_SIZE));
1126
                    /* XXX: could avoid copy if PCM 16 bits with same
1127
                       endianness as CPU */
1128
                ret = avcodec_decode_audio(&ist->st->codec, samples, &data_size,
1129
                                           ptr, len);
1130
                if (ret < 0)
1131
                    goto fail_decode;
1132
                ptr += ret;
1133
                len -= ret;
1134
                /* Some bug in mpeg audio decoder gives */
1135
                /* data_size < 0, it seems they are overflows */
1136
                if (data_size <= 0) {
1137
                    /* no audio frame */
1138
                    continue;
1139
                }
1140
                data_buf = (uint8_t *)samples;
1141
                ist->next_pts += ((int64_t)AV_TIME_BASE/2 * data_size) / 
1142
                    (ist->st->codec.sample_rate * ist->st->codec.channels);
1143
                break;}
1144
            case CODEC_TYPE_VIDEO:
1145
                    data_size = (ist->st->codec.width * ist->st->codec.height * 3) / 2;
1146
                    /* XXX: allocate picture correctly */
1147
                    avcodec_get_frame_defaults(&picture);
1148

    
1149
                    ret = avcodec_decode_video(&ist->st->codec, 
1150
                                               &picture, &got_picture, ptr, len);
1151
                    ist->st->quality= picture.quality;
1152
                    if (ret < 0) 
1153
                        goto fail_decode;
1154
                    if (!got_picture) {
1155
                        /* no picture yet */
1156
                        goto discard_packet;
1157
                    }
1158
                    if (ist->st->codec.frame_rate_base != 0) {
1159
                        ist->next_pts += ((int64_t)AV_TIME_BASE * 
1160
                                          ist->st->codec.frame_rate_base) /
1161
                            ist->st->codec.frame_rate;
1162
                    }
1163
                    len = 0;
1164
                    break;
1165
                default:
1166
                    goto fail_decode;
1167
                }
1168
            } else {
1169
                data_buf = ptr;
1170
                data_size = len;
1171
                ret = len;
1172
                len = 0;
1173
            }
1174

    
1175
            buffer_to_free = NULL;
1176
            if (ist->st->codec.codec_type == CODEC_TYPE_VIDEO) {
1177
                pre_process_video_frame(ist, (AVPicture *)&picture, 
1178
                                        &buffer_to_free);
1179
            }
1180

    
1181
            /* frame rate emulation */
1182
            if (ist->st->codec.rate_emu) {
1183
                int64_t pts = av_rescale((int64_t) ist->frame * ist->st->codec.frame_rate_base, 1000000, ist->st->codec.frame_rate);
1184
                int64_t now = av_gettime() - ist->start;
1185
                if (pts > now)
1186
                    usleep(pts - now);
1187

    
1188
                ist->frame++;
1189
            }
1190

    
1191
#if 0
1192
            /* mpeg PTS deordering : if it is a P or I frame, the PTS
1193
               is the one of the next displayed one */
1194
            /* XXX: add mpeg4 too ? */
1195
            if (ist->st->codec.codec_id == CODEC_ID_MPEG1VIDEO) {
1196
                if (ist->st->codec.pict_type != B_TYPE) {
1197
                    int64_t tmp;
1198
                    tmp = ist->last_ip_pts;
1199
                    ist->last_ip_pts  = ist->frac_pts.val;
1200
                    ist->frac_pts.val = tmp;
1201
                }
1202
            }
1203
#endif
1204
            /* if output time reached then transcode raw format, 
1205
               encode packets and output them */
1206
            if (start_time == 0 || ist->pts >= start_time)
1207
                for(i=0;i<nb_ostreams;i++) {
1208
                    int frame_size;
1209

    
1210
                    ost = ost_table[i];
1211
                    if (ost->source_index == ist_index) {
1212
                        os = output_files[ost->file_index];
1213

    
1214
#if 0
1215
                        printf("%d: got pts=%0.3f %0.3f\n", i, 
1216
                               (double)pkt->pts / AV_TIME_BASE, 
1217
                               ((double)ist->pts / AV_TIME_BASE) - 
1218
                               ((double)ost->st->pts.val * ost->st->time_base.num / ost->st->time_base.den));
1219
#endif
1220
                        /* set the input output pts pairs */
1221
                        ost->sync_ipts = (double)(ist->pts + input_files_ts_offset[ist->file_index])/ AV_TIME_BASE;
1222

    
1223
                        if (ost->encoding_needed) {
1224
                            switch(ost->st->codec.codec_type) {
1225
                            case CODEC_TYPE_AUDIO:
1226
                                do_audio_out(os, ost, ist, data_buf, data_size);
1227
                                break;
1228
                            case CODEC_TYPE_VIDEO:
1229
                                    do_video_out(os, ost, ist, &picture, &frame_size);
1230
                                    video_size += frame_size;
1231
                                    if (do_vstats && frame_size)
1232
                                        do_video_stats(os, ost, frame_size);
1233
                                break;
1234
                            default:
1235
                                av_abort();
1236
                            }
1237
                        } else {
1238
                            AVFrame avframe; //FIXME/XXX remove this
1239
                            AVPacket opkt;
1240
                            av_init_packet(&opkt);
1241

    
1242
                            /* no reencoding needed : output the packet directly */
1243
                            /* force the input stream PTS */
1244
                        
1245
                            avcodec_get_frame_defaults(&avframe);
1246
                            ost->st->codec.coded_frame= &avframe;
1247
                            avframe.key_frame = pkt->flags & PKT_FLAG_KEY; 
1248

    
1249
                            if(ost->st->codec.codec_type == CODEC_TYPE_AUDIO)
1250
                                audio_size += data_size;
1251
                            else if (ost->st->codec.codec_type == CODEC_TYPE_VIDEO) {
1252
                                video_size += data_size;
1253
                                ost->sync_opts++;
1254
                            }
1255

    
1256
                            opkt.stream_index= ost->index;
1257
                            opkt.data= data_buf;
1258
                            opkt.size= data_size;
1259
                            if(pkt->pts != AV_NOPTS_VALUE)
1260
                                opkt.pts= pkt->pts + input_files_ts_offset[ist->file_index];
1261
                            else
1262
                                opkt.pts= AV_NOPTS_VALUE;
1263
                            opkt.dts= pkt->dts + input_files_ts_offset[ist->file_index];
1264
                            opkt.flags= pkt->flags;
1265
                            
1266
                            av_interleaved_write_frame(os, &opkt);
1267
                            ost->st->codec.frame_number++;
1268
                            ost->frame_number++;
1269
                        }
1270
                    }
1271
                }
1272
            av_free(buffer_to_free);
1273
        }
1274
 discard_packet:
1275
    if (pkt == NULL) {
1276
        /* EOF handling */
1277
  
1278
        for(i=0;i<nb_ostreams;i++) {
1279
            ost = ost_table[i];
1280
            if (ost->source_index == ist_index) {
1281
                AVCodecContext *enc= &ost->st->codec;
1282
                os = output_files[ost->file_index];
1283
                
1284
                if(ost->st->codec.codec_type == CODEC_TYPE_AUDIO && enc->frame_size <=1)
1285
                    continue;
1286
                if(ost->st->codec.codec_type == CODEC_TYPE_VIDEO && (os->oformat->flags & AVFMT_RAWPICTURE))
1287
                    continue;
1288

    
1289
                if (ost->encoding_needed) {
1290
                    for(;;) {
1291
                        AVPacket pkt;
1292
                        av_init_packet(&pkt);
1293
                        pkt.stream_index= ost->index;
1294
 
1295
                        switch(ost->st->codec.codec_type) {
1296
                        case CODEC_TYPE_AUDIO:        
1297
                            ret = avcodec_encode_audio(enc, bit_buffer, VIDEO_BUFFER_SIZE, NULL);
1298
                            audio_size += ret;
1299
                            pkt.flags |= PKT_FLAG_KEY;
1300
                            break;
1301
                        case CODEC_TYPE_VIDEO:
1302
                            ret = avcodec_encode_video(enc, bit_buffer, VIDEO_BUFFER_SIZE, NULL);
1303
                            video_size += ret;
1304
                            if(enc->coded_frame && enc->coded_frame->key_frame)
1305
                                pkt.flags |= PKT_FLAG_KEY;
1306
                            if (ost->logfile && enc->stats_out) {
1307
                                fprintf(ost->logfile, "%s", enc->stats_out);
1308
                            }
1309
                            break;
1310
                        default:
1311
                            ret=-1;
1312
                        }
1313
                            
1314
                        if(ret<=0)
1315
                            break;
1316
                        pkt.data= bit_buffer;
1317
                        pkt.size= ret;
1318
                        if(enc->coded_frame)
1319
                            pkt.pts= enc->coded_frame->pts;
1320
                        av_interleaved_write_frame(os, &pkt);
1321
                    }
1322
                }
1323
            }
1324
        }
1325
    }
1326
 
1327
    return 0;
1328
 fail_decode:
1329
    return -1;
1330
}
1331

    
1332

    
1333
/*
1334
 * The following code is the main loop of the file converter
1335
 */
1336
static int av_encode(AVFormatContext **output_files,
1337
                     int nb_output_files,
1338
                     AVFormatContext **input_files,
1339
                     int nb_input_files,
1340
                     AVStreamMap *stream_maps, int nb_stream_maps)
1341
{
1342
    int ret, i, j, k, n, nb_istreams = 0, nb_ostreams = 0;
1343
    AVFormatContext *is, *os;
1344
    AVCodecContext *codec, *icodec;
1345
    AVOutputStream *ost, **ost_table = NULL;
1346
    AVInputStream *ist, **ist_table = NULL;
1347
    AVInputFile *file_table;
1348
    AVFormatContext *stream_no_data;
1349
    int key;
1350

    
1351
    file_table= (AVInputFile*) av_mallocz(nb_input_files * sizeof(AVInputFile));
1352
    if (!file_table)
1353
        goto fail;
1354

    
1355
    if (!bit_buffer)
1356
        bit_buffer = av_malloc(VIDEO_BUFFER_SIZE);
1357
    if (!bit_buffer)
1358
        goto fail;
1359
        
1360
    /* input stream init */
1361
    j = 0;
1362
    for(i=0;i<nb_input_files;i++) {
1363
        is = input_files[i];
1364
        file_table[i].ist_index = j;
1365
        file_table[i].nb_streams = is->nb_streams;
1366
        j += is->nb_streams;
1367
    }
1368
    nb_istreams = j;
1369

    
1370
    ist_table = av_mallocz(nb_istreams * sizeof(AVInputStream *));
1371
    if (!ist_table)
1372
        goto fail;
1373
    
1374
    for(i=0;i<nb_istreams;i++) {
1375
        ist = av_mallocz(sizeof(AVInputStream));
1376
        if (!ist)
1377
            goto fail;
1378
        ist_table[i] = ist;
1379
    }
1380
    j = 0;
1381
    for(i=0;i<nb_input_files;i++) {
1382
        is = input_files[i];
1383
        for(k=0;k<is->nb_streams;k++) {
1384
            ist = ist_table[j++];
1385
            ist->st = is->streams[k];
1386
            ist->file_index = i;
1387
            ist->index = k;
1388
            ist->discard = 1; /* the stream is discarded by default
1389
                                 (changed later) */
1390

    
1391
            if (ist->st->codec.rate_emu) {
1392
                ist->start = av_gettime();
1393
                ist->frame = 0;
1394
            }
1395
        }
1396
    }
1397

    
1398
    /* output stream init */
1399
    nb_ostreams = 0;
1400
    for(i=0;i<nb_output_files;i++) {
1401
        os = output_files[i];
1402
        nb_ostreams += os->nb_streams;
1403
    }
1404
    if (nb_stream_maps > 0 && nb_stream_maps != nb_ostreams) {
1405
        fprintf(stderr, "Number of stream maps must match number of output streams\n");
1406
        exit(1);
1407
    }
1408

    
1409
    /* Sanity check the mapping args -- do the input files & streams exist? */
1410
    for(i=0;i<nb_stream_maps;i++) {
1411
        int fi = stream_maps[i].file_index;
1412
        int si = stream_maps[i].stream_index;
1413
        
1414
        if (fi < 0 || fi > nb_input_files - 1 ||
1415
            si < 0 || si > file_table[fi].nb_streams - 1) {
1416
            fprintf(stderr,"Could not find input stream #%d.%d\n", fi, si);
1417
            exit(1);
1418
        }
1419
    }
1420
    
1421
    ost_table = av_mallocz(sizeof(AVOutputStream *) * nb_ostreams);
1422
    if (!ost_table)
1423
        goto fail;
1424
    for(i=0;i<nb_ostreams;i++) {
1425
        ost = av_mallocz(sizeof(AVOutputStream));
1426
        if (!ost)
1427
            goto fail;
1428
        ost_table[i] = ost;
1429
    }
1430
    
1431
    n = 0;
1432
    for(k=0;k<nb_output_files;k++) {
1433
        os = output_files[k];
1434
        for(i=0;i<os->nb_streams;i++) {
1435
            int found;
1436
            ost = ost_table[n++];
1437
            ost->file_index = k;
1438
            ost->index = i;
1439
            ost->st = os->streams[i];
1440
            if (nb_stream_maps > 0) {
1441
                ost->source_index = file_table[stream_maps[n-1].file_index].ist_index + 
1442
                    stream_maps[n-1].stream_index;
1443
                    
1444
                /* Sanity check that the stream types match */
1445
                if (ist_table[ost->source_index]->st->codec.codec_type != ost->st->codec.codec_type) {
1446
                    fprintf(stderr, "Codec type mismatch for mapping #%d.%d -> #%d.%d\n",
1447
                        stream_maps[n-1].file_index, stream_maps[n-1].stream_index,
1448
                        ost->file_index, ost->index);
1449
                    exit(1);
1450
                }
1451
                
1452
            } else {
1453
                /* get corresponding input stream index : we select the first one with the right type */
1454
                found = 0;
1455
                for(j=0;j<nb_istreams;j++) {
1456
                    ist = ist_table[j];
1457
                    if (ist->discard && 
1458
                        ist->st->codec.codec_type == ost->st->codec.codec_type) {
1459
                        ost->source_index = j;
1460
                        found = 1;
1461
                        break;
1462
                    }
1463
                }
1464
                
1465
                if (!found) {
1466
                    /* try again and reuse existing stream */
1467
                    for(j=0;j<nb_istreams;j++) {
1468
                        ist = ist_table[j];
1469
                        if (ist->st->codec.codec_type == ost->st->codec.codec_type) {
1470
                            ost->source_index = j;
1471
                            found = 1;
1472
                        }
1473
                    }
1474
                    if (!found) {
1475
                        fprintf(stderr, "Could not find input stream matching output stream #%d.%d\n",
1476
                                ost->file_index, ost->index);
1477
                        exit(1);
1478
                    }
1479
                }
1480
            }
1481
            ist = ist_table[ost->source_index];
1482
            ist->discard = 0;
1483
        }
1484
    }
1485

    
1486
    /* for each output stream, we compute the right encoding parameters */
1487
    for(i=0;i<nb_ostreams;i++) {
1488
        ost = ost_table[i];
1489
        ist = ist_table[ost->source_index];
1490

    
1491
        codec = &ost->st->codec;
1492
        icodec = &ist->st->codec;
1493

    
1494
        if (ost->st->stream_copy) {
1495
            /* if stream_copy is selected, no need to decode or encode */
1496
            codec->codec_id = icodec->codec_id;
1497
            codec->codec_type = icodec->codec_type;
1498
            if(!codec->codec_tag) codec->codec_tag = icodec->codec_tag;
1499
            codec->bit_rate = icodec->bit_rate;
1500
            switch(codec->codec_type) {
1501
            case CODEC_TYPE_AUDIO:
1502
                codec->sample_rate = icodec->sample_rate;
1503
                codec->channels = icodec->channels;
1504
                codec->frame_size = icodec->frame_size;
1505
                break;
1506
            case CODEC_TYPE_VIDEO:
1507
                codec->frame_rate = icodec->frame_rate;
1508
                codec->frame_rate_base = icodec->frame_rate_base;
1509
                codec->width = icodec->width;
1510
                codec->height = icodec->height;
1511
                break;
1512
            default:
1513
                av_abort();
1514
            }
1515
        } else {
1516
            switch(codec->codec_type) {
1517
            case CODEC_TYPE_AUDIO:
1518
                if (fifo_init(&ost->fifo, 2 * MAX_AUDIO_PACKET_SIZE))
1519
                    goto fail;
1520
                
1521
                if (codec->channels == icodec->channels &&
1522
                    codec->sample_rate == icodec->sample_rate) {
1523
                    ost->audio_resample = 0;
1524
                } else {
1525
                    if (codec->channels != icodec->channels &&
1526
                        (icodec->codec_id == CODEC_ID_AC3 ||
1527
                         icodec->codec_id == CODEC_ID_DTS)) {
1528
                        /* Special case for 5:1 AC3 and DTS input */
1529
                        /* and mono or stereo output      */
1530
                        /* Request specific number of channels */
1531
                        icodec->channels = codec->channels;
1532
                        if (codec->sample_rate == icodec->sample_rate)
1533
                            ost->audio_resample = 0;
1534
                        else {
1535
                            ost->audio_resample = 1;
1536
                        }
1537
                    } else {
1538
                        ost->audio_resample = 1; 
1539
                    }
1540
                }
1541
                if(audio_sync_method>1)
1542
                    ost->audio_resample = 1;
1543

    
1544
                if(ost->audio_resample){
1545
                    ost->resample = audio_resample_init(codec->channels, icodec->channels,
1546
                                                    codec->sample_rate, icodec->sample_rate);
1547
                    if(!ost->resample){
1548
                        printf("Can't resample.  Aborting.\n");
1549
                        av_abort();
1550
                    }
1551
                }
1552
                ist->decoding_needed = 1;
1553
                ost->encoding_needed = 1;
1554
                break;
1555
            case CODEC_TYPE_VIDEO:
1556
                if (codec->width == icodec->width &&
1557
                    codec->height == icodec->height &&
1558
                    frame_topBand == 0 &&
1559
                    frame_bottomBand == 0 &&
1560
                    frame_leftBand == 0 &&
1561
                    frame_rightBand == 0 && 
1562
                    frame_padtop == 0 &&
1563
                    frame_padbottom == 0 &&
1564
                    frame_padleft == 0 &&
1565
                    frame_padright == 0)
1566
                {
1567
                    ost->video_resample = 0;
1568
                    ost->video_crop = 0;
1569
                    ost->video_pad = 0;
1570
                } else if ((codec->width == icodec->width -
1571
                                (frame_leftBand + frame_rightBand)) &&
1572
                        (codec->height == icodec->height -
1573
                                (frame_topBand  + frame_bottomBand)))
1574
                {
1575
                    ost->video_resample = 0;
1576
                    ost->video_crop = 1;
1577
                    ost->topBand = frame_topBand;
1578
                    ost->leftBand = frame_leftBand;
1579
                } else if ((codec->width == icodec->width + 
1580
                                (frame_padleft + frame_padright)) &&
1581
                        (codec->height == icodec->height +
1582
                                (frame_padtop + frame_padbottom))) {
1583
                    ost->video_resample = 0;
1584
                    ost->video_crop = 0;
1585
                    ost->video_pad = 1;
1586
                    ost->padtop = frame_padtop;
1587
                    ost->padleft = frame_padleft;
1588
                    ost->padbottom = frame_padbottom;
1589
                    ost->padright = frame_padright;
1590
                    avcodec_get_frame_defaults(&ost->pict_tmp);
1591
                    if( avpicture_alloc( (AVPicture*)&ost->pict_tmp, PIX_FMT_YUV420P,
1592
                                codec->width, codec->height ) )
1593
                        goto fail;
1594
                } else {
1595
                    ost->video_resample = 1;
1596
                    ost->video_crop = 0; // cropping is handled as part of resample
1597
                    avcodec_get_frame_defaults(&ost->pict_tmp);
1598
                    if( avpicture_alloc( (AVPicture*)&ost->pict_tmp, PIX_FMT_YUV420P,
1599
                                         codec->width, codec->height ) )
1600
                        goto fail;
1601

    
1602
                    ost->img_resample_ctx = img_resample_full_init( 
1603
                                      ost->st->codec.width, ost->st->codec.height,
1604
                                      ist->st->codec.width, ist->st->codec.height,
1605
                                      frame_topBand, frame_bottomBand,
1606
                            frame_leftBand, frame_rightBand, 
1607
                            frame_padtop, frame_padbottom, 
1608
                            frame_padleft, frame_padright);
1609
                    
1610
                    ost->padtop = frame_padtop;
1611
                    ost->padleft = frame_padleft;
1612
                    ost->padbottom = frame_padbottom;
1613
                    ost->padright = frame_padright;
1614
                   
1615
                }
1616
                ost->encoding_needed = 1;
1617
                ist->decoding_needed = 1;
1618
                break;
1619
            default:
1620
                av_abort();
1621
            }
1622
            /* two pass mode */
1623
            if (ost->encoding_needed && 
1624
                (codec->flags & (CODEC_FLAG_PASS1 | CODEC_FLAG_PASS2))) {
1625
                char logfilename[1024];
1626
                FILE *f;
1627
                int size;
1628
                char *logbuffer;
1629
                
1630
                snprintf(logfilename, sizeof(logfilename), "%s-%d.log", 
1631
                         pass_logfilename ? 
1632
                         pass_logfilename : DEFAULT_PASS_LOGFILENAME, i);
1633
                if (codec->flags & CODEC_FLAG_PASS1) {
1634
                    f = fopen(logfilename, "w");
1635
                    if (!f) {
1636
                        perror(logfilename);
1637
                        exit(1);
1638
                    }
1639
                    ost->logfile = f;
1640
                } else {
1641
                    /* read the log file */
1642
                    f = fopen(logfilename, "r");
1643
                    if (!f) {
1644
                        perror(logfilename);
1645
                        exit(1);
1646
                    }
1647
                    fseek(f, 0, SEEK_END);
1648
                    size = ftell(f);
1649
                    fseek(f, 0, SEEK_SET);
1650
                    logbuffer = av_malloc(size + 1);
1651
                    if (!logbuffer) {
1652
                        fprintf(stderr, "Could not allocate log buffer\n");
1653
                        exit(1);
1654
                    }
1655
                    size = fread(logbuffer, 1, size, f);
1656
                    fclose(f);
1657
                    logbuffer[size] = '\0';
1658
                    codec->stats_in = logbuffer;
1659
                }
1660
            }
1661
        }
1662
    }
1663

    
1664
    /* dump the file output parameters - cannot be done before in case
1665
       of stream copy */
1666
    for(i=0;i<nb_output_files;i++) {
1667
        dump_format(output_files[i], i, output_files[i]->filename, 1);
1668
    }
1669

    
1670
    /* dump the stream mapping */
1671
    if (verbose >= 0) {
1672
        fprintf(stderr, "Stream mapping:\n");
1673
        for(i=0;i<nb_ostreams;i++) {
1674
            ost = ost_table[i];
1675
            fprintf(stderr, "  Stream #%d.%d -> #%d.%d\n",
1676
                    ist_table[ost->source_index]->file_index,
1677
                    ist_table[ost->source_index]->index,
1678
                    ost->file_index, 
1679
                    ost->index);
1680
        }
1681
    }
1682

    
1683
    /* open each encoder */
1684
    for(i=0;i<nb_ostreams;i++) {
1685
        ost = ost_table[i];
1686
        if (ost->encoding_needed) {
1687
            AVCodec *codec;
1688
            codec = avcodec_find_encoder(ost->st->codec.codec_id);
1689
            if (!codec) {
1690
                fprintf(stderr, "Unsupported codec for output stream #%d.%d\n", 
1691
                        ost->file_index, ost->index);
1692
                exit(1);
1693
            }
1694
            if (avcodec_open(&ost->st->codec, codec) < 0) {
1695
                fprintf(stderr, "Error while opening codec for stream #%d.%d - maybe incorrect parameters such as bit_rate, rate, width or height\n", 
1696
                        ost->file_index, ost->index);
1697
                exit(1);
1698
            }
1699
            extra_size += ost->st->codec.extradata_size;
1700
        }
1701
    }
1702

    
1703
    /* open each decoder */
1704
    for(i=0;i<nb_istreams;i++) {
1705
        ist = ist_table[i];
1706
        if (ist->decoding_needed) {
1707
            AVCodec *codec;
1708
            codec = avcodec_find_decoder(ist->st->codec.codec_id);
1709
            if (!codec) {
1710
                fprintf(stderr, "Unsupported codec (id=%d) for input stream #%d.%d\n", 
1711
                        ist->st->codec.codec_id, ist->file_index, ist->index);
1712
                exit(1);
1713
            }
1714
            if (avcodec_open(&ist->st->codec, codec) < 0) {
1715
                fprintf(stderr, "Error while opening codec for input stream #%d.%d\n", 
1716
                        ist->file_index, ist->index);
1717
                exit(1);
1718
            }
1719
            //if (ist->st->codec.codec_type == CODEC_TYPE_VIDEO)
1720
            //    ist->st->codec.flags |= CODEC_FLAG_REPEAT_FIELD;
1721
        }
1722
    }
1723

    
1724
    /* init pts */
1725
    for(i=0;i<nb_istreams;i++) {
1726
        ist = ist_table[i];
1727
        is = input_files[ist->file_index];
1728
        ist->pts = 0;
1729
        ist->next_pts = ist->st->start_time;
1730
        if(ist->next_pts == AV_NOPTS_VALUE) 
1731
            ist->next_pts=0;
1732
        ist->is_start = 1;
1733
    }
1734

    
1735
    /* compute buffer size max (should use a complete heuristic) */
1736
    for(i=0;i<nb_input_files;i++) {
1737
        file_table[i].buffer_size_max = 2048;
1738
    }
1739

    
1740
    /* set meta data information from input file if required */
1741
    for (i=0;i<nb_meta_data_maps;i++) {
1742
        AVFormatContext *out_file;
1743
        AVFormatContext *in_file;
1744

    
1745
        int out_file_index = meta_data_maps[i].out_file;
1746
        int in_file_index = meta_data_maps[i].in_file;
1747
        if ( out_file_index < 0 || out_file_index >= nb_output_files ) {
1748
            fprintf(stderr, "Invalid output file index %d map_meta_data(%d,%d)\n", out_file_index, out_file_index, in_file_index);
1749
            ret = -EINVAL;
1750
            goto fail;
1751
        }
1752
        if ( in_file_index < 0 || in_file_index >= nb_input_files ) {
1753
            fprintf(stderr, "Invalid input file index %d map_meta_data(%d,%d)\n", in_file_index, out_file_index, in_file_index);
1754
            ret = -EINVAL;
1755
            goto fail;
1756
        }                
1757
                 
1758
        out_file = output_files[out_file_index];
1759
        in_file = input_files[in_file_index];
1760

    
1761
        strcpy(out_file->title, in_file->title);
1762
        strcpy(out_file->author, in_file->author);
1763
        strcpy(out_file->copyright, in_file->copyright);
1764
        strcpy(out_file->comment, in_file->comment);
1765
        strcpy(out_file->album, in_file->album);
1766
        out_file->year = in_file->year;
1767
        out_file->track = in_file->track;
1768
        strcpy(out_file->genre, in_file->genre);
1769
    }
1770
        
1771
    /* open files and write file headers */
1772
    for(i=0;i<nb_output_files;i++) {
1773
        os = output_files[i];
1774
        if (av_write_header(os) < 0) {
1775
            fprintf(stderr, "Could not write header for output file #%d (incorrect codec parameters ?)\n", i);
1776
            ret = -EINVAL;
1777
            goto fail;
1778
        }
1779
    }
1780

    
1781
#ifndef CONFIG_WIN32
1782
    if ( !using_stdin && verbose >= 0) {
1783
        fprintf(stderr, "Press [q] to stop encoding\n");
1784
        url_set_interrupt_cb(decode_interrupt_cb);
1785
    }
1786
#endif
1787
    term_init();
1788

    
1789
    stream_no_data = 0;
1790
    key = -1;
1791

    
1792
    for(; received_sigterm == 0;) {
1793
        int file_index, ist_index;
1794
        AVPacket pkt;
1795
        double ipts_min;
1796
        double opts_min;
1797

    
1798
    redo:
1799
        ipts_min= 1e100;
1800
        opts_min= 1e100;
1801
        /* if 'q' pressed, exits */
1802
        if (!using_stdin) {
1803
            if (q_pressed)
1804
                break;
1805
            /* read_key() returns 0 on EOF */
1806
            key = read_key();
1807
            if (key == 'q')
1808
                break;
1809
        }
1810

    
1811
        /* select the stream that we must read now by looking at the
1812
           smallest output pts */
1813
        file_index = -1;
1814
        for(i=0;i<nb_ostreams;i++) {
1815
            double ipts, opts;
1816
            ost = ost_table[i];
1817
            os = output_files[ost->file_index];
1818
            ist = ist_table[ost->source_index];
1819
            if(ost->st->codec.codec_type == CODEC_TYPE_VIDEO)
1820
                opts = (double)ost->sync_opts * ost->st->codec.frame_rate_base / ost->st->codec.frame_rate;
1821
            else
1822
                opts = (double)ost->st->pts.val * ost->st->time_base.num / ost->st->time_base.den;
1823
            ipts = (double)ist->pts;
1824
            if (!file_table[ist->file_index].eof_reached){
1825
                if(ipts < ipts_min) {
1826
                    ipts_min = ipts;
1827
                    if(input_sync ) file_index = ist->file_index;
1828
                }
1829
                if(opts < opts_min) {
1830
                    opts_min = opts;
1831
                    if(!input_sync) file_index = ist->file_index;
1832
                }
1833
            }
1834
        }
1835
        /* if none, if is finished */
1836
        if (file_index < 0) {
1837
            break;
1838
        }
1839

    
1840
        /* finish if recording time exhausted */
1841
        if (recording_time > 0 && opts_min >= (recording_time / 1000000.0))
1842
            break;
1843

    
1844
        /* read a frame from it and output it in the fifo */
1845
        is = input_files[file_index];
1846
        if (av_read_frame(is, &pkt) < 0) {
1847
            file_table[file_index].eof_reached = 1;
1848
            continue;
1849
        }
1850

    
1851
        if (!pkt.size) {
1852
            stream_no_data = is;
1853
        } else {
1854
            stream_no_data = 0;
1855
        }
1856
        if (do_pkt_dump) {
1857
            av_pkt_dump(stdout, &pkt, do_hex_dump);
1858
        }
1859
        /* the following test is needed in case new streams appear
1860
           dynamically in stream : we ignore them */
1861
        if (pkt.stream_index >= file_table[file_index].nb_streams)
1862
            goto discard_packet;
1863
        ist_index = file_table[file_index].ist_index + pkt.stream_index;
1864
        ist = ist_table[ist_index];
1865
        if (ist->discard)
1866
            goto discard_packet;
1867

    
1868
//        fprintf(stderr, "next:%lld dts:%lld off:%lld %d\n", ist->next_pts, pkt.dts, input_files_ts_offset[ist->file_index], ist->st->codec.codec_type);
1869
        if (pkt.dts != AV_NOPTS_VALUE) {
1870
            int64_t delta= pkt.dts - ist->next_pts;
1871
            if(ABS(delta) > 10LL*AV_TIME_BASE && !copy_ts){
1872
                input_files_ts_offset[ist->file_index]-= delta;
1873
                if (verbose > 2)
1874
                    fprintf(stderr, "timestamp discontinuity %lld, new offset= %lld\n", delta, input_files_ts_offset[ist->file_index]);
1875
                for(i=0; i<file_table[file_index].nb_streams; i++){
1876
                    int index= file_table[file_index].ist_index + i;
1877
                    ist_table[index]->next_pts += delta;
1878
                    ist_table[index]->is_start=1;
1879
                }
1880
            }
1881
        }
1882

    
1883
        //fprintf(stderr,"read #%d.%d size=%d\n", ist->file_index, ist->index, pkt.size);
1884
        if (output_packet(ist, ist_index, ost_table, nb_ostreams, &pkt) < 0) {
1885

    
1886
            if (verbose >= 0)
1887
                fprintf(stderr, "Error while decoding stream #%d.%d\n",
1888
                        ist->file_index, ist->index);
1889

    
1890
            av_free_packet(&pkt);
1891
            goto redo;
1892
        }
1893
        
1894
    discard_packet:
1895
        av_free_packet(&pkt);
1896
        
1897
        /* dump report by using the output first video and audio streams */
1898
        print_report(output_files, ost_table, nb_ostreams, 0);
1899
    }
1900

    
1901
    /* at the end of stream, we must flush the decoder buffers */
1902
    for(i=0;i<nb_istreams;i++) {
1903
        ist = ist_table[i];
1904
        if (ist->decoding_needed) {
1905
            output_packet(ist, i, ost_table, nb_ostreams, NULL);
1906
        }
1907
    }
1908

    
1909
    term_exit();
1910

    
1911
    /* write the trailer if needed and close file */
1912
    for(i=0;i<nb_output_files;i++) {
1913
        os = output_files[i];
1914
        av_write_trailer(os);
1915
    }
1916

    
1917
    /* dump report by using the first video and audio streams */
1918
    print_report(output_files, ost_table, nb_ostreams, 1);
1919

    
1920
    /* close each encoder */
1921
    for(i=0;i<nb_ostreams;i++) {
1922
        ost = ost_table[i];
1923
        if (ost->encoding_needed) {
1924
            av_freep(&ost->st->codec.stats_in);
1925
            avcodec_close(&ost->st->codec);
1926
        }
1927
    }
1928
    
1929
    /* close each decoder */
1930
    for(i=0;i<nb_istreams;i++) {
1931
        ist = ist_table[i];
1932
        if (ist->decoding_needed) {
1933
            avcodec_close(&ist->st->codec);
1934
        }
1935
    }
1936

    
1937
    /* finished ! */
1938
    
1939
    ret = 0;
1940
 fail1:
1941
    av_free(file_table);
1942

    
1943
    if (ist_table) {
1944
        for(i=0;i<nb_istreams;i++) {
1945
            ist = ist_table[i];
1946
            av_free(ist);
1947
        }
1948
        av_free(ist_table);
1949
    }
1950
    if (ost_table) {
1951
        for(i=0;i<nb_ostreams;i++) {
1952
            ost = ost_table[i];
1953
            if (ost) {
1954
                if (ost->logfile) {
1955
                    fclose(ost->logfile);
1956
                    ost->logfile = NULL;
1957
                }
1958
                fifo_free(&ost->fifo); /* works even if fifo is not
1959
                                          initialized but set to zero */
1960
                av_free(ost->pict_tmp.data[0]);
1961
                if (ost->video_resample)
1962
                    img_resample_close(ost->img_resample_ctx);
1963
                if (ost->audio_resample)
1964
                    audio_resample_close(ost->resample);
1965
                av_free(ost);
1966
            }
1967
        }
1968
        av_free(ost_table);
1969
    }
1970
    return ret;
1971
 fail:
1972
    ret = -ENOMEM;
1973
    goto fail1;
1974
}
1975

    
1976
#if 0
1977
int file_read(const char *filename)
1978
{
1979
    URLContext *h;
1980
    unsigned char buffer[1024];
1981
    int len, i;
1982

1983
    if (url_open(&h, filename, O_RDONLY) < 0) {
1984
        printf("could not open '%s'\n", filename);
1985
        return -1;
1986
    }
1987
    for(;;) {
1988
        len = url_read(h, buffer, sizeof(buffer));
1989
        if (len <= 0)
1990
            break;
1991
        for(i=0;i<len;i++) putchar(buffer[i]);
1992
    }
1993
    url_close(h);
1994
    return 0;
1995
}
1996
#endif
1997

    
1998
static void opt_image_format(const char *arg)
1999
{
2000
    AVImageFormat *f;
2001
    
2002
    for(f = first_image_format; f != NULL; f = f->next) {
2003
        if (!strcmp(arg, f->name))
2004
            break;
2005
    }
2006
    if (!f) {
2007
        fprintf(stderr, "Unknown image format: '%s'\n", arg);
2008
        exit(1);
2009
    }
2010
    image_format = f;
2011
}
2012

    
2013
static void opt_format(const char *arg)
2014
{
2015
    /* compatibility stuff for pgmyuv */
2016
    if (!strcmp(arg, "pgmyuv")) {
2017
        opt_image_format(arg);
2018
        arg = "image";
2019
    }
2020

    
2021
    file_iformat = av_find_input_format(arg);
2022
    file_oformat = guess_format(arg, NULL, NULL);
2023
    if (!file_iformat && !file_oformat) {
2024
        fprintf(stderr, "Unknown input or output format: %s\n", arg);
2025
        exit(1);
2026
    }
2027
}
2028

    
2029
static void opt_video_bitrate(const char *arg)
2030
{
2031
    video_bit_rate = atoi(arg) * 1000;
2032
}
2033

    
2034
static void opt_video_bitrate_tolerance(const char *arg)
2035
{
2036
    video_bit_rate_tolerance = atoi(arg) * 1000;
2037
}
2038

    
2039
static void opt_video_bitrate_max(const char *arg)
2040
{
2041
    video_rc_max_rate = atoi(arg) * 1000;
2042
}
2043

    
2044
static void opt_video_bitrate_min(const char *arg)
2045
{
2046
    video_rc_min_rate = atoi(arg) * 1000;
2047
}
2048

    
2049
static void opt_video_buffer_size(const char *arg)
2050
{
2051
    video_rc_buffer_size = atoi(arg) * 8*1024;
2052
}
2053

    
2054
static void opt_video_rc_eq(char *arg)
2055
{
2056
    video_rc_eq = arg;
2057
}
2058

    
2059
static void opt_video_rc_override_string(char *arg)
2060
{
2061
    video_rc_override_string = arg;
2062
}
2063

    
2064

    
2065
static void opt_workaround_bugs(const char *arg)
2066
{
2067
    workaround_bugs = atoi(arg);
2068
}
2069

    
2070
static void opt_dct_algo(const char *arg)
2071
{
2072
    dct_algo = atoi(arg);
2073
}
2074

    
2075
static void opt_idct_algo(const char *arg)
2076
{
2077
    idct_algo = atoi(arg);
2078
}
2079

    
2080
static void opt_me_threshold(const char *arg)
2081
{
2082
    me_threshold = atoi(arg);
2083
}
2084

    
2085
static void opt_mb_threshold(const char *arg)
2086
{
2087
    mb_threshold = atoi(arg);
2088
}
2089

    
2090
static void opt_error_resilience(const char *arg)
2091
{
2092
    error_resilience = atoi(arg);
2093
}
2094

    
2095
static void opt_error_concealment(const char *arg)
2096
{
2097
    error_concealment = atoi(arg);
2098
}
2099

    
2100
static void opt_debug(const char *arg)
2101
{
2102
    debug = atoi(arg);
2103
}
2104

    
2105
static void opt_vismv(const char *arg)
2106
{
2107
    debug_mv = atoi(arg);
2108
}
2109
    
2110
static void opt_verbose(const char *arg)
2111
{
2112
    verbose = atoi(arg);
2113
    av_log_set_level(atoi(arg));
2114
}
2115

    
2116
static void opt_frame_rate(const char *arg)
2117
{
2118
    if (parse_frame_rate(&frame_rate, &frame_rate_base, arg) < 0) {
2119
        fprintf(stderr, "Incorrect frame rate\n");
2120
        exit(1);
2121
    }
2122
}
2123

    
2124
static void opt_frame_crop_top(const char *arg)
2125
{
2126
    frame_topBand = atoi(arg); 
2127
    if (frame_topBand < 0) {
2128
        fprintf(stderr, "Incorrect top crop size\n");
2129
        exit(1);
2130
    }
2131
    if ((frame_topBand % 2) != 0) {
2132
        fprintf(stderr, "Top crop size must be a multiple of 2\n");
2133
        exit(1);
2134
    }
2135
    if ((frame_topBand) >= frame_height){
2136
            fprintf(stderr, "Vertical crop dimensions are outside the range of the original image.\nRemember to crop first and scale second.\n");
2137
        exit(1);
2138
    }
2139
    frame_height -= frame_topBand;
2140
}
2141

    
2142
static void opt_frame_crop_bottom(const char *arg)
2143
{
2144
    frame_bottomBand = atoi(arg);
2145
    if (frame_bottomBand < 0) {
2146
        fprintf(stderr, "Incorrect bottom crop size\n");
2147
        exit(1);
2148
    }
2149
    if ((frame_bottomBand % 2) != 0) {
2150
        fprintf(stderr, "Bottom crop size must be a multiple of 2\n");
2151
        exit(1);        
2152
    }
2153
    if ((frame_bottomBand) >= frame_height){
2154
            fprintf(stderr, "Vertical crop dimensions are outside the range of the original image.\nRemember to crop first and scale second.\n");
2155
        exit(1);
2156
    }
2157
    frame_height -= frame_bottomBand;
2158
}
2159

    
2160
static void opt_frame_crop_left(const char *arg)
2161
{
2162
    frame_leftBand = atoi(arg);
2163
    if (frame_leftBand < 0) {
2164
        fprintf(stderr, "Incorrect left crop size\n");
2165
        exit(1);
2166
    }
2167
    if ((frame_leftBand % 2) != 0) {
2168
        fprintf(stderr, "Left crop size must be a multiple of 2\n");
2169
        exit(1);
2170
    }
2171
    if ((frame_leftBand) >= frame_width){
2172
            fprintf(stderr, "Horizontal crop dimensions are outside the range of the original image.\nRemember to crop first and scale second.\n");
2173
        exit(1);
2174
    }
2175
    frame_width -= frame_leftBand;
2176
}
2177

    
2178
static void opt_frame_crop_right(const char *arg)
2179
{
2180
    frame_rightBand = atoi(arg);
2181
    if (frame_rightBand < 0) {
2182
        fprintf(stderr, "Incorrect right crop size\n");
2183
        exit(1);
2184
    }
2185
    if ((frame_rightBand % 2) != 0) {
2186
        fprintf(stderr, "Right crop size must be a multiple of 2\n");
2187
        exit(1);        
2188
    }
2189
    if ((frame_rightBand) >= frame_width){
2190
            fprintf(stderr, "Horizontal crop dimensions are outside the range of the original image.\nRemember to crop first and scale second.\n");
2191
        exit(1);
2192
    }
2193
    frame_width -= frame_rightBand;
2194
}
2195

    
2196
static void opt_frame_size(const char *arg)
2197
{
2198
    if (parse_image_size(&frame_width, &frame_height, arg) < 0) {
2199
        fprintf(stderr, "Incorrect frame size\n");
2200
        exit(1);
2201
    }
2202
    if ((frame_width % 2) != 0 || (frame_height % 2) != 0) {
2203
        fprintf(stderr, "Frame size must be a multiple of 2\n");
2204
        exit(1);
2205
    }
2206
}
2207

    
2208

    
2209
#define SCALEBITS 10
2210
#define ONE_HALF  (1 << (SCALEBITS - 1))
2211
#define FIX(x)          ((int) ((x) * (1<<SCALEBITS) + 0.5))
2212

    
2213
#define RGB_TO_Y(r, g, b) \
2214
((FIX(0.29900) * (r) + FIX(0.58700) * (g) + \
2215
  FIX(0.11400) * (b) + ONE_HALF) >> SCALEBITS)
2216

    
2217
#define RGB_TO_U(r1, g1, b1, shift)\
2218
(((- FIX(0.16874) * r1 - FIX(0.33126) * g1 +         \
2219
     FIX(0.50000) * b1 + (ONE_HALF << shift) - 1) >> (SCALEBITS + shift)) + 128)
2220

    
2221
#define RGB_TO_V(r1, g1, b1, shift)\
2222
(((FIX(0.50000) * r1 - FIX(0.41869) * g1 -           \
2223
   FIX(0.08131) * b1 + (ONE_HALF << shift) - 1) >> (SCALEBITS + shift)) + 128)
2224

    
2225
static void opt_pad_color(const char *arg) {
2226
    /* Input is expected to be six hex digits similar to
2227
       how colors are expressed in html tags (but without the #) */
2228
    int rgb = strtol(arg, NULL, 16);
2229
    int r,g,b;
2230
    
2231
    r = (rgb >> 16); 
2232
    g = ((rgb >> 8) & 255);
2233
    b = (rgb & 255);
2234

    
2235
    padcolor[0] = RGB_TO_Y(r,g,b);
2236
    padcolor[1] = RGB_TO_U(r,g,b,0);
2237
    padcolor[2] = RGB_TO_V(r,g,b,0);
2238
}
2239

    
2240
static void opt_frame_pad_top(const char *arg)
2241
{
2242
    frame_padtop = atoi(arg); 
2243
    if (frame_padtop < 0) {
2244
        fprintf(stderr, "Incorrect top pad size\n");
2245
        exit(1);
2246
    }
2247
    if ((frame_padtop % 2) != 0) {
2248
        fprintf(stderr, "Top pad size must be a multiple of 2\n");
2249
        exit(1);
2250
    }
2251
}
2252

    
2253
static void opt_frame_pad_bottom(const char *arg)
2254
{
2255
    frame_padbottom = atoi(arg); 
2256
    if (frame_padbottom < 0) {
2257
        fprintf(stderr, "Incorrect bottom pad size\n");
2258
        exit(1);
2259
    }
2260
    if ((frame_padbottom % 2) != 0) {
2261
        fprintf(stderr, "Bottom pad size must be a multiple of 2\n");
2262
        exit(1);
2263
    }
2264
}
2265

    
2266

    
2267
static void opt_frame_pad_left(const char *arg)
2268
{
2269
    frame_padleft = atoi(arg); 
2270
    if (frame_padleft < 0) {
2271
        fprintf(stderr, "Incorrect left pad size\n");
2272
        exit(1);
2273
    }
2274
    if ((frame_padleft % 2) != 0) {
2275
        fprintf(stderr, "Left pad size must be a multiple of 2\n");
2276
        exit(1);
2277
    }
2278
}
2279

    
2280

    
2281
static void opt_frame_pad_right(const char *arg)
2282
{
2283
    frame_padright = atoi(arg); 
2284
    if (frame_padright < 0) {
2285
        fprintf(stderr, "Incorrect right pad size\n");
2286
        exit(1);
2287
    }
2288
    if ((frame_padright % 2) != 0) {
2289
        fprintf(stderr, "Right pad size must be a multiple of 2\n");
2290
        exit(1);
2291
    }
2292
}
2293

    
2294

    
2295
static void opt_frame_pix_fmt(const char *arg)
2296
{
2297
    frame_pix_fmt = avcodec_get_pix_fmt(arg);
2298
}
2299

    
2300
static void opt_frame_aspect_ratio(const char *arg)
2301
{
2302
    int x = 0, y = 0;
2303
    double ar = 0;
2304
    const char *p;
2305
    
2306
    p = strchr(arg, ':');
2307
    if (p) {
2308
        x = strtol(arg, (char **)&arg, 10);
2309
        if (arg == p)
2310
            y = strtol(arg+1, (char **)&arg, 10);
2311
        if (x > 0 && y > 0)
2312
            ar = (double)x / (double)y;
2313
    } else
2314
        ar = strtod(arg, (char **)&arg);
2315

    
2316
    if (!ar) {
2317
        fprintf(stderr, "Incorrect aspect ratio specification.\n");
2318
        exit(1);
2319
    }
2320
    frame_aspect_ratio = ar;
2321
}
2322

    
2323
static void opt_gop_size(const char *arg)
2324
{
2325
    gop_size = atoi(arg);
2326
}
2327

    
2328
static void opt_b_frames(const char *arg)
2329
{
2330
    b_frames = atoi(arg);
2331
    if (b_frames > FF_MAX_B_FRAMES) {
2332
        fprintf(stderr, "\nCannot have more than %d B frames, increase FF_MAX_B_FRAMES.\n", FF_MAX_B_FRAMES);
2333
        exit(1);
2334
    } else if (b_frames < 1) {
2335
        fprintf(stderr, "\nNumber of B frames must be higher than 0\n");
2336
        exit(1);
2337
    }
2338
}
2339

    
2340
static void opt_mb_decision(const char *arg)
2341
{
2342
    mb_decision = atoi(arg);
2343
}
2344

    
2345
static void opt_mb_cmp(const char *arg)
2346
{
2347
    mb_cmp = atoi(arg);
2348
}
2349

    
2350
static void opt_ildct_cmp(const char *arg)
2351
{
2352
    ildct_cmp = atoi(arg);
2353
}
2354

    
2355
static void opt_sub_cmp(const char *arg)
2356
{
2357
    sub_cmp = atoi(arg);
2358
}
2359

    
2360
static void opt_cmp(const char *arg)
2361
{
2362
    cmp = atoi(arg);
2363
}
2364

    
2365
static void opt_pre_cmp(const char *arg)
2366
{
2367
    pre_cmp = atoi(arg);
2368
}
2369

    
2370
static void opt_pre_me(const char *arg)
2371
{
2372
    pre_me = atoi(arg);
2373
}
2374

    
2375
static void opt_lumi_mask(const char *arg)
2376
{
2377
    lumi_mask = atof(arg);
2378
}
2379

    
2380
static void opt_dark_mask(const char *arg)
2381
{
2382
    dark_mask = atof(arg);
2383
}
2384

    
2385
static void opt_scplx_mask(const char *arg)
2386
{
2387
    scplx_mask = atof(arg);
2388
}
2389

    
2390
static void opt_tcplx_mask(const char *arg)
2391
{
2392
    tcplx_mask = atof(arg);
2393
}
2394

    
2395
static void opt_p_mask(const char *arg)
2396
{
2397
    p_mask = atof(arg);
2398
}
2399

    
2400
static void opt_qscale(const char *arg)
2401
{
2402
    video_qscale = atof(arg);
2403
    if (video_qscale < 0.01 ||
2404
        video_qscale > 255) {
2405
        fprintf(stderr, "qscale must be >= 0.01 and <= 255\n");
2406
        exit(1);
2407
    }
2408
}
2409

    
2410
static void opt_lmax(const char *arg)
2411
{
2412
    video_lmax = atof(arg)*FF_QP2LAMBDA;
2413
}
2414

    
2415
static void opt_lmin(const char *arg)
2416
{
2417
    video_lmin = atof(arg)*FF_QP2LAMBDA;
2418
}
2419

    
2420
static void opt_qmin(const char *arg)
2421
{
2422
    video_qmin = atoi(arg);
2423
    if (video_qmin < 0 ||
2424
        video_qmin > 31) {
2425
        fprintf(stderr, "qmin must be >= 1 and <= 31\n");
2426
        exit(1);
2427
    }
2428
}
2429

    
2430
static void opt_qmax(const char *arg)
2431
{
2432
    video_qmax = atoi(arg);
2433
    if (video_qmax < 0 ||
2434
        video_qmax > 31) {
2435
        fprintf(stderr, "qmax must be >= 1 and <= 31\n");
2436
        exit(1);
2437
    }
2438
}
2439

    
2440
static void opt_mb_qmin(const char *arg)
2441
{
2442
    video_mb_qmin = atoi(arg);
2443
    if (video_mb_qmin < 0 ||
2444
        video_mb_qmin > 31) {
2445
        fprintf(stderr, "qmin must be >= 1 and <= 31\n");
2446
        exit(1);
2447
    }
2448
}
2449

    
2450
static void opt_mb_qmax(const char *arg)
2451
{
2452
    video_mb_qmax = atoi(arg);
2453
    if (video_mb_qmax < 0 ||
2454
        video_mb_qmax > 31) {
2455
        fprintf(stderr, "qmax must be >= 1 and <= 31\n");
2456
        exit(1);
2457
    }
2458
}
2459

    
2460
static void opt_qdiff(const char *arg)
2461
{
2462
    video_qdiff = atoi(arg);
2463
    if (video_qdiff < 0 ||
2464
        video_qdiff > 31) {
2465
        fprintf(stderr, "qdiff must be >= 1 and <= 31\n");
2466
        exit(1);
2467
    }
2468
}
2469

    
2470
static void opt_qblur(const char *arg)
2471
{
2472
    video_qblur = atof(arg);
2473
}
2474

    
2475
static void opt_qcomp(const char *arg)
2476
{
2477
    video_qcomp = atof(arg);
2478
}
2479

    
2480
static void opt_rc_initial_cplx(const char *arg)
2481
{
2482
    video_rc_initial_cplx = atof(arg);
2483
}
2484
static void opt_b_qfactor(const char *arg)
2485
{
2486
    video_b_qfactor = atof(arg);
2487
}
2488
static void opt_i_qfactor(const char *arg)
2489
{
2490
    video_i_qfactor = atof(arg);
2491
}
2492
static void opt_b_qoffset(const char *arg)
2493
{
2494
    video_b_qoffset = atof(arg);
2495
}
2496
static void opt_i_qoffset(const char *arg)
2497
{
2498
    video_i_qoffset = atof(arg);
2499
}
2500

    
2501
static void opt_ibias(const char *arg)
2502
{
2503
    video_intra_quant_bias = atoi(arg);
2504
}
2505
static void opt_pbias(const char *arg)
2506
{
2507
    video_inter_quant_bias = atoi(arg);
2508
}
2509

    
2510
static void opt_packet_size(const char *arg)
2511
{
2512
    packet_size= atoi(arg);
2513
}
2514

    
2515
static void opt_error_rate(const char *arg)
2516
{
2517
    error_rate= atoi(arg);
2518
}
2519

    
2520
static void opt_strict(const char *arg)
2521
{
2522
    strict= atoi(arg);
2523
}
2524

    
2525
static void opt_top_field_first(const char *arg)
2526
{
2527
    top_field_first= atoi(arg);
2528
}
2529

    
2530
static void opt_noise_reduction(const char *arg)
2531
{
2532
    noise_reduction= atoi(arg);
2533
}
2534

    
2535
static void opt_qns(const char *arg)
2536
{
2537
    qns= atoi(arg);
2538
}
2539

    
2540
static void opt_sc_threshold(const char *arg)
2541
{
2542
    sc_threshold= atoi(arg);
2543
}
2544

    
2545
static void opt_me_range(const char *arg)
2546
{
2547
    me_range = atoi(arg);
2548
}
2549

    
2550
static void opt_thread_count(const char *arg)
2551
{
2552
    thread_count= atoi(arg);
2553
#if !defined(HAVE_PTHREADS) && !defined(HAVE_W32THREADS)
2554
    if (verbose >= 0)
2555
        fprintf(stderr, "Warning: not compiled with thread support, using thread emulation\n");
2556
#endif
2557
}
2558

    
2559
static void opt_audio_bitrate(const char *arg)
2560
{
2561
    audio_bit_rate = atoi(arg) * 1000;
2562
}
2563

    
2564
static void opt_audio_rate(const char *arg)
2565
{
2566
    audio_sample_rate = atoi(arg);
2567
}
2568

    
2569
static void opt_audio_channels(const char *arg)
2570
{
2571
    audio_channels = atoi(arg);
2572
}
2573

    
2574
static void opt_video_device(const char *arg)
2575
{
2576
    video_device = av_strdup(arg);
2577
}
2578

    
2579
static void opt_video_channel(const char *arg)
2580
{
2581
    video_channel = strtol(arg, NULL, 0);
2582
}
2583

    
2584
static void opt_video_standard(const char *arg)
2585
{
2586
    video_standard = av_strdup(arg);
2587
}
2588

    
2589
static void opt_audio_device(const char *arg)
2590
{
2591
    audio_device = av_strdup(arg);
2592
}
2593

    
2594
static void opt_dv1394(const char *arg)
2595
{
2596
    video_grab_format = "dv1394";
2597
    audio_grab_format = NULL;
2598
}
2599

    
2600
static void opt_audio_codec(const char *arg)
2601
{
2602
    AVCodec *p;
2603

    
2604
    if (!strcmp(arg, "copy")) {
2605
        audio_stream_copy = 1;
2606
    } else {
2607
        p = first_avcodec;
2608
        while (p) {
2609
            if (!strcmp(p->name, arg) && p->type == CODEC_TYPE_AUDIO)
2610
                break;
2611
            p = p->next;
2612
        }
2613
        if (p == NULL) {
2614
            fprintf(stderr, "Unknown audio codec '%s'\n", arg);
2615
            exit(1);
2616
        } else {
2617
            audio_codec_id = p->id;
2618
        }
2619
    }
2620
}
2621

    
2622
static void opt_audio_tag(const char *arg)
2623
{
2624
    char *tail;
2625
    audio_codec_tag= strtol(arg, &tail, 0);
2626

    
2627
    if(!tail || *tail)
2628
        audio_codec_tag= arg[0] + (arg[1]<<8) + (arg[2]<<16) + (arg[3]<<24);
2629
}
2630

    
2631
static void opt_video_tag(const char *arg)
2632
{
2633
    char *tail;
2634
    video_codec_tag= strtol(arg, &tail, 0);
2635

    
2636
    if(!tail || *tail)
2637
        video_codec_tag= arg[0] + (arg[1]<<8) + (arg[2]<<16) + (arg[3]<<24);
2638
}
2639

    
2640
static void add_frame_hooker(const char *arg)
2641
{
2642
    int argc = 0;
2643
    char *argv[64];
2644
    int i;
2645
    char *args = av_strdup(arg);
2646

    
2647
    using_vhook = 1;
2648

    
2649
    argv[0] = strtok(args, " ");
2650
    while (argc < 62 && (argv[++argc] = strtok(NULL, " "))) {
2651
    }
2652

    
2653
    i = frame_hook_add(argc, argv);
2654

    
2655
    if (i != 0) {
2656
        fprintf(stderr, "Failed to add video hook function: %s\n", arg);
2657
        exit(1);
2658
    }
2659
}
2660

    
2661
const char *motion_str[] = {
2662
    "zero",
2663
    "full",
2664
    "log",
2665
    "phods",
2666
    "epzs",
2667
    "x1",
2668
    NULL,
2669
};
2670

    
2671
static void opt_motion_estimation(const char *arg)
2672
{
2673
    const char **p;
2674
    p = motion_str;
2675
    for(;;) {
2676
        if (!*p) {
2677
            fprintf(stderr, "Unknown motion estimation method '%s'\n", arg);
2678
            exit(1);
2679
        }
2680
        if (!strcmp(*p, arg))
2681
            break;
2682
        p++;
2683
    }
2684
    me_method = (p - motion_str) + 1;
2685
}
2686

    
2687
static void opt_video_codec(const char *arg)
2688
{
2689
    AVCodec *p;
2690

    
2691
    if (!strcmp(arg, "copy")) {
2692
        video_stream_copy = 1;
2693
    } else {
2694
        p = first_avcodec;
2695
        while (p) {
2696
            if (!strcmp(p->name, arg) && p->type == CODEC_TYPE_VIDEO)
2697
                break;
2698
            p = p->next;
2699
        }
2700
        if (p == NULL) {
2701
            fprintf(stderr, "Unknown video codec '%s'\n", arg);
2702
            exit(1);
2703
        } else {
2704
            video_codec_id = p->id;
2705
        }
2706
    }
2707
}
2708

    
2709
static void opt_map(const char *arg)
2710
{
2711
    AVStreamMap *m;
2712
    const char *p;
2713

    
2714
    p = arg;
2715
    m = &stream_maps[nb_stream_maps++];
2716

    
2717
    m->file_index = strtol(arg, (char **)&p, 0);
2718
    if (*p)
2719
        p++;
2720

    
2721
    m->stream_index = strtol(p, (char **)&p, 0);
2722
}
2723

    
2724
static void opt_map_meta_data(const char *arg)
2725
{
2726
    AVMetaDataMap *m;
2727
    const char *p;
2728
        
2729
    p = arg;
2730
    m = &meta_data_maps[nb_meta_data_maps++];
2731

    
2732
    m->out_file = strtol(arg, (char **)&p, 0);
2733
    if (*p)
2734
        p++;
2735

    
2736
    m->in_file = strtol(p, (char **)&p, 0);
2737
}
2738

    
2739
static void opt_recording_time(const char *arg)
2740
{
2741
    recording_time = parse_date(arg, 1);
2742
}
2743

    
2744
static void opt_start_time(const char *arg)
2745
{
2746
    start_time = parse_date(arg, 1);
2747
}
2748

    
2749
static void opt_rec_timestamp(const char *arg)
2750
{
2751
    rec_timestamp = parse_date(arg, 0) / 1000000;
2752
}
2753

    
2754
static void opt_input_ts_offset(const char *arg)
2755
{
2756
    input_ts_offset = parse_date(arg, 1);
2757
}
2758

    
2759
static void opt_input_file(const char *filename)
2760
{
2761
    AVFormatContext *ic;
2762
    AVFormatParameters params, *ap = &params;
2763
    int err, i, ret, rfps, rfps_base;
2764
    int64_t timestamp;
2765

    
2766
    if (!strcmp(filename, "-"))
2767
        filename = "pipe:";
2768

    
2769
    using_stdin |= !strcmp(filename, "pipe:" ) || 
2770
                   !strcmp( filename, "/dev/stdin" );
2771

    
2772
    /* get default parameters from command line */
2773
    memset(ap, 0, sizeof(*ap));
2774
    ap->sample_rate = audio_sample_rate;
2775
    ap->channels = audio_channels;
2776
    ap->frame_rate = frame_rate;
2777
    ap->frame_rate_base = frame_rate_base;
2778
    ap->width = frame_width + frame_padleft + frame_padright;
2779
    ap->height = frame_height + frame_padtop + frame_padbottom;
2780
    ap->image_format = image_format;
2781
    ap->pix_fmt = frame_pix_fmt;
2782

    
2783
    /* open the input file with generic libav function */
2784
    err = av_open_input_file(&ic, filename, file_iformat, 0, ap);
2785
    if (err < 0) {
2786
        print_error(filename, err);
2787
        exit(1);
2788
    }
2789
    
2790
    /* If not enough info to get the stream parameters, we decode the
2791
       first frames to get it. (used in mpeg case for example) */
2792
    ret = av_find_stream_info(ic);
2793
    if (ret < 0 && verbose >= 0) {
2794
        fprintf(stderr, "%s: could not find codec parameters\n", filename);
2795
        exit(1);
2796
    }
2797

    
2798
    timestamp = start_time;
2799
    /* add the stream start time */
2800
    if (ic->start_time != AV_NOPTS_VALUE)
2801
        timestamp += ic->start_time;
2802

    
2803
    /* if seeking requested, we execute it */
2804
    if (start_time != 0) {
2805
        ret = av_seek_frame(ic, -1, timestamp, AVSEEK_FLAG_BACKWARD);
2806
        if (ret < 0) {
2807
            fprintf(stderr, "%s: could not seek to position %0.3f\n", 
2808
                    filename, (double)timestamp / AV_TIME_BASE);
2809
        }
2810
        /* reset seek info */
2811
        start_time = 0;
2812
    }
2813

    
2814
    /* update the current parameters so that they match the one of the input stream */
2815
    for(i=0;i<ic->nb_streams;i++) {
2816
        AVCodecContext *enc = &ic->streams[i]->codec;
2817
#if defined(HAVE_PTHREADS) || defined(HAVE_W32THREADS)
2818
        if(thread_count>1)
2819
            avcodec_thread_init(enc, thread_count);
2820
#endif
2821
        enc->thread_count= thread_count;
2822
        switch(enc->codec_type) {
2823
        case CODEC_TYPE_AUDIO:
2824
            //fprintf(stderr, "\nInput Audio channels: %d", enc->channels);
2825
            audio_channels = enc->channels;
2826
            audio_sample_rate = enc->sample_rate;
2827
            break;
2828
        case CODEC_TYPE_VIDEO:
2829
            frame_height = enc->height;
2830
            frame_width = enc->width;
2831
            frame_aspect_ratio = av_q2d(enc->sample_aspect_ratio) * enc->width / enc->height;
2832
            frame_pix_fmt = enc->pix_fmt;
2833
            rfps      = ic->streams[i]->r_frame_rate;
2834
            rfps_base = ic->streams[i]->r_frame_rate_base;
2835
            enc->workaround_bugs = workaround_bugs;
2836
            enc->error_resilience = error_resilience; 
2837
            enc->error_concealment = error_concealment; 
2838
            enc->idct_algo = idct_algo;
2839
            enc->debug = debug;
2840
            enc->debug_mv = debug_mv;            
2841
            enc->lowres= lowres;
2842
            if(bitexact)
2843
                enc->flags|= CODEC_FLAG_BITEXACT;
2844
            if(me_threshold)
2845
                enc->debug |= FF_DEBUG_MV;
2846

    
2847
            assert(enc->frame_rate_base == rfps_base); // should be true for now
2848
            if (enc->frame_rate != rfps) { 
2849

    
2850
                if (verbose >= 0)
2851
                    fprintf(stderr,"\nSeems that stream %d comes from film source: %2.2f->%2.2f\n",
2852
                            i, (float)enc->frame_rate / enc->frame_rate_base,
2853

    
2854
                    (float)rfps / rfps_base);
2855
            }
2856
            /* update the current frame rate to match the stream frame rate */
2857
            frame_rate      = rfps;
2858
            frame_rate_base = rfps_base;
2859

    
2860
            enc->rate_emu = rate_emu;
2861
            break;
2862
        case CODEC_TYPE_DATA:
2863
            break;
2864
        default:
2865
            av_abort();
2866
        }
2867
    }
2868
    
2869
    input_files[nb_input_files] = ic;
2870
    input_files_ts_offset[nb_input_files] = input_ts_offset - (copy_ts ? 0 : timestamp);
2871
    /* dump the file content */
2872
    if (verbose >= 0)
2873
        dump_format(ic, nb_input_files, filename, 0);
2874

    
2875
    nb_input_files++;
2876
    file_iformat = NULL;
2877
    file_oformat = NULL;
2878
    image_format = NULL;
2879

    
2880
    rate_emu = 0;
2881
}
2882

    
2883
static void check_audio_video_inputs(int *has_video_ptr, int *has_audio_ptr)
2884
{
2885
    int has_video, has_audio, i, j;
2886
    AVFormatContext *ic;
2887

    
2888
    has_video = 0;
2889
    has_audio = 0;
2890
    for(j=0;j<nb_input_files;j++) {
2891
        ic = input_files[j];
2892
        for(i=0;i<ic->nb_streams;i++) {
2893
            AVCodecContext *enc = &ic->streams[i]->codec;
2894
            switch(enc->codec_type) {
2895
            case CODEC_TYPE_AUDIO:
2896
                has_audio = 1;
2897
                break;
2898
            case CODEC_TYPE_VIDEO:
2899
                has_video = 1;
2900
                break;
2901
            case CODEC_TYPE_DATA:
2902
                break;
2903
            default:
2904
                av_abort();
2905
            }
2906
        }
2907
    }
2908
    *has_video_ptr = has_video;
2909
    *has_audio_ptr = has_audio;
2910
}
2911

    
2912
static void opt_output_file(const char *filename)
2913
{
2914
    AVStream *st;
2915
    AVFormatContext *oc;
2916
    int use_video, use_audio, nb_streams, input_has_video, input_has_audio;
2917
    int codec_id;
2918
    AVFormatParameters params, *ap = &params;
2919

    
2920
    if (!strcmp(filename, "-"))
2921
        filename = "pipe:";
2922

    
2923
    oc = av_alloc_format_context();
2924

    
2925
    if (!file_oformat) {
2926
        file_oformat = guess_format(NULL, filename, NULL);
2927
        if (!file_oformat) {
2928
            fprintf(stderr, "Unable for find a suitable output format for '%s'\n",
2929
                    filename);
2930
            exit(1);
2931
        }
2932
    }
2933
    
2934
    oc->oformat = file_oformat;
2935

    
2936
    if (!strcmp(file_oformat->name, "ffm") && 
2937
        strstart(filename, "http:", NULL)) {
2938
        /* special case for files sent to ffserver: we get the stream
2939
           parameters from ffserver */
2940
        if (read_ffserver_streams(oc, filename) < 0) {
2941
            fprintf(stderr, "Could not read stream parameters from '%s'\n", filename);
2942
            exit(1);
2943
        }
2944
    } else {
2945
        use_video = file_oformat->video_codec != CODEC_ID_NONE || video_stream_copy;
2946
        use_audio = file_oformat->audio_codec != CODEC_ID_NONE || audio_stream_copy;
2947

    
2948
        /* disable if no corresponding type found and at least one
2949
           input file */
2950
        if (nb_input_files > 0) {
2951
            check_audio_video_inputs(&input_has_video, &input_has_audio);
2952
            if (!input_has_video)
2953
                use_video = 0;
2954
            if (!input_has_audio)
2955
                use_audio = 0;
2956
        }
2957

    
2958
        /* manual disable */
2959
        if (audio_disable) {
2960
            use_audio = 0;
2961
        }
2962
        if (video_disable) {
2963
            use_video = 0;
2964
        }
2965
        
2966
        nb_streams = 0;
2967
        if (use_video) {
2968
            AVCodecContext *video_enc;
2969
            
2970
            st = av_new_stream(oc, nb_streams++);
2971
            if (!st) {
2972
                fprintf(stderr, "Could not alloc stream\n");
2973
                exit(1);
2974
            }
2975
#if defined(HAVE_PTHREADS) || defined(HAVE_W32THREADS)
2976
            if(thread_count>1)
2977
                avcodec_thread_init(&st->codec, thread_count);
2978
#endif
2979

    
2980
            video_enc = &st->codec;
2981
            
2982
            if(video_codec_tag)
2983
                video_enc->codec_tag= video_codec_tag;
2984
                
2985
            if(!strcmp(file_oformat->name, "mp4") || !strcmp(file_oformat->name, "mov") || !strcmp(file_oformat->name, "3gp"))
2986
                video_enc->flags |= CODEC_FLAG_GLOBAL_HEADER;
2987
            if (video_stream_copy) {
2988
                st->stream_copy = 1;
2989
                video_enc->codec_type = CODEC_TYPE_VIDEO;
2990
            } else {
2991
                char *p;
2992
                int i;
2993
                AVCodec *codec;
2994
            
2995
                codec_id = file_oformat->video_codec;
2996
                if (video_codec_id != CODEC_ID_NONE)
2997
                    codec_id = video_codec_id;
2998
                
2999
                video_enc->codec_id = codec_id;
3000
                codec = avcodec_find_encoder(codec_id);
3001
                
3002
                video_enc->bit_rate = video_bit_rate;
3003
                video_enc->bit_rate_tolerance = video_bit_rate_tolerance;
3004
                video_enc->frame_rate = frame_rate; 
3005
                video_enc->frame_rate_base = frame_rate_base; 
3006
                if(codec && codec->supported_framerates){
3007
                    const AVRational *p= codec->supported_framerates;
3008
                    AVRational req= (AVRational){frame_rate, frame_rate_base};
3009
                    const AVRational *best=NULL;
3010
                    AVRational best_error= (AVRational){INT_MAX, 1};
3011
                    for(; p->den!=0; p++){
3012
                        AVRational error= av_sub_q(req, *p);
3013
                        if(error.num <0) error.num *= -1;
3014
                        if(av_cmp_q(error, best_error) < 0){
3015
                            best_error= error;
3016
                            best= p;
3017
                        }
3018
                    }
3019
                    video_enc->frame_rate     = best->num;
3020
                    video_enc->frame_rate_base= best->den;
3021
                }
3022
                
3023
                video_enc->width = frame_width + frame_padright + frame_padleft;
3024
                video_enc->height = frame_height + frame_padtop + frame_padbottom;
3025
                video_enc->sample_aspect_ratio = av_d2q(frame_aspect_ratio*frame_height/frame_width, 255);
3026
                video_enc->pix_fmt = frame_pix_fmt;
3027

    
3028
                if(codec && codec->pix_fmts){
3029
                    const enum PixelFormat *p= codec->pix_fmts;
3030
                    for(; *p!=-1; p++){
3031
                        if(*p == video_enc->pix_fmt)
3032
                            break;
3033
                    }
3034
                    if(*p == -1)
3035
                        video_enc->pix_fmt = codec->pix_fmts[0];
3036
                }
3037

    
3038
                if (!intra_only)
3039
                    video_enc->gop_size = gop_size;
3040
                else
3041
                    video_enc->gop_size = 0;
3042
                if (video_qscale || same_quality) {
3043
                    video_enc->flags |= CODEC_FLAG_QSCALE;
3044
                    st->quality = FF_QP2LAMBDA * video_qscale;
3045
                }
3046

    
3047
                if(intra_matrix)
3048
                    video_enc->intra_matrix = intra_matrix;
3049
                if(inter_matrix)
3050
                    video_enc->inter_matrix = inter_matrix;
3051

    
3052
                if(bitexact)
3053
                    video_enc->flags |= CODEC_FLAG_BITEXACT;
3054

    
3055
                video_enc->mb_decision = mb_decision;
3056
                video_enc->mb_cmp = mb_cmp;
3057
                video_enc->ildct_cmp = ildct_cmp;
3058
                video_enc->me_sub_cmp = sub_cmp;
3059
                video_enc->me_cmp = cmp;
3060
                video_enc->me_pre_cmp = pre_cmp;
3061
                video_enc->pre_me = pre_me;
3062
                video_enc->lumi_masking = lumi_mask;
3063
                video_enc->dark_masking = dark_mask;
3064
                video_enc->spatial_cplx_masking = scplx_mask;
3065
                video_enc->temporal_cplx_masking = tcplx_mask;
3066
                video_enc->p_masking = p_mask;
3067
                video_enc->quantizer_noise_shaping= qns;
3068
                
3069
                if (use_umv) {
3070
                    video_enc->flags |= CODEC_FLAG_H263P_UMV;
3071
                }
3072
                if (use_ss) {
3073
                    video_enc->flags |= CODEC_FLAG_H263P_SLICE_STRUCT;
3074
                }
3075
                   if (use_aic) {
3076
                    video_enc->flags |= CODEC_FLAG_H263P_AIC;
3077
                }
3078
                   if (use_aiv) {
3079
                    video_enc->flags |= CODEC_FLAG_H263P_AIV;
3080
                }
3081
                if (use_4mv) {
3082
                    video_enc->flags |= CODEC_FLAG_4MV;
3083
                }
3084
                if (use_obmc) {
3085
                    video_enc->flags |= CODEC_FLAG_OBMC;
3086
                }
3087
                if (use_loop) {
3088
                    video_enc->flags |= CODEC_FLAG_LOOP_FILTER;
3089
                }
3090
            
3091
                if(use_part) {
3092
                    video_enc->flags |= CODEC_FLAG_PART;
3093
                }
3094
                   if (use_alt_scan) {
3095
                    video_enc->flags |= CODEC_FLAG_ALT_SCAN;
3096
                }
3097
                   if (use_trell) {
3098
                    video_enc->flags |= CODEC_FLAG_TRELLIS_QUANT;
3099
                }
3100
                   if (use_scan_offset) {
3101
                    video_enc->flags |= CODEC_FLAG_SVCD_SCAN_OFFSET;
3102
                }
3103
                   if (closed_gop) {
3104
                    video_enc->flags |= CODEC_FLAG_CLOSED_GOP;
3105
                }
3106
                if (strict_gop) {
3107
                    video_enc->flags2 |= CODEC_FLAG2_STRICT_GOP;
3108
                }
3109
                   if (use_qpel) {
3110
                    video_enc->flags |= CODEC_FLAG_QPEL;
3111
                }
3112
                   if (use_qprd) {
3113
                    video_enc->flags |= CODEC_FLAG_QP_RD;
3114
                }
3115
                   if (use_cbprd) {
3116
                    video_enc->flags |= CODEC_FLAG_CBP_RD;
3117
                }
3118
                if (b_frames) {
3119
                    video_enc->max_b_frames = b_frames;
3120
                    video_enc->b_frame_strategy = 0;
3121
                    video_enc->b_quant_factor = 2.0;
3122
                }
3123
                if (do_interlace_dct) {
3124
                    video_enc->flags |= CODEC_FLAG_INTERLACED_DCT;
3125
                }
3126
                if (do_interlace_me) {
3127
                    video_enc->flags |= CODEC_FLAG_INTERLACED_ME;
3128
                }
3129
                video_enc->qmin = video_qmin;
3130
                video_enc->qmax = video_qmax;
3131
                video_enc->lmin = video_lmin;
3132
                video_enc->lmax = video_lmax;
3133
                video_enc->mb_qmin = video_mb_qmin;
3134
                video_enc->mb_qmax = video_mb_qmax;
3135
                video_enc->max_qdiff = video_qdiff;
3136
                video_enc->qblur = video_qblur;
3137
                video_enc->qcompress = video_qcomp;
3138
                video_enc->rc_eq = video_rc_eq;
3139
                video_enc->debug = debug;
3140
                video_enc->debug_mv = debug_mv;
3141
                video_enc->thread_count = thread_count;
3142
                p= video_rc_override_string;
3143
                for(i=0; p; i++){
3144
                    int start, end, q;
3145
                    int e=sscanf(p, "%d,%d,%d", &start, &end, &q);
3146
                    if(e!=3){
3147
                        fprintf(stderr, "error parsing rc_override\n");
3148
                        exit(1);
3149
                    }
3150
                    video_enc->rc_override= 
3151
                        av_realloc(video_enc->rc_override, 
3152
                                   sizeof(RcOverride)*(i+1));
3153
                    video_enc->rc_override[i].start_frame= start;
3154
                    video_enc->rc_override[i].end_frame  = end;
3155
                    if(q>0){
3156
                        video_enc->rc_override[i].qscale= q;
3157
                        video_enc->rc_override[i].quality_factor= 1.0;
3158
                    }
3159
                    else{
3160
                        video_enc->rc_override[i].qscale= 0;
3161
                        video_enc->rc_override[i].quality_factor= -q/100.0;
3162
                    }
3163
                    p= strchr(p, '/');
3164
                    if(p) p++;
3165
                }
3166
                video_enc->rc_override_count=i;
3167

    
3168
                video_enc->rc_max_rate = video_rc_max_rate;
3169
                video_enc->rc_min_rate = video_rc_min_rate;
3170
                video_enc->rc_buffer_size = video_rc_buffer_size;
3171
                video_enc->rc_initial_buffer_occupancy = video_rc_buffer_size*3/4;
3172
                video_enc->rc_buffer_aggressivity= video_rc_buffer_aggressivity;
3173
                video_enc->rc_initial_cplx= video_rc_initial_cplx;
3174
                video_enc->i_quant_factor = video_i_qfactor;
3175
                video_enc->b_quant_factor = video_b_qfactor;
3176
                video_enc->i_quant_offset = video_i_qoffset;
3177
                video_enc->b_quant_offset = video_b_qoffset;
3178
                video_enc->intra_quant_bias = video_intra_quant_bias;
3179
                video_enc->inter_quant_bias = video_inter_quant_bias;
3180
                video_enc->dct_algo = dct_algo;
3181
                video_enc->idct_algo = idct_algo;
3182
                video_enc->me_threshold= me_threshold;
3183
                video_enc->mb_threshold= mb_threshold;
3184
                video_enc->intra_dc_precision= intra_dc_precision - 8;
3185
                video_enc->strict_std_compliance = strict;
3186
                video_enc->error_rate = error_rate;
3187
                video_enc->noise_reduction= noise_reduction;
3188
                video_enc->scenechange_threshold= sc_threshold;
3189
                video_enc->me_range = me_range;
3190
                video_enc->coder_type= coder;
3191
                video_enc->context_model= context;
3192
                video_enc->prediction_method= predictor;
3193
                video_enc->profile= video_profile;
3194
                video_enc->level= video_level;
3195
                video_enc->nsse_weight= nsse_weight;
3196
                video_enc->me_subpel_quality= subpel_quality;
3197

    
3198
                if(packet_size){
3199
                    video_enc->rtp_mode= 1;
3200
                    video_enc->rtp_payload_size= packet_size;
3201
                }
3202
            
3203
                if (do_psnr)
3204
                    video_enc->flags|= CODEC_FLAG_PSNR;
3205
            
3206
                video_enc->me_method = me_method;
3207

    
3208
                /* two pass mode */
3209
                if (do_pass) {
3210
                    if (do_pass == 1) {
3211
                        video_enc->flags |= CODEC_FLAG_PASS1;
3212
                    } else {
3213
                        video_enc->flags |= CODEC_FLAG_PASS2;
3214
                    }
3215
                }
3216
            }
3217
        }
3218
    
3219
        if (use_audio) {
3220
            AVCodecContext *audio_enc;
3221

    
3222
            st = av_new_stream(oc, nb_streams++);
3223
            if (!st) {
3224
                fprintf(stderr, "Could not alloc stream\n");
3225
                exit(1);
3226
            }
3227
#if defined(HAVE_PTHREADS) || defined(HAVE_W32THREADS)
3228
            if(thread_count>1)
3229
                avcodec_thread_init(&st->codec, thread_count);
3230
#endif
3231

    
3232
            audio_enc = &st->codec;
3233
            audio_enc->codec_type = CODEC_TYPE_AUDIO;
3234

    
3235
            if(audio_codec_tag)
3236
                audio_enc->codec_tag= audio_codec_tag;
3237

    
3238
            if(!strcmp(file_oformat->name, "mp4") || !strcmp(file_oformat->name, "mov") || !strcmp(file_oformat->name, "3gp"))
3239
                audio_enc->flags |= CODEC_FLAG_GLOBAL_HEADER;
3240
            if (audio_stream_copy) {
3241
                st->stream_copy = 1;
3242
                audio_enc->channels = audio_channels;
3243
            } else {
3244
                codec_id = file_oformat->audio_codec;
3245
                if (audio_codec_id != CODEC_ID_NONE)
3246
                    codec_id = audio_codec_id;
3247
                audio_enc->codec_id = codec_id;
3248
                
3249
                audio_enc->bit_rate = audio_bit_rate;
3250
                audio_enc->strict_std_compliance = strict;
3251
                audio_enc->thread_count = thread_count;
3252
                /* For audio codecs other than AC3 or DTS we limit */
3253
                /* the number of coded channels to stereo   */
3254
                if (audio_channels > 2 && codec_id != CODEC_ID_AC3
3255
                    && codec_id != CODEC_ID_DTS) {
3256
                    audio_enc->channels = 2;
3257
                } else
3258
                    audio_enc->channels = audio_channels;
3259
            }
3260
            audio_enc->sample_rate = audio_sample_rate;
3261
        }
3262

    
3263
        oc->nb_streams = nb_streams;
3264

    
3265
        if (!nb_streams) {
3266
            fprintf(stderr, "No audio or video streams available\n");
3267
            exit(1);
3268
        }
3269

    
3270
        oc->timestamp = rec_timestamp;
3271
            
3272
        if (str_title)
3273
            pstrcpy(oc->title, sizeof(oc->title), str_title);
3274
        if (str_author)
3275
            pstrcpy(oc->author, sizeof(oc->author), str_author);
3276
        if (str_copyright)
3277
            pstrcpy(oc->copyright, sizeof(oc->copyright), str_copyright);
3278
        if (str_comment)
3279
            pstrcpy(oc->comment, sizeof(oc->comment), str_comment);
3280
    }
3281

    
3282
    output_files[nb_output_files++] = oc;
3283

    
3284
    strcpy(oc->filename, filename);
3285

    
3286
    /* check filename in case of an image number is expected */
3287
    if (oc->oformat->flags & AVFMT_NEEDNUMBER) {
3288
        if (filename_number_test(oc->filename) < 0) {
3289
            print_error(oc->filename, AVERROR_NUMEXPECTED);
3290
            exit(1);
3291
        }
3292
    }
3293

    
3294
    if (!(oc->oformat->flags & AVFMT_NOFILE)) {
3295
        /* test if it already exists to avoid loosing precious files */
3296
        if (!file_overwrite && 
3297
            (strchr(filename, ':') == NULL ||
3298
             strstart(filename, "file:", NULL))) {
3299
            if (url_exist(filename)) {
3300
                int c;
3301
                
3302
                if ( !using_stdin ) {
3303
                    fprintf(stderr,"File '%s' already exists. Overwrite ? [y/N] ", filename);
3304
                    fflush(stderr);
3305
                    c = getchar();
3306
                    if (toupper(c) != 'Y') {
3307
                        fprintf(stderr, "Not overwriting - exiting\n");
3308
                        exit(1);
3309
                    }
3310
                                }
3311
                                else {
3312
                    fprintf(stderr,"File '%s' already exists. Exiting.\n", filename);
3313
                    exit(1);
3314
                                }
3315
            }
3316
        }
3317
        
3318
        /* open the file */
3319
        if (url_fopen(&oc->pb, filename, URL_WRONLY) < 0) {
3320
            fprintf(stderr, "Could not open '%s'\n", filename);
3321
            exit(1);
3322
        }
3323
    }
3324

    
3325
    memset(ap, 0, sizeof(*ap));
3326
    ap->image_format = image_format;
3327
    if (av_set_parameters(oc, ap) < 0) {
3328
        fprintf(stderr, "%s: Invalid encoding parameters\n",
3329
                oc->filename);
3330
        exit(1);
3331
    }
3332

    
3333
    oc->packet_size= mux_packet_size;
3334
    oc->mux_rate= mux_rate;
3335
    oc->preload= (int)(mux_preload*AV_TIME_BASE);
3336
    oc->max_delay= (int)(mux_max_delay*AV_TIME_BASE);
3337

    
3338
    /* reset some options */
3339
    file_oformat = NULL;
3340
    file_iformat = NULL;
3341
    image_format = NULL;
3342
    audio_disable = 0;
3343
    video_disable = 0;
3344
    audio_codec_id = CODEC_ID_NONE;
3345
    video_codec_id = CODEC_ID_NONE;
3346
    audio_stream_copy = 0;
3347
    video_stream_copy = 0;
3348
}
3349

    
3350
/* prepare dummy protocols for grab */
3351
static void prepare_grab(void)
3352
{
3353
    int has_video, has_audio, i, j;
3354
    AVFormatContext *oc;
3355
    AVFormatContext *ic;
3356
    AVFormatParameters vp1, *vp = &vp1;
3357
    AVFormatParameters ap1, *ap = &ap1;
3358
    
3359
    /* see if audio/video inputs are needed */
3360
    has_video = 0;
3361
    has_audio = 0;
3362
    memset(ap, 0, sizeof(*ap));
3363
    memset(vp, 0, sizeof(*vp));
3364
    vp->frame_rate_base= 1;
3365
    for(j=0;j<nb_output_files;j++) {
3366
        oc = output_files[j];
3367
        for(i=0;i<oc->nb_streams;i++) {
3368
            AVCodecContext *enc = &oc->streams[i]->codec;
3369
            switch(enc->codec_type) {
3370
            case CODEC_TYPE_AUDIO:
3371
                if (enc->sample_rate > ap->sample_rate)
3372
                    ap->sample_rate = enc->sample_rate;
3373
                if (enc->channels > ap->channels)
3374
                    ap->channels = enc->channels;
3375
                has_audio = 1;
3376
                break;
3377
            case CODEC_TYPE_VIDEO:
3378
                if (enc->width > vp->width)
3379
                    vp->width = enc->width;
3380
                if (enc->height > vp->height)
3381
                    vp->height = enc->height;
3382
                
3383
                if (vp->frame_rate_base*(int64_t)enc->frame_rate > enc->frame_rate_base*(int64_t)vp->frame_rate){
3384
                    vp->frame_rate      = enc->frame_rate;
3385
                    vp->frame_rate_base = enc->frame_rate_base;
3386
                }
3387
                has_video = 1;
3388
                break;
3389
            default:
3390
                av_abort();
3391
            }
3392
        }
3393
    }
3394
    
3395
    if (has_video == 0 && has_audio == 0) {
3396
        fprintf(stderr, "Output file must have at least one audio or video stream\n");
3397
        exit(1);
3398
    }
3399
    
3400
    if (has_video) {
3401
        AVInputFormat *fmt1;
3402
        fmt1 = av_find_input_format(video_grab_format);
3403
        vp->device  = video_device;
3404
        vp->channel = video_channel;
3405
        vp->standard = video_standard;
3406
        if (av_open_input_file(&ic, "", fmt1, 0, vp) < 0) {
3407
            fprintf(stderr, "Could not find video grab device\n");
3408
            exit(1);
3409
        }
3410
        /* If not enough info to get the stream parameters, we decode the
3411
           first frames to get it. */
3412
        if ((ic->ctx_flags & AVFMTCTX_NOHEADER) && av_find_stream_info(ic) < 0) {
3413
            fprintf(stderr, "Could not find video grab parameters\n");
3414
            exit(1);
3415
        }
3416
        /* by now video grab has one stream */
3417
        ic->streams[0]->r_frame_rate      = vp->frame_rate;
3418
        ic->streams[0]->r_frame_rate_base = vp->frame_rate_base;
3419
        input_files[nb_input_files] = ic;
3420

    
3421
        if (verbose >= 0)
3422
            dump_format(ic, nb_input_files, "", 0);
3423

    
3424
        nb_input_files++;
3425
    }
3426
    if (has_audio && audio_grab_format) {
3427
        AVInputFormat *fmt1;
3428
        fmt1 = av_find_input_format(audio_grab_format);
3429
        ap->device = audio_device;
3430
        if (av_open_input_file(&ic, "", fmt1, 0, ap) < 0) {
3431
            fprintf(stderr, "Could not find audio grab device\n");
3432
            exit(1);
3433
        }
3434
        input_files[nb_input_files] = ic;
3435

    
3436
        if (verbose >= 0)
3437
            dump_format(ic, nb_input_files, "", 0);
3438

    
3439
        nb_input_files++;
3440
    }
3441
}
3442

    
3443
/* same option as mencoder */
3444
static void opt_pass(const char *pass_str)
3445
{
3446
    int pass;
3447
    pass = atoi(pass_str);
3448
    if (pass != 1 && pass != 2) {
3449
        fprintf(stderr, "pass number can be only 1 or 2\n");
3450
        exit(1);
3451
    }
3452
    do_pass = pass;
3453
}
3454

    
3455
#if defined(CONFIG_WIN32) || defined(CONFIG_OS2)
3456
static int64_t getutime(void)
3457
{
3458
  return av_gettime();
3459
}
3460
#else
3461
static int64_t getutime(void)
3462
{
3463
    struct rusage rusage;
3464

    
3465
    getrusage(RUSAGE_SELF, &rusage);
3466
    return (rusage.ru_utime.tv_sec * 1000000LL) + rusage.ru_utime.tv_usec;
3467
}
3468
#endif
3469

    
3470
extern int ffm_nopts;
3471

    
3472
static void opt_bitexact(void)
3473
{
3474
    bitexact=1;
3475
    /* disable generate of real time pts in ffm (need to be supressed anyway) */
3476
    ffm_nopts = 1;
3477
}
3478

    
3479
static void show_formats(void)
3480
{
3481
    AVInputFormat *ifmt;
3482
    AVOutputFormat *ofmt;
3483
    AVImageFormat *image_fmt;
3484
    URLProtocol *up;
3485
    AVCodec *p, *p2;
3486
    const char **pp, *last_name;
3487

    
3488
    printf("File formats:\n");
3489
    last_name= "000";
3490
    for(;;){
3491
        int decode=0;
3492
        int encode=0;
3493
        const char *name=NULL;
3494

    
3495
        for(ofmt = first_oformat; ofmt != NULL; ofmt = ofmt->next) {
3496
            if((name == NULL || strcmp(ofmt->name, name)<0) &&
3497
                strcmp(ofmt->name, last_name)>0){
3498
                name= ofmt->name;
3499
                encode=1;
3500
            }
3501
        }
3502
        for(ifmt = first_iformat; ifmt != NULL; ifmt = ifmt->next) {
3503
            if((name == NULL || strcmp(ifmt->name, name)<0) &&
3504
                strcmp(ifmt->name, last_name)>0){
3505
                name= ifmt->name;
3506
                encode=0;
3507
            }
3508
            if(name && strcmp(ifmt->name, name)==0)
3509
                decode=1;
3510
        }
3511
        if(name==NULL)
3512
            break;
3513
        last_name= name;
3514
        
3515
        printf(
3516
            " %s%s %s\n", 
3517
            decode ? "D":" ", 
3518
            encode ? "E":" ", 
3519
            name);
3520
    }
3521
    printf("\n");
3522

    
3523
    printf("Image formats:\n");
3524
    for(image_fmt = first_image_format; image_fmt != NULL; 
3525
        image_fmt = image_fmt->next) {
3526
        printf(
3527
            " %s%s %s\n",
3528
            image_fmt->img_read  ? "D":" ",
3529
            image_fmt->img_write ? "E":" ",
3530
            image_fmt->name);
3531
    }
3532
    printf("\n");
3533

    
3534
    printf("Codecs:\n");
3535
    last_name= "000";
3536
    for(;;){
3537
        int decode=0;
3538
        int encode=0;
3539
        int cap=0;
3540

    
3541
        p2=NULL;
3542
        for(p = first_avcodec; p != NULL; p = p->next) {
3543
            if((p2==NULL || strcmp(p->name, p2->name)<0) &&
3544
                strcmp(p->name, last_name)>0){
3545
                p2= p;
3546
                decode= encode= cap=0;
3547
            }
3548
            if(p2 && strcmp(p->name, p2->name)==0){
3549
                if(p->decode) decode=1;
3550
                if(p->encode) encode=1;
3551
                cap |= p->capabilities;
3552
            }
3553
        }
3554
        if(p2==NULL)
3555
            break;
3556
        last_name= p2->name;
3557
        
3558
        printf(
3559
            " %s%s%s%s%s%s %s", 
3560
            decode ? "D": (/*p2->decoder ? "d":*/" "), 
3561
            encode ? "E":" ", 
3562
            p2->type == CODEC_TYPE_AUDIO ? "A":"V",
3563
            cap & CODEC_CAP_DRAW_HORIZ_BAND ? "S":" ",
3564
            cap & CODEC_CAP_DR1 ? "D":" ",
3565
            cap & CODEC_CAP_TRUNCATED ? "T":" ",
3566
            p2->name);
3567
       /* if(p2->decoder && decode==0)
3568
            printf(" use %s for decoding", p2->decoder->name);*/
3569
        printf("\n");
3570
    }
3571
    printf("\n");
3572

    
3573
    printf("Supported file protocols:\n");
3574
    for(up = first_protocol; up != NULL; up = up->next)
3575
        printf(" %s:", up->name);
3576
    printf("\n");
3577
    
3578
    printf("Frame size, frame rate abbreviations:\n ntsc pal qntsc qpal sntsc spal film ntsc-film sqcif qcif cif 4cif\n");
3579
    printf("Motion estimation methods:\n");
3580
    pp = motion_str;
3581
    while (*pp) {
3582
        printf(" %s", *pp);
3583
        if ((pp - motion_str + 1) == ME_ZERO) 
3584
            printf("(fastest)");
3585
        else if ((pp - motion_str + 1) == ME_FULL) 
3586
            printf("(slowest)");
3587
        else if ((pp - motion_str + 1) == ME_EPZS) 
3588
            printf("(default)");
3589
        pp++;
3590
    }
3591
    printf("\n\n");
3592
    printf(
3593
"Note, the names of encoders and decoders dont always match, so there are\n"
3594
"several cases where the above table shows encoder only or decoder only entries\n"
3595
"even though both encoding and decoding are supported for example, the h263\n"
3596
"decoder corresponds to the h263 and h263p encoders, for file formats its even\n"
3597
"worse\n");
3598
    exit(1);
3599
}
3600

    
3601
void parse_matrix_coeffs(uint16_t *dest, const char *str)
3602
{
3603
    int i;
3604
    const char *p = str;
3605
    for(i = 0;; i++) {
3606
        dest[i] = atoi(p);
3607
        if(i == 63)
3608
            break;
3609
        p = strchr(p, ',');
3610
        if(!p) {
3611
            fprintf(stderr, "Syntax error in matrix \"%s\" at coeff %d\n", str, i);
3612
            exit(1);
3613
        }
3614
        p++;
3615
    }
3616
}
3617

    
3618
void opt_inter_matrix(const char *arg)
3619
{
3620
    inter_matrix = av_mallocz(sizeof(uint16_t) * 64);
3621
    parse_matrix_coeffs(inter_matrix, arg);
3622
}
3623

    
3624
void opt_intra_matrix(const char *arg)
3625
{
3626
    intra_matrix = av_mallocz(sizeof(uint16_t) * 64);
3627
    parse_matrix_coeffs(intra_matrix, arg);
3628
}
3629

    
3630
static void opt_target(const char *arg)
3631
{
3632
    int norm = -1;
3633

    
3634
    if(!strncmp(arg, "pal-", 4)) {
3635
        norm = 0;
3636
        arg += 4;
3637
    } else if(!strncmp(arg, "ntsc-", 5)) {
3638
        norm = 1;
3639
        arg += 5;
3640
    } else {
3641
        int fr;
3642
        /* Calculate FR via float to avoid int overflow */
3643
        fr = (int)(frame_rate * 1000.0 / frame_rate_base);
3644
        if(fr == 25000) {
3645
            norm = 0;
3646
        } else if((fr == 29970) || (fr == 23976)) {
3647
            norm = 1;
3648
        } else {
3649
            /* Try to determine PAL/NTSC by peeking in the input files */
3650
            if(nb_input_files) {
3651
                int i, j;
3652
                for(j = 0; j < nb_input_files; j++) {
3653
                    for(i = 0; i < input_files[j]->nb_streams; i++) {
3654
                        AVCodecContext *c = &input_files[j]->streams[i]->codec;
3655
                        if(c->codec_type != CODEC_TYPE_VIDEO)
3656
                            continue;
3657
                        fr = c->frame_rate * 1000 / c->frame_rate_base;
3658
                        if(fr == 25000) {
3659
                            norm = 0;
3660
                            break;
3661
                        } else if((fr == 29970) || (fr == 23976)) {
3662
                            norm = 1;
3663
                            break;
3664
                        }
3665
                    }
3666
                    if(norm >= 0)
3667
                        break;
3668
                }
3669
            }
3670
        }
3671
        if(verbose && norm >= 0)
3672
            printf("Assuming %s for target.\n", norm ? "NTSC" : "PAL");
3673
    }
3674

    
3675
    if(norm < 0) {
3676
        fprintf(stderr, "Could not determine norm (PAL/NTSC) for target.\n");
3677
        fprintf(stderr, "Please prefix target with \"pal-\" or \"ntsc-\",\n");
3678
        fprintf(stderr, "or set a framerate with \"-r xxx\".\n");
3679
        exit(1);
3680
    }
3681

    
3682
    if(!strcmp(arg, "vcd")) {
3683

    
3684
        opt_video_codec("mpeg1video");
3685
        opt_audio_codec("mp2");
3686
        opt_format("vcd");
3687

    
3688
        opt_frame_size(norm ? "352x240" : "352x288");
3689

    
3690
        video_bit_rate = 1150000;
3691
        video_rc_max_rate = 1150000;
3692
        video_rc_min_rate = 1150000;
3693
        video_rc_buffer_size = 40*1024*8;
3694

    
3695
        audio_bit_rate = 224000;
3696
        audio_sample_rate = 44100;
3697
        
3698
        mux_packet_size= 2324;
3699
        mux_rate= 2352 * 75 * 8;
3700

    
3701
        /* We have to offset the PTS, so that it is consistent with the SCR.
3702
           SCR starts at 36000, but the first two packs contain only padding
3703
           and the first pack from the other stream, respectively, may also have
3704
           been written before.
3705
           So the real data starts at SCR 36000+3*1200. */
3706
        mux_preload= (36000+3*1200) / 90000.0; //0.44
3707
    } else if(!strcmp(arg, "svcd")) {
3708

    
3709
        opt_video_codec("mpeg2video");
3710
        opt_audio_codec("mp2");
3711
        opt_format("svcd");
3712

    
3713
        opt_frame_size(norm ? "480x480" : "480x576");
3714
        opt_gop_size(norm ? "18" : "15");
3715

    
3716
        video_bit_rate = 2040000;
3717
        video_rc_max_rate = 2516000;
3718
        video_rc_min_rate = 0; //1145000;
3719
        video_rc_buffer_size = 224*1024*8;
3720
        use_scan_offset = 1;
3721

    
3722
        audio_bit_rate = 224000;
3723
        audio_sample_rate = 44100;
3724

    
3725
        mux_packet_size= 2324;
3726

    
3727
    } else if(!strcmp(arg, "dvd")) {
3728

    
3729
        opt_video_codec("mpeg2video");
3730
        opt_audio_codec("ac3");
3731
        opt_format("dvd");
3732

    
3733
        opt_frame_size(norm ? "720x480" : "720x576");
3734
        opt_gop_size(norm ? "18" : "15");
3735

    
3736
        video_bit_rate = 6000000;
3737
        video_rc_max_rate = 9000000;
3738
        video_rc_min_rate = 0; //1500000;
3739
        video_rc_buffer_size = 224*1024*8;
3740

    
3741
        audio_bit_rate = 448000;
3742
        audio_sample_rate = 48000;
3743

    
3744
    } else {
3745
        fprintf(stderr, "Unknown target: %s\n", arg);
3746
        exit(1);
3747
    }
3748
}
3749

    
3750
static void show_version(void)
3751
{
3752
    printf("ffmpeg      " FFMPEG_VERSION "\n"
3753
           "libavcodec  %d\n"
3754
           "libavformat %d\n", 
3755
           avcodec_build(), LIBAVFORMAT_BUILD);
3756
    exit(1);
3757
}
3758

    
3759
const OptionDef options[] = {
3760
    /* main options */
3761
    { "L", 0, {(void*)show_license}, "show license" },
3762
    { "h", 0, {(void*)show_help}, "show help" },
3763
    { "version", 0, {(void*)show_version}, "show version" },
3764
    { "formats", 0, {(void*)show_formats}, "show available formats, codecs, protocols, ..." },
3765
    { "f", HAS_ARG, {(void*)opt_format}, "force format", "fmt" },
3766
    { "img", HAS_ARG, {(void*)opt_image_format}, "force image format", "img_fmt" },
3767
    { "i", HAS_ARG, {(void*)opt_input_file}, "input file name", "filename" },
3768
    { "y", OPT_BOOL, {(void*)&file_overwrite}, "overwrite output files" },
3769
    { "map", HAS_ARG | OPT_EXPERT, {(void*)opt_map}, "set input stream mapping", "file:stream" },
3770
    { "map_meta_data", HAS_ARG | OPT_EXPERT, {(void*)opt_map_meta_data}, "set meta data information of outfile from infile", "outfile:infile" },
3771
    { "t", HAS_ARG, {(void*)opt_recording_time}, "set the recording time", "duration" },
3772
    { "ss", HAS_ARG, {(void*)opt_start_time}, "set the start time offset", "time_off" },
3773
    { "itsoffset", HAS_ARG, {(void*)opt_input_ts_offset}, "set the input ts offset", "time_off" },
3774
    { "title", HAS_ARG | OPT_STRING, {(void*)&str_title}, "set the title", "string" },
3775
    { "timestamp", HAS_ARG, {(void*)&opt_rec_timestamp}, "set the timestamp", "time" },
3776
    { "author", HAS_ARG | OPT_STRING, {(void*)&str_author}, "set the author", "string" },
3777
    { "copyright", HAS_ARG | OPT_STRING, {(void*)&str_copyright}, "set the copyright", "string" },
3778
    { "comment", HAS_ARG | OPT_STRING, {(void*)&str_comment}, "set the comment", "string" },
3779
    { "debug", HAS_ARG | OPT_EXPERT, {(void*)opt_debug}, "print specific debug info", "" },
3780
    { "vismv", HAS_ARG | OPT_EXPERT, {(void*)opt_vismv}, "visualize motion vectors", "" },
3781
    { "benchmark", OPT_BOOL | OPT_EXPERT, {(void*)&do_benchmark}, 
3782
      "add timings for benchmarking" },
3783
    { "dump", OPT_BOOL | OPT_EXPERT, {(void*)&do_pkt_dump}, 
3784
      "dump each input packet" },
3785
    { "hex", OPT_BOOL | OPT_EXPERT, {(void*)&do_hex_dump}, 
3786
      "when dumping packets, also dump the payload" },
3787
    { "bitexact", OPT_EXPERT, {(void*)opt_bitexact}, "only use bit exact algorithms (for codec testing)" }, 
3788
    { "re", OPT_BOOL | OPT_EXPERT, {(void*)&rate_emu}, "read input at native frame rate", "" },
3789
    { "loop", OPT_BOOL | OPT_EXPERT, {(void*)&loop_input}, "loop (current only works with images)" },
3790
    { "v", HAS_ARG, {(void*)opt_verbose}, "control amount of logging", "verbose" },
3791
    { "target", HAS_ARG, {(void*)opt_target}, "specify target file type (\"vcd\", \"svcd\", \"dvd\", \"pal-vcd\", \"ntsc-svcd\", ...)", "type" },
3792
    { "threads", HAS_ARG | OPT_EXPERT, {(void*)opt_thread_count}, "thread count", "count" },
3793
    { "vsync", HAS_ARG | OPT_INT | OPT_EXPERT, {(void*)&video_sync_method}, "video sync method", "" },
3794
    { "async", HAS_ARG | OPT_INT | OPT_EXPERT, {(void*)&audio_sync_method}, "audio sync method", "" },
3795
    { "copyts", OPT_BOOL | OPT_EXPERT, {(void*)&copy_ts}, "copy timestamps" },
3796

    
3797
    /* video options */
3798
    { "b", HAS_ARG | OPT_VIDEO, {(void*)opt_video_bitrate}, "set video bitrate (in kbit/s)", "bitrate" },
3799
    { "r", HAS_ARG | OPT_VIDEO, {(void*)opt_frame_rate}, "set frame rate (Hz value, fraction or abbreviation)", "rate" },
3800
    { "s", HAS_ARG | OPT_VIDEO, {(void*)opt_frame_size}, "set frame size (WxH or abbreviation)", "size" },
3801
    { "aspect", HAS_ARG | OPT_VIDEO, {(void*)opt_frame_aspect_ratio}, "set aspect ratio (4:3, 16:9 or 1.3333, 1.7777)", "aspect" },
3802
    { "pix_fmt", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_frame_pix_fmt}, "set pixel format", "format" },
3803
    { "croptop", HAS_ARG | OPT_VIDEO, {(void*)opt_frame_crop_top}, "set top crop band size (in pixels)", "size" },
3804
    { "cropbottom", HAS_ARG | OPT_VIDEO, {(void*)opt_frame_crop_bottom}, "set bottom crop band size (in pixels)", "size" },
3805
    { "cropleft", HAS_ARG | OPT_VIDEO, {(void*)opt_frame_crop_left}, "set left crop band size (in pixels)", "size" },
3806
    { "cropright", HAS_ARG | OPT_VIDEO, {(void*)opt_frame_crop_right}, "set right crop band size (in pixels)", "size" },
3807
    { "padtop", HAS_ARG | OPT_VIDEO, {(void*)opt_frame_pad_top}, "set top pad band size (in pixels)", "size" },
3808
    { "padbottom", HAS_ARG | OPT_VIDEO, {(void*)opt_frame_pad_bottom}, "set bottom pad band size (in pixels)", "size" },
3809
    { "padleft", HAS_ARG | OPT_VIDEO, {(void*)opt_frame_pad_left}, "set left pad band size (in pixels)", "size" },
3810
    { "padright", HAS_ARG | OPT_VIDEO, {(void*)opt_frame_pad_right}, "set right pad band size (in pixels)", "size" },
3811
    { "padcolor", HAS_ARG | OPT_VIDEO, {(void*)opt_pad_color}, "set color of pad bands (Hex 000000 thru FFFFFF)", "color" },
3812
    { "g", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_gop_size}, "set the group of picture size", "gop_size" },
3813
    { "intra", OPT_BOOL | OPT_EXPERT | OPT_VIDEO, {(void*)&intra_only}, "use only intra frames"},
3814
    { "vn", OPT_BOOL | OPT_VIDEO, {(void*)&video_disable}, "disable video" },
3815
    { "qscale", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_qscale}, "use fixed video quantiser scale (VBR)", "q" },
3816
    { "qmin", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_qmin}, "min video quantiser scale (VBR)", "q" },
3817
    { "qmax", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_qmax}, "max video quantiser scale (VBR)", "q" },
3818
    { "lmin", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_lmin}, "min video lagrange factor (VBR)", "lambda" },
3819
    { "lmax", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_lmax}, "max video lagrange factor (VBR)", "lambda" },
3820
    { "mbqmin", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_mb_qmin}, "min macroblock quantiser scale (VBR)", "q" },
3821
    { "mbqmax", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_mb_qmax}, "max macroblock quantiser scale (VBR)", "q" },
3822
    { "qdiff", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_qdiff}, "max difference between the quantiser scale (VBR)", "q" },
3823
    { "qblur", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_qblur}, "video quantiser scale blur (VBR)", "blur" },
3824
    { "qcomp", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_qcomp}, "video quantiser scale compression (VBR)", "compression" },
3825
    { "rc_init_cplx", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_rc_initial_cplx}, "initial complexity for 1-pass encoding", "complexity" },
3826
    { "b_qfactor", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_b_qfactor}, "qp factor between p and b frames", "factor" },
3827
    { "i_qfactor", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_i_qfactor}, "qp factor between p and i frames", "factor" },
3828
    { "b_qoffset", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_b_qoffset}, "qp offset between p and b frames", "offset" },
3829
    { "i_qoffset", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_i_qoffset}, "qp offset between p and i frames", "offset" },
3830
    { "ibias", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_ibias}, "intra quant bias", "bias" },
3831
    { "pbias", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_pbias}, "inter quant bias", "bias" },
3832
//    { "b_strategy", HAS_ARG | OPT_EXPERT, {(void*)opt_b_strategy}, "dynamic b frame selection strategy", "strategy" },
3833
    { "rc_eq", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_video_rc_eq}, "set rate control equation", "equation" },
3834
    { "rc_override", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_video_rc_override_string}, "rate control override for specific intervals", "override" },
3835
    { "bt", HAS_ARG | OPT_VIDEO, {(void*)opt_video_bitrate_tolerance}, "set video bitrate tolerance (in kbit/s)", "tolerance" },
3836
    { "maxrate", HAS_ARG | OPT_VIDEO, {(void*)opt_video_bitrate_max}, "set max video bitrate tolerance (in kbit/s)", "bitrate" },
3837
    { "minrate", HAS_ARG | OPT_VIDEO, {(void*)opt_video_bitrate_min}, "set min video bitrate tolerance (in kbit/s)", "bitrate" },
3838
    { "bufsize", HAS_ARG | OPT_VIDEO, {(void*)opt_video_buffer_size}, "set ratecontrol buffer size (in kByte)", "size" },
3839
    { "vcodec", HAS_ARG | OPT_VIDEO, {(void*)opt_video_codec}, "force video codec ('copy' to copy stream)", "codec" },
3840
    { "me", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_motion_estimation}, "set motion estimation method", 
3841
      "method" },
3842
    { "dct_algo", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_dct_algo}, "set dct algo",  "algo" },
3843
    { "idct_algo", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_idct_algo}, "set idct algo",  "algo" },
3844
    { "me_threshold", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_me_threshold}, "motion estimaton threshold",  "" },
3845
    { "mb_threshold", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_mb_threshold}, "macroblock threshold",  "" },
3846
    { "er", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_error_resilience}, "set error resilience",  "n" },
3847
    { "ec", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_error_concealment}, "set error concealment",  "bit_mask" },
3848
    { "bf", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_b_frames}, "use 'frames' B frames", "frames" },
3849
    { "hq", OPT_BOOL, {(void*)&mb_decision}, "activate high quality settings" },
3850
    { "mbd", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_mb_decision}, "macroblock decision", "mode" },
3851
    { "mbcmp", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_mb_cmp}, "macroblock compare function", "cmp function" },
3852
    { "ildctcmp", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_ildct_cmp}, "ildct compare function", "cmp function" },
3853
    { "subcmp", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_sub_cmp}, "subpel compare function", "cmp function" },
3854
    { "cmp", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_cmp}, "fullpel compare function", "cmp function" },
3855
    { "precmp", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_pre_cmp}, "pre motion estimation compare function", "cmp function" },
3856
    { "preme", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_pre_me}, "pre motion estimation", "" },
3857
    { "lumi_mask", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_lumi_mask}, "luminance masking", "" },
3858
    { "dark_mask", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_dark_mask}, "darkness masking", "" },
3859
    { "scplx_mask", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_scplx_mask}, "spatial complexity masking", "" },
3860
    { "tcplx_mask", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_tcplx_mask}, "temporal complexity masking", "" },
3861
    { "p_mask", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_p_mask}, "inter masking", "" },
3862
    { "4mv", OPT_BOOL | OPT_EXPERT | OPT_VIDEO, {(void*)&use_4mv}, "use four motion vector by macroblock (MPEG4)" },
3863
    { "obmc", OPT_BOOL | OPT_EXPERT | OPT_VIDEO, {(void*)&use_obmc}, "use overlapped block motion compensation (h263+)" },
3864
    { "lf", OPT_BOOL | OPT_EXPERT | OPT_VIDEO, {(void*)&use_loop}, "use loop filter (h263+)" },
3865
    { "part", OPT_BOOL | OPT_EXPERT | OPT_VIDEO, {(void*)&use_part}, "use data partitioning (MPEG4)" },
3866
    { "bug", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_workaround_bugs}, "workaround not auto detected encoder bugs", "param" },
3867
    { "ps", HAS_ARG | OPT_EXPERT, {(void*)opt_packet_size}, "set packet size in bits", "size" },
3868
    { "error", HAS_ARG | OPT_EXPERT, {(void*)opt_error_rate}, "error rate", "rate" },
3869
    { "strict", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_strict}, "how strictly to follow the standards", "strictness" },
3870
    { "sameq", OPT_BOOL | OPT_VIDEO, {(void*)&same_quality}, 
3871
      "use same video quality as source (implies VBR)" },
3872
    { "pass", HAS_ARG | OPT_VIDEO, {(void*)&opt_pass}, "select the pass number (1 or 2)", "n" },
3873
    { "passlogfile", HAS_ARG | OPT_STRING | OPT_VIDEO, {(void*)&pass_logfilename}, "select two pass log file name", "file" },
3874
    { "deinterlace", OPT_BOOL | OPT_EXPERT | OPT_VIDEO, {(void*)&do_deinterlace}, 
3875
      "deinterlace pictures" },
3876
    { "ildct", OPT_BOOL | OPT_EXPERT | OPT_VIDEO, {(void*)&do_interlace_dct}, 
3877
      "force interlaced dct support in encoder (MPEG2/MPEG4)" },
3878
    { "ilme", OPT_BOOL | OPT_EXPERT | OPT_VIDEO, {(void*)&do_interlace_me}, 
3879
      "force interlaced me support in encoder (MPEG2/MPEG4)" },
3880
    { "psnr", OPT_BOOL | OPT_EXPERT | OPT_VIDEO, {(void*)&do_psnr}, "calculate PSNR of compressed frames" },
3881
    { "vstats", OPT_BOOL | OPT_EXPERT | OPT_VIDEO, {(void*)&do_vstats}, "dump video coding statistics to file" }, 
3882
    { "vhook", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)add_frame_hooker}, "insert video processing module", "module" },
3883
    { "aic", OPT_BOOL | OPT_EXPERT | OPT_VIDEO, {(void*)&use_aic}, "enable Advanced intra coding (h263+)" },
3884
    { "aiv", OPT_BOOL | OPT_EXPERT | OPT_VIDEO, {(void*)&use_aiv}, "enable Alternative inter vlc (h263+)" },
3885
    { "umv", OPT_BOOL | OPT_EXPERT | OPT_VIDEO, {(void*)&use_umv}, "enable Unlimited Motion Vector (h263+)" },
3886
    { "ssm", OPT_BOOL | OPT_EXPERT | OPT_VIDEO, {(void*)&use_ss}, "enable Slice Structured mode (h263+)" },
3887
    { "alt", OPT_BOOL | OPT_EXPERT | OPT_VIDEO, {(void*)&use_alt_scan}, "enable alternate scantable (MPEG2/MPEG4)" },
3888
    { "qprd", OPT_BOOL | OPT_EXPERT | OPT_VIDEO, {(void*)&use_qprd}, "" },
3889
    { "cbp", OPT_BOOL | OPT_EXPERT | OPT_VIDEO, {(void*)&use_cbprd}, "" },
3890
    { "trell", OPT_BOOL | OPT_EXPERT | OPT_VIDEO, {(void*)&use_trell}, "enable trellis quantization" },
3891
    { "cgop", OPT_BOOL | OPT_EXPERT | OPT_VIDEO, {(void*)&closed_gop}, "closed gop" },
3892
    { "sgop", OPT_BOOL | OPT_EXPERT | OPT_VIDEO, {(void*)&strict_gop}, "strict gop" },
3893
    { "scan_offset", OPT_BOOL | OPT_EXPERT | OPT_VIDEO, {(void*)&use_scan_offset}, "enable SVCD Scan Offset placeholder" },
3894
    { "qpel", OPT_BOOL | OPT_EXPERT | OPT_VIDEO, {(void*)&use_qpel}, "enable 1/4-pel" },
3895
    { "intra_matrix", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_intra_matrix}, "specify intra matrix coeffs", "matrix" },
3896
    { "inter_matrix", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_inter_matrix}, "specify inter matrix coeffs", "matrix" },
3897
    { "top", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_top_field_first}, "top=1/bottom=0/auto=-1 field first", "" },
3898
    { "nr", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_noise_reduction}, "noise reduction", "" },
3899
    { "qns", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_qns}, "quantization noise shaping", "" },
3900
    { "sc_threshold", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_sc_threshold}, "scene change threshold", "threshold" },
3901
    { "me_range", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_me_range}, "limit motion vectors range (1023 for DivX player)", "range" },
3902
    { "dc", OPT_INT | HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)&intra_dc_precision}, "intra_dc_precision", "precision" },
3903
    { "coder", OPT_INT | HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)&coder}, "coder type", "" },
3904
    { "context", OPT_INT | HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)&context}, "context model", "" },
3905
    { "pred", OPT_INT | HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)&predictor}, "prediction method", "" },
3906
    { "vprofile", OPT_INT | HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)&video_profile}, "profile", "" },
3907
    { "vlevel", OPT_INT | HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)&video_level}, "level", "" },
3908
    { "nssew", OPT_INT | HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)&nsse_weight}, "weight", "" },
3909
    { "subq", OPT_INT | HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)&subpel_quality}, "", "" },
3910
    { "lowres", OPT_INT | HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)&lowres}, "", "" },
3911
    { "vtag", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_video_tag}, "force video tag/fourcc", "fourcc/tag" },
3912

    
3913
    /* audio options */
3914
    { "ab", HAS_ARG | OPT_AUDIO, {(void*)opt_audio_bitrate}, "set audio bitrate (in kbit/s)", "bitrate", },
3915
    { "ar", HAS_ARG | OPT_AUDIO, {(void*)opt_audio_rate}, "set audio sampling rate (in Hz)", "rate" },
3916
    { "ac", HAS_ARG | OPT_AUDIO, {(void*)opt_audio_channels}, "set number of audio channels", "channels" },
3917
    { "an", OPT_BOOL | OPT_AUDIO, {(void*)&audio_disable}, "disable audio" },
3918
    { "acodec", HAS_ARG | OPT_AUDIO, {(void*)opt_audio_codec}, "force audio codec ('copy' to copy stream)", "codec" },
3919
    { "atag", HAS_ARG | OPT_EXPERT | OPT_AUDIO, {(void*)opt_audio_tag}, "force audio tag/fourcc", "fourcc/tag" },
3920

    
3921
    /* grab options */
3922
    { "vd", HAS_ARG | OPT_EXPERT | OPT_VIDEO | OPT_GRAB, {(void*)opt_video_device}, "set video grab device", "device" },
3923
    { "vc", HAS_ARG | OPT_EXPERT | OPT_VIDEO | OPT_GRAB, {(void*)opt_video_channel}, "set video grab channel (DV1394 only)", "channel" },
3924
    { "tvstd", HAS_ARG | OPT_EXPERT | OPT_VIDEO | OPT_GRAB, {(void*)opt_video_standard}, "set television standard (NTSC, PAL (SECAM))", "standard" },
3925
    { "dv1394", OPT_EXPERT | OPT_GRAB, {(void*)opt_dv1394}, "set DV1394 grab", "" },
3926
    { "ad", HAS_ARG | OPT_EXPERT | OPT_AUDIO | OPT_GRAB, {(void*)opt_audio_device}, "set audio device", "device" },
3927
 
3928
    /* muxer options */   
3929
    { "muxrate", OPT_INT | HAS_ARG | OPT_EXPERT, {(void*)&mux_rate}, "set mux rate", "rate" },
3930
    { "packetsize", OPT_INT | HAS_ARG | OPT_EXPERT, {(void*)&mux_packet_size}, "set packet size", "size" },
3931
    { "muxdelay", OPT_FLOAT | HAS_ARG | OPT_EXPERT, {(void*)&mux_max_delay}, "set the maximum demux-decode delay", "seconds" },
3932
    { "muxpreload", OPT_FLOAT | HAS_ARG | OPT_EXPERT, {(void*)&mux_preload}, "set the initial demux-decode delay", "seconds" },
3933
    { NULL, },
3934
};
3935

    
3936
static void show_banner(void)
3937
{
3938
    printf("ffmpeg version " FFMPEG_VERSION ", build %d, Copyright (c) 2000-2004 Fabrice Bellard\n",
3939
        LIBAVCODEC_BUILD);
3940
    printf("  configuration: %s\n", FFMPEG_CONFIGURATION);
3941
    printf("  built on " __DATE__ " " __TIME__);
3942
#ifdef __GNUC__
3943
    printf(", gcc: %s\n", __VERSION__);
3944
#else
3945
    printf(", using a non-gcc compiler\n");
3946
#endif
3947
}
3948

    
3949
static void show_license(void)
3950
{
3951
    show_banner();
3952
#ifdef CONFIG_GPL
3953
    printf(
3954
    "This program is free software; you can redistribute it and/or modify\n"   
3955
    "it under the terms of the GNU General Public License as published by\n"
3956
    "the Free Software Foundation; either version 2 of the License, or\n"
3957
    "(at your option) any later version.\n"
3958
    "\n"
3959
    "This program is distributed in the hope that it will be useful,\n"
3960
    "but WITHOUT ANY WARRANTY; without even the implied warranty of\n"
3961
    "MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n"
3962
    "GNU General Public License for more details.\n"
3963
    "\n"
3964
    "You should have received a copy of the GNU General Public License\n"
3965
    "along with this program; if not, write to the Free Software\n"
3966
    "Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA\n"
3967
    );
3968
#else
3969
    printf(
3970
    "This library is free software; you can redistribute it and/or\n"
3971
    "modify it under the terms of the GNU Lesser General Public\n"
3972
    "License as published by the Free Software Foundation; either\n"
3973
    "version 2 of the License, or (at your option) any later version.\n"
3974
    "\n"
3975
    "This library is distributed in the hope that it will be useful,\n"
3976
    "but WITHOUT ANY WARRANTY; without even the implied warranty of\n"
3977
    "MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n"
3978
    "Lesser General Public License for more details.\n"
3979
    "\n"
3980
    "You should have received a copy of the GNU Lesser General Public\n"
3981
    "License along with this library; if not, write to the Free Software\n"
3982
    "Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA\n"
3983
    );
3984
#endif
3985
    exit(1);
3986
}
3987

    
3988
static void show_help(void)
3989
{
3990
    show_banner();
3991
    printf("usage: ffmpeg [[infile options] -i infile]... {[outfile options] outfile}...\n"
3992
           "Hyper fast Audio and Video encoder\n");
3993
    printf("\n");
3994
    show_help_options(options, "Main options:\n",
3995
                      OPT_EXPERT | OPT_AUDIO | OPT_VIDEO, 0);
3996
    show_help_options(options, "\nVideo options:\n",
3997
                      OPT_EXPERT | OPT_AUDIO | OPT_VIDEO | OPT_GRAB, 
3998
                      OPT_VIDEO);
3999
    show_help_options(options, "\nAdvanced Video options:\n",
4000
                      OPT_EXPERT | OPT_AUDIO | OPT_VIDEO | OPT_GRAB, 
4001
                      OPT_VIDEO | OPT_EXPERT);
4002
    show_help_options(options, "\nAudio options:\n",
4003
                      OPT_EXPERT | OPT_AUDIO | OPT_VIDEO | OPT_GRAB, 
4004
                      OPT_AUDIO);
4005
    show_help_options(options, "\nAdvanced Audio options:\n",
4006
                      OPT_EXPERT | OPT_AUDIO | OPT_VIDEO | OPT_GRAB, 
4007
                      OPT_AUDIO | OPT_EXPERT);
4008
    show_help_options(options, "\nAudio/Video grab options:\n",
4009
                      OPT_GRAB, 
4010
                      OPT_GRAB);
4011
    show_help_options(options, "\nAdvanced options:\n",
4012
                      OPT_EXPERT | OPT_AUDIO | OPT_VIDEO | OPT_GRAB, 
4013
                      OPT_EXPERT);
4014
    exit(1);
4015
}
4016

    
4017
void parse_arg_file(const char *filename)
4018
{
4019
    opt_output_file(filename);
4020
}
4021

    
4022
int main(int argc, char **argv)
4023
{
4024
    int i;
4025
    int64_t ti;
4026

    
4027
    av_register_all();
4028

    
4029
    if (argc <= 1)
4030
        show_help();
4031
    else
4032
        show_banner();
4033
    
4034
    /* parse options */
4035
    parse_options(argc, argv, options);
4036

    
4037
    /* file converter / grab */
4038
    if (nb_output_files <= 0) {
4039
        fprintf(stderr, "Must supply at least one output file\n");
4040
        exit(1);
4041
    }
4042
    
4043
    if (nb_input_files == 0) {
4044
        input_sync = 1;
4045
        prepare_grab();
4046
    }
4047

    
4048
    ti = getutime();
4049
    av_encode(output_files, nb_output_files, input_files, nb_input_files, 
4050
              stream_maps, nb_stream_maps);
4051
    ti = getutime() - ti;
4052
    if (do_benchmark) {
4053
        printf("bench: utime=%0.3fs\n", ti / 1000000.0);
4054
    }
4055

    
4056
    /* close files */
4057
    for(i=0;i<nb_output_files;i++) {
4058
        /* maybe av_close_output_file ??? */
4059
        AVFormatContext *s = output_files[i];
4060
        int j;
4061
        if (!(s->oformat->flags & AVFMT_NOFILE))
4062
            url_fclose(&s->pb);
4063
        for(j=0;j<s->nb_streams;j++)
4064
            av_free(s->streams[j]);
4065
        av_free(s);
4066
    }
4067
    for(i=0;i<nb_input_files;i++)
4068
        av_close_input_file(input_files[i]);
4069

    
4070
    av_free_static();
4071

    
4072
    if(intra_matrix)
4073
        av_free(intra_matrix);
4074
    if(inter_matrix)
4075
        av_free(inter_matrix);
4076
    
4077
#ifdef POWERPC_PERFORMANCE_REPORT
4078
    extern void powerpc_display_perf_report(void);
4079
    powerpc_display_perf_report();
4080
#endif /* POWERPC_PERFORMANCE_REPORT */
4081

    
4082
#ifndef CONFIG_WIN32
4083
    if (received_sigterm) {
4084
        fprintf(stderr,
4085
            "Received signal %d: terminating.\n",
4086
            (int) received_sigterm);
4087
        exit (255);
4088
    }
4089
#endif
4090
    exit(0); /* not all OS-es handle main() return value */
4091
    return 0;
4092
}