Statistics
| Branch: | Revision:

ffmpeg / ffmpeg.c @ bbf18b21

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

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

    
209
static int mux_rate= 0;
210
static int mux_packet_size= 0;
211
static float mux_preload= 0.5;
212
static float mux_max_delay= 0.7;
213

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

    
237
static int rate_emu = 0;
238

    
239
static char *video_grab_format = "video4linux";
240
static char *video_device = NULL;
241
static char *grab_device = NULL;
242
static int  video_channel = 0;
243
static char *video_standard = "ntsc";
244

    
245
static char *audio_grab_format = "audio_device";
246
static char *audio_device = NULL;
247

    
248
static int using_stdin = 0;
249
static int using_vhook = 0;
250
static int verbose = 1;
251
static int thread_count= 1;
252
static int q_pressed = 0;
253
static int me_range = 0;
254
static int64_t video_size = 0;
255
static int64_t audio_size = 0;
256
static int64_t extra_size = 0;
257
static int nb_frames_dup = 0;
258
static int nb_frames_drop = 0;
259
static int input_sync;
260

    
261
static int pgmyuv_compatibility_hack=0;
262

    
263

    
264
#define DEFAULT_PASS_LOGFILENAME "ffmpeg2pass"
265

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

    
282
    int video_crop;          /* video_resample and video_crop are mutually exclusive */
283
    int topBand;             /* cropping area sizes */
284
    int leftBand;
285
    
286
    int video_pad;           /* video_resample and video_pad are mutually exclusive */
287
    int padtop;              /* padding area sizes */
288
    int padbottom;
289
    int padleft;
290
    int padright;
291
    
292
    /* audio only */
293
    int audio_resample;
294
    ReSampleContext *resample; /* for audio resampling */
295
    FifoBuffer fifo;     /* for compression: one audio fifo per codec */
296
    FILE *logfile;
297
} AVOutputStream;
298

    
299
typedef struct AVInputStream {
300
    int file_index;
301
    int index;
302
    AVStream *st;
303
    int discard;             /* true if stream data should be discarded */
304
    int decoding_needed;     /* true if the packets must be decoded in 'raw_fifo' */
305
    int64_t sample_index;      /* current sample */
306

    
307
    int64_t       start;     /* time when read started */
308
    unsigned long frame;     /* current frame */
309
    int64_t       next_pts;  /* synthetic pts for cases where pkt.pts
310
                                is not defined */
311
    int64_t       pts;       /* current pts */
312
    int is_start;            /* is 1 at the start and after a discontinuity */
313
} AVInputStream;
314

    
315
typedef struct AVInputFile {
316
    int eof_reached;      /* true if eof reached */
317
    int ist_index;        /* index of first stream in ist_table */
318
    int buffer_size;      /* current total buffer size */
319
    int buffer_size_max;  /* buffer size at which we consider we can stop
320
                             buffering */
321
    int nb_streams;       /* nb streams we are aware of */
322
} AVInputFile;
323

    
324
#ifndef CONFIG_WIN32
325

    
326
/* init terminal so that we can grab keys */
327
static struct termios oldtty;
328

    
329
static void term_exit(void)
330
{
331
    tcsetattr (0, TCSANOW, &oldtty);
332
}
333

    
334
static volatile sig_atomic_t received_sigterm = 0;
335

    
336
static void
337
sigterm_handler(int sig)
338
{
339
    received_sigterm = sig;
340
    term_exit();
341
}
342

    
343
static void term_init(void)
344
{
345
    struct termios tty;
346

    
347
    tcgetattr (0, &tty);
348
    oldtty = tty;
349

    
350
    tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
351
                          |INLCR|IGNCR|ICRNL|IXON);
352
    tty.c_oflag |= OPOST;
353
    tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
354
    tty.c_cflag &= ~(CSIZE|PARENB);
355
    tty.c_cflag |= CS8;
356
    tty.c_cc[VMIN] = 1;
357
    tty.c_cc[VTIME] = 0;
358
    
359
    tcsetattr (0, TCSANOW, &tty);
360

    
361
    signal(SIGINT , sigterm_handler); /* Interrupt (ANSI).  */
362
    signal(SIGQUIT, sigterm_handler); /* Quit (POSIX).  */
363
    signal(SIGTERM, sigterm_handler); /* Termination (ANSI).  */
364
    /*
365
    register a function to be called at normal program termination
366
    */
367
    atexit(term_exit);
368
#ifdef CONFIG_BEOS_NETSERVER
369
    fcntl(0, F_SETFL, fcntl(0, F_GETFL) | O_NONBLOCK);
370
#endif
371
}
372

    
373
/* read a key without blocking */
374
static int read_key(void)
375
{
376
    int n = 1;
377
    unsigned char ch;
378
#ifndef CONFIG_BEOS_NETSERVER
379
    struct timeval tv;
380
    fd_set rfds;
381

    
382
    FD_ZERO(&rfds);
383
    FD_SET(0, &rfds);
384
    tv.tv_sec = 0;
385
    tv.tv_usec = 0;
386
    n = select(1, &rfds, NULL, NULL, &tv);
387
#endif
388
    if (n > 0) {
389
        n = read(0, &ch, 1);
390
        if (n == 1)
391
            return ch;
392

    
393
        return n;
394
    }
395
    return -1;
396
}
397

    
398
static int decode_interrupt_cb(void)
399
{
400
    return q_pressed || (q_pressed = read_key() == 'q');
401
}
402

    
403
#else
404

    
405
static volatile int received_sigterm = 0;
406

    
407
/* no interactive support */
408
static void term_exit(void)
409
{
410
}
411

    
412
static void term_init(void)
413
{
414
}
415

    
416
static int read_key(void)
417
{
418
    return 0;
419
}
420

    
421
#endif
422

    
423
static int read_ffserver_streams(AVFormatContext *s, const char *filename)
424
{
425
    int i, err;
426
    AVFormatContext *ic;
427

    
428
    err = av_open_input_file(&ic, filename, NULL, FFM_PACKET_SIZE, NULL);
429
    if (err < 0)
430
        return err;
431
    /* copy stream format */
432
    s->nb_streams = ic->nb_streams;
433
    for(i=0;i<ic->nb_streams;i++) {
434
        AVStream *st;
435

    
436
        st = av_mallocz(sizeof(AVStream));
437
        memcpy(st, ic->streams[i], sizeof(AVStream));
438
        s->streams[i] = st;
439
    }
440

    
441
    av_close_input_file(ic);
442
    return 0;
443
}
444

    
445
#define MAX_AUDIO_PACKET_SIZE (128 * 1024)
446

    
447
static void do_audio_out(AVFormatContext *s, 
448
                         AVOutputStream *ost, 
449
                         AVInputStream *ist,
450
                         unsigned char *buf, int size)
451
{
452
    uint8_t *buftmp;
453
    static uint8_t *audio_buf = NULL;
454
    static uint8_t *audio_out = NULL;
455
    const int audio_out_size= 4*MAX_AUDIO_PACKET_SIZE;
456

    
457
    int size_out, frame_bytes, ret;
458
    AVCodecContext *enc= &ost->st->codec;
459

    
460
    /* SC: dynamic allocation of buffers */
461
    if (!audio_buf)
462
        audio_buf = av_malloc(2*MAX_AUDIO_PACKET_SIZE);
463
    if (!audio_out)
464
        audio_out = av_malloc(audio_out_size);
465
    if (!audio_buf || !audio_out)
466
        return;               /* Should signal an error ! */
467

    
468
    if(audio_sync_method){
469
        double delta = ost->sync_ipts * enc->sample_rate - ost->sync_opts 
470
                - fifo_size(&ost->fifo, ost->fifo.rptr)/(ost->st->codec.channels * 2);
471
        double idelta= delta*ist->st->codec.sample_rate / enc->sample_rate;
472
        int byte_delta= ((int)idelta)*2*ist->st->codec.channels;
473

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

    
490
                    if(byte_delta + size <= MAX_AUDIO_PACKET_SIZE)
491
                        ist->is_start=0;
492
                    else
493
                        byte_delta= MAX_AUDIO_PACKET_SIZE - size;
494

    
495
                    memset(input_tmp, 0, byte_delta);
496
                    memcpy(input_tmp + byte_delta, buf, size);
497
                    buf= input_tmp;
498
                    size += byte_delta;
499
                    if(verbose > 2)
500
                        fprintf(stderr, "adding %d audio samples of silence\n", (int)delta);
501
                }
502
            }else if(audio_sync_method>1){
503
                int comp= clip(delta, -audio_sync_method, audio_sync_method);
504
                assert(ost->audio_resample);
505
                if(verbose > 2)
506
                    fprintf(stderr, "compensating audio timestamp drift:%f compensation:%d in:%d\n", delta, comp, enc->sample_rate);
507
//                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));
508
                av_resample_compensate(*(struct AVResampleContext**)ost->resample, comp, enc->sample_rate);
509
            }
510
        } 
511
    }else
512
        ost->sync_opts= lrintf(ost->sync_ipts * enc->sample_rate)
513
                        - fifo_size(&ost->fifo, ost->fifo.rptr)/(ost->st->codec.channels * 2); //FIXME wrong
514

    
515
    if (ost->audio_resample) {
516
        buftmp = audio_buf;
517
        size_out = audio_resample(ost->resample, 
518
                                  (short *)buftmp, (short *)buf,
519
                                  size / (ist->st->codec.channels * 2));
520
        size_out = size_out * enc->channels * 2;
521
    } else {
522
        buftmp = buf;
523
        size_out = size;
524
    }
525

    
526
    /* now encode as many frames as possible */
527
    if (enc->frame_size > 1) {
528
        /* output resampled raw samples */
529
        fifo_write(&ost->fifo, buftmp, size_out, 
530
                   &ost->fifo.wptr);
531

    
532
        frame_bytes = enc->frame_size * 2 * enc->channels;
533
        
534
        while (fifo_read(&ost->fifo, audio_buf, frame_bytes, 
535
                     &ost->fifo.rptr) == 0) {
536
            AVPacket pkt;
537
            av_init_packet(&pkt);
538

    
539
            ret = avcodec_encode_audio(enc, audio_out, audio_out_size, 
540
                                       (short *)audio_buf);
541
            audio_size += ret;
542
            pkt.stream_index= ost->index;
543
            pkt.data= audio_out;
544
            pkt.size= ret;
545
            if(enc->coded_frame)
546
                pkt.pts= enc->coded_frame->pts;
547
            pkt.flags |= PKT_FLAG_KEY;
548
            av_interleaved_write_frame(s, &pkt);
549
            
550
            ost->sync_opts += enc->frame_size;
551
        }
552
    } else {
553
        AVPacket pkt;
554
        av_init_packet(&pkt);
555

    
556
        ost->sync_opts += size_out / (2 * enc->channels);
557

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

    
583
static void pre_process_video_frame(AVInputStream *ist, AVPicture *picture, void **bufp)
584
{
585
    AVCodecContext *dec;
586
    AVPicture *picture2;
587
    AVPicture picture_tmp;
588
    uint8_t *buf = 0;
589

    
590
    dec = &ist->st->codec;
591

    
592
    /* deinterlace : must be done before any resize */
593
    if (do_deinterlace || using_vhook) {
594
        int size;
595

    
596
        /* create temporary picture */
597
        size = avpicture_get_size(dec->pix_fmt, dec->width, dec->height);
598
        buf = av_malloc(size);
599
        if (!buf)
600
            return;
601
        
602
        picture2 = &picture_tmp;
603
        avpicture_fill(picture2, buf, dec->pix_fmt, dec->width, dec->height);
604

    
605
        if (do_deinterlace){
606
            if(avpicture_deinterlace(picture2, picture, 
607
                                     dec->pix_fmt, dec->width, dec->height) < 0) {
608
                /* if error, do not deinterlace */
609
                av_free(buf);
610
                buf = NULL;
611
                picture2 = picture;
612
            }
613
        } else {
614
            if (img_convert(picture2, dec->pix_fmt, picture, 
615
                            dec->pix_fmt, dec->width, dec->height) < 0) {
616
                /* if error, do not copy */
617
                av_free(buf);
618
                buf = NULL;
619
                picture2 = picture;
620
            }
621
        }
622
    } else {
623
        picture2 = picture;
624
    }
625

    
626
    frame_hook_process(picture2, dec->pix_fmt, dec->width, dec->height);
627

    
628
    if (picture != picture2)
629
        *picture = *picture2;
630
    *bufp = buf;
631
}
632

    
633
/* we begin to correct av delay at this threshold */
634
#define AV_DELAY_MAX 0.100
635

    
636

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

    
652
        if (padleft || padright) {
653
            optr = img->data[i] + (img->linesize[i] * (padtop >> shift)) +
654
                (img->linesize[i] - (padright >> shift));
655

    
656
            for (y = 0; y < ((height - (padtop + padbottom)) >> shift); y++) {
657
                memset(optr, color[i], (padleft + padright) >> shift);
658
                optr += img->linesize[i];
659
            }
660
        }
661
      
662
        if (padbottom) {
663
            optr = img->data[i] + (img->linesize[i] * ((height - padbottom) >> shift));
664
            memset(optr, color[i], ((img->linesize[i] * padbottom) >> shift));
665
        }
666
    }
667
}
668

    
669
static int bit_buffer_size= 1024*256;
670
static uint8_t *bit_buffer= NULL;
671

    
672
static void do_video_out(AVFormatContext *s, 
673
                         AVOutputStream *ost, 
674
                         AVInputStream *ist,
675
                         AVFrame *in_picture,
676
                         int *frame_size)
