Statistics
| Branch: | Revision:

ffmpeg / ffmpeg.c @ 8a6cb114

History | View | Annotate | Download (141 KB)

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

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

    
42
#include "cmdutils.h"
43

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

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

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

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

    
63
extern const OptionDef options[];
64

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

    
68
#define MAX_FILES 20
69

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

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

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

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

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

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

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

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

    
234
static int rate_emu = 0;
235

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

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

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

    
258
static int pgmyuv_compatibility_hack=0;
259

    
260

    
261
#define DEFAULT_PASS_LOGFILENAME "ffmpeg2pass"
262

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

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

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

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

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

    
321
#ifndef CONFIG_WIN32
322

    
323
/* init terminal so that we can grab keys */
324
static struct termios oldtty;
325

    
326
static void term_exit(void)
327
{
328
    tcsetattr (0, TCSANOW, &oldtty);
329
}
330

    
331
static volatile sig_atomic_t received_sigterm = 0;
332

    
333
static void
334
sigterm_handler(int sig)
335
{
336
    received_sigterm = sig;
337
    term_exit();
338
}
339

    
340
static void term_init(void)
341
{
342
    struct termios tty;
343

    
344
    tcgetattr (0, &tty);
345
    oldtty = tty;
346

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

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

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

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

    
390
        return n;
391
    }
392
    return -1;
393
}
394

    
395
static int decode_interrupt_cb(void)
396
{
397
    return q_pressed || (q_pressed = read_key() == 'q');
398
}
399

    
400
#else
401

    
402
static volatile int received_sigterm = 0;
403

    
404
/* no interactive support */
405
static void term_exit(void)
406
{
407
}
408

    
409
static void term_init(void)
410
{
411
}
412

    
413
static int read_key(void)
414
{
415
    return 0;
416
}
417

    
418
#endif
419

    
420
static int read_ffserver_streams(AVFormatContext *s, const char *filename)
421
{
422
    int i, err;
423
    AVFormatContext *ic;
424

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

    
433
        st = av_mallocz(sizeof(AVStream));
434
        memcpy(st, ic->streams[i], sizeof(AVStream));
435
        s->streams[i] = st;
436
    }
437

    
438
    av_close_input_file(ic);
439
    return 0;
440
}
441

    
442
#define MAX_AUDIO_PACKET_SIZE (128 * 1024)
443

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

    
454
    int size_out, frame_bytes, ret;
455
    AVCodecContext *enc= &ost->st->codec;
456

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

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

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

    
487
                    if(byte_delta + size <= MAX_AUDIO_PACKET_SIZE)
488
                        ist->is_start=0;
489
                    else
490
                        byte_delta= MAX_AUDIO_PACKET_SIZE - size;
491

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

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

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

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

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

    
553
        ost->sync_opts += size_out / (2 * enc->channels);
554

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

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

    
587
    dec = &ist->st->codec;
588

    
589
    /* deinterlace : must be done before any resize */
590
    if (do_deinterlace || using_vhook) {
591
        int size;
592

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

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

    
623
    frame_hook_process(picture2, dec->pix_fmt, dec->width, dec->height);
624

    
625
    if (picture != picture2)
626
        *picture = *picture2;
627
    *bufp = buf;
628
}
629

    
630
/* we begin to correct av delay at this threshold */
631
#define AV_DELAY_MAX 0.100
632

    
633

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

    
649
        if (padleft || padright) {
650
            optr = img->data[i] + (img->linesize[i] * (padtop >> shift)) +
651
                (img->linesize[i] - (padright >> shift));
652

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

    
666
static int bit_buffer_size= 1024*256;
667
static uint8_t *bit_buffer= NULL;
668

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

    
685
    enc = &ost->st->codec;
686
    dec = &ist->st->codec;
687

    
688
    /* by default, we output a single frame */
689
    nb_frames = 1;
690

    
691
    *frame_size = 0;
692

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

    
714
    if (nb_frames <= 0) 
715
        return;
716

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

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

    
735
            if (verbose >= 0)
736
                fprintf(stderr, "pixel format conversion not handled\n");
737

    
738
            goto the_end;
739
        }
740
    } else {
741
        formatted_picture = in_picture;
742
    }
743

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

    
773
                if (verbose >= 0)
774
                    fprintf(stderr, "pixel format conversion not handled\n");
775

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

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

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

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

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

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

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

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

    
833
            if (img_convert((AVPicture*)final_picture, enc->pix_fmt, 
834
                        (AVPicture*)&ost->pict_tmp, PIX_FMT_YUV420P, 
835
                        enc->width, enc->height) < 0) {
836

    
837
                if (verbose >= 0)
838
                    fprintf(stderr, "pixel format conversion not handled\n");
839

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

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

    
865
            av_interleaved_write_frame(s, &pkt);
866
            enc->coded_frame = old_frame;
867
        } else {
868
            AVFrame big_picture;
869

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

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

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

    
926
static double psnr(double d){
927
    if(d==0) return INFINITY;
928
    return -10.0*log(d)/log(10.0);
929
}
930

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

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

    
1004

    
1005
    oc = output_files[0];
1006

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

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

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

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

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

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

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

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

    
1191
                ist->frame++;
1192
            }
1193

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

    
1213
                    ost = ost_table[i];
1214
                    if (ost->source_index == ist_index) {
1215
                        os = output_files[ost->file_index];
1216

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

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

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

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

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

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

    
1335

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

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

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

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

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

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

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

    
1489
        codec = &ost->st->codec;
1490
        icodec = &ist->st->codec;
1491

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

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

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

    
1666
    if (!bit_buffer)
1667
        bit_buffer = av_malloc(bit_buffer_size);
1668
    if (!bit_buffer)
1669
        goto fail;
1670

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

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

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

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

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

    
1742
    /* compute buffer size max (should use a complete heuristic) */
1743
    for(i=0;i<nb_input_files;i++) {
1744
        file_table[i].buffer_size_max = 2048;
1745
    }
1746

    
1747
    /* set meta data information from input file if required */
1748
    for (i=0;i<nb_meta_data_maps;i++) {
1749
        AVFormatContext *out_file;
1750
        AVFormatContext *in_file;
1751

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

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

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

    
1796
    stream_no_data = 0;
1797
    key = -1;
1798

    
1799
    for(; received_sigterm == 0;) {
1800
        int file_index, ist_index;
1801
        AVPacket pkt;
1802
        double ipts_min;
1803
        double opts_min;
1804

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

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

    
1847
        /* finish if recording time exhausted */
1848
        if (recording_time > 0 && opts_min >= (recording_time / 1000000.0))
1849
            break;
1850

    
1851
        /* read a frame from it and output it in the fifo */
1852
        is = input_files[file_index];
1853
        if (av_read_frame(is, &pkt) < 0) {
1854
            file_table[file_index].eof_reached = 1;
1855
            continue;
1856
        }
1857

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

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

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

    
1893
            if (verbose >= 0)
1894
                fprintf(stderr, "Error while decoding stream #%d.%d\n",
1895
                        ist->file_index, ist->index);
1896

    
1897
            av_free_packet(&pkt);
1898
            goto redo;
1899
        }
1900
        
1901
    discard_packet:
1902
        av_free_packet(&pkt);
1903
        
1904
        /* dump report by using the output first video and audio streams */
1905
        print_report(output_files, ost_table, nb_ostreams, 0);
1906
    }
1907

    
1908
    /* at the end of stream, we must flush the decoder buffers */
1909
    for(i=0;i<nb_istreams;i++) {
1910
        ist = ist_table[i];
1911
        if (ist->decoding_needed) {
1912
            output_packet(ist, i, ost_table, nb_ostreams, NULL);
1913
        }
1914
    }
1915

    
1916
    term_exit();
1917

    
1918
    /* write the trailer if needed and close file */
1919
    for(i=0;i<nb_output_files;i++) {
1920
        os = output_files[i];
1921
        av_write_trailer(os);
1922
    }
1923

    
1924
    /* dump report by using the first video and audio streams */
1925
    print_report(output_files, ost_table, nb_ostreams, 1);
1926

    
1927
    /* close each encoder */
1928
    for(i=0;i<nb_ostreams;i++) {
1929
        ost = ost_table[i];
1930
        if (ost->encoding_needed) {
1931
            av_freep(&ost->st->codec.stats_in);
1932
            avcodec_close(&ost->st->codec);
1933
        }
1934
    }
1935
    
1936
    /* close each decoder */
1937
    for(i=0;i<nb_istreams;i++) {
1938
        ist = ist_table[i];
1939
        if (ist->decoding_needed) {
1940
            avcodec_close(&ist->st->codec);
1941
        }
1942
    }
1943

    
1944
    /* finished ! */
1945
    
1946
    ret = 0;
1947
 fail1:
1948
    av_free(file_table);
1949

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

    
1983
#if 0
1984
int file_read(const char *filename)
1985
{
1986
    URLContext *h;
1987
    unsigned char buffer[1024];
1988
    int len, i;
1989

1990
    if (url_open(&h, filename, O_RDONLY) < 0) {
1991
        printf("could not open '%s'\n", filename);
1992
        return -1;
1993
    }
1994
    for(;;) {
1995
        len = url_read(h, buffer, sizeof(buffer));
1996
        if (len <= 0)
1997
            break;
1998
        for(i=0;i<len;i++) putchar(buffer[i]);
1999
    }
2000
    url_close(h);
2001
    return 0;
2002
}
2003
#endif
2004

    
2005
static void opt_image_format(const char *arg)
2006
{
2007
    AVImageFormat *f;
2008
    
2009
    for(f = first_image_format; f != NULL; f = f->next) {
2010
        if (!strcmp(arg, f->name))
2011
            break;
2012
    }
2013
    if (!f) {
2014
        fprintf(stderr, "Unknown image format: '%s'\n", arg);
2015
        exit(1);
2016
    }
2017
    image_format = f;
2018
}
2019

    
2020
static void opt_format(const char *arg)
2021
{
2022
    /* compatibility stuff for pgmyuv */
2023
    if (!strcmp(arg, "pgmyuv")) {
2024
        pgmyuv_compatibility_hack=1;
2025
//        opt_image_format(arg);
2026
        arg = "image2";
2027
    }
2028

    
2029
    file_iformat = av_find_input_format(arg);
2030
    file_oformat = guess_format(arg, NULL, NULL);
2031
    if (!file_iformat && !file_oformat) {
2032
        fprintf(stderr, "Unknown input or output format: %s\n", arg);
2033
        exit(1);
2034
    }
2035
}
2036

    
2037
static void opt_video_bitrate(const char *arg)
2038
{
2039
    video_bit_rate = atoi(arg) * 1000;
2040
}
2041

    
2042
static void opt_video_bitrate_tolerance(const char *arg)
2043
{
2044
    video_bit_rate_tolerance = atoi(arg) * 1000;
2045
}
2046

    
2047
static void opt_video_bitrate_max(const char *arg)
2048
{
2049
    video_rc_max_rate = atoi(arg) * 1000;
2050
}
2051

    
2052
static void opt_video_bitrate_min(const char *arg)
2053
{
2054
    video_rc_min_rate = atoi(arg) * 1000;
2055
}
2056

    
2057
static void opt_video_buffer_size(const char *arg)
2058
{
2059
    video_rc_buffer_size = atoi(arg) * 8*1024;
2060
}
2061

    
2062
static void opt_video_rc_eq(char *arg)
2063
{
2064
    video_rc_eq = arg;
2065
}
2066

    
2067
static void opt_video_rc_override_string(char *arg)
2068
{
2069
    video_rc_override_string = arg;
2070
}
2071

    
2072

    
2073
static void opt_workaround_bugs(const char *arg)
2074
{
2075
    workaround_bugs = atoi(arg);
2076
}
2077

    
2078
static void opt_dct_algo(const char *arg)
2079
{
2080
    dct_algo = atoi(arg);
2081
}
2082

    
2083
static void opt_idct_algo(const char *arg)
2084
{
2085
    idct_algo = atoi(arg);
2086
}
2087

    
2088
static void opt_me_threshold(const char *arg)
2089
{
2090
    me_threshold = atoi(arg);
2091
}
2092

    
2093
static void opt_mb_threshold(const char *arg)
2094
{
2095
    mb_threshold = atoi(arg);
2096
}
2097

    
2098
static void opt_error_resilience(const char *arg)
2099
{
2100
    error_resilience = atoi(arg);
2101
}
2102

    
2103
static void opt_error_concealment(const char *arg)
2104
{
2105
    error_concealment = atoi(arg);
2106
}
2107

    
2108
static void opt_debug(const char *arg)
2109
{
2110
    debug = atoi(arg);
2111
}
2112

    
2113
static void opt_vismv(const char *arg)
2114
{
2115
    debug_mv = atoi(arg);
2116
}
2117
    
2118
static void opt_verbose(const char *arg)
2119
{
2120
    verbose = atoi(arg);
2121
    av_log_set_level(atoi(arg));
2122
}
2123

    
2124
static void opt_frame_rate(const char *arg)
2125
{
2126
    if (parse_frame_rate(&frame_rate, &frame_rate_base, arg) < 0) {
2127
        fprintf(stderr, "Incorrect frame rate\n");
2128
        exit(1);
2129
    }
2130
}
2131

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

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

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

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

    
2204
static void opt_frame_size(const char *arg)
2205
{
2206
    if (parse_image_size(&frame_width, &frame_height, arg) < 0) {
2207
        fprintf(stderr, "Incorrect frame size\n");
2208
        exit(1);
2209
    }
2210
    if ((frame_width % 2) != 0 || (frame_height % 2) != 0) {
2211
        fprintf(stderr, "Frame size must be a multiple of 2\n");
2212
        exit(1);
2213
    }
2214
}
2215

    
2216

    
2217
#define SCALEBITS 10
2218
#define ONE_HALF  (1 << (SCALEBITS - 1))
2219
#define FIX(x)          ((int) ((x) * (1<<SCALEBITS) + 0.5))
2220

    
2221
#define RGB_TO_Y(r, g, b) \
2222
((FIX(0.29900) * (r) + FIX(0.58700) * (g) + \
2223
  FIX(0.11400) * (b) + ONE_HALF) >> SCALEBITS)
2224

    
2225
#define RGB_TO_U(r1, g1, b1, shift)\
2226
(((- FIX(0.16874) * r1 - FIX(0.33126) * g1 +         \
2227
     FIX(0.50000) * b1 + (ONE_HALF << shift) - 1) >> (SCALEBITS + shift)) + 128)
2228

    
2229
#define RGB_TO_V(r1, g1, b1, shift)\
2230
(((FIX(0.50000) * r1 - FIX(0.41869) * g1 -           \
2231
   FIX(0.08131) * b1 + (ONE_HALF << shift) - 1) >> (SCALEBITS + shift)) + 128)
2232

    
2233
static void opt_pad_color(const char *arg) {
2234
    /* Input is expected to be six hex digits similar to
2235
       how colors are expressed in html tags (but without the #) */
2236
    int rgb = strtol(arg, NULL, 16);
2237
    int r,g,b;
2238
    
2239
    r = (rgb >> 16); 
2240
    g = ((rgb >> 8) & 255);
2241
    b = (rgb & 255);
2242

    
2243
    padcolor[0] = RGB_TO_Y(r,g,b);
2244
    padcolor[1] = RGB_TO_U(r,g,b,0);
2245
    padcolor[2] = RGB_TO_V(r,g,b,0);
2246
}
2247

    
2248
static void opt_frame_pad_top(const char *arg)
2249
{
2250
    frame_padtop = atoi(arg); 
2251
    if (frame_padtop < 0) {
2252
        fprintf(stderr, "Incorrect top pad size\n");
2253
        exit(1);
2254
    }
2255
    if ((frame_padtop % 2) != 0) {
2256
        fprintf(stderr, "Top pad size must be a multiple of 2\n");
2257
        exit(1);
2258
    }
2259
}
2260

    
2261
static void opt_frame_pad_bottom(const char *arg)
2262
{
2263
    frame_padbottom = atoi(arg); 
2264
    if (frame_padbottom < 0) {
2265
        fprintf(stderr, "Incorrect bottom pad size\n");
2266
        exit(1);
2267
    }
2268
    if ((frame_padbottom % 2) != 0) {
2269
        fprintf(stderr, "Bottom pad size must be a multiple of 2\n");
2270
        exit(1);
2271
    }
2272
}
2273

    
2274

    
2275
static void opt_frame_pad_left(const char *arg)
2276
{
2277
    frame_padleft = atoi(arg); 
2278
    if (frame_padleft < 0) {
2279
        fprintf(stderr, "Incorrect left pad size\n");
2280
        exit(1);
2281
    }
2282
    if ((frame_padleft % 2) != 0) {
2283
        fprintf(stderr, "Left pad size must be a multiple of 2\n");
2284
        exit(1);
2285
    }
2286
}
2287

    
2288

    
2289
static void opt_frame_pad_right(const char *arg)
2290
{
2291
    frame_padright = atoi(arg); 
2292
    if (frame_padright < 0) {
2293
        fprintf(stderr, "Incorrect right pad size\n");
2294
        exit(1);
2295
    }
2296
    if ((frame_padright % 2) != 0) {
2297
        fprintf(stderr, "Right pad size must be a multiple of 2\n");
2298
        exit(1);
2299
    }
2300
}
2301

    
2302

    
2303
static void opt_frame_pix_fmt(const char *arg)
2304
{
2305
    frame_pix_fmt = avcodec_get_pix_fmt(arg);
2306
}
2307

    
2308
static void opt_frame_aspect_ratio(const char *arg)
2309
{
2310
    int x = 0, y = 0;
2311
    double ar = 0;
2312
    const char *p;
2313
    
2314
    p = strchr(arg, ':');
2315
    if (p) {
2316
        x = strtol(arg, (char **)&arg, 10);
2317
        if (arg == p)
2318
            y = strtol(arg+1, (char **)&arg, 10);
2319
        if (x > 0 && y > 0)
2320
            ar = (double)x / (double)y;
2321
    } else
2322
        ar = strtod(arg, (char **)&arg);
2323

    
2324
    if (!ar) {
2325
        fprintf(stderr, "Incorrect aspect ratio specification.\n");
2326
        exit(1);
2327
    }
2328
    frame_aspect_ratio = ar;
2329
}
2330

    
2331
static void opt_gop_size(const char *arg)
2332
{
2333
    gop_size = atoi(arg);
2334
}
2335

    
2336
static void opt_b_frames(const char *arg)
2337
{
2338
    b_frames = atoi(arg);
2339
    if (b_frames > FF_MAX_B_FRAMES) {
2340
        fprintf(stderr, "\nCannot have more than %d B frames, increase FF_MAX_B_FRAMES.\n", FF_MAX_B_FRAMES);
2341
        exit(1);
2342
    } else if (b_frames < 1) {
2343
        fprintf(stderr, "\nNumber of B frames must be higher than 0\n");
2344
        exit(1);
2345
    }
2346
}
2347

    
2348
static void opt_mb_decision(const char *arg)
2349
{
2350
    mb_decision = atoi(arg);
2351
}
2352

    
2353
static void opt_mb_cmp(const char *arg)
2354
{
2355
    mb_cmp = atoi(arg);
2356
}
2357

    
2358
static void opt_ildct_cmp(const char *arg)
2359
{
2360
    ildct_cmp = atoi(arg);
2361
}
2362

    
2363
static void opt_sub_cmp(const char *arg)
2364
{
2365
    sub_cmp = atoi(arg);
2366
}
2367

    
2368
static void opt_cmp(const char *arg)
2369
{
2370
    cmp = atoi(arg);
2371
}
2372

    
2373
static void opt_pre_cmp(const char *arg)
2374
{
2375
    pre_cmp = atoi(arg);
2376
}
2377

    
2378
static void opt_pre_me(const char *arg)
2379
{
2380
    pre_me = atoi(arg);
2381
}
2382

    
2383
static void opt_lumi_mask(const char *arg)
2384
{
2385
    lumi_mask = atof(arg);
2386
}
2387

    
2388
static void opt_dark_mask(const char *arg)
2389
{
2390
    dark_mask = atof(arg);
2391
}
2392

    
2393
static void opt_scplx_mask(const char *arg)
2394
{
2395
    scplx_mask = atof(arg);
2396
}
2397

    
2398
static void opt_tcplx_mask(const char *arg)
2399
{
2400
    tcplx_mask = atof(arg);
2401
}
2402

    
2403
static void opt_p_mask(const char *arg)
2404
{
2405
    p_mask = atof(arg);
2406
}
2407

    
2408
static void opt_qscale(const char *arg)
2409
{
2410
    video_qscale = atof(arg);
2411
    if (video_qscale < 0.01 ||
2412
        video_qscale > 255) {
2413
        fprintf(stderr, "qscale must be >= 0.01 and <= 255\n");
2414
        exit(1);
2415
    }
2416
}
2417

    
2418
static void opt_lmax(const char *arg)
2419
{
2420
    video_lmax = atof(arg)*FF_QP2LAMBDA;
2421
}
2422

    
2423
static void opt_lmin(const char *arg)
2424
{
2425
    video_lmin = atof(arg)*FF_QP2LAMBDA;
2426
}
2427

    
2428
static void opt_qmin(const char *arg)
2429
{
2430
    video_qmin = atoi(arg);
2431
    if (video_qmin < 0 ||
2432
        video_qmin > 31) {
2433
        fprintf(stderr, "qmin must be >= 1 and <= 31\n");
2434
        exit(1);
2435
    }
2436
}
2437

    
2438
static void opt_qmax(const char *arg)
2439
{
2440
    video_qmax = atoi(arg);
2441
    if (video_qmax < 0 ||
2442
        video_qmax > 31) {
2443
        fprintf(stderr, "qmax must be >= 1 and <= 31\n");
2444
        exit(1);
2445
    }
2446
}
2447

    
2448
static void opt_mb_qmin(const char *arg)
2449
{
2450
    video_mb_qmin = atoi(arg);
2451
    if (video_mb_qmin < 0 ||
2452
        video_mb_qmin > 31) {
2453
        fprintf(stderr, "qmin must be >= 1 and <= 31\n");
2454
        exit(1);
2455
    }
2456
}
2457

    
2458
static void opt_mb_qmax(const char *arg)
2459
{
2460
    video_mb_qmax = atoi(arg);
2461
    if (video_mb_qmax < 0 ||
2462
        video_mb_qmax > 31) {
2463
        fprintf(stderr, "qmax must be >= 1 and <= 31\n");
2464
        exit(1);
2465
    }
2466
}
2467

    
2468
static void opt_qdiff(const char *arg)
2469
{
2470
    video_qdiff = atoi(arg);
2471
    if (video_qdiff < 0 ||
2472
        video_qdiff > 31) {
2473
        fprintf(stderr, "qdiff must be >= 1 and <= 31\n");
2474
        exit(1);
2475
    }
2476
}
2477

    
2478
static void opt_qblur(const char *arg)
2479
{
2480
    video_qblur = atof(arg);
2481
}
2482

    
2483
static void opt_qcomp(const char *arg)
2484
{
2485
    video_qcomp = atof(arg);
2486
}
2487

    
2488
static void opt_rc_initial_cplx(const char *arg)
2489
{
2490
    video_rc_initial_cplx = atof(arg);
2491
}
2492
static void opt_b_qfactor(const char *arg)
2493
{
2494
    video_b_qfactor = atof(arg);
2495
}
2496
static void opt_i_qfactor(const char *arg)
2497
{
2498
    video_i_qfactor = atof(arg);
2499
}
2500
static void opt_b_qoffset(const char *arg)
2501
{
2502
    video_b_qoffset = atof(arg);
2503
}
2504
static void opt_i_qoffset(const char *arg)
2505
{
2506
    video_i_qoffset = atof(arg);
2507
}
2508

    
2509
static void opt_ibias(const char *arg)
2510
{
2511
    video_intra_quant_bias = atoi(arg);
2512
}
2513
static void opt_pbias(const char *arg)
2514
{
2515
    video_inter_quant_bias = atoi(arg);
2516
}
2517

    
2518
static void opt_packet_size(const char *arg)
2519
{
2520
    packet_size= atoi(arg);
2521
}
2522

    
2523
static void opt_error_rate(const char *arg)
2524
{
2525
    error_rate= atoi(arg);
2526
}
2527

    
2528
static void opt_strict(const char *arg)
2529
{
2530
    strict= atoi(arg);
2531
}
2532

    
2533
static void opt_top_field_first(const char *arg)
2534
{
2535
    top_field_first= atoi(arg);
2536
}
2537

    
2538
static void opt_noise_reduction(const char *arg)
2539
{
2540
    noise_reduction= atoi(arg);
2541
}
2542

    
2543
static void opt_qns(const char *arg)
2544
{
2545
    qns= atoi(arg);
2546
}
2547

    
2548
static void opt_sc_threshold(const char *arg)
2549
{
2550
    sc_threshold= atoi(arg);
2551
}
2552

    
2553
static void opt_me_range(const char *arg)
2554
{
2555
    me_range = atoi(arg);
2556
}
2557

    
2558
static void opt_thread_count(const char *arg)
2559
{
2560
    thread_count= atoi(arg);
2561
#if !defined(HAVE_THREADS)
2562
    if (verbose >= 0)
2563
        fprintf(stderr, "Warning: not compiled with thread support, using thread emulation\n");
2564
#endif
2565
}
2566

    
2567
static void opt_audio_bitrate(const char *arg)
2568
{
2569
    audio_bit_rate = atoi(arg) * 1000;
2570
}
2571

    
2572
static void opt_audio_rate(const char *arg)
2573
{
2574
    audio_sample_rate = atoi(arg);
2575
}
2576

    
2577
static void opt_audio_channels(const char *arg)
2578
{
2579
    audio_channels = atoi(arg);
2580
}
2581

    
2582
static void opt_video_device(const char *arg)
2583
{
2584
    video_device = av_strdup(arg);
2585
}
2586

    
2587
static void opt_grab_device(const char *arg)
2588
{
2589
    grab_device = av_strdup(arg);
2590
}
2591

    
2592
static void opt_video_channel(const char *arg)
2593
{
2594
    video_channel = strtol(arg, NULL, 0);
2595
}
2596

    
2597
static void opt_video_standard(const char *arg)
2598
{
2599
    video_standard = av_strdup(arg);
2600
}
2601

    
2602
static void opt_audio_device(const char *arg)
2603
{
2604
    audio_device = av_strdup(arg);
2605
}
2606

    
2607
static void opt_audio_codec(const char *arg)
2608
{
2609
    AVCodec *p;
2610

    
2611
    if (!strcmp(arg, "copy")) {
2612
        audio_stream_copy = 1;
2613
    } else {
2614
        p = first_avcodec;
2615
        while (p) {
2616
            if (!strcmp(p->name, arg) && p->type == CODEC_TYPE_AUDIO)
2617
                break;
2618
            p = p->next;
2619
        }
2620
        if (p == NULL) {
2621
            fprintf(stderr, "Unknown audio codec '%s'\n", arg);
2622
            exit(1);
2623
        } else {
2624
            audio_codec_id = p->id;
2625
        }
2626
    }
2627
}
2628

    
2629
static void opt_audio_tag(const char *arg)
2630
{
2631
    char *tail;
2632
    audio_codec_tag= strtol(arg, &tail, 0);
2633

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

    
2638
static void opt_video_tag(const char *arg)
2639
{
2640
    char *tail;
2641
    video_codec_tag= strtol(arg, &tail, 0);
2642

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

    
2647
static void add_frame_hooker(const char *arg)
2648
{
2649
    int argc = 0;
2650
    char *argv[64];
2651
    int i;
2652
    char *args = av_strdup(arg);
2653

    
2654
    using_vhook = 1;
2655

    
2656
    argv[0] = strtok(args, " ");
2657
    while (argc < 62 && (argv[++argc] = strtok(NULL, " "))) {
2658
    }
2659

    
2660
    i = frame_hook_add(argc, argv);
2661

    
2662
    if (i != 0) {
2663
        fprintf(stderr, "Failed to add video hook function: %s\n", arg);
2664
        exit(1);
2665
    }
2666
}
2667

    
2668
const char *motion_str[] = {
2669
    "zero",
2670
    "full",
2671
    "log",
2672
    "phods",
2673
    "epzs",
2674
    "x1",
2675
    NULL,
2676
};
2677

    
2678
static void opt_motion_estimation(const char *arg)
2679
{
2680
    const char **p;
2681
    p = motion_str;
2682
    for(;;) {
2683
        if (!*p) {
2684
            fprintf(stderr, "Unknown motion estimation method '%s'\n", arg);
2685
            exit(1);
2686
        }
2687
        if (!strcmp(*p, arg))
2688
            break;
2689
        p++;
2690
    }
2691
    me_method = (p - motion_str) + 1;
2692
}
2693

    
2694
static void opt_video_codec(const char *arg)
2695
{
2696
    AVCodec *p;
2697

    
2698
    if (!strcmp(arg, "copy")) {
2699
        video_stream_copy = 1;
2700
    } else {
2701
        p = first_avcodec;
2702
        while (p) {
2703
            if (!strcmp(p->name, arg) && p->type == CODEC_TYPE_VIDEO)
2704
                break;
2705
            p = p->next;
2706
        }
2707
        if (p == NULL) {
2708
            fprintf(stderr, "Unknown video codec '%s'\n", arg);
2709
            exit(1);
2710
        } else {
2711
            video_codec_id = p->id;
2712
        }
2713
    }
2714
}
2715

    
2716
static void opt_map(const char *arg)
2717
{
2718
    AVStreamMap *m;
2719
    const char *p;
2720

    
2721
    p = arg;
2722
    m = &stream_maps[nb_stream_maps++];
2723

    
2724
    m->file_index = strtol(arg, (char **)&p, 0);
2725
    if (*p)
2726
        p++;
2727

    
2728
    m->stream_index = strtol(p, (char **)&p, 0);
2729
}
2730

    
2731
static void opt_map_meta_data(const char *arg)
2732
{
2733
    AVMetaDataMap *m;
2734
    const char *p;
2735
        
2736
    p = arg;
2737
    m = &meta_data_maps[nb_meta_data_maps++];
2738

    
2739
    m->out_file = strtol(arg, (char **)&p, 0);
2740
    if (*p)
2741
        p++;
2742

    
2743
    m->in_file = strtol(p, (char **)&p, 0);
2744
}
2745

    
2746
static void opt_recording_time(const char *arg)
2747
{
2748
    recording_time = parse_date(arg, 1);
2749
}
2750

    
2751
static void opt_start_time(const char *arg)
2752
{
2753
    start_time = parse_date(arg, 1);
2754
}
2755

    
2756
static void opt_rec_timestamp(const char *arg)
2757
{
2758
    rec_timestamp = parse_date(arg, 0) / 1000000;
2759
}
2760

    
2761
static void opt_input_ts_offset(const char *arg)
2762
{
2763
    input_ts_offset = parse_date(arg, 1);
2764
}
2765

    
2766
static void opt_input_file(const char *filename)
2767
{
2768
    AVFormatContext *ic;
2769
    AVFormatParameters params, *ap = &params;
2770
    int err, i, ret, rfps, rfps_base;
2771
    int64_t timestamp;
2772

    
2773
    if (!strcmp(filename, "-"))
2774
        filename = "pipe:";
2775

    
2776
    using_stdin |= !strncmp(filename, "pipe:", 5) || 
2777
                   !strcmp( filename, "/dev/stdin" );
2778

    
2779
    /* get default parameters from command line */
2780
    memset(ap, 0, sizeof(*ap));
2781
    ap->sample_rate = audio_sample_rate;
2782
    ap->channels = audio_channels;
2783
    ap->frame_rate = frame_rate;
2784
    ap->frame_rate_base = frame_rate_base;
2785
    ap->width = frame_width + frame_padleft + frame_padright;
2786
    ap->height = frame_height + frame_padtop + frame_padbottom;
2787
    ap->image_format = image_format;
2788
    ap->pix_fmt = frame_pix_fmt;
2789
    ap->device  = grab_device;
2790
    ap->channel = video_channel;
2791
    ap->standard = video_standard;
2792
    ap->video_codec_id = video_codec_id;
2793
    ap->audio_codec_id = audio_codec_id;
2794
    if(pgmyuv_compatibility_hack)
2795
        ap->video_codec_id= CODEC_ID_PGMYUV;
2796

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

    
2812
    timestamp = start_time;
2813
    /* add the stream start time */
2814
    if (ic->start_time != AV_NOPTS_VALUE)
2815
        timestamp += ic->start_time;
2816

    
2817
    /* if seeking requested, we execute it */
2818
    if (start_time != 0) {
2819
        ret = av_seek_frame(ic, -1, timestamp, AVSEEK_FLAG_BACKWARD);
2820
        if (ret < 0) {
2821
            fprintf(stderr, "%s: could not seek to position %0.3f\n", 
2822
                    filename, (double)timestamp / AV_TIME_BASE);
2823
        }
2824
        /* reset seek info */
2825
        start_time = 0;
2826
    }
2827

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

    
2861
            assert(enc->frame_rate_base == rfps_base); // should be true for now
2862
            if (enc->frame_rate != rfps) { 
2863

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

    
2868
                    (float)rfps / rfps_base);
2869
            }
2870
            /* update the current frame rate to match the stream frame rate */
2871
            frame_rate      = rfps;
2872
            frame_rate_base = rfps_base;
2873

    
2874
            enc->rate_emu = rate_emu;
2875
            break;
2876
        case CODEC_TYPE_DATA:
2877
            break;
2878
        default:
2879
            av_abort();
2880
        }
2881
    }
2882
    
2883
    input_files[nb_input_files] = ic;
2884
    input_files_ts_offset[nb_input_files] = input_ts_offset - (copy_ts ? 0 : timestamp);
2885
    /* dump the file content */
2886
    if (verbose >= 0)
2887
        dump_format(ic, nb_input_files, filename, 0);
2888

    
2889
    nb_input_files++;
2890
    file_iformat = NULL;
2891
    file_oformat = NULL;
2892
    image_format = NULL;
2893

    
2894
    grab_device = NULL;
2895
    video_channel = 0;
2896
    
2897
    rate_emu = 0;
2898
}
2899

    
2900
static void opt_grab(const char *arg)
2901
{
2902
    file_iformat = av_find_input_format(arg);
2903
    opt_input_file("");
2904
}
2905

    
2906
static void check_audio_video_inputs(int *has_video_ptr, int *has_audio_ptr)
2907
{
2908
    int has_video, has_audio, i, j;
2909
    AVFormatContext *ic;
2910

    
2911
    has_video = 0;
2912
    has_audio = 0;
2913
    for(j=0;j<nb_input_files;j++) {
2914
        ic = input_files[j];
2915
        for(i=0;i<ic->nb_streams;i++) {
2916
            AVCodecContext *enc = &ic->streams[i]->codec;
2917
            switch(enc->codec_type) {
2918
            case CODEC_TYPE_AUDIO:
2919
                has_audio = 1;
2920
                break;
2921
            case CODEC_TYPE_VIDEO:
2922
                has_video = 1;
2923
                break;
2924
            case CODEC_TYPE_DATA:
2925
                break;
2926
            default:
2927
                av_abort();
2928
            }
2929
        }
2930
    }
2931
    *has_video_ptr = has_video;
2932
    *has_audio_ptr = has_audio;
2933
}
2934

    
2935
static void opt_output_file(const char *filename)
2936
{
2937
    AVStream *st;
2938
    AVFormatContext *oc;
2939
    int use_video, use_audio, nb_streams, input_has_video, input_has_audio;
2940
    int codec_id;
2941
    AVFormatParameters params, *ap = &params;
2942

    
2943
    if (!strcmp(filename, "-"))
2944
        filename = "pipe:";
2945

    
2946
    oc = av_alloc_format_context();
2947

    
2948
    if (!file_oformat) {
2949
        file_oformat = guess_format(NULL, filename, NULL);
2950
        if (!file_oformat) {
2951
            fprintf(stderr, "Unable for find a suitable output format for '%s'\n",
2952
                    filename);
2953
            exit(1);
2954
        }
2955
    }
2956
    
2957
    oc->oformat = file_oformat;
2958

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

    
2971
        /* disable if no corresponding type found and at least one
2972
           input file */
2973
        if (nb_input_files > 0) {
2974
            check_audio_video_inputs(&input_has_video, &input_has_audio);
2975
            if (!input_has_video)
2976
                use_video = 0;
2977
            if (!input_has_audio)
2978
                use_audio = 0;
2979
        }
2980

    
2981
        /* manual disable */
2982
        if (audio_disable) {
2983
            use_audio = 0;
2984
        }
2985
        if (video_disable) {
2986
            use_video = 0;
2987
        }
2988
        
2989
        nb_streams = 0;
2990
        if (use_video) {
2991
            AVCodecContext *video_enc;
2992
            
2993
            st = av_new_stream(oc, nb_streams++);
2994
            if (!st) {
2995
                fprintf(stderr, "Could not alloc stream\n");
2996
                exit(1);
2997
            }
2998
#if defined(HAVE_THREADS)
2999
            if(thread_count>1)
3000
                avcodec_thread_init(&st->codec, thread_count);
3001
#endif
3002

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

    
3051
                if(codec && codec->pix_fmts){
3052
                    const enum PixelFormat *p= codec->pix_fmts;
3053
                    for(; *p!=-1; p++){
3054
                        if(*p == video_enc->pix_fmt)
3055
                            break;
3056
                    }
3057
                    if(*p == -1)
3058
                        video_enc->pix_fmt = codec->pix_fmts[0];
3059
                }
3060

    
3061
                if (!intra_only)
3062
                    video_enc->gop_size = gop_size;
3063
                else
3064
                    video_enc->gop_size = 0;
3065
                if (video_qscale || same_quality) {
3066
                    video_enc->flags |= CODEC_FLAG_QSCALE;
3067
                    st->quality = FF_QP2LAMBDA * video_qscale;
3068
                }
3069

    
3070
                if(intra_matrix)
3071
                    video_enc->intra_matrix = intra_matrix;
3072
                if(inter_matrix)
3073
                    video_enc->inter_matrix = inter_matrix;
3074

    
3075
                if(bitexact)
3076
                    video_enc->flags |= CODEC_FLAG_BITEXACT;
3077

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

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

    
3221
                if(packet_size){
3222
                    video_enc->rtp_mode= 1;
3223
                    video_enc->rtp_payload_size= packet_size;
3224
                }
3225
            
3226
                if (do_psnr)
3227
                    video_enc->flags|= CODEC_FLAG_PSNR;
3228
            
3229
                video_enc->me_method = me_method;
3230

    
3231
                /* two pass mode */
3232
                if (do_pass) {
3233
                    if (do_pass == 1) {
3234
                        video_enc->flags |= CODEC_FLAG_PASS1;
3235
                    } else {
3236
                        video_enc->flags |= CODEC_FLAG_PASS2;
3237
                    }
3238
                }
3239
            }
3240
        }