677
{
678
    int nb_frames, i, ret;
679
    AVFrame *final_picture, *formatted_picture;
680
    AVFrame picture_format_temp, picture_crop_temp;
681
    uint8_t *buf = NULL, *buf1 = NULL;
682
    AVCodecContext *enc, *dec;
683
    enum PixelFormat target_pixfmt;
684
    
685
    avcodec_get_frame_defaults(&picture_format_temp);
686
    avcodec_get_frame_defaults(&picture_crop_temp);
687

    
688
    enc = &ost->st->codec;
689
    dec = &ist->st->codec;
690

    
691
    /* by default, we output a single frame */
692
    nb_frames = 1;
693

    
694
    *frame_size = 0;
695

    
696
    if(video_sync_method){
697
        double vdelta;
698
        vdelta = ost->sync_ipts * enc->frame_rate / enc->frame_rate_base - ost->sync_opts;
699
        //FIXME set to 0.5 after we fix some dts/pts bugs like in avidec.c
700
        if (vdelta < -1.1)
701
            nb_frames = 0;
702
        else if (vdelta > 1.1)
703
            nb_frames = lrintf(vdelta);
704
//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);
705
        if (nb_frames == 0){
706
            ++nb_frames_drop;
707
            if (verbose>2)
708
                fprintf(stderr, "*** drop!\n");
709
        }else if (nb_frames > 1) {
710
            nb_frames_dup += nb_frames;
711
            if (verbose>2)
712
                fprintf(stderr, "*** %d dup!\n", nb_frames-1);
713
        }
714
    }else
715
        ost->sync_opts= lrintf(ost->sync_ipts * enc->frame_rate / enc->frame_rate_base);
716

    
717
    nb_frames= FFMIN(nb_frames, max_frames[CODEC_TYPE_VIDEO] - ost->frame_number);
718
    if (nb_frames <= 0) 
719
        return;
720

    
721
    /* convert pixel format if needed */
722
    target_pixfmt = ost->video_resample || ost->video_pad
723
        ? PIX_FMT_YUV420P : enc->pix_fmt;
724
    if (dec->pix_fmt != target_pixfmt) {
725
        int size;
726

    
727
        /* create temporary picture */
728
        size = avpicture_get_size(target_pixfmt, dec->width, dec->height);
729
        buf = av_malloc(size);
730
        if (!buf)
731
            return;
732
        formatted_picture = &picture_format_temp;
733
        avpicture_fill((AVPicture*)formatted_picture, buf, target_pixfmt, dec->width, dec->height);
734
        
735
        if (img_convert((AVPicture*)formatted_picture, target_pixfmt, 
736
                        (AVPicture *)in_picture, dec->pix_fmt, 
737
                        dec->width, dec->height) < 0) {
738

    
739
            if (verbose >= 0)
740
                fprintf(stderr, "pixel format conversion not handled\n");
741

    
742
            goto the_end;
743
        }
744
    } else {
745
        formatted_picture = in_picture;
746
    }
747

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

    
777
                if (verbose >= 0)
778
                    fprintf(stderr, "pixel format conversion not handled\n");
779

    
780
                goto the_end;
781
            }
782
        }
783
    } else if (ost->video_crop) {
784
        picture_crop_temp.data[0] = formatted_picture->data[0] +
785
                (ost->topBand * formatted_picture->linesize[0]) + ost->leftBand;
786

    
787
        picture_crop_temp.data[1] = formatted_picture->data[1] +
788
                ((ost->topBand >> 1) * formatted_picture->linesize[1]) +
789
                (ost->leftBand >> 1);
790

    
791
        picture_crop_temp.data[2] = formatted_picture->data[2] +
792
                ((ost->topBand >> 1) * formatted_picture->linesize[2]) +
793
                (ost->leftBand >> 1);
794

    
795
        picture_crop_temp.linesize[0] = formatted_picture->linesize[0];
796
        picture_crop_temp.linesize[1] = formatted_picture->linesize[1];
797
        picture_crop_temp.linesize[2] = formatted_picture->linesize[2];
798
        final_picture = &picture_crop_temp;
799
    } else if (ost->video_pad) {
800
        final_picture = &ost->pict_tmp;
801

    
802
        for (i = 0; i < 3; i++) {
803
            uint8_t *optr, *iptr;
804
            int shift = (i == 0) ? 0 : 1;
805
            int y, yheight;
806
            
807
            /* set offset to start writing image into */
808
            optr = final_picture->data[i] + (((final_picture->linesize[i] * 
809
                            ost->padtop) + ost->padleft) >> shift);
810
            iptr = formatted_picture->data[i];
811

    
812
            yheight = (enc->height - ost->padtop - ost->padbottom) >> shift;
813
            for (y = 0; y < yheight; y++) {
814
                /* copy unpadded image row into padded image row */
815
                memcpy(optr, iptr, formatted_picture->linesize[i]);
816
                optr += final_picture->linesize[i];
817
                iptr += formatted_picture->linesize[i];
818
            }
819
        }
820

    
821
        fill_pad_region((AVPicture*)final_picture, enc->height, enc->width,
822
                ost->padtop, ost->padbottom, ost->padleft, ost->padright,
823
                padcolor);
824
        
825
        if (enc->pix_fmt != PIX_FMT_YUV420P) {
826
            int size;
827

    
828
            av_free(buf);
829
            /* create temporary picture */
830
            size = avpicture_get_size(enc->pix_fmt, enc->width, enc->height);
831
            buf = av_malloc(size);
832
            if (!buf)
833
                return;
834
            final_picture = &picture_format_temp;
835
            avpicture_fill((AVPicture*)final_picture, buf, enc->pix_fmt, enc->width, enc->height);
836

    
837
            if (img_convert((AVPicture*)final_picture, enc->pix_fmt, 
838
                        (AVPicture*)&ost->pict_tmp, PIX_FMT_YUV420P, 
839
                        enc->width, enc->height) < 0) {
840

    
841
                if (verbose >= 0)
842
                    fprintf(stderr, "pixel format conversion not handled\n");
843

    
844
                goto the_end;
845
            }
846
        }
847
    } else {
848
        final_picture = formatted_picture;
849
    }
850
    /* duplicates frame if needed */
851
    for(i=0;i<nb_frames;i++) {
852
        AVPacket pkt;
853
        av_init_packet(&pkt);
854
        pkt.stream_index= ost->index;
855

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

    
869
            av_interleaved_write_frame(s, &pkt);
870
            enc->coded_frame = old_frame;
871
        } else {
872
            AVFrame big_picture;
873

    
874
            big_picture= *final_picture;
875
            /* better than nothing: use input picture interlaced
876
               settings */
877
            big_picture.interlaced_frame = in_picture->interlaced_frame;
878
            if(do_interlace_me || do_interlace_dct){
879
                if(top_field_first == -1)
880
                    big_picture.top_field_first = in_picture->top_field_first;
881
                else
882
                    big_picture.top_field_first = top_field_first;
883
            }
884

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

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

    
930
static double psnr(double d){
931
    if(d==0) return INFINITY;
932
    return -10.0*log(d)/log(10.0);
933
}
934

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

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

    
1008

    
1009
    oc = output_files[0];
1010

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

    
1068
        if (verbose > 1)
1069
          sprintf(buf + strlen(buf), " dup=%d drop=%d",
1070
                  nb_frames_dup, nb_frames_drop);
1071
        
1072
        if (verbose >= 0)
1073
            fprintf(stderr, "%s    \r", buf);
1074

    
1075
        fflush(stderr);
1076
    }
1077
        
1078
    if (is_last_report && verbose >= 0){
1079
        int64_t raw= audio_size + video_size + extra_size;
1080
        fprintf(stderr, "\n");
1081
        fprintf(stderr, "video:%1.0fkB audio:%1.0fkB global headers:%1.0fkB muxing overhead %f%%\n",
1082
                video_size/1024.0,
1083
                audio_size/1024.0,
1084
                extra_size/1024.0,
1085
                100.0*(total_size - raw)/raw
1086
        );
1087
    }
1088
}
1089

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

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

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

    
1182
            buffer_to_free = NULL;
1183
            if (ist->st->codec.codec_type == CODEC_TYPE_VIDEO) {
1184
                pre_process_video_frame(ist, (AVPicture *)&picture, 
1185
                                        &buffer_to_free);
1186
            }
1187

    
1188
            /* frame rate emulation */
1189
            if (ist->st->codec.rate_emu) {
1190
                int64_t pts = av_rescale((int64_t) ist->frame * ist->st->codec.frame_rate_base, 1000000, ist->st->codec.frame_rate);
1191
                int64_t now = av_gettime() - ist->start;
1192
                if (pts > now)
1193
                    usleep(pts - now);
1194

    
1195
                ist->frame++;
1196
            }
1197

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

    
1217
                    ost = ost_table[i];
1218
                    if (ost->source_index == ist_index) {
1219
                        os = output_files[ost->file_index];
1220

    
1221
#if 0
1222
                        printf("%d: got pts=%0.3f %0.3f\n", i, 
1223
                               (double)pkt->pts / AV_TIME_BASE, 
1224
                               ((double)ist->pts / AV_TIME_BASE) - 
1225
                               ((double)ost->st->pts.val * ost->st->time_base.num / ost->st->time_base.den));
1226
#endif
1227
                        /* set the input output pts pairs */
1228
                        ost->sync_ipts = (double)(ist->pts + input_files_ts_offset[ist->file_index])/ AV_TIME_BASE;
1229

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

    
1249
                            /* no reencoding needed : output the packet directly */
1250
                            /* force the input stream PTS */
1251
                        
1252
                            avcodec_get_frame_defaults(&avframe);
1253
                            ost->st->codec.coded_frame= &avframe;
1254
                            avframe.key_frame = pkt->flags & PKT_FLAG_KEY; 
1255

    
1256
                            if(ost->st->codec.codec_type == CODEC_TYPE_AUDIO)
1257
                                audio_size += data_size;
1258
                            else if (ost->st->codec.codec_type == CODEC_TYPE_VIDEO) {
1259
                                video_size += data_size;
1260
                                ost->sync_opts++;
1261
                            }
1262

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

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

    
1339

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

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

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

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

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

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

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

    
1493
        codec = &ost->st->codec;
1494
        icodec = &ist->st->codec;
1495

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

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

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

    
1670
    if (!bit_buffer)
1671
        bit_buffer = av_malloc(bit_buffer_size);
1672
    if (!bit_buffer)
1673
        goto fail;
1674

    
1675
    /* dump the file output parameters - cannot be done before in case
1676
       of stream copy */
1677
    for(i=0;i<nb_output_files;i++) {
1678
        dump_format(output_files[i], i, output_files[i]->filename, 1);
1679
    }
1680

    
1681
    /* dump the stream mapping */
1682
    if (verbose >= 0) {
1683
        fprintf(stderr, "Stream mapping:\n");
1684
        for(i=0;i<nb_ostreams;i++) {
1685
            ost = ost_table[i];
1686
            fprintf(stderr, "  Stream #%d.%d -> #%d.%d\n",
1687
                    ist_table[ost->source_index]->file_index,
1688
                    ist_table[ost->source_index]->index,
1689
                    ost->file_index, 
1690
                    ost->index);
1691
        }
1692
    }
1693

    
1694
    /* open each encoder */
1695
    for(i=0;i<nb_ostreams;i++) {
1696
        ost = ost_table[i];
1697
        if (ost->encoding_needed) {
1698
            AVCodec *codec;
1699
            codec = avcodec_find_encoder(ost->st->codec.codec_id);
1700
            if (!codec) {
1701
                fprintf(stderr, "Unsupported codec for output stream #%d.%d\n", 
1702
                        ost->file_index, ost->index);
1703
                exit(1);
1704
            }
1705
            if (avcodec_open(&ost->st->codec, codec) < 0) {
1706
                fprintf(stderr, "Error while opening codec for stream #%d.%d - maybe incorrect parameters such as bit_rate, rate, width or height\n", 
1707
                        ost->file_index, ost->index);
1708
                exit(1);
1709
            }
1710
            extra_size += ost->st->codec.extradata_size;
1711
        }
1712
    }
1713

    
1714
    /* open each decoder */
1715
    for(i=0;i<nb_istreams;i++) {
1716
        ist = ist_table[i];
1717
        if (ist->decoding_needed) {
1718
            AVCodec *codec;
1719
            codec = avcodec_find_decoder(ist->st->codec.codec_id);
1720
            if (!codec) {
1721
                fprintf(stderr, "Unsupported codec (id=%d) for input stream #%d.%d\n", 
1722
                        ist->st->codec.codec_id, ist->file_index, ist->index);
1723
                exit(1);
1724
            }
1725
            if (avcodec_open(&ist->st->codec, codec) < 0) {
1726
                fprintf(stderr, "Error while opening codec for input stream #%d.%d\n", 
1727
                        ist->file_index, ist->index);
1728
                exit(1);
1729
            }
1730
            //if (ist->st->codec.codec_type == CODEC_TYPE_VIDEO)
1731
            //    ist->st->codec.flags |= CODEC_FLAG_REPEAT_FIELD;
1732
        }
1733
    }
1734

    
1735
    /* init pts */
1736
    for(i=0;i<nb_istreams;i++) {
1737
        ist = ist_table[i];
1738
        is = input_files[ist->file_index];
1739
        ist->pts = 0;
1740
        ist->next_pts = ist->st->start_time;
1741
        if(ist->next_pts == AV_NOPTS_VALUE) 
1742
            ist->next_pts=0;
1743
        ist->is_start = 1;
1744
    }
1745

    
1746
    /* compute buffer size max (should use a complete heuristic) */
1747
    for(i=0;i<nb_input_files;i++) {
1748
        file_table[i].buffer_size_max = 2048;
1749
    }
1750

    
1751
    /* set meta data information from input file if required */
1752
    for (i=0;i<nb_meta_data_maps;i++) {
1753
        AVFormatContext *out_file;
1754
        AVFormatContext *in_file;
1755

    
1756
        int out_file_index = meta_data_maps[i].out_file;
1757
        int in_file_index = meta_data_maps[i].in_file;
1758
        if ( out_file_index < 0 || out_file_index >= nb_output_files ) {
1759
            fprintf(stderr, "Invalid output file index %d map_meta_data(%d,%d)\n", out_file_index, out_file_index, in_file_index);
1760
            ret = -EINVAL;
1761
            goto fail;
1762
        }
1763
        if ( in_file_index < 0 || in_file_index >= nb_input_files ) {
1764
            fprintf(stderr, "Invalid input file index %d map_meta_data(%d,%d)\n", in_file_index, out_file_index, in_file_index);
1765
            ret = -EINVAL;
1766
            goto fail;
1767
        }                
1768
                 
1769
        out_file = output_files[out_file_index];
1770
        in_file = input_files[in_file_index];
1771

    
1772
        strcpy(out_file->title, in_file->title);
1773
        strcpy(out_file->author, in_file->author);
1774
        strcpy(out_file->copyright, in_file->copyright);
1775
        strcpy(out_file->comment, in_file->comment);
1776
        strcpy(out_file->album, in_file->album);
1777
        out_file->year = in_file->year;
1778
        out_file->track = in_file->track;
1779
        strcpy(out_file->genre, in_file->genre);
1780
    }
1781
        
1782
    /* open files and write file headers */
1783
    for(i=0;i<nb_output_files;i++) {
1784
        os = output_files[i];
1785
        if (av_write_header(os) < 0) {
1786
            fprintf(stderr, "Could not write header for output file #%d (incorrect codec parameters ?)\n", i);
1787
            ret = -EINVAL;
1788
            goto fail;
1789
        }
1790
    }
1791

    
1792
#ifndef CONFIG_WIN32
1793
    if ( !using_stdin && verbose >= 0) {
1794
        fprintf(stderr, "Press [q] to stop encoding\n");
1795
        url_set_interrupt_cb(decode_interrupt_cb);
1796
    }
1797
#endif
1798
    term_init();
1799

    
1800
    stream_no_data = 0;
1801
    key = -1;
1802

    
1803
    for(; received_sigterm == 0;) {
1804
        int file_index, ist_index;
1805
        AVPacket pkt;
1806
        double ipts_min;
1807
        double opts_min;
1808

    
1809
    redo:
1810
        ipts_min= 1e100;
1811
        opts_min= 1e100;
1812
        /* if 'q' pressed, exits */
1813
        if (!using_stdin) {
1814
            if (q_pressed)
1815
                break;
1816
            /* read_key() returns 0 on EOF */
1817
            key = read_key();
1818
            if (key == 'q')
1819
                break;
1820
        }
1821

    
1822
        /* select the stream that we must read now by looking at the
1823
           smallest output pts */
1824
        file_index = -1;
1825
        for(i=0;i<nb_ostreams;i++) {
1826
            double ipts, opts;
1827
            ost = ost_table[i];
1828
            os = output_files[ost->file_index];
1829
            ist = ist_table[ost->source_index];
1830
            if(ost->st->codec.codec_type == CODEC_TYPE_VIDEO)
1831
                opts = (double)ost->sync_opts * ost->st->codec.frame_rate_base / ost->st->codec.frame_rate;
1832
            else
1833
                opts = (double)ost->st->pts.val * ost->st->time_base.num / ost->st->time_base.den;
1834
            ipts = (double)ist->pts;
1835
            if (!file_table[ist->file_index].eof_reached){
1836
                if(ipts < ipts_min) {
1837
                    ipts_min = ipts;
1838
                    if(input_sync ) file_index = ist->file_index;
1839
                }
1840
                if(opts < opts_min) {
1841
                    opts_min = opts;
1842
                    if(!input_sync) file_index = ist->file_index;
1843
                }
1844
            }
1845
            if(ost->frame_number >= max_frames[ost->st->codec.codec_type]){
1846
                file_index= -1;
1847
                break;
1848
            }
1849
        }
1850
        /* if none, if is finished */
1851
        if (file_index < 0) {
1852
            break;
1853
        }
1854

    
1855
        /* finish if recording time exhausted */
1856
        if (recording_time > 0 && opts_min >= (recording_time / 1000000.0))
1857
            break;
1858

    
1859
        /* read a frame from it and output it in the fifo */
1860
        is = input_files[file_index];
1861
        if (av_read_frame(is, &pkt) < 0) {
1862
            file_table[file_index].eof_reached = 1;
1863
            continue;
1864
        }
1865

    
1866
        if (!pkt.size) {
1867
            stream_no_data = is;
1868
        } else {
1869
            stream_no_data = 0;
1870
        }
1871
        if (do_pkt_dump) {
1872
            av_pkt_dump(stdout, &pkt, do_hex_dump);
1873
        }
1874
        /* the following test is needed in case new streams appear
1875
           dynamically in stream : we ignore them */
1876
        if (pkt.stream_index >= file_table[file_index].nb_streams)
1877
            goto discard_packet;
1878
        ist_index = file_table[file_index].ist_index + pkt.stream_index;
1879
        ist = ist_table[ist_index];
1880
        if (ist->discard)
1881
            goto discard_packet;
1882

    
1883
//        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);
1884
        if (pkt.dts != AV_NOPTS_VALUE) {
1885
            int64_t delta= pkt.dts - ist->next_pts;
1886
            if(ABS(delta) > 10LL*AV_TIME_BASE && !copy_ts){
1887
                input_files_ts_offset[ist->file_index]-= delta;
1888
                if (verbose > 2)
1889
                    fprintf(stderr, "timestamp discontinuity %lld, new offset= %lld\n", delta, input_files_ts_offset[ist->file_index]);
1890
                for(i=0; i<file_table[file_index].nb_streams; i++){
1891
                    int index= file_table[file_index].ist_index + i;
1892
                    ist_table[index]->next_pts += delta;
1893
                    ist_table[index]->is_start=1;
1894
                }
1895
            }
1896
        }
1897

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

    
1901
            if (verbose >= 0)
1902
                fprintf(stderr, "Error while decoding stream #%d.%d\n",
1903
                        ist->file_index, ist->index);
1904

    
1905
            av_free_packet(&pkt);
1906
            goto redo;
1907
        }
1908
        
1909
    discard_packet:
1910
        av_free_packet(&pkt);
1911
        
1912
        /* dump report by using the output first video and audio streams */
1913
        print_report(output_files, ost_table, nb_ostreams, 0);
1914
    }