3241
    
3242
        if (use_audio) {
3243
            AVCodecContext *audio_enc;
3244

    
3245
            st = av_new_stream(oc, nb_streams++);
3246
            if (!st) {
3247
                fprintf(stderr, "Could not alloc stream\n");
3248
                exit(1);
3249
            }
3250
#if defined(HAVE_THREADS)
3251
            if(thread_count>1)
3252
                avcodec_thread_init(&st->codec, thread_count);
3253
#endif
3254

    
3255
            audio_enc = &st->codec;
3256
            audio_enc->codec_type = CODEC_TYPE_AUDIO;
3257

    
3258
            if(audio_codec_tag)
3259
                audio_enc->codec_tag= audio_codec_tag;
3260

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

    
3286
        oc->nb_streams = nb_streams;
3287

    
3288
        if (!nb_streams) {
3289
            fprintf(stderr, "No audio or video streams available\n");
3290
            exit(1);
3291
        }
3292

    
3293
        oc->timestamp = rec_timestamp;
3294
            
3295
        if (str_title)
3296
            pstrcpy(oc->title, sizeof(oc->title), str_title);
3297
        if (str_author)
3298
            pstrcpy(oc->author, sizeof(oc->author), str_author);
3299
        if (str_copyright)
3300
            pstrcpy(oc->copyright, sizeof(oc->copyright), str_copyright);
3301
        if (str_comment)
3302
            pstrcpy(oc->comment, sizeof(oc->comment), str_comment);
3303
    }