1915

    
1916
    /* at the end of stream, we must flush the decoder buffers */
1917
    for(i=0;i<nb_istreams;i++) {
1918
        ist = ist_table[i];
1919
        if (ist->decoding_needed) {
1920
            output_packet(ist, i, ost_table, nb_ostreams, NULL);
1921
        }
1922
    }
1923

    
1924
    term_exit();
1925

    
1926
    /* write the trailer if needed and close file */
1927
    for(i=0;i<nb_output_files;i++) {
1928
        os = output_files[i];
1929
        av_write_trailer(os);
1930
    }
1931

    
1932
    /* dump report by using the first video and audio streams */
1933
    print_report(output_files, ost_table, nb_ostreams, 1);
1934

    
1935
    /* close each encoder */
1936
    for(i=0;i<nb_ostreams;i++) {
1937
        ost = ost_table[i];
1938
        if (ost->encoding_needed) {
1939
            av_freep(&ost->st->codec.stats_in);
1940
            avcodec_close(&ost->st->codec);
1941
        }
1942
    }
1943
    
1944
    /* close each decoder */
1945
    for(i=0;i<nb_istreams;i++) {
1946
        ist = ist_table[i];
1947
        if (ist->decoding_needed) {
1948
            avcodec_close(&ist->st->codec);
1949
        }
1950
    }
1951

    
1952
    /* finished ! */
1953
    
1954
    ret = 0;
1955
 fail1:
1956
    av_free(file_table);
1957

    
1958
    if (ist_table) {
1959
        for(i=0;i<nb_istreams;i++) {
1960
            ist = ist_table[i];
1961
            av_free(ist);
1962
        }
1963
        av_free(ist_table);
1964
    }
1965
    if (ost_table) {
1966
        for(i=0;i<nb_ostreams;i++) {
1967
            ost = ost_table[i];
1968
            if (ost) {
1969
                if (ost->logfile) {
1970
                    fclose(ost->logfile);
1971
                    ost->logfile = NULL;
1972
                }
1973
                fifo_free(&ost->fifo); /* works even if fifo is not
1974
                                          initialized but set to zero */
1975
                av_free(ost->pict_tmp.data[0]);
1976
                if (ost->video_resample)
1977
                    img_resample_close(ost->img_resample_ctx);
1978
                if (ost->audio_resample)
1979
                    audio_resample_close(ost->resample);
1980
                av_free(ost);
1981
            }
1982
        }
1983
        av_free(ost_table);
1984
    }
1985
    return ret;
1986
 fail:
1987
    ret = -ENOMEM;
1988
    goto fail1;
1989
}
1990

    
1991
#if 0
1992
int file_read(const char *filename)
1993
{
1994
    URLContext *h;
1995
    unsigned char buffer[1024];
1996
    int len, i;
1997

1998
    if (url_open(&h, filename, O_RDONLY) < 0) {
1999
        printf("could not open '%s'\n", filename);
2000
        return -1;
2001
    }
2002
    for(;;) {
2003
        len = url_read(h, buffer, sizeof(buffer));
2004
        if (len <= 0)
2005
            break;
2006
        for(i=0;i<len;i++) putchar(buffer[i]);
2007
    }
2008
    url_close(h);
2009
    return 0;
2010
}
2011
#endif
2012

    
2013
static void opt_image_format(const char *arg)
2014
{
2015
    AVImageFormat *f;
2016
    
2017
    for(f = first_image_format; f != NULL; f = f->next) {
2018
        if (!strcmp(arg, f->name))
2019
            break;
2020
    }
2021
    if (!f) {
2022
        fprintf(stderr, "Unknown image format: '%s'\n", arg);
2023
        exit(1);
2024
    }
2025
    image_format = f;
2026
}
2027

    
2028
static void opt_format(const char *arg)
2029
{
2030
    /* compatibility stuff for pgmyuv */
2031
    if (!strcmp(arg, "pgmyuv")) {
2032
        pgmyuv_compatibility_hack=1;
2033
//        opt_image_format(arg);
2034
        arg = "image2";
2035
    }
2036

    
2037
    file_iformat = av_find_input_format(arg);
2038
    file_oformat = guess_format(arg, NULL, NULL);
2039
    if (!file_iformat && !file_oformat) {
2040
        fprintf(stderr, "Unknown input or output format: %s\n", arg);
2041
        exit(1);
2042
    }
2043
}
2044

    
2045
static void opt_video_bitrate(const char *arg)
2046
{
2047
    video_bit_rate = atoi(arg) * 1000;
2048
}
2049

    
2050
static void opt_video_bitrate_tolerance(const char *arg)
2051
{
2052
    video_bit_rate_tolerance = atoi(arg) * 1000;
2053
}
2054

    
2055
static void opt_video_bitrate_max(const char *arg)
2056
{
2057
    video_rc_max_rate = atoi(arg) * 1000;
2058
}
2059

    
2060
static void opt_video_bitrate_min(const char *arg)
2061
{
2062
    video_rc_min_rate = atoi(arg) * 1000;
2063
}
2064

    
2065
static void opt_video_buffer_size(const char *arg)
2066
{
2067
    video_rc_buffer_size = atoi(arg) * 8*1024;
2068
}
2069

    
2070
static void opt_video_rc_eq(char *arg)
2071
{
2072
    video_rc_eq = arg;
2073
}
2074

    
2075
static void opt_video_rc_override_string(char *arg)
2076
{
2077
    video_rc_override_string = arg;
2078
}
2079

    
2080

    
2081
static void opt_workaround_bugs(const char *arg)
2082
{
2083
    workaround_bugs = atoi(arg);
2084
}
2085

    
2086
static void opt_dct_algo(const char *arg)
2087
{
2088
    dct_algo = atoi(arg);
2089
}
2090

    
2091
static void opt_idct_algo(const char *arg)
2092
{
2093
    idct_algo = atoi(arg);
2094
}
2095

    
2096
static void opt_me_threshold(const char *arg)
2097
{
2098
    me_threshold = atoi(arg);
2099
}
2100

    
2101
static void opt_mb_threshold(const char *arg)
2102
{
2103
    mb_threshold = atoi(arg);
2104
}
2105

    
2106
static void opt_error_resilience(const char *arg)
2107
{
2108
    error_resilience = atoi(arg);
2109
}
2110

    
2111
static void opt_error_concealment(const char *arg)
2112
{
2113
    error_concealment = atoi(arg);
2114
}
2115

    
2116
static void opt_debug(const char *arg)
2117
{
2118
    debug = atoi(arg);
2119
}
2120

    
2121
static void opt_vismv(const char *arg)
2122
{
2123
    debug_mv = atoi(arg);
2124
}
2125
    
2126
static void opt_verbose(const char *arg)
2127
{
2128
    verbose = atoi(arg);
2129
    av_log_set_level(atoi(arg));
2130
}
2131

    
2132
static void opt_frame_rate(const char *arg)
2133
{
2134
    if (parse_frame_rate(&frame_rate, &frame_rate_base, arg) < 0) {
2135
        fprintf(stderr, "Incorrect frame rate\n");
2136
        exit(1);
2137
    }
2138
}
2139

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

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

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

    
2194
static void opt_frame_crop_right(const char *arg)
2195
{
2196
    frame_rightBand = atoi(arg);
2197
    if (frame_rightBand < 0) {
2198
        fprintf(stderr, "Incorrect right crop size\n");
2199
        exit(1);
2200
    }
2201
    if ((frame_rightBand % 2) != 0) {
2202
        fprintf(stderr, "Right crop size must be a multiple of 2\n");
2203
        exit(1);        
2204
    }
2205
    if ((frame_rightBand) >= frame_width){
2206
            fprintf(stderr, "Horizontal crop dimensions are outside the range of the original image.\nRemember to crop first and scale second.\n");
2207
        exit(1);
2208
    }
2209
    frame_width -= frame_rightBand;
2210
}
2211

    
2212
static void opt_frame_size(const char *arg)
2213
{
2214
    if (parse_image_size(&frame_width, &frame_height, arg) < 0) {
2215
        fprintf(stderr, "Incorrect frame size\n");
2216
        exit(1);
2217
    }
2218
    if ((frame_width % 2) != 0 || (frame_height % 2) != 0) {
2219
        fprintf(stderr, "Frame size must be a multiple of 2\n");
2220
        exit(1);
2221
    }
2222
}
2223

    
2224

    
2225
#define SCALEBITS 10
2226
#define ONE_HALF  (1 << (SCALEBITS - 1))
2227
#define FIX(x)          ((int) ((x) * (1<<SCALEBITS) + 0.5))
2228

    
2229
#define RGB_TO_Y(r, g, b) \
2230
((FIX(0.29900) * (r) + FIX(0.58700) * (g) + \
2231
  FIX(0.11400) * (b) + ONE_HALF) >> SCALEBITS)
2232

    
2233
#define RGB_TO_U(r1, g1, b1, shift)\
2234
(((- FIX(0.16874) * r1 - FIX(0.33126) * g1 +         \
2235
     FIX(0.50000) * b1 + (ONE_HALF << shift) - 1) >> (SCALEBITS + shift)) + 128)
2236

    
2237
#define RGB_TO_V(r1, g1, b1, shift)\
2238
(((FIX(0.50000) * r1 - FIX(0.41869) * g1 -           \
2239
   FIX(0.08131) * b1 + (ONE_HALF << shift) - 1) >> (SCALEBITS + shift)) + 128)