3304

    
3305
    output_files[nb_output_files++] = oc;
3306

    
3307
    strcpy(oc->filename, filename);
3308

    
3309
    /* check filename in case of an image number is expected */
3310
    if (oc->oformat->flags & AVFMT_NEEDNUMBER) {
3311
        if (filename_number_test(oc->filename) < 0) {
3312
            print_error(oc->filename, AVERROR_NUMEXPECTED);
3313
            exit(1);
3314
        }
3315
    }
3316

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

    
3348
    memset(ap, 0, sizeof(*ap));
3349
    ap->image_format = image_format;
3350
    if (av_set_parameters(oc, ap) < 0) {
3351
        fprintf(stderr, "%s: Invalid encoding parameters\n",
3352
                oc->filename);
3353
        exit(1);
3354
    }
3355

    
3356
    oc->packet_size= mux_packet_size;
3357
    oc->mux_rate= mux_rate;
3358
    oc->preload= (int)(mux_preload*AV_TIME_BASE);
3359
    oc->max_delay= (int)(mux_max_delay*AV_TIME_BASE);
3360

    
3361
    /* reset some options */
3362
    file_oformat = NULL;
3363
    file_iformat = NULL;
3364
    image_format = NULL;
3365
    audio_disable = 0;
3366
    video_disable = 0;
3367
    audio_codec_id = CODEC_ID_NONE;
3368
    video_codec_id = CODEC_ID_NONE;
3369
    audio_stream_copy = 0;
3370
    video_stream_copy = 0;
3371
}
3372

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

    
3444
        if (verbose >= 0)
3445
            dump_format(ic, nb_input_files, "", 0);
3446

    
3447
        nb_input_files++;
3448
    }
3449
    if (has_audio && audio_grab_format) {
3450
        AVInputFormat *fmt1;
3451
        fmt1 = av_find_input_format(audio_grab_format);
3452
        ap->device = audio_device;
3453
        if (av_open_input_file(&ic, "", fmt1, 0, ap) < 0) {
3454
            fprintf(stderr, "Could not find audio grab device\n");
3455
            exit(1);
3456
        }
3457
        input_files[nb_input_files] = ic;
3458

    
3459
        if (verbose >= 0)
3460
            dump_format(ic, nb_input_files, "", 0);
3461

    
3462
        nb_input_files++;
3463
    }
3464
}
3465

    
3466
/* same option as mencoder */
3467
static void opt_pass(const char *pass_str)
3468
{
3469
    int pass;
3470
    pass = atoi(pass_str);
3471
    if (pass != 1 && pass != 2) {
3472
        fprintf(stderr, "pass number can be only 1 or 2\n");
3473
        exit(1);
3474
    }
3475
    do_pass = pass;
3476
}
3477

    
3478
#if defined(CONFIG_WIN32) || defined(CONFIG_OS2)
3479
static int64_t getutime(void)
3480
{
3481
  return av_gettime();
3482
}
3483
#else
3484
static int64_t getutime(void)
3485
{
3486
    struct rusage rusage;
3487

    
3488
    getrusage(RUSAGE_SELF, &rusage);
3489
    return (rusage.ru_utime.tv_sec * 1000000LL) + rusage.ru_utime.tv_usec;
3490
}
3491
#endif
3492

    
3493
extern int ffm_nopts;
3494

    
3495
static void opt_bitexact(void)
3496
{
3497
    bitexact=1;
3498
    /* disable generate of real time pts in ffm (need to be supressed anyway) */
3499
    ffm_nopts = 1;
3500
}
3501

    
3502
static void show_formats(void)
3503
{
3504
    AVInputFormat *ifmt;
3505
    AVOutputFormat *ofmt;
3506
    AVImageFormat *image_fmt;
3507
    URLProtocol *up;
3508
    AVCodec *p, *p2;
3509
    const char **pp, *last_name;
3510

    
3511
    printf("File formats:\n");
3512
    last_name= "000";
3513
    for(;;){
3514
        int decode=0;
3515
        int encode=0;
3516
        const char *name=NULL;
3517
        const char *long_name=NULL;
3518

    
3519
        for(ofmt = first_oformat; ofmt != NULL; ofmt = ofmt->next) {
3520
            if((name == NULL || strcmp(ofmt->name, name)<0) &&
3521
                strcmp(ofmt->name, last_name)>0){
3522
                name= ofmt->name;
3523
                long_name= ofmt->long_name;
3524
                encode=1;
3525
            }
3526
        }
3527
        for(ifmt = first_iformat; ifmt != NULL; ifmt = ifmt->next) {
3528
            if((name == NULL || strcmp(ifmt->name, name)<0) &&
3529
                strcmp(ifmt->name, last_name)>0){
3530
                name= ifmt->name;
3531
                long_name= ifmt->long_name;
3532
                encode=0;
3533
            }
3534
            if(name && strcmp(ifmt->name, name)==0)
3535
                decode=1;
3536
        }
3537
        if(name==NULL)
3538
            break;
3539
        last_name= name;
3540
        
3541
        printf(
3542
            " %s%s %-15s %s\n", 
3543
            decode ? "D":" ", 
3544
            encode ? "E":" ", 
3545
            name,
3546
            long_name ? long_name:" ");
3547
    }
3548
    printf("\n");
3549

    
3550
    printf("Image formats (filename extensions, if any, follow):\n");
3551
    for(image_fmt = first_image_format; image_fmt != NULL; 
3552
        image_fmt = image_fmt->next) {
3553
        printf(
3554
            " %s%s %-6s %s\n",
3555
            image_fmt->img_read  ? "D":" ",
3556
            image_fmt->img_write ? "E":" ",
3557
            image_fmt->name,
3558
            image_fmt->extensions ? image_fmt->extensions:" ");
3559
    }
3560
    printf("\n");
3561

    
3562
    printf("Codecs:\n");
3563
    last_name= "000";
3564
    for(;;){
3565
        int decode=0;
3566
        int encode=0;
3567
        int cap=0;
3568

    
3569
        p2=NULL;
3570
        for(p = first_avcodec; p != NULL; p = p->next) {
3571
            if((p2==NULL || strcmp(p->name, p2->name)<0) &&
3572
                strcmp(p->name, last_name)>0){
3573
                p2= p;
3574
                decode= encode= cap=0;
3575
            }
3576
            if(p2 && strcmp(p->name, p2->name)==0){
3577
                if(p->decode) decode=1;
3578
                if(p->encode) encode=1;
3579
                cap |= p->capabilities;
3580
            }
3581
        }
3582
        if(p2==NULL)
3583
            break;
3584
        last_name= p2->name;
3585
        
3586
        printf(
3587
            " %s%s%s%s%s%s %s", 
3588
            decode ? "D": (/*p2->decoder ? "d":*/" "), 
3589
            encode ? "E":" ", 
3590
            p2->type == CODEC_TYPE_AUDIO ? "A":"V",
3591
            cap & CODEC_CAP_DRAW_HORIZ_BAND ? "S":" ",
3592
            cap & CODEC_CAP_DR1 ? "D":" ",
3593
            cap & CODEC_CAP_TRUNCATED ? "T":" ",
3594
            p2->name);
3595
       /* if(p2->decoder && decode==0)
3596
            printf(" use %s for decoding", p2->decoder->name);*/
3597
        printf("\n");
3598
    }
3599
    printf("\n");
3600

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

    
3629
void parse_matrix_coeffs(uint16_t *dest, const char *str)
3630
{
3631
    int i;
3632
    const char *p = str;
3633
    for(i = 0;; i++) {
3634
        dest[i] = atoi(p);
3635
        if(i == 63)
3636
            break;
3637
        p = strchr(p, ',');
3638
        if(!p) {
3639
            fprintf(stderr, "Syntax error in matrix \"%s\" at coeff %d\n", str, i);
3640
            exit(1);
3641
        }
3642
        p++;
3643
    }
3644
}
3645

    
3646
void opt_inter_matrix(const char *arg)
3647
{
3648
    inter_matrix = av_mallocz(sizeof(uint16_t) * 64);
3649
    parse_matrix_coeffs(inter_matrix, arg);
3650
}
3651

    
3652
void opt_intra_matrix(const char *arg)
3653
{
3654
    intra_matrix = av_mallocz(sizeof(uint16_t) * 64);
3655
    parse_matrix_coeffs(intra_matrix, arg);
3656
}
3657

    
3658
static void opt_target(const char *arg)
3659
{
3660
    int norm = -1;
3661

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

    
3703
    if(norm < 0) {
3704
        fprintf(stderr, "Could not determine norm (PAL/NTSC) for target.\n");
3705
        fprintf(stderr, "Please prefix target with \"pal-\" or \"ntsc-\",\n");
3706
        fprintf(stderr, "or set a framerate with \"-r xxx\".\n");
3707
        exit(1);
3708
    }
3709

    
3710
    if(!strcmp(arg, "vcd")) {
3711

    
3712
        opt_video_codec("mpeg1video");
3713
        opt_audio_codec("mp2");
3714
        opt_format("vcd");
3715

    
3716
        opt_frame_size(norm ? "352x240" : "352x288");
3717

    
3718
        video_bit_rate = 1150000;
3719
        video_rc_max_rate = 1150000;
3720
        video_rc_min_rate = 1150000;
3721
        video_rc_buffer_size = 40*1024*8;
3722

    
3723
        audio_bit_rate = 224000;
3724
        audio_sample_rate = 44100;
3725
        
3726
        mux_packet_size= 2324;
3727
        mux_rate= 2352 * 75 * 8;
3728

    
3729
        /* We have to offset the PTS, so that it is consistent with the SCR.
3730
           SCR starts at 36000, but the first two packs contain only padding
3731
           and the first pack from the other stream, respectively, may also have
3732
           been written before.
3733
           So the real data starts at SCR 36000+3*1200. */
3734
        mux_preload= (36000+3*1200) / 90000.0; //0.44
3735
    } else if(!strcmp(arg, "svcd")) {
3736

    
3737
        opt_video_codec("mpeg2video");
3738
        opt_audio_codec("mp2");
3739
        opt_format("svcd");
3740

    
3741
        opt_frame_size(norm ? "480x480" : "480x576");
3742
        opt_gop_size(norm ? "18" : "15");
3743

    
3744
        video_bit_rate = 2040000;
3745
        video_rc_max_rate = 2516000;
3746
        video_rc_min_rate = 0; //1145000;
3747
        video_rc_buffer_size = 224*1024*8;
3748
        use_scan_offset = 1;
3749

    
3750
        audio_bit_rate = 224000;
3751
        audio_sample_rate = 44100;
3752

    
3753
        mux_packet_size= 2324;
3754

    
3755
    } else if(!strcmp(arg, "dvd")) {
3756

    
3757
        opt_video_codec("mpeg2video");
3758
        opt_audio_codec("ac3");
3759
        opt_format("dvd");
3760

    
3761
        opt_frame_size(norm ? "720x480" : "720x576");
3762
        opt_gop_size(norm ? "18" : "15");
3763

    
3764
        video_bit_rate = 6000000;
3765
        video_rc_max_rate = 9000000;
3766
        video_rc_min_rate = 0; //1500000;
3767
        video_rc_buffer_size = 224*1024*8;
3768

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

    
3772
        audio_bit_rate = 448000;
3773
        audio_sample_rate = 48000;
3774

    
3775
    } else {
3776
        fprintf(stderr, "Unknown target: %s\n", arg);
3777
        exit(1);
3778
    }
3779
}
3780

    
3781
static void show_version(void)
3782
{
3783
    printf("ffmpeg      " FFMPEG_VERSION "\n"
3784
           "libavcodec  %d\n"
3785
           "libavformat %d\n", 
3786
           avcodec_build(), LIBAVFORMAT_BUILD);
3787
    exit(1);
3788
}
3789

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

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

    
3944
    /* audio options */
3945
    { "ab", HAS_ARG | OPT_AUDIO, {(void*)opt_audio_bitrate}, "set audio bitrate (in kbit/s)", "bitrate", },
3946
    { "ar", HAS_ARG | OPT_AUDIO, {(void*)opt_audio_rate}, "set audio sampling rate (in Hz)", "rate" },
3947
    { "ac", HAS_ARG | OPT_AUDIO, {(void*)opt_audio_channels}, "set number of audio channels", "channels" },
3948
    { "an", OPT_BOOL | OPT_AUDIO, {(void*)&audio_disable}, "disable audio" },
3949
    { "acodec", HAS_ARG | OPT_AUDIO, {(void*)opt_audio_codec}, "force audio codec ('copy' to copy stream)", "codec" },
3950
    { "atag", HAS_ARG | OPT_EXPERT | OPT_AUDIO, {(void*)opt_audio_tag}, "force audio tag/fourcc", "fourcc/tag" },
3951

    
3952
    /* grab options */
3953
    { "vd", HAS_ARG | OPT_EXPERT | OPT_VIDEO | OPT_GRAB, {(void*)opt_video_device}, "set video grab device", "device" },
3954
    { "vc", HAS_ARG | OPT_EXPERT | OPT_VIDEO | OPT_GRAB, {(void*)opt_video_channel}, "set video grab channel (DV1394 only)", "channel" },
3955
    { "tvstd", HAS_ARG | OPT_EXPERT | OPT_VIDEO | OPT_GRAB, {(void*)opt_video_standard}, "set television standard (NTSC, PAL (SECAM))", "standard" },
3956
    { "ad", HAS_ARG | OPT_EXPERT | OPT_AUDIO | OPT_GRAB, {(void*)opt_audio_device}, "set audio device", "device" },
3957

    
3958
    /* G.2 grab options */ 
3959
    { "grab", HAS_ARG | OPT_EXPERT | OPT_GRAB, {(void*)opt_grab}, "request grabbing using", "format" },
3960
    { "gd", HAS_ARG | OPT_EXPERT | OPT_VIDEO | OPT_GRAB, {(void*)opt_grab_device}, "set grab device", "device" },
3961
 
3962
    /* muxer options */   
3963
    { "muxrate", OPT_INT | HAS_ARG | OPT_EXPERT, {(void*)&mux_rate}, "set mux rate", "rate" },
3964
    { "packetsize", OPT_INT | HAS_ARG | OPT_EXPERT, {(void*)&mux_packet_size}, "set packet size", "size" },
3965
    { "muxdelay", OPT_FLOAT | HAS_ARG | OPT_EXPERT, {(void*)&mux_max_delay}, "set the maximum demux-decode delay", "seconds" },
3966
    { "muxpreload", OPT_FLOAT | HAS_ARG | OPT_EXPERT, {(void*)&mux_preload}, "set the initial demux-decode delay", "seconds" },
3967
    { NULL, },
3968
};
3969

    
3970
static void show_banner(void)
3971
{
3972
    printf("ffmpeg version " FFMPEG_VERSION ", build %d, Copyright (c) 2000-2004 Fabrice Bellard\n",
3973
        LIBAVCODEC_BUILD);
3974
    printf("  configuration: %s\n", FFMPEG_CONFIGURATION);
3975
    printf("  built on " __DATE__ " " __TIME__);
3976
#ifdef __GNUC__
3977
    printf(", gcc: %s\n", __VERSION__);
3978
#else
3979
    printf(", using a non-gcc compiler\n");
3980
#endif
3981
}
3982

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

    
4022
static void show_help(void)
4023
{
4024
    show_banner();
4025
    printf("usage: ffmpeg [[infile options] -i infile]... {[outfile options] outfile}...\n"
4026
           "Hyper fast Audio and Video encoder\n");
4027
    printf("\n");
4028
    show_help_options(options, "Main options:\n",
4029
                      OPT_EXPERT | OPT_AUDIO | OPT_VIDEO, 0);
4030
    show_help_options(options, "\nVideo options:\n",
4031
                      OPT_EXPERT | OPT_AUDIO | OPT_VIDEO | OPT_GRAB, 
4032
                      OPT_VIDEO);
4033
    show_help_options(options, "\nAdvanced Video options:\n",
4034
                      OPT_EXPERT | OPT_AUDIO | OPT_VIDEO | OPT_GRAB, 
4035
                      OPT_VIDEO | OPT_EXPERT);
4036
    show_help_options(options, "\nAudio options:\n",
4037
                      OPT_EXPERT | OPT_AUDIO | OPT_VIDEO | OPT_GRAB, 
4038
                      OPT_AUDIO);
4039
    show_help_options(options, "\nAdvanced Audio options:\n",
4040
                      OPT_EXPERT | OPT_AUDIO | OPT_VIDEO | OPT_GRAB, 
4041
                      OPT_AUDIO | OPT_EXPERT);
4042
    show_help_options(options, "\nAudio/Video grab options:\n",
4043
                      OPT_GRAB, 
4044
                      OPT_GRAB);
4045
    show_help_options(options, "\nAdvanced options:\n",
4046
                      OPT_EXPERT | OPT_AUDIO | OPT_VIDEO | OPT_GRAB, 
4047
                      OPT_EXPERT);
4048
    exit(1);
4049
}
4050

    
4051
void parse_arg_file(const char *filename)
4052
{
4053
    opt_output_file(filename);
4054
}
4055

    
4056
int main(int argc, char **argv)
4057
{
4058
    int i;
4059
    int64_t ti;
4060

    
4061
    av_register_all();
4062

    
4063
    if (argc <= 1)
4064
        show_help();
4065
    else
4066
        show_banner();
4067
    
4068
    /* parse options */
4069
    parse_options(argc, argv, options);
4070

    
4071
    /* file converter / grab */
4072
    if (nb_output_files <= 0) {
4073
        fprintf(stderr, "Must supply at least one output file\n");
4074
        exit(1);
4075
    }
4076
    
4077
    if (nb_input_files == 0) {
4078
        input_sync = 1;
4079
        prepare_grab();
4080
    }
4081

    
4082
    ti = getutime();
4083
    av_encode(output_files, nb_output_files, input_files, nb_input_files, 
4084
              stream_maps, nb_stream_maps);
4085
    ti = getutime() - ti;
4086
    if (do_benchmark) {
4087
        printf("bench: utime=%0.3fs\n", ti / 1000000.0);
4088
    }
4089

    
4090
    /* close files */
4091
    for(i=0;i<nb_output_files;i++) {
4092
        /* maybe av_close_output_file ??? */
4093
        AVFormatContext *s = output_files[i];
4094
        int j;
4095
        if (!(s->oformat->flags & AVFMT_NOFILE))
4096
            url_fclose(&s->pb);
4097
        for(j=0;j<s->nb_streams;j++)
4098
            av_free(s->streams[j]);
4099
        av_free(s);
4100
    }
4101
    for(i=0;i<nb_input_files;i++)
4102
        av_close_input_file(input_files[i]);
4103

    
4104
    av_free_static();
4105

    
4106
    if(intra_matrix)
4107
        av_free(intra_matrix);
4108
    if(inter_matrix)
4109
        av_free(inter_matrix);
4110
    
4111
#ifdef POWERPC_PERFORMANCE_REPORT
4112
    extern void powerpc_display_perf_report(void);
4113
    powerpc_display_perf_report();
4114
#endif /* POWERPC_PERFORMANCE_REPORT */
4115

    
4116
#ifndef CONFIG_WIN32
4117
    if (received_sigterm) {
4118
        fprintf(stderr,
4119
            "Received signal %d: terminating.\n",
4120
            (int) received_sigterm);
4121
        exit (255);
4122
    }
4123
#endif
4124
    exit(0); /* not all OS-es handle main() return value */
4125
    return 0;
4126
}