2240

    
2241
static void opt_pad_color(const char *arg) {
2242
    /* Input is expected to be six hex digits similar to
2243
       how colors are expressed in html tags (but without the #) */
2244
    int rgb = strtol(arg, NULL, 16);
2245
    int r,g,b;
2246
    
2247
    r = (rgb >> 16); 
2248
    g = ((rgb >> 8) & 255);
2249
    b = (rgb & 255);
2250

    
2251
    padcolor[0] = RGB_TO_Y(r,g,b);
2252
    padcolor[1] = RGB_TO_U(r,g,b,0);
2253
    padcolor[2] = RGB_TO_V(r,g,b,0);
2254
}
2255

    
2256
static void opt_frame_pad_top(const char *arg)
2257
{
2258
    frame_padtop = atoi(arg); 
2259
    if (frame_padtop < 0) {
2260
        fprintf(stderr, "Incorrect top pad size\n");
2261
        exit(1);
2262
    }
2263
    if ((frame_padtop % 2) != 0) {
2264
        fprintf(stderr, "Top pad size must be a multiple of 2\n");
2265
        exit(1);
2266
    }
2267
}
2268

    
2269
static void opt_frame_pad_bottom(const char *arg)
2270
{
2271
    frame_padbottom = atoi(arg); 
2272
    if (frame_padbottom < 0) {
2273
        fprintf(stderr, "Incorrect bottom pad size\n");
2274
        exit(1);
2275
    }
2276
    if ((frame_padbottom % 2) != 0) {
2277
        fprintf(stderr, "Bottom pad size must be a multiple of 2\n");
2278
        exit(1);
2279
    }
2280
}
2281

    
2282

    
2283
static void opt_frame_pad_left(const char *arg)
2284
{
2285
    frame_padleft = atoi(arg); 
2286
    if (frame_padleft < 0) {
2287
        fprintf(stderr, "Incorrect left pad size\n");
2288
        exit(1);
2289
    }
2290
    if ((frame_padleft % 2) != 0) {
2291
        fprintf(stderr, "Left pad size must be a multiple of 2\n");
2292
        exit(1);
2293
    }
2294
}
2295

    
2296

    
2297
static void opt_frame_pad_right(const char *arg)
2298
{
2299
    frame_padright = atoi(arg); 
2300
    if (frame_padright < 0) {
2301
        fprintf(stderr, "Incorrect right pad size\n");
2302
        exit(1);
2303
    }
2304
    if ((frame_padright % 2) != 0) {
2305
        fprintf(stderr, "Right pad size must be a multiple of 2\n");
2306
        exit(1);
2307
    }
2308
}
2309

    
2310

    
2311
static void opt_frame_pix_fmt(const char *arg)
2312
{
2313
    frame_pix_fmt = avcodec_get_pix_fmt(arg);
2314
}
2315

    
2316
static void opt_frame_aspect_ratio(const char *arg)
2317
{
2318
    int x = 0, y = 0;
2319
    double ar = 0;
2320
    const char *p;
2321
    
2322
    p = strchr(arg, ':');
2323
    if (p) {
2324
        x = strtol(arg, (char **)&arg, 10);
2325
        if (arg == p)
2326
            y = strtol(arg+1, (char **)&arg, 10);
2327
        if (x > 0 && y > 0)
2328
            ar = (double)x / (double)y;
2329
    } else
2330
        ar = strtod(arg, (char **)&arg);
2331

    
2332
    if (!ar) {
2333
        fprintf(stderr, "Incorrect aspect ratio specification.\n");
2334
        exit(1);
2335
    }
2336
    frame_aspect_ratio = ar;
2337
}
2338

    
2339
static void opt_gop_size(const char *arg)
2340
{
2341
    gop_size = atoi(arg);
2342
}
2343

    
2344
static void opt_b_frames(const char *arg)
2345
{
2346
    b_frames = atoi(arg);
2347
    if (b_frames > FF_MAX_B_FRAMES) {
2348
        fprintf(stderr, "\nCannot have more than %d B frames, increase FF_MAX_B_FRAMES.\n", FF_MAX_B_FRAMES);
2349
        exit(1);
2350
    } else if (b_frames < 1) {
2351
        fprintf(stderr, "\nNumber of B frames must be higher than 0\n");
2352
        exit(1);
2353
    }
2354
}
2355

    
2356
static void opt_mb_decision(const char *arg)
2357
{
2358
    mb_decision = atoi(arg);
2359
}
2360

    
2361
static void opt_mb_cmp(const char *arg)
2362
{
2363
    mb_cmp = atoi(arg);
2364
}
2365

    
2366
static void opt_ildct_cmp(const char *arg)
2367
{
2368
    ildct_cmp = atoi(arg);
2369
}
2370

    
2371
static void opt_sub_cmp(const char *arg)
2372
{
2373
    sub_cmp = atoi(arg);
2374
}
2375

    
2376
static void opt_cmp(const char *arg)
2377
{
2378
    cmp = atoi(arg);
2379
}
2380

    
2381
static void opt_pre_cmp(const char *arg)
2382
{
2383
    pre_cmp = atoi(arg);
2384
}
2385

    
2386
static void opt_pre_me(const char *arg)
2387
{
2388
    pre_me = atoi(arg);
2389
}
2390

    
2391
static void opt_lumi_mask(const char *arg)
2392
{
2393
    lumi_mask = atof(arg);
2394
}
2395

    
2396
static void opt_dark_mask(const char *arg)
2397
{
2398
    dark_mask = atof(arg);
2399
}
2400

    
2401
static void opt_scplx_mask(const char *arg)
2402
{
2403
    scplx_mask = atof(arg);
2404
}
2405

    
2406
static void opt_tcplx_mask(const char *arg)
2407
{
2408
    tcplx_mask = atof(arg);
2409
}
2410

    
2411
static void opt_p_mask(const char *arg)
2412
{
2413
    p_mask = atof(arg);
2414
}
2415

    
2416
static void opt_qscale(const char *arg)
2417
{
2418
    video_qscale = atof(arg);
2419
    if (video_qscale < 0.01 ||
2420
        video_qscale > 255) {
2421
        fprintf(stderr, "qscale must be >= 0.01 and <= 255\n");
2422
        exit(1);
2423
    }
2424
}
2425

    
2426
static void opt_lmax(const char *arg)
2427
{
2428
    video_lmax = atof(arg)*FF_QP2LAMBDA;
2429
}
2430

    
2431
static void opt_lmin(const char *arg)
2432
{
2433
    video_lmin = atof(arg)*FF_QP2LAMBDA;
2434
}
2435

    
2436
static void opt_qmin(const char *arg)
2437
{
2438
    video_qmin = atoi(arg);
2439
    if (video_qmin < 0 ||
2440
        video_qmin > 31) {
2441
        fprintf(stderr, "qmin must be >= 1 and <= 31\n");
2442
        exit(1);
2443
    }
2444
}
2445

    
2446
static void opt_qmax(const char *arg)
2447
{
2448
    video_qmax = atoi(arg);
2449
    if (video_qmax < 0 ||
2450
        video_qmax > 31) {
2451
        fprintf(stderr, "qmax must be >= 1 and <= 31\n");
2452
        exit(1);
2453
    }
2454
}
2455

    
2456
static void opt_mb_qmin(const char *arg)
2457
{
2458
    video_mb_qmin = atoi(arg);
2459
    if (video_mb_qmin < 0 ||
2460
        video_mb_qmin > 31) {
2461
        fprintf(stderr, "qmin must be >= 1 and <= 31\n");
2462
        exit(1);
2463
    }
2464
}
2465

    
2466
static void opt_mb_qmax(const char *arg)
2467
{
2468
    video_mb_qmax = atoi(arg);
2469
    if (video_mb_qmax < 0 ||
2470
        video_mb_qmax > 31) {
2471
        fprintf(stderr, "qmax must be >= 1 and <= 31\n");
2472
        exit(1);
2473
    }
2474
}
2475

    
2476
static void opt_qdiff(const char *arg)
2477
{
2478
    video_qdiff = atoi(arg);
2479
    if (video_qdiff < 0 ||
2480
        video_qdiff > 31) {
2481
        fprintf(stderr, "qdiff must be >= 1 and <= 31\n");
2482
        exit(1);
2483
    }
2484
}
2485

    
2486
static void opt_qblur(const char *arg)
2487
{
2488
    video_qblur = atof(arg);
2489
}
2490

    
2491
static void opt_qcomp(const char *arg)
2492
{
2493
    video_qcomp = atof(arg);
2494
}
2495

    
2496
static void opt_rc_initial_cplx(const char *arg)
2497
{
2498
    video_rc_initial_cplx = atof(arg);
2499
}
2500
static void opt_b_qfactor(const char *arg)
2501
{
2502
    video_b_qfactor = atof(arg);
2503
}
2504
static void opt_i_qfactor(const char *arg)
2505
{
2506
    video_i_qfactor = atof(arg);
2507
}
2508
static void opt_b_qoffset(const char *arg)
2509
{
2510
    video_b_qoffset = atof(arg);
2511
}
2512
static void opt_i_qoffset(const char *arg)
2513
{
2514
    video_i_qoffset = atof(arg);
2515
}
2516

    
2517
static void opt_ibias(const char *arg)
2518
{
2519
    video_intra_quant_bias = atoi(arg);
2520
}
2521
static void opt_pbias(const char *arg)
2522
{
2523
    video_inter_quant_bias = atoi(arg);
2524
}
2525

    
2526
static void opt_packet_size(const char *arg)
2527
{
2528
    packet_size= atoi(arg);
2529
}
2530

    
2531
static void opt_error_rate(const char *arg)
2532
{
2533
    error_rate= atoi(arg);
2534
}
2535

    
2536
static void opt_strict(const char *arg)
2537
{
2538
    strict= atoi(arg);
2539
}
2540

    
2541
static void opt_top_field_first(const char *arg)
2542
{
2543
    top_field_first= atoi(arg);
2544
}
2545

    
2546
static void opt_noise_reduction(const char *arg)
2547
{
2548
    noise_reduction= atoi(arg);
2549
}
2550

    
2551
static void opt_qns(const char *arg)
2552
{
2553
    qns= atoi(arg);
2554
}
2555

    
2556
static void opt_sc_threshold(const char *arg)
2557
{
2558
    sc_threshold= atoi(arg);
2559
}
2560

    
2561
static void opt_me_range(const char *arg)
2562
{
2563
    me_range = atoi(arg);
2564
}
2565

    
2566
static void opt_thread_count(const char *arg)
2567
{
2568
    thread_count= atoi(arg);
2569
#if !defined(HAVE_THREADS)
2570
    if (verbose >= 0)
2571
        fprintf(stderr, "Warning: not compiled with thread support, using thread emulation\n");
2572
#endif
2573
}
2574

    
2575
static void opt_audio_bitrate(const char *arg)
2576
{
2577
    audio_bit_rate = atoi(arg) * 1000;
2578
}
2579

    
2580
static void opt_audio_rate(const char *arg)
2581
{
2582
    audio_sample_rate = atoi(arg);
2583
}
2584

    
2585
static void opt_audio_channels(const char *arg)
2586
{
2587
    audio_channels = atoi(arg);
2588
}
2589

    
2590
static void opt_video_device(const char *arg)
2591
{
2592
    video_device = av_strdup(arg);
2593
}
2594

    
2595
static void opt_grab_device(const char *arg)
2596
{
2597
    grab_device = av_strdup(arg);
2598
}
2599

    
2600
static void opt_video_channel(const char *arg)
2601
{
2602
    video_channel = strtol(arg, NULL, 0);
2603
}
2604

    
2605
static void opt_video_standard(const char *arg)
2606
{
2607
    video_standard = av_strdup(arg);
2608
}
2609

    
2610
static void opt_audio_device(const char *arg)
2611
{
2612
    audio_device = av_strdup(arg);
2613
}
2614

    
2615
static void opt_audio_codec(const char *arg)
2616
{
2617
    AVCodec *p;
2618

    
2619
    if (!strcmp(arg, "copy")) {
2620
        audio_stream_copy = 1;
2621
    } else {
2622
        p = first_avcodec;
2623
        while (p) {
2624
            if (!strcmp(p->name, arg) && p->type == CODEC_TYPE_AUDIO)
2625
                break;
2626
            p = p->next;
2627
        }
2628
        if (p == NULL) {
2629
            fprintf(stderr, "Unknown audio codec '%s'\n", arg);
2630
            exit(1);
2631
        } else {
2632
            audio_codec_id = p->id;
2633
        }
2634
    }
2635
}
2636

    
2637
static void opt_audio_tag(const char *arg)
2638
{
2639
    char *tail;
2640
    audio_codec_tag= strtol(arg, &tail, 0);
2641

    
2642
    if(!tail || *tail)
2643
        audio_codec_tag= arg[0] + (arg[1]<<8) + (arg[2]<<16) + (arg[3]<<24);
2644
}
2645

    
2646
static void opt_video_tag(const char *arg)
2647
{
2648
    char *tail;
2649
    video_codec_tag= strtol(arg, &tail, 0);
2650

    
2651
    if(!tail || *tail)
2652
        video_codec_tag= arg[0] + (arg[1]<<8) + (arg[2]<<16) + (arg[3]<<24);
2653
}
2654

    
2655
static void add_frame_hooker(const char *arg)
2656
{
2657
    int argc = 0;
2658
    char *argv[64];
2659
    int i;
2660
    char *args = av_strdup(arg);
2661

    
2662
    using_vhook = 1;
2663

    
2664
    argv[0] = strtok(args, " ");
2665
    while (argc < 62 && (argv[++argc] = strtok(NULL, " "))) {
2666
    }
2667

    
2668
    i = frame_hook_add(argc, argv);
2669

    
2670
    if (i != 0) {
2671
        fprintf(stderr, "Failed to add video hook function: %s\n", arg);
2672
        exit(1);
2673
    }
2674
}
2675

    
2676
const char *motion_str[] = {
2677
    "zero",
2678
    "full",
2679
    "log",
2680
    "phods",
2681
    "epzs",
2682
    "x1",
2683
    NULL,
2684
};
2685

    
2686
static void opt_motion_estimation(const char *arg)
2687
{
2688
    const char **p;
2689
    p = motion_str;
2690
    for(;;) {
2691
        if (!*p) {
2692
            fprintf(stderr, "Unknown motion estimation method '%s'\n", arg);
2693
            exit(1);
2694
        }
2695
        if (!strcmp(*p, arg))
2696
            break;
2697
        p++;
2698
    }
2699
    me_method = (p - motion_str) + 1;
2700
}
2701

    
2702
static void opt_video_codec(const char *arg)
2703
{
2704
    AVCodec *p;
2705

    
2706
    if (!strcmp(arg, "copy")) {
2707
        video_stream_copy = 1;
2708
    } else {
2709
        p = first_avcodec;
2710
        while (p) {
2711
            if (!strcmp(p->name, arg) && p->type == CODEC_TYPE_VIDEO)
2712
                break;
2713
            p = p->next;
2714
        }
2715
        if (p == NULL) {
2716
            fprintf(stderr, "Unknown video codec '%s'\n", arg);
2717
            exit(1);
2718
        } else {
2719
            video_codec_id = p->id;
2720
        }
2721
    }
2722
}
2723

    
2724
static void opt_map(const char *arg)
2725
{
2726
    AVStreamMap *m;
2727
    const char *p;
2728

    
2729
    p = arg;
2730
    m = &stream_maps[nb_stream_maps++];
2731

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

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

    
2739
static void opt_map_meta_data(const char *arg)
2740
{
2741
    AVMetaDataMap *m;
2742
    const char *p;
2743
        
2744
    p = arg;
2745
    m = &meta_data_maps[nb_meta_data_maps++];
2746

    
2747
    m->out_file = strtol(arg, (char **)&p, 0);
2748
    if (*p)
2749
        p++;
2750

    
2751
    m->in_file = strtol(p, (char **)&p, 0);
2752
}
2753

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

    
2759
static void opt_start_time(const char *arg)
2760
{
2761
    start_time = parse_date(arg, 1);
2762
}
2763

    
2764
static void opt_rec_timestamp(const char *arg)
2765
{
2766
    rec_timestamp = parse_date(arg, 0) / 1000000;
2767
}
2768

    
2769
static void opt_input_ts_offset(const char *arg)
2770
{
2771
    input_ts_offset = parse_date(arg, 1);
2772
}
2773

    
2774
static void opt_input_file(const char *filename)
2775
{
2776
    AVFormatContext *ic;
2777
    AVFormatParameters params, *ap = &params;
2778
    int err, i, ret, rfps, rfps_base;
2779
    int64_t timestamp;
2780

    
2781
    if (!strcmp(filename, "-"))
2782
        filename = "pipe:";
2783

    
2784
    using_stdin |= !strncmp(filename, "pipe:", 5) || 
2785
                   !strcmp( filename, "/dev/stdin" );
2786

    
2787
    /* get default parameters from command line */
2788
    memset(ap, 0, sizeof(*ap));
2789
    ap->sample_rate = audio_sample_rate;
2790
    ap->channels = audio_channels;
2791
    ap->frame_rate = frame_rate;
2792
    ap->frame_rate_base = frame_rate_base;
2793
    ap->width = frame_width + frame_padleft + frame_padright;
2794
    ap->height = frame_height + frame_padtop + frame_padbottom;
2795
    ap->image_format = image_format;
2796
    ap->pix_fmt = frame_pix_fmt;
2797
    ap->device  = grab_device;
2798
    ap->channel = video_channel;
2799
    ap->standard = video_standard;
2800
    ap->video_codec_id = video_codec_id;
2801
    ap->audio_codec_id = audio_codec_id;
2802
    if(pgmyuv_compatibility_hack)
2803
        ap->video_codec_id= CODEC_ID_PGMYUV;
2804

    
2805
    /* open the input file with generic libav function */
2806
    err = av_open_input_file(&ic, filename, file_iformat, 0, ap);
2807
    if (err < 0) {
2808
        print_error(filename, err);
2809
        exit(1);
2810
    }
2811
    
2812
    /* If not enough info to get the stream parameters, we decode the
2813
       first frames to get it. (used in mpeg case for example) */
2814
    ret = av_find_stream_info(ic);
2815
    if (ret < 0 && verbose >= 0) {
2816
        fprintf(stderr, "%s: could not find codec parameters\n", filename);
2817
        exit(1);
2818
    }
2819

    
2820
    timestamp = start_time;
2821
    /* add the stream start time */
2822
    if (ic->start_time != AV_NOPTS_VALUE)
2823
        timestamp += ic->start_time;
2824

    
2825
    /* if seeking requested, we execute it */
2826
    if (start_time != 0) {
2827
        ret = av_seek_frame(ic, -1, timestamp, AVSEEK_FLAG_BACKWARD);
2828
        if (ret < 0) {
2829
            fprintf(stderr, "%s: could not seek to position %0.3f\n", 
2830
                    filename, (double)timestamp / AV_TIME_BASE);
2831
        }
2832
        /* reset seek info */
2833
        start_time = 0;
2834
    }
2835

    
2836
    /* update the current parameters so that they match the one of the input stream */
2837
    for(i=0;i<ic->nb_streams;i++) {
2838
        AVCodecContext *enc = &ic->streams[i]->codec;
2839
#if defined(HAVE_THREADS)
2840
        if(thread_count>1)
2841
            avcodec_thread_init(enc, thread_count);
2842
#endif
2843
        enc->thread_count= thread_count;
2844
        switch(enc->codec_type) {
2845
        case CODEC_TYPE_AUDIO:
2846
            //fprintf(stderr, "\nInput Audio channels: %d", enc->channels);
2847
            audio_channels = enc->channels;
2848
            audio_sample_rate = enc->sample_rate;
2849
            break;
2850
        case CODEC_TYPE_VIDEO:
2851
            frame_height = enc->height;
2852
            frame_width = enc->width;
2853
            frame_aspect_ratio = av_q2d(enc->sample_aspect_ratio) * enc->width / enc->height;
2854
            frame_pix_fmt = enc->pix_fmt;
2855
            rfps      = ic->streams[i]->r_frame_rate;
2856
            rfps_base = ic->streams[i]->r_frame_rate_base;
2857
            enc->workaround_bugs = workaround_bugs;
2858
            enc->error_resilience = error_resilience; 
2859
            enc->error_concealment = error_concealment; 
2860
            enc->idct_algo = idct_algo;
2861
            enc->debug = debug;
2862
            enc->debug_mv = debug_mv;            
2863
            enc->lowres= lowres;
2864
            if(bitexact)
2865
                enc->flags|= CODEC_FLAG_BITEXACT;
2866
            if(me_threshold)
2867
                enc->debug |= FF_DEBUG_MV;
2868

    
2869
            assert(enc->frame_rate_base == rfps_base); // should be true for now
2870
            if (enc->frame_rate != rfps) { 
2871

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

    
2876
                    (float)rfps / rfps_base);
2877
            }
2878
            /* update the current frame rate to match the stream frame rate */
2879
            frame_rate      = rfps;
2880
            frame_rate_base = rfps_base;
2881

    
2882
            enc->rate_emu = rate_emu;
2883
            break;
2884
        case CODEC_TYPE_DATA:
2885
            break;
2886
        default:
2887
            av_abort();
2888
        }
2889
    }
2890
    
2891
    input_files[nb_input_files] = ic;
2892
    input_files_ts_offset[nb_input_files] = input_ts_offset - (copy_ts ? 0 : timestamp);
2893
    /* dump the file content */
2894
    if (verbose >= 0)
2895
        dump_format(ic, nb_input_files, filename, 0);
2896

    
2897
    nb_input_files++;
2898
    file_iformat = NULL;
2899
    file_oformat = NULL;
2900
    image_format = NULL;
2901

    
2902
    grab_device = NULL;
2903
    video_channel = 0;
2904
    
2905
    rate_emu = 0;
2906
}
2907

    
2908
static void opt_grab(const char *arg)
2909
{
2910
    file_iformat = av_find_input_format(arg);
2911
    opt_input_file("");
2912
}
2913

    
2914
static void check_audio_video_inputs(int *has_video_ptr, int *has_audio_ptr)
2915
{
2916
    int has_video, has_audio, i, j;
2917
    AVFormatContext *ic;
2918

    
2919
    has_video = 0;
2920
    has_audio = 0;
2921
    for(j=0;j<nb_input_files;j++) {
2922
        ic = input_files[j];
2923
        for(i=0;i<ic->nb_streams;i++) {
2924
            AVCodecContext *enc = &ic->streams[i]->codec;
2925
            switch(enc->codec_type) {
2926
            case CODEC_TYPE_AUDIO:
2927
                has_audio = 1;
2928
                break;
2929
            case CODEC_TYPE_VIDEO:
2930
                has_video = 1;
2931
                break;
2932
            case CODEC_TYPE_DATA:
2933
                break;
2934
            default:
2935
                av_abort();
2936
            }
2937
        }
2938
    }
2939
    *has_video_ptr = has_video;
2940
    *has_audio_ptr = has_audio;
2941
}
2942

    
2943
static void opt_output_file(const char *filename)
2944
{
2945
    AVStream *st;
2946
    AVFormatContext *oc;
2947
    int use_video, use_audio, nb_streams, input_has_video, input_has_audio;
2948
    int codec_id;
2949
    AVFormatParameters params, *ap = &params;
2950

    
2951
    if (!strcmp(filename, "-"))
2952
        filename = "pipe:";
2953

    
2954
    oc = av_alloc_format_context();
2955

    
2956
    if (!file_oformat) {
2957
        file_oformat = guess_format(NULL, filename, NULL);
2958
        if (!file_oformat) {
2959
            fprintf(stderr, "Unable for find a suitable output format for '%s'\n",
2960
                    filename);
2961
            exit(1);
2962
        }
2963
    }
2964
    
2965
    oc->oformat = file_oformat;
2966

    
2967
    if (!strcmp(file_oformat->name, "ffm") && 
2968
        strstart(filename, "http:", NULL)) {
2969
        /* special case for files sent to ffserver: we get the stream
2970
           parameters from ffserver */
2971
        if (read_ffserver_streams(oc, filename) < 0) {
2972
            fprintf(stderr, "Could not read stream parameters from '%s'\n", filename);
2973
            exit(1);
2974
        }
2975
    } else {
2976
        use_video = file_oformat->video_codec != CODEC_ID_NONE || video_stream_copy;
2977
        use_audio = file_oformat->audio_codec != CODEC_ID_NONE || audio_stream_copy;
2978

    
2979
        /* disable if no corresponding type found and at least one
2980
           input file */
2981
        if (nb_input_files > 0) {
2982
            check_audio_video_inputs(&input_has_video, &input_has_audio);
2983
            if (!input_has_video)
2984
                use_video = 0;
2985
            if (!input_has_audio)
2986
                use_audio = 0;
2987
        }
2988

    
2989
        /* manual disable */
2990
        if (audio_disable) {
2991
            use_audio = 0;
2992
        }
2993
        if (video_disable) {
2994
            use_video = 0;
2995
        }
2996
        
2997
        nb_streams = 0;
2998
        if (use_video) {
2999
            AVCodecContext *video_enc;
3000
            
3001
            st = av_new_stream(oc, nb_streams++);
3002
            if (!st) {
3003
                fprintf(stderr, "Could not alloc stream\n");
3004
                exit(1);
3005
            }
3006
#if defined(HAVE_THREADS)
3007
            if(thread_count>1)
3008
                avcodec_thread_init(&st->codec, thread_count);
3009
#endif
3010

    
3011
            video_enc = &st->codec;
3012
            
3013
            if(video_codec_tag)
3014
                video_enc->codec_tag= video_codec_tag;
3015
                
3016
            if(!strcmp(file_oformat->name, "mp4") || !strcmp(file_oformat->name, "mov") || !strcmp(file_oformat->name, "3gp"))
3017
                video_enc->flags |= CODEC_FLAG_GLOBAL_HEADER;
3018
            if (video_stream_copy) {
3019
                st->stream_copy = 1;
3020
                video_enc->codec_type = CODEC_TYPE_VIDEO;
3021
            } else {
3022
                char *p;
3023
                int i;
3024
                AVCodec *codec;
3025
            
3026
                codec_id = av_guess_codec(file_oformat, NULL, filename, NULL, CODEC_TYPE_VIDEO);
3027
                if (video_codec_id != CODEC_ID_NONE)
3028
                    codec_id = video_codec_id;
3029
                
3030
                video_enc->codec_id = codec_id;
3031
                codec = avcodec_find_encoder(codec_id);
3032
                
3033
                video_enc->bit_rate = video_bit_rate;
3034
                video_enc->bit_rate_tolerance = video_bit_rate_tolerance;
3035
                video_enc->frame_rate = frame_rate; 
3036
                video_enc->frame_rate_base = frame_rate_base; 
3037
                if(codec && codec->supported_framerates){
3038
                    const AVRational *p= codec->supported_framerates;
3039
                    AVRational req= (AVRational){frame_rate, frame_rate_base};
3040
                    const AVRational *best=NULL;
3041
                    AVRational best_error= (AVRational){INT_MAX, 1};
3042
                    for(; p->den!=0; p++){
3043
                        AVRational error= av_sub_q(req, *p);
3044
                        if(error.num <0) error.num *= -1;
3045
                        if(av_cmp_q(error, best_error) < 0){
3046
                            best_error= error;
3047
                            best= p;
3048
                        }
3049
                    }
3050
                    video_enc->frame_rate     = best->num;
3051
                    video_enc->frame_rate_base= best->den;
3052
                }
3053
                
3054
                video_enc->width = frame_width + frame_padright + frame_padleft;
3055
                video_enc->height = frame_height + frame_padtop + frame_padbottom;
3056
                video_enc->sample_aspect_ratio = av_d2q(frame_aspect_ratio*frame_height/frame_width, 255);
3057
                video_enc->pix_fmt = frame_pix_fmt;
3058

    
3059
                if(codec && codec->pix_fmts){
3060
                    const enum PixelFormat *p= codec->pix_fmts;
3061
                    for(; *p!=-1; p++){
3062
                        if(*p == video_enc->pix_fmt)
3063
                            break;
3064
                    }
3065
                    if(*p == -1)
3066
                        video_enc->pix_fmt = codec->pix_fmts[0];
3067
                }
3068

    
3069
                if (!intra_only)
3070
                    video_enc->gop_size = gop_size;
3071
                else
3072
                    video_enc->gop_size = 0;
3073
                if (video_qscale || same_quality) {
3074
                    video_enc->flags |= CODEC_FLAG_QSCALE;
3075
                    st->quality = FF_QP2LAMBDA * video_qscale;
3076
                }
3077

    
3078
                if(intra_matrix)
3079
                    video_enc->intra_matrix = intra_matrix;
3080
                if(inter_matrix)
3081
                    video_enc->inter_matrix = inter_matrix;
3082

    
3083
                if(bitexact)
3084
                    video_enc->flags |= CODEC_FLAG_BITEXACT;
3085

    
3086
                video_enc->mb_decision = mb_decision;
3087
                video_enc->mb_cmp = mb_cmp;
3088
                video_enc->ildct_cmp = ildct_cmp;
3089
                video_enc->me_sub_cmp = sub_cmp;
3090
                video_enc->me_cmp = cmp;
3091
                video_enc->me_pre_cmp = pre_cmp;
3092
                video_enc->pre_me = pre_me;
3093
                video_enc->lumi_masking = lumi_mask;
3094
                video_enc->dark_masking = dark_mask;
3095
                video_enc->spatial_cplx_masking = scplx_mask;
3096
                video_enc->temporal_cplx_masking = tcplx_mask;
3097
                video_enc->p_masking = p_mask;
3098
                video_enc->quantizer_noise_shaping= qns;
3099
                
3100
                if (use_umv) {
3101
                    video_enc->flags |= CODEC_FLAG_H263P_UMV;
3102
                }
3103
                if (use_ss) {
3104
                    video_enc->flags |= CODEC_FLAG_H263P_SLICE_STRUCT;
3105
                }
3106
                   if (use_aic) {
3107
                    video_enc->flags |= CODEC_FLAG_H263P_AIC;
3108
                }
3109
                   if (use_aiv) {
3110
                    video_enc->flags |= CODEC_FLAG_H263P_AIV;
3111
                }
3112
                if (use_4mv) {
3113
                    video_enc->flags |= CODEC_FLAG_4MV;
3114
                }
3115
                if (use_obmc) {
3116
                    video_enc->flags |= CODEC_FLAG_OBMC;
3117
                }
3118
                if (use_loop) {
3119
                    video_enc->flags |= CODEC_FLAG_LOOP_FILTER;
3120
                }
3121
            
3122
                if(use_part) {
3123
                    video_enc->flags |= CODEC_FLAG_PART;
3124
                }
3125
                   if (use_alt_scan) {
3126
                    video_enc->flags |= CODEC_FLAG_ALT_SCAN;
3127
                }
3128
                   if (use_trell) {
3129
                    video_enc->flags |= CODEC_FLAG_TRELLIS_QUANT;
3130
                }
3131
                   if (use_scan_offset) {
3132
                    video_enc->flags |= CODEC_FLAG_SVCD_SCAN_OFFSET;
3133
                }
3134
                   if (closed_gop) {
3135
                    video_enc->flags |= CODEC_FLAG_CLOSED_GOP;
3136
                }
3137
                if (strict_gop) {
3138
                    video_enc->flags2 |= CODEC_FLAG2_STRICT_GOP;
3139
                }
3140
                   if (use_qpel) {
3141
                    video_enc->flags |= CODEC_FLAG_QPEL;
3142
                }
3143
                   if (use_qprd) {
3144
                    video_enc->flags |= CODEC_FLAG_QP_RD;
3145
                }
3146
                   if (use_cbprd) {
3147
                    video_enc->flags |= CODEC_FLAG_CBP_RD;
3148
                }
3149
                if (b_frames) {
3150
                    video_enc->max_b_frames = b_frames;
3151
                    video_enc->b_frame_strategy = 0;
3152
                    video_enc->b_quant_factor = 2.0;
3153
                }
3154
                if (do_interlace_dct) {
3155
                    video_enc->flags |= CODEC_FLAG_INTERLACED_DCT;
3156
                }
3157
                if (do_interlace_me) {
3158
                    video_enc->flags |= CODEC_FLAG_INTERLACED_ME;
3159
                }
3160
                video_enc->qmin = video_qmin;
3161
                video_enc->qmax = video_qmax;
3162
                video_enc->lmin = video_lmin;
3163
                video_enc->lmax = video_lmax;
3164
                video_enc->mb_qmin = video_mb_qmin;
3165
                video_enc->mb_qmax = video_mb_qmax;
3166
                video_enc->max_qdiff = video_qdiff;
3167
                video_enc->qblur = video_qblur;
3168
                video_enc->qcompress = video_qcomp;
3169
                video_enc->rc_eq = video_rc_eq;
3170
                video_enc->debug = debug;
3171
                video_enc->debug_mv = debug_mv;
3172
                video_enc->thread_count = thread_count;
3173
                p= video_rc_override_string;
3174
                for(i=0; p; i++){
3175
                    int start, end, q;
3176
                    int e=sscanf(p, "%d,%d,%d", &start, &end, &q);
3177
                    if(e!=3){
3178
                        fprintf(stderr, "error parsing rc_override\n");
3179
                        exit(1);
3180
                    }
3181
                    video_enc->rc_override= 
3182
                        av_realloc(video_enc->rc_override, 
3183
                                   sizeof(RcOverride)*(i+1));
3184
                    video_enc->rc_override[i].start_frame= start;
3185
                    video_enc->rc_override[i].end_frame  = end;
3186
                    if(q>0){
3187
                        video_enc->rc_override[i].qscale= q;
3188
                        video_enc->rc_override[i].quality_factor= 1.0;
3189
                    }
3190
                    else{
3191
                        video_enc->rc_override[i].qscale= 0;
3192
                        video_enc->rc_override[i].quality_factor= -q/100.0;
3193
                    }
3194
                    p= strchr(p, '/');
3195
                    if(p) p++;
3196
                }
3197
                video_enc->rc_override_count=i;
3198

    
3199
                video_enc->rc_max_rate = video_rc_max_rate;
3200
                video_enc->rc_min_rate = video_rc_min_rate;
3201
                video_enc->rc_buffer_size = video_rc_buffer_size;
3202
                video_enc->rc_initial_buffer_occupancy = video_rc_buffer_size*3/4;
3203
                video_enc->rc_buffer_aggressivity= video_rc_buffer_aggressivity;
3204
                video_enc->rc_initial_cplx= video_rc_initial_cplx;
3205
                video_enc->i_quant_factor = video_i_qfactor;
3206
                video_enc->b_quant_factor = video_b_qfactor;
3207
                video_enc->i_quant_offset = video_i_qoffset;
3208
                video_enc->b_quant_offset = video_b_qoffset;
3209
                video_enc->intra_quant_bias = video_intra_quant_bias;
3210
                video_enc->inter_quant_bias = video_inter_quant_bias;
3211
                video_enc->dct_algo = dct_algo;
3212
                video_enc->idct_algo = idct_algo;
3213
                video_enc->me_threshold= me_threshold;
3214
                video_enc->mb_threshold= mb_threshold;
3215
                video_enc->intra_dc_precision= intra_dc_precision - 8;
3216
                video_enc->strict_std_compliance = strict;
3217
                video_enc->error_rate = error_rate;
3218
                video_enc->noise_reduction= noise_reduction;
3219
                video_enc->scenechange_threshold= sc_threshold;
3220
                video_enc->me_range = me_range;
3221
                video_enc->coder_type= coder;
3222
                video_enc->context_model= context;
3223
                video_enc->prediction_method= predictor;
3224
                video_enc->profile= video_profile;
3225
                video_enc->level= video_level;
3226
                video_enc->nsse_weight= nsse_weight;
3227
                video_enc->me_subpel_quality= subpel_quality;
3228
                video_enc->frame_skip_threshold= frame_skip_threshold;
3229
                video_enc->frame_skip_factor= frame_skip_factor;
3230

    
3231
                if(packet_size){
3232
                    video_enc->rtp_mode= 1;
3233
                    video_enc->rtp_payload_size= packet_size;
3234
                }
3235
            
3236
                if (do_psnr)
3237
                    video_enc->flags|= CODEC_FLAG_PSNR;
3238
            
3239
                video_enc->me_method = me_method;
3240

    
3241
                /* two pass mode */
3242
                if (do_pass) {
3243
                    if (do_pass == 1) {
3244
                        video_enc->flags |= CODEC_FLAG_PASS1;
3245
                    } else {
3246
                        video_enc->flags |= CODEC_FLAG_PASS2;
3247
                    }
3248
                }
3249
            }
3250
        }
3251
    
3252
        if (use_audio) {
3253
            AVCodecContext *audio_enc;
3254

    
3255
            st = av_new_stream(oc, nb_streams++);
3256
            if (!st) {
3257
                fprintf(stderr, "Could not alloc stream\n");
3258
                exit(1);
3259
            }
3260
#if defined(HAVE_THREADS)
3261
            if(thread_count>1)
3262
                avcodec_thread_init(&st->codec, thread_count);
3263
#endif
3264

    
3265
            audio_enc = &st->codec;
3266
            audio_enc->codec_type = CODEC_TYPE_AUDIO;
3267

    
3268
            if(audio_codec_tag)
3269
                audio_enc->codec_tag= audio_codec_tag;
3270

    
3271
            if(!strcmp(file_oformat->name, "mp4") || !strcmp(file_oformat->name, "mov") || !strcmp(file_oformat->name, "3gp"))
3272
                audio_enc->flags |= CODEC_FLAG_GLOBAL_HEADER;
3273
            if (audio_stream_copy) {
3274
                st->stream_copy = 1;
3275
                audio_enc->channels = audio_channels;
3276
            } else {
3277
                codec_id = av_guess_codec(file_oformat, NULL, filename, NULL, CODEC_TYPE_AUDIO);
3278
                if (audio_codec_id != CODEC_ID_NONE)
3279
                    codec_id = audio_codec_id;
3280
                audio_enc->codec_id = codec_id;
3281
                
3282
                audio_enc->bit_rate = audio_bit_rate;
3283
                audio_enc->strict_std_compliance = strict;
3284
                audio_enc->thread_count = thread_count;
3285
                /* For audio codecs other than AC3 or DTS we limit */
3286
                /* the number of coded channels to stereo   */
3287
                if (audio_channels > 2 && codec_id != CODEC_ID_AC3
3288
                    && codec_id != CODEC_ID_DTS) {
3289
                    audio_enc->channels = 2;
3290
                } else
3291
                    audio_enc->channels = audio_channels;
3292
            }
3293
            audio_enc->sample_rate = audio_sample_rate;
3294
        }
3295

    
3296
        oc->nb_streams = nb_streams;
3297

    
3298
        if (!nb_streams) {
3299
            fprintf(stderr, "No audio or video streams available\n");
3300
            exit(1);
3301
        }
3302

    
3303
        oc->timestamp = rec_timestamp;
3304
            
3305
        if (str_title)
3306
            pstrcpy(oc->title, sizeof(oc->title), str_title);
3307
        if (str_author)
3308
            pstrcpy(oc->author, sizeof(oc->author), str_author);
3309
        if (str_copyright)
3310
            pstrcpy(oc->copyright, sizeof(oc->copyright), str_copyright);
3311
        if (str_comment)
3312
            pstrcpy(oc->comment, sizeof(oc->comment), str_comment);
3313
    }
3314

    
3315
    output_files[nb_output_files++] = oc;
3316

    
3317
    strcpy(oc->filename, filename);
3318

    
3319
    /* check filename in case of an image number is expected */
3320
    if (oc->oformat->flags & AVFMT_NEEDNUMBER) {
3321
        if (filename_number_test(oc->filename) < 0) {
3322
            print_error(oc->filename, AVERROR_NUMEXPECTED);
3323
            exit(1);
3324
        }
3325
    }
3326

    
3327
    if (!(oc->oformat->flags & AVFMT_NOFILE)) {
3328
        /* test if it already exists to avoid loosing precious files */
3329
        if (!file_overwrite && 
3330
            (strchr(filename, ':') == NULL ||
3331
             strstart(filename, "file:", NULL))) {
3332
            if (url_exist(filename)) {
3333
                int c;
3334
                
3335
                if ( !using_stdin ) {
3336
                    fprintf(stderr,"File '%s' already exists. Overwrite ? [y/N] ", filename);
3337
                    fflush(stderr);
3338
                    c = getchar();
3339
                    if (toupper(c) != 'Y') {
3340
                        fprintf(stderr, "Not overwriting - exiting\n");
3341
                        exit(1);
3342
                    }
3343
                                }
3344
                                else {
3345
                    fprintf(stderr,"File '%s' already exists. Exiting.\n", filename);
3346
                    exit(1);
3347
                                }
3348
            }
3349
        }
3350
        
3351
        /* open the file */
3352
        if (url_fopen(&oc->pb, filename, URL_WRONLY) < 0) {
3353
            fprintf(stderr, "Could not open '%s'\n", filename);
3354
            exit(1);
3355
        }
3356
    }
3357

    
3358
    memset(ap, 0, sizeof(*ap));
3359
    ap->image_format = image_format;
3360
    if (av_set_parameters(oc, ap) < 0) {
3361
        fprintf(stderr, "%s: Invalid encoding parameters\n",
3362
                oc->filename);
3363
        exit(1);
3364
    }
3365

    
3366
    oc->packet_size= mux_packet_size;
3367
    oc->mux_rate= mux_rate;
3368
    oc->preload= (int)(mux_preload*AV_TIME_BASE);
3369
    oc->max_delay= (int)(mux_max_delay*AV_TIME_BASE);
3370

    
3371
    /* reset some options */
3372
    file_oformat = NULL;
3373
    file_iformat = NULL;
3374
    image_format = NULL;
3375
    audio_disable = 0;
3376
    video_disable = 0;
3377
    audio_codec_id = CODEC_ID_NONE;
3378
    video_codec_id = CODEC_ID_NONE;
3379
    audio_stream_copy = 0;
3380
    video_stream_copy = 0;
3381
}
3382

    
3383
/* prepare dummy protocols for grab */
3384
static void prepare_grab(void)
3385
{
3386
    int has_video, has_audio, i, j;
3387
    AVFormatContext *oc;
3388
    AVFormatContext *ic;
3389
    AVFormatParameters vp1, *vp = &vp1;
3390
    AVFormatParameters ap1, *ap = &ap1;
3391
    
3392
    /* see if audio/video inputs are needed */
3393
    has_video = 0;
3394
    has_audio = 0;
3395
    memset(ap, 0, sizeof(*ap));
3396
    memset(vp, 0, sizeof(*vp));
3397
    vp->frame_rate_base= 1;
3398
    for(j=0;j<nb_output_files;j++) {
3399
        oc = output_files[j];
3400
        for(i=0;i<oc->nb_streams;i++) {
3401
            AVCodecContext *enc = &oc->streams[i]->codec;
3402
            switch(enc->codec_type) {
3403
            case CODEC_TYPE_AUDIO:
3404
                if (enc->sample_rate > ap->sample_rate)
3405
                    ap->sample_rate = enc->sample_rate;
3406
                if (enc->channels > ap->channels)
3407
                    ap->channels = enc->channels;
3408
                has_audio = 1;
3409
                break;
3410
            case CODEC_TYPE_VIDEO:
3411
                if (enc->width > vp->width)
3412
                    vp->width = enc->width;
3413
                if (enc->height > vp->height)
3414
                    vp->height = enc->height;
3415
                
3416
                if (vp->frame_rate_base*(int64_t)enc->frame_rate > enc->frame_rate_base*(int64_t)vp->frame_rate){
3417
                    vp->frame_rate      = enc->frame_rate;
3418
                    vp->frame_rate_base = enc->frame_rate_base;
3419
                }
3420
                has_video = 1;
3421
                break;
3422
            default:
3423
                av_abort();
3424
            }
3425
        }
3426
    }
3427
    
3428
    if (has_video == 0 && has_audio == 0) {
3429
        fprintf(stderr, "Output file must have at least one audio or video stream\n");
3430
        exit(1);
3431
    }
3432
    
3433
    if (has_video) {
3434
        AVInputFormat *fmt1;
3435
        fmt1 = av_find_input_format(video_grab_format);
3436
        vp->device  = video_device;
3437
        vp->channel = video_channel;
3438
        vp->standard = video_standard;
3439
        if (av_open_input_file(&ic, "", fmt1, 0, vp) < 0) {
3440
            fprintf(stderr, "Could not find video grab device\n");
3441
            exit(1);
3442
        }
3443
        /* If not enough info to get the stream parameters, we decode the
3444
           first frames to get it. */
3445
        if ((ic->ctx_flags & AVFMTCTX_NOHEADER) && av_find_stream_info(ic) < 0) {
3446
            fprintf(stderr, "Could not find video grab parameters\n");
3447
            exit(1);
3448
        }
3449
        /* by now video grab has one stream */
3450
        ic->streams[0]->r_frame_rate      = vp->frame_rate;
3451
        ic->streams[0]->r_frame_rate_base = vp->frame_rate_base;
3452
        input_files[nb_input_files] = ic;
3453

    
3454
        if (verbose >= 0)
3455
            dump_format(ic, nb_input_files, "", 0);
3456

    
3457
        nb_input_files++;
3458
    }
3459
    if (has_audio && audio_grab_format) {
3460
        AVInputFormat *fmt1;
3461
        fmt1 = av_find_input_format(audio_grab_format);
3462
        ap->device = audio_device;
3463
        if (av_open_input_file(&ic, "", fmt1, 0, ap) < 0) {
3464
            fprintf(stderr, "Could not find audio grab device\n");
3465
            exit(1);
3466
        }
3467
        input_files[nb_input_files] = ic;
3468

    
3469
        if (verbose >= 0)
3470
            dump_format(ic, nb_input_files, "", 0);
3471

    
3472
        nb_input_files++;
3473
    }
3474
}
3475

    
3476
/* same option as mencoder */
3477
static void opt_pass(const char *pass_str)
3478
{
3479
    int pass;
3480
    pass = atoi(pass_str);
3481
    if (pass != 1 && pass != 2) {
3482
        fprintf(stderr, "pass number can be only 1 or 2\n");
3483
        exit(1);
3484
    }
3485
    do_pass = pass;
3486
}
3487

    
3488
#if defined(CONFIG_WIN32) || defined(CONFIG_OS2)
3489
static int64_t getutime(void)
3490
{
3491
  return av_gettime();
3492
}
3493
#else
3494
static int64_t getutime(void)
3495
{
3496
    struct rusage rusage;
3497

    
3498
    getrusage(RUSAGE_SELF, &rusage);
3499
    return (rusage.ru_utime.tv_sec * 1000000LL) + rusage.ru_utime.tv_usec;
3500
}
3501
#endif
3502

    
3503
extern int ffm_nopts;
3504

    
3505
static void opt_bitexact(void)
3506
{
3507
    bitexact=1;
3508
    /* disable generate of real time pts in ffm (need to be supressed anyway) */
3509
    ffm_nopts = 1;
3510
}
3511

    
3512
static void show_formats(void)
3513
{
3514
    AVInputFormat *ifmt;
3515
    AVOutputFormat *ofmt;
3516
    AVImageFormat *image_fmt;
3517
    URLProtocol *up;
3518
    AVCodec *p, *p2;
3519
    const char **pp, *last_name;
3520

    
3521
    printf("File formats:\n");
3522
    last_name= "000";
3523
    for(;;){
3524
        int decode=0;
3525
        int encode=0;
3526
        const char *name=NULL;
3527
        const char *long_name=NULL;
3528

    
3529
        for(ofmt = first_oformat; ofmt != NULL; ofmt = ofmt->next) {
3530
            if((name == NULL || strcmp(ofmt->name, name)<0) &&
3531
                strcmp(ofmt->name, last_name)>0){
3532
                name= ofmt->name;
3533
                long_name= ofmt->long_name;
3534
                encode=1;
3535
            }
3536
        }
3537
        for(ifmt = first_iformat; ifmt != NULL; ifmt = ifmt->next) {
3538
            if((name == NULL || strcmp(ifmt->name, name)<0) &&
3539
                strcmp(ifmt->name, last_name)>0){
3540
                name= ifmt->name;
3541
                long_name= ifmt->long_name;
3542
                encode=0;
3543
            }
3544
            if(name && strcmp(ifmt->name, name)==0)
3545
                decode=1;
3546
        }
3547
        if(name==NULL)
3548
            break;
3549
        last_name= name;
3550
        
3551
        printf(
3552
            " %s%s %-15s %s\n", 
3553
            decode ? "D":" ", 
3554
            encode ? "E":" ", 
3555
            name,
3556
            long_name ? long_name:" ");
3557
    }
3558
    printf("\n");
3559

    
3560
    printf("Image formats (filename extensions, if any, follow):\n");
3561
    for(image_fmt = first_image_format; image_fmt != NULL; 
3562
        image_fmt = image_fmt->next) {
3563
        printf(
3564
            " %s%s %-6s %s\n",
3565
            image_fmt->img_read  ? "D":" ",
3566
            image_fmt->img_write ? "E":" ",
3567
            image_fmt->name,
3568
            image_fmt->extensions ? image_fmt->extensions:" ");
3569
    }
3570
    printf("\n");
3571

    
3572
    printf("Codecs:\n");
3573
    last_name= "000";
3574
    for(;;){
3575
        int decode=0;
3576
        int encode=0;
3577
        int cap=0;
3578

    
3579
        p2=NULL;
3580
        for(p = first_avcodec; p != NULL; p = p->next) {
3581
            if((p2==NULL || strcmp(p->name, p2->name)<0) &&
3582
                strcmp(p->name, last_name)>0){
3583
                p2= p;
3584
                decode= encode= cap=0;
3585
            }
3586
            if(p2 && strcmp(p->name, p2->name)==0){
3587
                if(p->decode) decode=1;
3588
                if(p->encode) encode=1;
3589
                cap |= p->capabilities;
3590
            }
3591
        }
3592
        if(p2==NULL)
3593
            break;
3594
        last_name= p2->name;
3595
        
3596
        printf(
3597
            " %s%s%s%s%s%s %s", 
3598
            decode ? "D": (/*p2->decoder ? "d":*/" "), 
3599
            encode ? "E":" ", 
3600
            p2->type == CODEC_TYPE_AUDIO ? "A":"V",
3601
            cap & CODEC_CAP_DRAW_HORIZ_BAND ? "S":" ",
3602
            cap & CODEC_CAP_DR1 ? "D":" ",
3603
            cap & CODEC_CAP_TRUNCATED ? "T":" ",
3604
            p2->name);
3605
       /* if(p2->decoder && decode==0)
3606
            printf(" use %s for decoding", p2->decoder->name);*/
3607
        printf("\n");
3608
    }
3609
    printf("\n");
3610

    
3611
    printf("Supported file protocols:\n");
3612
    for(up = first_protocol; up != NULL; up = up->next)
3613
        printf(" %s:", up->name);
3614
    printf("\n");
3615
    
3616
    printf("Frame size, frame rate abbreviations:\n ntsc pal qntsc qpal sntsc spal film ntsc-film sqcif qcif cif 4cif\n");
3617
    printf("Motion estimation methods:\n");
3618
    pp = motion_str;
3619
    while (*pp) {
3620
        printf(" %s", *pp);
3621
        if ((pp - motion_str + 1) == ME_ZERO) 
3622
            printf("(fastest)");
3623
        else if ((pp - motion_str + 1) == ME_FULL) 
3624
            printf("(slowest)");
3625
        else if ((pp - motion_str + 1) == ME_EPZS) 
3626
            printf("(default)");
3627
        pp++;
3628
    }
3629
    printf("\n\n");
3630
    printf(
3631
"Note, the names of encoders and decoders dont always match, so there are\n"
3632
"several cases where the above table shows encoder only or decoder only entries\n"
3633
"even though both encoding and decoding are supported for example, the h263\n"
3634
"decoder corresponds to the h263 and h263p encoders, for file formats its even\n"
3635
"worse\n");
3636
    exit(1);
3637
}
3638

    
3639
void parse_matrix_coeffs(uint16_t *dest, const char *str)
3640
{
3641
    int i;
3642
    const char *p = str;
3643
    for(i = 0;; i++) {
3644
        dest[i] = atoi(p);
3645
        if(i == 63)
3646
            break;
3647
        p = strchr(p, ',');
3648
        if(!p) {
3649
            fprintf(stderr, "Syntax error in matrix \"%s\" at coeff %d\n", str, i);
3650
            exit(1);
3651
        }
3652
        p++;
3653
    }
3654
}
3655

    
3656
void opt_inter_matrix(const char *arg)
3657
{
3658
    inter_matrix = av_mallocz(sizeof(uint16_t) * 64);
3659
    parse_matrix_coeffs(inter_matrix, arg);
3660
}
3661

    
3662
void opt_intra_matrix(const char *arg)
3663
{
3664
    intra_matrix = av_mallocz(sizeof(uint16_t) * 64);
3665
    parse_matrix_coeffs(intra_matrix, arg);
3666
}
3667

    
3668
static void opt_target(const char *arg)
3669
{
3670
    int norm = -1;
3671

    
3672
    if(!strncmp(arg, "pal-", 4)) {
3673
        norm = 0;
3674
        arg += 4;
3675
    } else if(!strncmp(arg, "ntsc-", 5)) {
3676
        norm = 1;
3677
        arg += 5;
3678
    } else {
3679
        int fr;
3680
        /* Calculate FR via float to avoid int overflow */
3681
        fr = (int)(frame_rate * 1000.0 / frame_rate_base);
3682
        if(fr == 25000) {
3683
            norm = 0;
3684
        } else if((fr == 29970) || (fr == 23976)) {
3685
            norm = 1;
3686
        } else {
3687
            /* Try to determine PAL/NTSC by peeking in the input files */
3688
            if(nb_input_files) {
3689
                int i, j;
3690
                for(j = 0; j < nb_input_files; j++) {
3691
                    for(i = 0; i < input_files[j]->nb_streams; i++) {
3692
                        AVCodecContext *c = &input_files[j]->streams[i]->codec;
3693
                        if(c->codec_type != CODEC_TYPE_VIDEO)
3694
                            continue;
3695
                        fr = c->frame_rate * 1000 / c->frame_rate_base;
3696
                        if(fr == 25000) {
3697
                            norm = 0;
3698
                            break;
3699
                        } else if((fr == 29970) || (fr == 23976)) {
3700
                            norm = 1;
3701
                            break;
3702
                        }
3703
                    }
3704
                    if(norm >= 0)
3705
                        break;
3706
                }
3707
            }
3708
        }
3709
        if(verbose && norm >= 0)
3710
            printf("Assuming %s for target.\n", norm ? "NTSC" : "PAL");
3711
    }
3712

    
3713
    if(norm < 0) {
3714
        fprintf(stderr, "Could not determine norm (PAL/NTSC) for target.\n");
3715
        fprintf(stderr, "Please prefix target with \"pal-\" or \"ntsc-\",\n");
3716
        fprintf(stderr, "or set a framerate with \"-r xxx\".\n");
3717
        exit(1);
3718
    }
3719

    
3720
    if(!strcmp(arg, "vcd")) {
3721

    
3722
        opt_video_codec("mpeg1video");
3723
        opt_audio_codec("mp2");
3724
        opt_format("vcd");
3725

    
3726
        opt_frame_size(norm ? "352x240" : "352x288");
3727

    
3728
        video_bit_rate = 1150000;
3729
        video_rc_max_rate = 1150000;
3730
        video_rc_min_rate = 1150000;
3731
        video_rc_buffer_size = 40*1024*8;
3732

    
3733
        audio_bit_rate = 224000;
3734
        audio_sample_rate = 44100;
3735
        
3736
        mux_packet_size= 2324;
3737
        mux_rate= 2352 * 75 * 8;
3738

    
3739
        /* We have to offset the PTS, so that it is consistent with the SCR.
3740
           SCR starts at 36000, but the first two packs contain only padding
3741
           and the first pack from the other stream, respectively, may also have
3742
           been written before.
3743
           So the real data starts at SCR 36000+3*1200. */
3744
        mux_preload= (36000+3*1200) / 90000.0; //0.44
3745
    } else if(!strcmp(arg, "svcd")) {
3746

    
3747
        opt_video_codec("mpeg2video");
3748
        opt_audio_codec("mp2");
3749
        opt_format("svcd");
3750

    
3751
        opt_frame_size(norm ? "480x480" : "480x576");
3752
        opt_gop_size(norm ? "18" : "15");
3753

    
3754
        video_bit_rate = 2040000;
3755
        video_rc_max_rate = 2516000;
3756
        video_rc_min_rate = 0; //1145000;
3757
        video_rc_buffer_size = 224*1024*8;
3758
        use_scan_offset = 1;
3759

    
3760
        audio_bit_rate = 224000;
3761
        audio_sample_rate = 44100;
3762

    
3763
        mux_packet_size= 2324;
3764

    
3765
    } else if(!strcmp(arg, "dvd")) {
3766

    
3767
        opt_video_codec("mpeg2video");
3768
        opt_audio_codec("ac3");
3769
        opt_format("dvd");
3770

    
3771
        opt_frame_size(norm ? "720x480" : "720x576");
3772
        opt_gop_size(norm ? "18" : "15");
3773

    
3774
        video_bit_rate = 6000000;
3775
        video_rc_max_rate = 9000000;
3776
        video_rc_min_rate = 0; //1500000;
3777
        video_rc_buffer_size = 224*1024*8;
3778

    
3779
        mux_packet_size= 2048;  // from www.mpucoder.com: DVD sectors contain 2048 bytes of data, this is also the size of one pack.
3780
        mux_rate = 10080000;    // from mplex project: data_rate = 1260000. mux_rate = data_rate * 8
3781

    
3782
        audio_bit_rate = 448000;
3783
        audio_sample_rate = 48000;
3784

    
3785
    } else {
3786
        fprintf(stderr, "Unknown target: %s\n", arg);
3787
        exit(1);
3788
    }
3789
}
3790

    
3791
static void show_version(void)
3792
{
3793
    printf("ffmpeg      " FFMPEG_VERSION "\n"
3794
           "libavcodec  %d\n"
3795
           "libavformat %d\n", 
3796
           avcodec_build(), LIBAVFORMAT_BUILD);
3797
    exit(1);
3798
}
3799

    
3800
const OptionDef options[] = {
3801
    /* main options */
3802
    { "L", 0, {(void*)show_license}, "show license" },
3803
    { "h", 0, {(void*)show_help}, "show help" },
3804
    { "version", 0, {(void*)show_version}, "show version" },
3805
    { "formats", 0, {(void*)show_formats}, "show available formats, codecs, protocols, ..." },
3806
    { "f", HAS_ARG, {(void*)opt_format}, "force format", "fmt" },
3807
    { "img", HAS_ARG, {(void*)opt_image_format}, "force image format", "img_fmt" },
3808
    { "i", HAS_ARG, {(void*)opt_input_file}, "input file name", "filename" },
3809
    { "y", OPT_BOOL, {(void*)&file_overwrite}, "overwrite output files" },
3810
    { "map", HAS_ARG | OPT_EXPERT, {(void*)opt_map}, "set input stream mapping", "file:stream" },
3811
    { "map_meta_data", HAS_ARG | OPT_EXPERT, {(void*)opt_map_meta_data}, "set meta data information of outfile from infile", "outfile:infile" },
3812
    { "t", HAS_ARG, {(void*)opt_recording_time}, "set the recording time", "duration" },
3813
    { "ss", HAS_ARG, {(void*)opt_start_time}, "set the start time offset", "time_off" },
3814
    { "itsoffset", HAS_ARG, {(void*)opt_input_ts_offset}, "set the input ts offset", "time_off" },
3815
    { "title", HAS_ARG | OPT_STRING, {(void*)&str_title}, "set the title", "string" },
3816
    { "timestamp", HAS_ARG, {(void*)&opt_rec_timestamp}, "set the timestamp", "time" },
3817
    { "author", HAS_ARG | OPT_STRING, {(void*)&str_author}, "set the author", "string" },
3818
    { "copyright", HAS_ARG | OPT_STRING, {(void*)&str_copyright}, "set the copyright", "string" },
3819
    { "comment", HAS_ARG | OPT_STRING, {(void*)&str_comment}, "set the comment", "string" },
3820
    { "debug", HAS_ARG | OPT_EXPERT, {(void*)opt_debug}, "print specific debug info", "" },
3821
    { "vismv", HAS_ARG | OPT_EXPERT, {(void*)opt_vismv}, "visualize motion vectors", "" },
3822
    { "benchmark", OPT_BOOL | OPT_EXPERT, {(void*)&do_benchmark}, 
3823
      "add timings for benchmarking" },
3824
    { "dump", OPT_BOOL | OPT_EXPERT, {(void*)&do_pkt_dump}, 
3825
      "dump each input packet" },
3826
    { "hex", OPT_BOOL | OPT_EXPERT, {(void*)&do_hex_dump}, 
3827
      "when dumping packets, also dump the payload" },
3828
    { "bitexact", OPT_EXPERT, {(void*)opt_bitexact}, "only use bit exact algorithms (for codec testing)" }, 
3829
    { "re", OPT_BOOL | OPT_EXPERT, {(void*)&rate_emu}, "read input at native frame rate", "" },
3830
    { "loop", OPT_BOOL | OPT_EXPERT, {(void*)&loop_input}, "loop (current only works with images)" },
3831
    { "v", HAS_ARG, {(void*)opt_verbose}, "control amount of logging", "verbose" },
3832
    { "target", HAS_ARG, {(void*)opt_target}, "specify target file type (\"vcd\", \"svcd\", \"dvd\", \"pal-vcd\", \"ntsc-svcd\", ...)", "type" },
3833
    { "threads", HAS_ARG | OPT_EXPERT, {(void*)opt_thread_count}, "thread count", "count" },
3834
    { "vsync", HAS_ARG | OPT_INT | OPT_EXPERT, {(void*)&video_sync_method}, "video sync method", "" },
3835
    { "async", HAS_ARG | OPT_INT | OPT_EXPERT, {(void*)&audio_sync_method}, "audio sync method", "" },
3836
    { "copyts", OPT_BOOL | OPT_EXPERT, {(void*)&copy_ts}, "copy timestamps" },
3837

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

    
3959
    /* audio options */
3960
    { "ab", HAS_ARG | OPT_AUDIO, {(void*)opt_audio_bitrate}, "set audio bitrate (in kbit/s)", "bitrate", },
3961
    { "ar", HAS_ARG | OPT_AUDIO, {(void*)opt_audio_rate}, "set audio sampling rate (in Hz)", "rate" },
3962
    { "ac", HAS_ARG | OPT_AUDIO, {(void*)opt_audio_channels}, "set number of audio channels", "channels" },
3963
    { "an", OPT_BOOL | OPT_AUDIO, {(void*)&audio_disable}, "disable audio" },
3964
    { "acodec", HAS_ARG | OPT_AUDIO, {(void*)opt_audio_codec}, "force audio codec ('copy' to copy stream)", "codec" },
3965
    { "atag", HAS_ARG | OPT_EXPERT | OPT_AUDIO, {(void*)opt_audio_tag}, "force audio tag/fourcc", "fourcc/tag" },
3966

    
3967
    /* grab options */
3968
    { "vd", HAS_ARG | OPT_EXPERT | OPT_VIDEO | OPT_GRAB, {(void*)opt_video_device}, "set video grab device", "device" },
3969
    { "vc", HAS_ARG | OPT_EXPERT | OPT_VIDEO | OPT_GRAB, {(void*)opt_video_channel}, "set video grab channel (DV1394 only)", "channel" },
3970
    { "tvstd", HAS_ARG | OPT_EXPERT | OPT_VIDEO | OPT_GRAB, {(void*)opt_video_standard}, "set television standard (NTSC, PAL (SECAM))", "standard" },
3971
    { "ad", HAS_ARG | OPT_EXPERT | OPT_AUDIO | OPT_GRAB, {(void*)opt_audio_device}, "set audio device", "device" },
3972

    
3973
    /* G.2 grab options */ 
3974
    { "grab", HAS_ARG | OPT_EXPERT | OPT_GRAB, {(void*)opt_grab}, "request grabbing using", "format" },
3975
    { "gd", HAS_ARG | OPT_EXPERT | OPT_VIDEO | OPT_GRAB, {(void*)opt_grab_device}, "set grab device", "device" },
3976
 
3977
    /* muxer options */   
3978
    { "muxrate", OPT_INT | HAS_ARG | OPT_EXPERT, {(void*)&mux_rate}, "set mux rate", "rate" },
3979
    { "packetsize", OPT_INT | HAS_ARG | OPT_EXPERT, {(void*)&mux_packet_size}, "set packet size", "size" },
3980
    { "muxdelay", OPT_FLOAT | HAS_ARG | OPT_EXPERT, {(void*)&mux_max_delay}, "set the maximum demux-decode delay", "seconds" },
3981
    { "muxpreload", OPT_FLOAT | HAS_ARG | OPT_EXPERT, {(void*)&mux_preload}, "set the initial demux-decode delay", "seconds" },
3982
    { NULL, },
3983
};
3984

    
3985
static void show_banner(void)
3986
{
3987
    printf("ffmpeg version " FFMPEG_VERSION ", build %d, Copyright (c) 2000-2004 Fabrice Bellard\n",
3988
        LIBAVCODEC_BUILD);
3989
    printf("  configuration: %s\n", FFMPEG_CONFIGURATION);
3990
    printf("  built on " __DATE__ " " __TIME__);
3991
#ifdef __GNUC__
3992
    printf(", gcc: %s\n", __VERSION__);
3993
#else
3994
    printf(", using a non-gcc compiler\n");
3995
#endif
3996
}
3997

    
3998
static void show_license(void)
3999
{
4000
    show_banner();
4001
#ifdef CONFIG_GPL
4002
    printf(
4003
    "This program is free software; you can redistribute it and/or modify\n"   
4004
    "it under the terms of the GNU General Public License as published by\n"
4005
    "the Free Software Foundation; either version 2 of the License, or\n"
4006
    "(at your option) any later version.\n"
4007
    "\n"
4008
    "This program is distributed in the hope that it will be useful,\n"
4009
    "but WITHOUT ANY WARRANTY; without even the implied warranty of\n"
4010
    "MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n"
4011
    "GNU General Public License for more details.\n"
4012
    "\n"
4013
    "You should have received a copy of the GNU General Public License\n"
4014
    "along with this program; if not, write to the Free Software\n"
4015
    "Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA\n"
4016
    );
4017
#else
4018
    printf(
4019
    "This library is free software; you can redistribute it and/or\n"
4020
    "modify it under the terms of the GNU Lesser General Public\n"
4021
    "License as published by the Free Software Foundation; either\n"
4022
    "version 2 of the License, or (at your option) any later version.\n"
4023
    "\n"
4024
    "This library is distributed in the hope that it will be useful,\n"
4025
    "but WITHOUT ANY WARRANTY; without even the implied warranty of\n"
4026
    "MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n"
4027
    "Lesser General Public License for more details.\n"
4028
    "\n"
4029
    "You should have received a copy of the GNU Lesser General Public\n"
4030
    "License along with this library; if not, write to the Free Software\n"
4031
    "Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA\n"
4032
    );
4033
#endif
4034
    exit(1);
4035
}
4036

    
4037
static void show_help(void)
4038
{
4039
    show_banner();
4040
    printf("usage: ffmpeg [[infile options] -i infile]... {[outfile options] outfile}...\n"
4041
           "Hyper fast Audio and Video encoder\n");
4042
    printf("\n");
4043
    show_help_options(options, "Main options:\n",
4044
                      OPT_EXPERT | OPT_AUDIO | OPT_VIDEO, 0);
4045
    show_help_options(options, "\nVideo options:\n",
4046
                      OPT_EXPERT | OPT_AUDIO | OPT_VIDEO | OPT_GRAB, 
4047
                      OPT_VIDEO);
4048
    show_help_options(options, "\nAdvanced Video options:\n",
4049
                      OPT_EXPERT | OPT_AUDIO | OPT_VIDEO | OPT_GRAB, 
4050
                      OPT_VIDEO | OPT_EXPERT);
4051
    show_help_options(options, "\nAudio options:\n",
4052
                      OPT_EXPERT | OPT_AUDIO | OPT_VIDEO | OPT_GRAB, 
4053
                      OPT_AUDIO);
4054
    show_help_options(options, "\nAdvanced Audio options:\n",
4055
                      OPT_EXPERT | OPT_AUDIO | OPT_VIDEO | OPT_GRAB, 
4056
                      OPT_AUDIO | OPT_EXPERT);
4057
    show_help_options(options, "\nAudio/Video grab options:\n",
4058
                      OPT_GRAB, 
4059
                      OPT_GRAB);
4060
    show_help_options(options, "\nAdvanced options:\n",
4061
                      OPT_EXPERT | OPT_AUDIO | OPT_VIDEO | OPT_GRAB, 
4062
                      OPT_EXPERT);
4063
    exit(1);
4064
}
4065

    
4066
void parse_arg_file(const char *filename)
4067
{
4068
    opt_output_file(filename);
4069
}
4070

    
4071
int main(int argc, char **argv)
4072
{
4073
    int i;
4074
    int64_t ti;
4075

    
4076
    av_register_all();
4077

    
4078
    if (argc <= 1)
4079
        show_help();
4080
    else
4081
        show_banner();
4082
    
4083
    /* parse options */
4084
    parse_options(argc, argv, options);
4085

    
4086
    /* file converter / grab */
4087
    if (nb_output_files <= 0) {
4088
        fprintf(stderr, "Must supply at least one output file\n");
4089
        exit(1);
4090
    }
4091
    
4092
    if (nb_input_files == 0) {
4093
        input_sync = 1;
4094
        prepare_grab();
4095
    }
4096

    
4097
    ti = getutime();
4098
    av_encode(output_files, nb_output_files, input_files, nb_input_files, 
4099
              stream_maps, nb_stream_maps);
4100
    ti = getutime() - ti;
4101
    if (do_benchmark) {
4102
        printf("bench: utime=%0.3fs\n", ti / 1000000.0);
4103
    }
4104

    
4105
    /* close files */
4106
    for(i=0;i<nb_output_files;i++) {
4107
        /* maybe av_close_output_file ??? */
4108
        AVFormatContext *s = output_files[i];
4109
        int j;
4110
        if (!(s->oformat->flags & AVFMT_NOFILE))
4111
            url_fclose(&s->pb);
4112
        for(j=0;j<s->nb_streams;j++)
4113
            av_free(s->streams[j]);
4114
        av_free(s);
4115
    }
4116
    for(i=0;i<nb_input_files;i++)
4117
        av_close_input_file(input_files[i]);
4118

    
4119
    av_free_static();
4120

    
4121
    if(intra_matrix)
4122
        av_free(intra_matrix);
4123
    if(inter_matrix)
4124
        av_free(inter_matrix);
4125
    
4126
#ifdef POWERPC_PERFORMANCE_REPORT
4127
    extern void powerpc_display_perf_report(void);
4128
    powerpc_display_perf_report();
4129
#endif /* POWERPC_PERFORMANCE_REPORT */
4130

    
4131
#ifndef CONFIG_WIN32
4132
    if (received_sigterm) {
4133
        fprintf(stderr,
4134
            "Received signal %d: terminating.\n",
4135
            (int) received_sigterm);
4136
        exit (255);
4137
    }
4138
#endif
4139
    exit(0); /* not all OS-es handle main() return value */
4140
    return 0;
4141
}