Statistics
| Branch: | Revision:

ffmpeg / ffmpeg.c @ 3c895fc0

History | View | Annotate | Download (127 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

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

    
41
#include "cmdutils.h"
42

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

    
47
/* select an input stream for an output stream */
48
typedef struct AVStreamMap {
49
    int file_index;
50
    int stream_index;
51
} AVStreamMap;
52

    
53
extern const OptionDef options[];
54

    
55
static void show_help(void);
56
static void show_license(void);
57

    
58
#define MAX_FILES 20
59

    
60
static AVFormatContext *input_files[MAX_FILES];
61
static int nb_input_files = 0;
62

    
63
static AVFormatContext *output_files[MAX_FILES];
64
static int nb_output_files = 0;
65

    
66
static AVStreamMap stream_maps[MAX_FILES];
67
static int nb_stream_maps;
68

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

    
174
static int gop_size = 12;
175
static int intra_only = 0;
176
static int audio_sample_rate = 44100;
177
static int audio_bit_rate = 64000;
178
static int audio_disable = 0;
179
static int audio_channels = 1;
180
static int audio_codec_id = CODEC_ID_NONE;
181

    
182
static int64_t recording_time = 0;
183
static int64_t start_time = 0;
184
static int64_t rec_timestamp = 0;
185
static int file_overwrite = 0;
186
static char *str_title = NULL;
187
static char *str_author = NULL;
188
static char *str_copyright = NULL;
189
static char *str_comment = NULL;
190
static int do_benchmark = 0;
191
static int do_hex_dump = 0;
192
static int do_pkt_dump = 0;
193
static int do_psnr = 0;
194
static int do_vstats = 0;
195
static int do_pass = 0;
196
static int bitexact = 0;
197
static char *pass_logfilename = NULL;
198
static int audio_stream_copy = 0;
199
static int video_stream_copy = 0;
200
static int sync_method= 1;
201

    
202
static int rate_emu = 0;
203

    
204
static char *video_grab_format = "video4linux";
205
static char *video_device = NULL;
206
static int  video_channel = 0;
207
static char *video_standard = "ntsc";
208

    
209
static char *audio_grab_format = "audio_device";
210
static char *audio_device = NULL;
211

    
212
static int using_stdin = 0;
213
static int using_vhook = 0;
214
static int verbose = 1;
215
static int thread_count= 1;
216
static int q_pressed = 0;
217
static int me_range = 0;
218
static int64_t video_size = 0;
219
static int64_t audio_size = 0;
220
static int64_t extra_size = 0;
221

    
222
#define DEFAULT_PASS_LOGFILENAME "ffmpeg2pass"
223

    
224
typedef struct AVOutputStream {
225
    int file_index;          /* file index */
226
    int index;               /* stream index in the output file */
227
    int source_index;        /* AVInputStream index */
228
    AVStream *st;            /* stream in the output file */
229
    int encoding_needed;     /* true if encoding needed for this stream */
230
    int frame_number;
231
    /* input pts and corresponding output pts
232
       for A/V sync */
233
    double sync_ipts;        /* dts from the AVPacket of the demuxer in second units */
234
    int64_t sync_opts;       /* output frame counter, could be changed to some true timestamp */ //FIXME look at frame_number
235
    /* video only */
236
    int video_resample;      /* video_resample and video_crop are mutually exclusive */
237
    AVFrame pict_tmp;      /* temporary image for resampling */
238
    ImgReSampleContext *img_resample_ctx; /* for image resampling */
239

    
240
    int video_crop;          /* video_resample and video_crop are mutually exclusive */
241
    int topBand;             /* cropping area sizes */
242
    int leftBand;
243
    
244
    int video_pad;           /* video_resample and video_pad are mutually exclusive */
245
    int padtop;              /* padding area sizes */
246
    int padbottom;
247
    int padleft;
248
    int padright;
249
    
250
    /* audio only */
251
    int audio_resample;
252
    ReSampleContext *resample; /* for audio resampling */
253
    FifoBuffer fifo;     /* for compression: one audio fifo per codec */
254
    FILE *logfile;
255
} AVOutputStream;
256

    
257
typedef struct AVInputStream {
258
    int file_index;
259
    int index;
260
    AVStream *st;
261
    int discard;             /* true if stream data should be discarded */
262
    int decoding_needed;     /* true if the packets must be decoded in 'raw_fifo' */
263
    int64_t sample_index;      /* current sample */
264

    
265
    int64_t       start;     /* time when read started */
266
    unsigned long frame;     /* current frame */
267
    int64_t       next_pts;  /* synthetic pts for cases where pkt.pts
268
                                is not defined */
269
    int64_t       pts;       /* current pts */
270
} AVInputStream;
271

    
272
typedef struct AVInputFile {
273
    int eof_reached;      /* true if eof reached */
274
    int ist_index;        /* index of first stream in ist_table */
275
    int buffer_size;      /* current total buffer size */
276
    int buffer_size_max;  /* buffer size at which we consider we can stop
277
                             buffering */
278
    int nb_streams;       /* nb streams we are aware of */
279
} AVInputFile;
280

    
281
#ifndef CONFIG_WIN32
282

    
283
/* init terminal so that we can grab keys */
284
static struct termios oldtty;
285

    
286
static void term_exit(void)
287
{
288
    tcsetattr (0, TCSANOW, &oldtty);
289
}
290

    
291
static volatile sig_atomic_t received_sigterm = 0;
292

    
293
static void
294
sigterm_handler(int sig)
295
{
296
    received_sigterm = sig;
297
    term_exit();
298
}
299

    
300
static void term_init(void)
301
{
302
    struct termios tty;
303

    
304
    tcgetattr (0, &tty);
305
    oldtty = tty;
306

    
307
    tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
308
                          |INLCR|IGNCR|ICRNL|IXON);
309
    tty.c_oflag |= OPOST;
310
    tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
311
    tty.c_cflag &= ~(CSIZE|PARENB);
312
    tty.c_cflag |= CS8;
313
    tty.c_cc[VMIN] = 1;
314
    tty.c_cc[VTIME] = 0;
315
    
316
    tcsetattr (0, TCSANOW, &tty);
317

    
318
    signal(SIGINT , sigterm_handler); /* Interrupt (ANSI).  */
319
    signal(SIGQUIT, sigterm_handler); /* Quit (POSIX).  */
320
    signal(SIGTERM, sigterm_handler); /* Termination (ANSI).  */
321
    /*
322
    register a function to be called at normal program termination
323
    */
324
    atexit(term_exit);
325
#ifdef CONFIG_BEOS_NETSERVER
326
    fcntl(0, F_SETFL, fcntl(0, F_GETFL) | O_NONBLOCK);
327
#endif
328
}
329

    
330
/* read a key without blocking */
331
static int read_key(void)
332
{
333
    int n = 1;
334
    unsigned char ch;
335
#ifndef CONFIG_BEOS_NETSERVER
336
    struct timeval tv;
337
    fd_set rfds;
338

    
339
    FD_ZERO(&rfds);
340
    FD_SET(0, &rfds);
341
    tv.tv_sec = 0;
342
    tv.tv_usec = 0;
343
    n = select(1, &rfds, NULL, NULL, &tv);
344
#endif
345
    if (n > 0) {
346
        n = read(0, &ch, 1);
347
        if (n == 1)
348
            return ch;
349

    
350
        return n;
351
    }
352
    return -1;
353
}
354

    
355
static int decode_interrupt_cb(void)
356
{
357
    return q_pressed || (q_pressed = read_key() == 'q');
358
}
359

    
360
#else
361

    
362
static volatile int received_sigterm = 0;
363

    
364
/* no interactive support */
365
static void term_exit(void)
366
{
367
}
368

    
369
static void term_init(void)
370
{
371
}
372

    
373
static int read_key(void)
374
{
375
    return 0;
376
}
377

    
378
#endif
379

    
380
static int read_ffserver_streams(AVFormatContext *s, const char *filename)
381
{
382
    int i, err;
383
    AVFormatContext *ic;
384

    
385
    err = av_open_input_file(&ic, filename, NULL, FFM_PACKET_SIZE, NULL);
386
    if (err < 0)
387
        return err;
388
    /* copy stream format */
389
    s->nb_streams = ic->nb_streams;
390
    for(i=0;i<ic->nb_streams;i++) {
391
        AVStream *st;
392

    
393
        st = av_mallocz(sizeof(AVStream));
394
        memcpy(st, ic->streams[i], sizeof(AVStream));
395
        s->streams[i] = st;
396
    }
397

    
398
    av_close_input_file(ic);
399
    return 0;
400
}
401

    
402
#define MAX_AUDIO_PACKET_SIZE (128 * 1024)
403

    
404
static void do_audio_out(AVFormatContext *s, 
405
                         AVOutputStream *ost, 
406
                         AVInputStream *ist,
407
                         unsigned char *buf, int size)
408
{
409
    uint8_t *buftmp;
410
    static uint8_t *audio_buf = NULL;
411
    static uint8_t *audio_out = NULL;
412
    const int audio_out_size= 4*MAX_AUDIO_PACKET_SIZE;
413

    
414
    int size_out, frame_bytes, ret;
415
    AVCodecContext *enc;
416

    
417
    /* SC: dynamic allocation of buffers */
418
    if (!audio_buf)
419
        audio_buf = av_malloc(2*MAX_AUDIO_PACKET_SIZE);
420
    if (!audio_out)
421
        audio_out = av_malloc(audio_out_size);
422
    if (!audio_buf || !audio_out)
423
        return;               /* Should signal an error ! */
424

    
425
    
426
    enc = &ost->st->codec;
427

    
428
    if (ost->audio_resample) {
429
        buftmp = audio_buf;
430
        size_out = audio_resample(ost->resample, 
431
                                  (short *)buftmp, (short *)buf,
432
                                  size / (ist->st->codec.channels * 2));
433
        size_out = size_out * enc->channels * 2;
434
    } else {
435
        buftmp = buf;
436
        size_out = size;
437
    }
438

    
439
    /* now encode as many frames as possible */
440
    if (enc->frame_size > 1) {
441
        /* output resampled raw samples */
442
        fifo_write(&ost->fifo, buftmp, size_out, 
443
                   &ost->fifo.wptr);
444

    
445
        frame_bytes = enc->frame_size * 2 * enc->channels;
446
        
447
        while (fifo_read(&ost->fifo, audio_buf, frame_bytes, 
448
                     &ost->fifo.rptr) == 0) {
449
            AVPacket pkt;
450
            av_init_packet(&pkt);
451

    
452
            ret = avcodec_encode_audio(enc, audio_out, audio_out_size, 
453
                                       (short *)audio_buf);
454
            audio_size += ret;
455
            pkt.stream_index= ost->index;
456
            pkt.data= audio_out;
457
            pkt.size= ret;
458
            if(enc->coded_frame)
459
                pkt.pts= enc->coded_frame->pts;
460
            pkt.flags |= PKT_FLAG_KEY;
461
            av_interleaved_write_frame(s, &pkt);
462
        }
463
    } else {
464
        AVPacket pkt;
465
        av_init_packet(&pkt);
466
        /* output a pcm frame */
467
        /* XXX: change encoding codec API to avoid this ? */
468
        switch(enc->codec->id) {
469
        case CODEC_ID_PCM_S16LE:
470
        case CODEC_ID_PCM_S16BE:
471
        case CODEC_ID_PCM_U16LE:
472
        case CODEC_ID_PCM_U16BE:
473
            break;
474
        default:
475
            size_out = size_out >> 1;
476
            break;
477
        }
478
        ret = avcodec_encode_audio(enc, audio_out, size_out, 
479
                                   (short *)buftmp);
480
        audio_size += ret;
481
        pkt.stream_index= ost->index;
482
        pkt.data= audio_out;
483
        pkt.size= ret;
484
        if(enc->coded_frame)
485
            pkt.pts= enc->coded_frame->pts;
486
        pkt.flags |= PKT_FLAG_KEY;
487
        av_interleaved_write_frame(s, &pkt);
488
    }
489
}
490

    
491
static void pre_process_video_frame(AVInputStream *ist, AVPicture *picture, void **bufp)
492
{
493
    AVCodecContext *dec;
494
    AVPicture *picture2;
495
    AVPicture picture_tmp;
496
    uint8_t *buf = 0;
497

    
498
    dec = &ist->st->codec;
499

    
500
    /* deinterlace : must be done before any resize */
501
    if (do_deinterlace || using_vhook) {
502
        int size;
503

    
504
        /* create temporary picture */
505
        size = avpicture_get_size(dec->pix_fmt, dec->width, dec->height);
506
        buf = av_malloc(size);
507
        if (!buf)
508
            return;
509
        
510
        picture2 = &picture_tmp;
511
        avpicture_fill(picture2, buf, dec->pix_fmt, dec->width, dec->height);
512

    
513
        if (do_deinterlace){
514
            if(avpicture_deinterlace(picture2, picture, 
515
                                     dec->pix_fmt, dec->width, dec->height) < 0) {
516
                /* if error, do not deinterlace */
517
                av_free(buf);
518
                buf = NULL;
519
                picture2 = picture;
520
            }
521
        } else {
522
            if (img_convert(picture2, dec->pix_fmt, picture, 
523
                            dec->pix_fmt, dec->width, dec->height) < 0) {
524
                /* if error, do not copy */
525
                av_free(buf);
526
                buf = NULL;
527
                picture2 = picture;
528
            }
529
        }
530
    } else {
531
        picture2 = picture;
532
    }
533

    
534
    frame_hook_process(picture2, dec->pix_fmt, dec->width, dec->height);
535

    
536
    if (picture != picture2)
537
        *picture = *picture2;
538
    *bufp = buf;
539
}
540

    
541
/* we begin to correct av delay at this threshold */
542
#define AV_DELAY_MAX 0.100
543

    
544

    
545
/* Expects img to be yuv420 */
546
static void fill_pad_region(AVPicture* img, int height, int width,
547
        int padtop, int padbottom, int padleft, int padright, int *color) {
548
  
549
    int i, y, shift;
550
    uint8_t *optr;
551
    
552
    for (i = 0; i < 3; i++) {
553
        shift = (i == 0) ? 0 : 1;
554
        
555
        if (padtop || padleft) {
556
            memset(img->data[i], color[i], (((img->linesize[i] * padtop) + 
557
                            padleft) >> shift));
558
        }
559

    
560
        if (padleft || padright) {
561
            optr = img->data[i] + (img->linesize[i] * (padtop >> shift)) +
562
                (img->linesize[i] - (padright >> shift));
563

    
564
            for (y = 0; y < ((height - (padtop + padbottom)) >> shift); y++) {
565
                memset(optr, color[i], (padleft + padright) >> shift);
566
                optr += img->linesize[i];
567
            }
568
        }
569
      
570
        if (padbottom) {
571
            optr = img->data[i] + (img->linesize[i] * ((height - padbottom) >> shift));
572
            memset(optr, color[i], ((img->linesize[i] * padbottom) >> shift));
573
        }
574
    }
575
}
576

    
577

    
578
static void do_video_out(AVFormatContext *s, 
579
                         AVOutputStream *ost, 
580
                         AVInputStream *ist,
581
                         AVFrame *in_picture,
582
                         int *frame_size, AVOutputStream *audio_sync)
583
{
584
    int nb_frames, i, ret;
585
    AVFrame *final_picture, *formatted_picture;
586
    AVFrame picture_format_temp, picture_crop_temp;
587
    static uint8_t *video_buffer= NULL;
588
    uint8_t *buf = NULL, *buf1 = NULL;
589
    AVCodecContext *enc, *dec;
590
    enum PixelFormat target_pixfmt;
591
    
592
#define VIDEO_BUFFER_SIZE (1024*1024)
593

    
594
    avcodec_get_frame_defaults(&picture_format_temp);
595
    avcodec_get_frame_defaults(&picture_crop_temp);
596

    
597
    enc = &ost->st->codec;
598
    dec = &ist->st->codec;
599

    
600
    /* by default, we output a single frame */
601
    nb_frames = 1;
602

    
603
    *frame_size = 0;
604

    
605
    if(sync_method){
606
        double vdelta;
607
        vdelta = ost->sync_ipts * enc->frame_rate / enc->frame_rate_base - ost->sync_opts;
608
        //FIXME set to 0.5 after we fix some dts/pts bugs like in avidec.c
609
        if (vdelta < -1.1)
610
            nb_frames = 0;
611
        else if (vdelta > 1.1)
612
            nb_frames = 2;
613
//printf("vdelta:%f, ost->sync_opts:%lld, ost->sync_ipts:%f nb_frames:%d\n", vdelta, ost->sync_opts, ost->sync_ipts, nb_frames);
614
    }
615
    ost->sync_opts+= nb_frames;
616

    
617
    if (nb_frames <= 0) 
618
        return;
619

    
620
    if (!video_buffer)
621
        video_buffer = av_malloc(VIDEO_BUFFER_SIZE);
622
    if (!video_buffer)
623
        return;
624

    
625
    /* convert pixel format if needed */
626
    target_pixfmt = ost->video_resample || ost->video_pad
627
        ? PIX_FMT_YUV420P : enc->pix_fmt;
628
    if (dec->pix_fmt != target_pixfmt) {
629
        int size;
630

    
631
        /* create temporary picture */
632
        size = avpicture_get_size(target_pixfmt, dec->width, dec->height);
633
        buf = av_malloc(size);
634
        if (!buf)
635
            return;
636
        formatted_picture = &picture_format_temp;
637
        avpicture_fill((AVPicture*)formatted_picture, buf, target_pixfmt, dec->width, dec->height);
638
        
639
        if (img_convert((AVPicture*)formatted_picture, target_pixfmt, 
640
                        (AVPicture *)in_picture, dec->pix_fmt, 
641
                        dec->width, dec->height) < 0) {
642

    
643
            if (verbose >= 0)
644
                fprintf(stderr, "pixel format conversion not handled\n");
645

    
646
            goto the_end;
647
        }
648
    } else {
649
        formatted_picture = in_picture;
650
    }
651

    
652
    /* XXX: resampling could be done before raw format conversion in
653
       some cases to go faster */
654
    /* XXX: only works for YUV420P */
655
    if (ost->video_resample) {
656
        final_picture = &ost->pict_tmp;
657
        img_resample(ost->img_resample_ctx, (AVPicture*)final_picture, (AVPicture*)formatted_picture);
658
       
659
        if (ost->padtop || ost->padbottom || ost->padleft || ost->padright) {
660
            fill_pad_region((AVPicture*)final_picture, enc->height, enc->width,
661
                    ost->padtop, ost->padbottom, ost->padleft, ost->padright,
662
                    padcolor);
663
        }
664
        
665
        if (enc->pix_fmt != PIX_FMT_YUV420P) {
666
            int size;
667
            
668
            av_free(buf);
669
            /* create temporary picture */
670
            size = avpicture_get_size(enc->pix_fmt, enc->width, enc->height);
671
            buf = av_malloc(size);
672
            if (!buf)
673
                return;
674
            final_picture = &picture_format_temp;
675
            avpicture_fill((AVPicture*)final_picture, buf, enc->pix_fmt, enc->width, enc->height);
676
        
677
            if (img_convert((AVPicture*)final_picture, enc->pix_fmt, 
678
                            (AVPicture*)&ost->pict_tmp, PIX_FMT_YUV420P, 
679
                            enc->width, enc->height) < 0) {
680

    
681
                if (verbose >= 0)
682
                    fprintf(stderr, "pixel format conversion not handled\n");
683

    
684
                goto the_end;
685
            }
686
        }
687
    } else if (ost->video_crop) {
688
        picture_crop_temp.data[0] = formatted_picture->data[0] +
689
                (ost->topBand * formatted_picture->linesize[0]) + ost->leftBand;
690

    
691
        picture_crop_temp.data[1] = formatted_picture->data[1] +
692
                ((ost->topBand >> 1) * formatted_picture->linesize[1]) +
693
                (ost->leftBand >> 1);
694

    
695
        picture_crop_temp.data[2] = formatted_picture->data[2] +
696
                ((ost->topBand >> 1) * formatted_picture->linesize[2]) +
697
                (ost->leftBand >> 1);
698

    
699
        picture_crop_temp.linesize[0] = formatted_picture->linesize[0];
700
        picture_crop_temp.linesize[1] = formatted_picture->linesize[1];
701
        picture_crop_temp.linesize[2] = formatted_picture->linesize[2];
702
        final_picture = &picture_crop_temp;
703
    } else if (ost->video_pad) {
704
        final_picture = &ost->pict_tmp;
705

    
706
        for (i = 0; i < 3; i++) {
707
            uint8_t *optr, *iptr;
708
            int shift = (i == 0) ? 0 : 1;
709
            int y, yheight;
710
            
711
            /* set offset to start writing image into */
712
            optr = final_picture->data[i] + (((final_picture->linesize[i] * 
713
                            ost->padtop) + ost->padleft) >> shift);
714
            iptr = formatted_picture->data[i];
715

    
716
            yheight = (enc->height - ost->padtop - ost->padbottom) >> shift;
717
            for (y = 0; y < yheight; y++) {
718
                /* copy unpadded image row into padded image row */
719
                memcpy(optr, iptr, formatted_picture->linesize[i]);
720
                optr += final_picture->linesize[i];
721
                iptr += formatted_picture->linesize[i];
722
            }
723
        }
724

    
725
        fill_pad_region((AVPicture*)final_picture, enc->height, enc->width,
726
                ost->padtop, ost->padbottom, ost->padleft, ost->padright,
727
                padcolor);
728
        
729
        if (enc->pix_fmt != PIX_FMT_YUV420P) {
730
            int size;
731

    
732
            av_free(buf);
733
            /* create temporary picture */
734
            size = avpicture_get_size(enc->pix_fmt, enc->width, enc->height);
735
            buf = av_malloc(size);
736
            if (!buf)
737
                return;
738
            final_picture = &picture_format_temp;
739
            avpicture_fill((AVPicture*)final_picture, buf, enc->pix_fmt, enc->width, enc->height);
740

    
741
            if (img_convert((AVPicture*)final_picture, enc->pix_fmt, 
742
                        (AVPicture*)&ost->pict_tmp, PIX_FMT_YUV420P, 
743
                        enc->width, enc->height) < 0) {
744

    
745
                if (verbose >= 0)
746
                    fprintf(stderr, "pixel format conversion not handled\n");
747

    
748
                goto the_end;
749
            }
750
        }
751
    } else {
752
        final_picture = formatted_picture;
753
    }
754
    /* duplicates frame if needed */
755
    /* XXX: pb because no interleaving */
756
    for(i=0;i<nb_frames;i++) {
757
        AVPacket pkt;
758
        av_init_packet(&pkt);
759
        pkt.stream_index= ost->index;
760

    
761
        if (s->oformat->flags & AVFMT_RAWPICTURE) {
762
            /* raw pictures are written as AVPicture structure to
763
               avoid any copies. We support temorarily the older
764
               method. */
765
            AVFrame* old_frame = enc->coded_frame;
766
            enc->coded_frame = dec->coded_frame; //FIXME/XXX remove this hack
767
            pkt.data= (uint8_t *)final_picture;
768
            pkt.size=  sizeof(AVPicture);
769
            if(dec->coded_frame)
770
                pkt.pts= dec->coded_frame->pts;
771
            if(dec->coded_frame && dec->coded_frame->key_frame)
772
                pkt.flags |= PKT_FLAG_KEY;
773

    
774
            av_interleaved_write_frame(s, &pkt);
775
            enc->coded_frame = old_frame;
776
        } else {
777
            AVFrame big_picture;
778

    
779
            big_picture= *final_picture;
780
            /* better than nothing: use input picture interlaced
781
               settings */
782
            big_picture.interlaced_frame = in_picture->interlaced_frame;
783
            if(do_interlace_me || do_interlace_dct){
784
                if(top_field_first == -1)
785
                    big_picture.top_field_first = in_picture->top_field_first;
786
                else
787
                    big_picture.top_field_first = 1;
788
            }
789

    
790
            /* handles sameq here. This is not correct because it may
791
               not be a global option */
792
            if (same_quality) {
793
                big_picture.quality = ist->st->quality;
794
            }else
795
                big_picture.quality = ost->st->quality;
796
            if(!me_threshold)
797
                big_picture.pict_type = 0;
798
            big_picture.pts = AV_NOPTS_VALUE; //FIXME
799
            ret = avcodec_encode_video(enc, 
800
                                       video_buffer, VIDEO_BUFFER_SIZE,
801
                                       &big_picture);
802
            //enc->frame_number = enc->real_pict_num;
803
            if(ret){
804
                pkt.data= video_buffer;
805
                pkt.size= ret;
806
                if(enc->coded_frame)
807
                    pkt.pts= enc->coded_frame->pts;
808
                if(enc->coded_frame && enc->coded_frame->key_frame)
809
                    pkt.flags |= PKT_FLAG_KEY;
810
                av_interleaved_write_frame(s, &pkt);
811
                *frame_size = ret;
812
                //fprintf(stderr,"\nFrame: %3d %3d size: %5d type: %d",
813
                //        enc->frame_number-1, enc->real_pict_num, ret,
814
                //        enc->pict_type);
815
                /* if two pass, output log */
816
                if (ost->logfile && enc->stats_out) {
817
                    fprintf(ost->logfile, "%s", enc->stats_out);
818
                }
819
            }
820
        }
821
        ost->frame_number++;
822
    }
823
 the_end:
824
    av_free(buf);
825
    av_free(buf1);
826
}
827

    
828
static double psnr(double d){
829
    if(d==0) return INFINITY;
830
    return -10.0*log(d)/log(10.0);
831
}
832

    
833
static void do_video_stats(AVFormatContext *os, AVOutputStream *ost, 
834
                           int frame_size)
835
{
836
    static FILE *fvstats=NULL;
837
    char filename[40];
838
    time_t today2;
839
    struct tm *today;
840
    AVCodecContext *enc;
841
    int frame_number;
842
    int64_t ti;
843
    double ti1, bitrate, avg_bitrate;
844
    
845
    if (!fvstats) {
846
        today2 = time(NULL);
847
        today = localtime(&today2);
848
        sprintf(filename, "vstats_%02d%02d%02d.log", today->tm_hour,
849
                                               today->tm_min,
850
                                               today->tm_sec);
851
        fvstats = fopen(filename,"w");
852
        if (!fvstats) {
853
            perror("fopen");
854
            exit(1);
855
        }
856
    }
857
    
858
    ti = MAXINT64;
859
    enc = &ost->st->codec;
860
    if (enc->codec_type == CODEC_TYPE_VIDEO) {
861
        frame_number = ost->frame_number;
862
        fprintf(fvstats, "frame= %5d q= %2.1f ", frame_number, enc->coded_frame->quality/(float)FF_QP2LAMBDA);
863
        if (enc->flags&CODEC_FLAG_PSNR)
864
            fprintf(fvstats, "PSNR= %6.2f ", psnr(enc->coded_frame->error[0]/(enc->width*enc->height*255.0*255.0)));
865
        
866
        fprintf(fvstats,"f_size= %6d ", frame_size);
867
        /* compute pts value */
868
        ti1 = (double)ost->sync_opts *enc->frame_rate_base / enc->frame_rate;
869
        if (ti1 < 0.01)
870
            ti1 = 0.01;
871
    
872
        bitrate = (double)(frame_size * 8) * enc->frame_rate / enc->frame_rate_base / 1000.0;
873
        avg_bitrate = (double)(video_size * 8) / ti1 / 1000.0;
874
        fprintf(fvstats, "s_size= %8.0fkB time= %0.3f br= %7.1fkbits/s avg_br= %7.1fkbits/s ",
875
            (double)video_size / 1024, ti1, bitrate, avg_bitrate);
876
        fprintf(fvstats,"type= %c\n", av_get_pict_type_char(enc->coded_frame->pict_type));        
877
    }
878
}
879

    
880
static void print_report(AVFormatContext **output_files,
881
                         AVOutputStream **ost_table, int nb_ostreams,
882
                         int is_last_report)
883
{
884
    char buf[1024];
885
    AVOutputStream *ost;
886
    AVFormatContext *oc, *os;
887
    int64_t total_size;
888
    AVCodecContext *enc;
889
    int frame_number, vid, i;
890
    double bitrate, ti1, pts;
891
    static int64_t last_time = -1;
892
    
893
    if (!is_last_report) {
894
        int64_t cur_time;
895
        /* display the report every 0.5 seconds */
896
        cur_time = av_gettime();
897
        if (last_time == -1) {
898
            last_time = cur_time;
899
            return;
900
        } 
901
        if ((cur_time - last_time) < 500000)
902
            return;
903
        last_time = cur_time;
904
    }
905

    
906

    
907
    oc = output_files[0];
908

    
909
    total_size = url_ftell(&oc->pb);
910
    
911
    buf[0] = '\0';
912
    ti1 = 1e10;
913
    vid = 0;
914
    for(i=0;i<nb_ostreams;i++) {
915
        ost = ost_table[i];
916
        os = output_files[ost->file_index];
917
        enc = &ost->st->codec;
918
        if (vid && enc->codec_type == CODEC_TYPE_VIDEO) {
919
            sprintf(buf + strlen(buf), "q=%2.1f ",
920
                    enc->coded_frame->quality/(float)FF_QP2LAMBDA);
921
        }
922
        if (!vid && enc->codec_type == CODEC_TYPE_VIDEO) {
923
            frame_number = ost->frame_number;
924
            sprintf(buf + strlen(buf), "frame=%5d q=%2.1f ",
925
                    frame_number, enc->coded_frame ? enc->coded_frame->quality/(float)FF_QP2LAMBDA : 0);
926
            if(is_last_report)
927
                sprintf(buf + strlen(buf), "L");
928
            if (enc->flags&CODEC_FLAG_PSNR){
929
                int j;
930
                double error, error_sum=0;
931
                double scale, scale_sum=0;
932
                char type[3]= {'Y','U','V'};
933
                sprintf(buf + strlen(buf), "PSNR=");
934
                for(j=0; j<3; j++){
935
                    if(is_last_report){
936
                        error= enc->error[j];
937
                        scale= enc->width*enc->height*255.0*255.0*frame_number;
938
                    }else{
939
                        error= enc->coded_frame->error[j];
940
                        scale= enc->width*enc->height*255.0*255.0;
941
                    }
942
                    if(j) scale/=4;
943
                    error_sum += error;
944
                    scale_sum += scale;
945
                    sprintf(buf + strlen(buf), "%c:%2.2f ", type[j], psnr(error/scale));
946
                }
947
                sprintf(buf + strlen(buf), "*:%2.2f ", psnr(error_sum/scale_sum));
948
            }
949
            vid = 1;
950
        }
951
        /* compute min output value */
952
        pts = (double)ost->st->pts.val * ost->st->time_base.num / ost->st->time_base.den;
953
        if ((pts < ti1) && (pts > 0))
954
            ti1 = pts;
955
    }
956
    if (ti1 < 0.01)
957
        ti1 = 0.01;
958
    
959
    if (verbose || is_last_report) {
960
        bitrate = (double)(total_size * 8) / ti1 / 1000.0;
961
        
962
        sprintf(buf + strlen(buf), 
963
            "size=%8.0fkB time=%0.1f bitrate=%6.1fkbits/s",
964
            (double)total_size / 1024, ti1, bitrate);
965
        
966
        if (verbose >= 0)
967
            fprintf(stderr, "%s    \r", buf);
968

    
969
        fflush(stderr);
970
    }
971
        
972
    if (is_last_report && verbose >= 0){
973
        int64_t raw= audio_size + video_size + extra_size;
974
        fprintf(stderr, "\n");
975
        fprintf(stderr, "video:%1.0fkB audio:%1.0fkB global headers:%1.0fkB muxing overhead %f%%\n",
976
                video_size/1024.0,
977
                audio_size/1024.0,
978
                extra_size/1024.0,
979
                100.0*(total_size - raw)/raw
980
        );
981
    }
982
}
983

    
984
/* pkt = NULL means EOF (needed to flush decoder buffers) */
985
static int output_packet(AVInputStream *ist, int ist_index,
986
                         AVOutputStream **ost_table, int nb_ostreams,
987
                         const AVPacket *pkt)
988
{
989
    AVFormatContext *os;
990
    AVOutputStream *ost;
991
    uint8_t *ptr;
992
    int len, ret, i;
993
    uint8_t *data_buf;
994
    int data_size, got_picture;
995
    AVFrame picture;
996
    short samples[AVCODEC_MAX_AUDIO_FRAME_SIZE / 2];
997
    void *buffer_to_free;
998
    
999
    if (pkt && pkt->pts != AV_NOPTS_VALUE) { //FIXME seems redundant, as libavformat does this too
1000
        ist->next_pts = ist->pts = pkt->dts;
1001
    } else {
1002
        ist->pts = ist->next_pts;
1003
    }
1004
    
1005
    if (pkt == NULL) {
1006
        /* EOF handling */
1007
        ptr = NULL;
1008
        len = 0;
1009
        goto handle_eof;
1010
    }
1011

    
1012
    len = pkt->size;
1013
    ptr = pkt->data;
1014
    while (len > 0) {
1015
    handle_eof:
1016
        /* decode the packet if needed */
1017
        data_buf = NULL; /* fail safe */
1018
        data_size = 0;
1019
        if (ist->decoding_needed) {
1020
            switch(ist->st->codec.codec_type) {
1021
            case CODEC_TYPE_AUDIO:
1022
                    /* XXX: could avoid copy if PCM 16 bits with same
1023
                       endianness as CPU */
1024
                ret = avcodec_decode_audio(&ist->st->codec, samples, &data_size,
1025
                                           ptr, len);
1026
                if (ret < 0)
1027
                    goto fail_decode;
1028
                ptr += ret;
1029
                len -= ret;
1030
                /* Some bug in mpeg audio decoder gives */
1031
                /* data_size < 0, it seems they are overflows */
1032
                if (data_size <= 0) {
1033
                    /* no audio frame */
1034
                    continue;
1035
                }
1036
                data_buf = (uint8_t *)samples;
1037
                ist->next_pts += ((int64_t)AV_TIME_BASE/2 * data_size) / 
1038
                    (ist->st->codec.sample_rate * ist->st->codec.channels);
1039
                break;
1040
            case CODEC_TYPE_VIDEO:
1041
                    data_size = (ist->st->codec.width * ist->st->codec.height * 3) / 2;
1042
                    /* XXX: allocate picture correctly */
1043
                    avcodec_get_frame_defaults(&picture);
1044

    
1045
                    ret = avcodec_decode_video(&ist->st->codec, 
1046
                                               &picture, &got_picture, ptr, len);
1047
                    ist->st->quality= picture.quality;
1048
                    if (ret < 0) 
1049
                        goto fail_decode;
1050
                    if (!got_picture) {
1051
                        /* no picture yet */
1052
                        goto discard_packet;
1053
                    }
1054
                    if (ist->st->codec.frame_rate_base != 0) {
1055
                        ist->next_pts += ((int64_t)AV_TIME_BASE * 
1056
                                          ist->st->codec.frame_rate_base) /
1057
                            ist->st->codec.frame_rate;
1058
                    }
1059
                    len = 0;
1060
                    break;
1061
                default:
1062
                    goto fail_decode;
1063
                }
1064
            } else {
1065
                data_buf = ptr;
1066
                data_size = len;
1067
                ret = len;
1068
                len = 0;
1069
            }
1070

    
1071
            buffer_to_free = NULL;
1072
            if (ist->st->codec.codec_type == CODEC_TYPE_VIDEO) {
1073
                pre_process_video_frame(ist, (AVPicture *)&picture, 
1074
                                        &buffer_to_free);
1075
            }
1076

    
1077
            /* frame rate emulation */
1078
            if (ist->st->codec.rate_emu) {
1079
                int64_t pts = av_rescale((int64_t) ist->frame * ist->st->codec.frame_rate_base, 1000000, ist->st->codec.frame_rate);
1080
                int64_t now = av_gettime() - ist->start;
1081
                if (pts > now)
1082
                    usleep(pts - now);
1083

    
1084
                ist->frame++;
1085
            }
1086

    
1087
#if 0
1088
            /* mpeg PTS deordering : if it is a P or I frame, the PTS
1089
               is the one of the next displayed one */
1090
            /* XXX: add mpeg4 too ? */
1091
            if (ist->st->codec.codec_id == CODEC_ID_MPEG1VIDEO) {
1092
                if (ist->st->codec.pict_type != B_TYPE) {
1093
                    int64_t tmp;
1094
                    tmp = ist->last_ip_pts;
1095
                    ist->last_ip_pts  = ist->frac_pts.val;
1096
                    ist->frac_pts.val = tmp;
1097
                }
1098
            }
1099
#endif
1100
            /* if output time reached then transcode raw format, 
1101
               encode packets and output them */
1102
            if (start_time == 0 || ist->pts >= start_time)
1103
                for(i=0;i<nb_ostreams;i++) {
1104
                    int frame_size;
1105

    
1106
                    ost = ost_table[i];
1107
                    if (ost->source_index == ist_index) {
1108
                        os = output_files[ost->file_index];
1109

    
1110
#if 0
1111
                        printf("%d: got pts=%0.3f %0.3f\n", i, 
1112
                               (double)pkt->pts / AV_TIME_BASE, 
1113
                               ((double)ist->pts / AV_TIME_BASE) - 
1114
                               ((double)ost->st->pts.val * ost->time_base.num / ost->time_base.den));
1115
#endif
1116
                        /* set the input output pts pairs */
1117
                        ost->sync_ipts = (double)ist->pts / AV_TIME_BASE;
1118

    
1119
                        if (ost->encoding_needed) {
1120
                            switch(ost->st->codec.codec_type) {
1121
                            case CODEC_TYPE_AUDIO:
1122
                                do_audio_out(os, ost, ist, data_buf, data_size);
1123
                                break;
1124
                            case CODEC_TYPE_VIDEO:
1125
                                /* find an audio stream for synchro */
1126
                                {
1127
                                    int i;
1128
                                    AVOutputStream *audio_sync, *ost1;
1129
                                    audio_sync = NULL;
1130
                                    for(i=0;i<nb_ostreams;i++) {
1131
                                        ost1 = ost_table[i];
1132
                                        if (ost1->file_index == ost->file_index &&
1133
                                            ost1->st->codec.codec_type == CODEC_TYPE_AUDIO) {
1134
                                            audio_sync = ost1;
1135
                                            break;
1136
                                        }
1137
                                    }
1138

    
1139
                                    do_video_out(os, ost, ist, &picture, &frame_size, audio_sync);
1140
                                    video_size += frame_size;
1141
                                    if (do_vstats && frame_size)
1142
                                        do_video_stats(os, ost, frame_size);
1143
                                }
1144
                                break;
1145
                            default:
1146
                                av_abort();
1147
                            }
1148
                        } else {
1149
                            AVFrame avframe; //FIXME/XXX remove this
1150
                            AVPacket opkt;
1151
                            av_init_packet(&opkt);
1152

    
1153
                            /* no reencoding needed : output the packet directly */
1154
                            /* force the input stream PTS */
1155
                        
1156
                            avcodec_get_frame_defaults(&avframe);
1157
                            ost->st->codec.coded_frame= &avframe;
1158
                            avframe.key_frame = pkt->flags & PKT_FLAG_KEY; 
1159

    
1160
                            if(ost->st->codec.codec_type == CODEC_TYPE_AUDIO)
1161
                                audio_size += data_size;
1162
                            else if (ost->st->codec.codec_type == CODEC_TYPE_VIDEO)
1163
                                video_size += data_size;
1164

    
1165
                            opkt.stream_index= ost->index;
1166
                            opkt.data= data_buf;
1167
                            opkt.size= data_size;
1168
                            opkt.pts= pkt->pts; //FIXME ist->pts?
1169
                            opkt.dts= pkt->dts;
1170
                            opkt.flags= pkt->flags;
1171
                            
1172
                            av_interleaved_write_frame(os, &opkt);
1173
                            ost->st->codec.frame_number++;
1174
                            ost->frame_number++;
1175
                        }
1176
                    }
1177
                }
1178
            av_free(buffer_to_free);
1179
        }
1180
 discard_packet:
1181
    return 0;
1182
 fail_decode:
1183
    return -1;
1184
}
1185

    
1186

    
1187
/*
1188
 * The following code is the main loop of the file converter
1189
 */
1190
static int av_encode(AVFormatContext **output_files,
1191
                     int nb_output_files,
1192
                     AVFormatContext **input_files,
1193
                     int nb_input_files,
1194
                     AVStreamMap *stream_maps, int nb_stream_maps)
1195
{
1196
    int ret, i, j, k, n, nb_istreams = 0, nb_ostreams = 0;
1197
    AVFormatContext *is, *os;
1198
    AVCodecContext *codec, *icodec;
1199
    AVOutputStream *ost, **ost_table = NULL;
1200
    AVInputStream *ist, **ist_table = NULL;
1201
    AVInputFile *file_table;
1202
    AVFormatContext *stream_no_data;
1203
    int key;
1204

    
1205
    file_table= (AVInputFile*) av_mallocz(nb_input_files * sizeof(AVInputFile));
1206
    if (!file_table)
1207
        goto fail;
1208

    
1209
    /* input stream init */
1210
    j = 0;
1211
    for(i=0;i<nb_input_files;i++) {
1212
        is = input_files[i];
1213
        file_table[i].ist_index = j;
1214
        file_table[i].nb_streams = is->nb_streams;
1215
        j += is->nb_streams;
1216
    }
1217
    nb_istreams = j;
1218

    
1219
    ist_table = av_mallocz(nb_istreams * sizeof(AVInputStream *));
1220
    if (!ist_table)
1221
        goto fail;
1222
    
1223
    for(i=0;i<nb_istreams;i++) {
1224
        ist = av_mallocz(sizeof(AVInputStream));
1225
        if (!ist)
1226
            goto fail;
1227
        ist_table[i] = ist;
1228
    }
1229
    j = 0;
1230
    for(i=0;i<nb_input_files;i++) {
1231
        is = input_files[i];
1232
        for(k=0;k<is->nb_streams;k++) {
1233
            ist = ist_table[j++];
1234
            ist->st = is->streams[k];
1235
            ist->file_index = i;
1236
            ist->index = k;
1237
            ist->discard = 1; /* the stream is discarded by default
1238
                                 (changed later) */
1239

    
1240
            if (ist->st->codec.rate_emu) {
1241
                ist->start = av_gettime();
1242
                ist->frame = 0;
1243
            }
1244
        }
1245
    }
1246

    
1247
    /* output stream init */
1248
    nb_ostreams = 0;
1249
    for(i=0;i<nb_output_files;i++) {
1250
        os = output_files[i];
1251
        nb_ostreams += os->nb_streams;
1252
    }
1253
    if (nb_stream_maps > 0 && nb_stream_maps != nb_ostreams) {
1254
        fprintf(stderr, "Number of stream maps must match number of output streams\n");
1255
        exit(1);
1256
    }
1257

    
1258
    /* Sanity check the mapping args -- do the input files & streams exist? */
1259
    for(i=0;i<nb_stream_maps;i++) {
1260
        int fi = stream_maps[i].file_index;
1261
        int si = stream_maps[i].stream_index;
1262
        
1263
        if (fi < 0 || fi > nb_input_files - 1 ||
1264
            si < 0 || si > file_table[fi].nb_streams - 1) {
1265
            fprintf(stderr,"Could not find input stream #%d.%d\n", fi, si);
1266
            exit(1);
1267
        }
1268
    }
1269
    
1270
    ost_table = av_mallocz(sizeof(AVOutputStream *) * nb_ostreams);
1271
    if (!ost_table)
1272
        goto fail;
1273
    for(i=0;i<nb_ostreams;i++) {
1274
        ost = av_mallocz(sizeof(AVOutputStream));
1275
        if (!ost)
1276
            goto fail;
1277
        ost_table[i] = ost;
1278
    }
1279
    
1280
    n = 0;
1281
    for(k=0;k<nb_output_files;k++) {
1282
        os = output_files[k];
1283
        for(i=0;i<os->nb_streams;i++) {
1284
            int found;
1285
            ost = ost_table[n++];
1286
            ost->file_index = k;
1287
            ost->index = i;
1288
            ost->st = os->streams[i];
1289
            if (nb_stream_maps > 0) {
1290
                ost->source_index = file_table[stream_maps[n-1].file_index].ist_index + 
1291
                    stream_maps[n-1].stream_index;
1292
                    
1293
                /* Sanity check that the stream types match */
1294
                if (ist_table[ost->source_index]->st->codec.codec_type != ost->st->codec.codec_type) {
1295
                    fprintf(stderr, "Codec type mismatch for mapping #%d.%d -> #%d.%d\n",
1296
                        stream_maps[n-1].file_index, stream_maps[n-1].stream_index,
1297
                        ost->file_index, ost->index);
1298
                    exit(1);
1299
                }
1300
                
1301
            } else {
1302
                /* get corresponding input stream index : we select the first one with the right type */
1303
                found = 0;
1304
                for(j=0;j<nb_istreams;j++) {
1305
                    ist = ist_table[j];
1306
                    if (ist->discard && 
1307
                        ist->st->codec.codec_type == ost->st->codec.codec_type) {
1308
                        ost->source_index = j;
1309
                        found = 1;
1310
                    }
1311
                }
1312
                
1313
                if (!found) {
1314
                    /* try again and reuse existing stream */
1315
                    for(j=0;j<nb_istreams;j++) {
1316
                        ist = ist_table[j];
1317
                        if (ist->st->codec.codec_type == ost->st->codec.codec_type) {
1318
                            ost->source_index = j;
1319
                            found = 1;
1320
                        }
1321
                    }
1322
                    if (!found) {
1323
                        fprintf(stderr, "Could not find input stream matching output stream #%d.%d\n",
1324
                                ost->file_index, ost->index);
1325
                        exit(1);
1326
                    }
1327
                }
1328
            }
1329
            ist = ist_table[ost->source_index];
1330
            ist->discard = 0;
1331
        }
1332
    }
1333

    
1334
    /* for each output stream, we compute the right encoding parameters */
1335
    for(i=0;i<nb_ostreams;i++) {
1336
        ost = ost_table[i];
1337
        ist = ist_table[ost->source_index];
1338

    
1339
        codec = &ost->st->codec;
1340
        icodec = &ist->st->codec;
1341

    
1342
        if (ost->st->stream_copy) {
1343
            /* if stream_copy is selected, no need to decode or encode */
1344
            codec->codec_id = icodec->codec_id;
1345
            codec->codec_type = icodec->codec_type;
1346
            codec->codec_tag = icodec->codec_tag;
1347
            codec->bit_rate = icodec->bit_rate;
1348
            switch(codec->codec_type) {
1349
            case CODEC_TYPE_AUDIO:
1350
                codec->sample_rate = icodec->sample_rate;
1351
                codec->channels = icodec->channels;
1352
                codec->frame_size = icodec->frame_size;
1353
                break;
1354
            case CODEC_TYPE_VIDEO:
1355
                codec->frame_rate = icodec->frame_rate;
1356
                codec->frame_rate_base = icodec->frame_rate_base;
1357
                codec->width = icodec->width;
1358
                codec->height = icodec->height;
1359
                break;
1360
            default:
1361
                av_abort();
1362
            }
1363
        } else {
1364
            switch(codec->codec_type) {
1365
            case CODEC_TYPE_AUDIO:
1366
                if (fifo_init(&ost->fifo, 2 * MAX_AUDIO_PACKET_SIZE))
1367
                    goto fail;
1368
                
1369
                if (codec->channels == icodec->channels &&
1370
                    codec->sample_rate == icodec->sample_rate) {
1371
                    ost->audio_resample = 0;
1372
                } else {
1373
                    if (codec->channels != icodec->channels &&
1374
                        icodec->codec_id == CODEC_ID_AC3) {
1375
                        /* Special case for 5:1 AC3 input */
1376
                        /* and mono or stereo output      */
1377
                        /* Request specific number of channels */
1378
                        icodec->channels = codec->channels;
1379
                        if (codec->sample_rate == icodec->sample_rate)
1380
                            ost->audio_resample = 0;
1381
                        else {
1382
                            ost->audio_resample = 1;
1383
                            ost->resample = audio_resample_init(codec->channels, icodec->channels,
1384
                                                        codec->sample_rate, 
1385
                                                        icodec->sample_rate);
1386
                            if(!ost->resample)
1387
                              {
1388
                                printf("Can't resample.  Aborting.\n");
1389
                                av_abort();
1390
                              }
1391
                        }
1392
                        /* Request specific number of channels */
1393
                        icodec->channels = codec->channels;
1394
                    } else {
1395
                        ost->audio_resample = 1; 
1396
                        ost->resample = audio_resample_init(codec->channels, icodec->channels,
1397
                                                        codec->sample_rate, 
1398
                                                        icodec->sample_rate);
1399
                        if(!ost->resample)
1400
                          {
1401
                            printf("Can't resample.  Aborting.\n");
1402
                            av_abort();
1403
                          }
1404
                    }
1405
                }
1406
                ist->decoding_needed = 1;
1407
                ost->encoding_needed = 1;
1408
                break;
1409
            case CODEC_TYPE_VIDEO:
1410
                if (codec->width == icodec->width &&
1411
                    codec->height == icodec->height &&
1412
                    frame_topBand == 0 &&
1413
                    frame_bottomBand == 0 &&
1414
                    frame_leftBand == 0 &&
1415
                    frame_rightBand == 0 && 
1416
                    frame_padtop == 0 &&
1417
                    frame_padbottom == 0 &&
1418
                    frame_padleft == 0 &&
1419
                    frame_padright == 0)
1420
                {
1421
                    ost->video_resample = 0;
1422
                    ost->video_crop = 0;
1423
                    ost->video_pad = 0;
1424
                } else if ((codec->width == icodec->width -
1425
                                (frame_leftBand + frame_rightBand)) &&
1426
                        (codec->height == icodec->height -
1427
                                (frame_topBand  + frame_bottomBand)))
1428
                {
1429
                    ost->video_resample = 0;
1430
                    ost->video_crop = 1;
1431
                    ost->topBand = frame_topBand;
1432
                    ost->leftBand = frame_leftBand;
1433
                } else if ((codec->width == icodec->width + 
1434
                                (frame_padleft + frame_padright)) &&
1435
                        (codec->height == icodec->height +
1436
                                (frame_padtop + frame_padbottom))) {
1437
                    ost->video_resample = 0;
1438
                    ost->video_crop = 0;
1439
                    ost->video_pad = 1;
1440
                    ost->padtop = frame_padtop;
1441
                    ost->padleft = frame_padleft;
1442
                    ost->padbottom = frame_padbottom;
1443
                    ost->padright = frame_padright;
1444
                    avcodec_get_frame_defaults(&ost->pict_tmp);
1445
                    if( avpicture_alloc( (AVPicture*)&ost->pict_tmp, PIX_FMT_YUV420P,
1446
                                codec->width, codec->height ) )
1447
                        goto fail;
1448
                } else {
1449
                    ost->video_resample = 1;
1450
                    ost->video_crop = 0; // cropping is handled as part of resample
1451
                    avcodec_get_frame_defaults(&ost->pict_tmp);
1452
                    if( avpicture_alloc( (AVPicture*)&ost->pict_tmp, PIX_FMT_YUV420P,
1453
                                         codec->width, codec->height ) )
1454
                        goto fail;
1455

    
1456
                    ost->img_resample_ctx = img_resample_full_init( 
1457
                                      ost->st->codec.width, ost->st->codec.height,
1458
                                      ist->st->codec.width, ist->st->codec.height,
1459
                                      frame_topBand, frame_bottomBand,
1460
                            frame_leftBand, frame_rightBand, 
1461
                            frame_padtop, frame_padbottom, 
1462
                            frame_padleft, frame_padright);
1463
                    
1464
                    ost->padtop = frame_padtop;
1465
                    ost->padleft = frame_padleft;
1466
                    ost->padbottom = frame_padbottom;
1467
                    ost->padright = frame_padright;
1468
                   
1469
                }
1470
                ost->encoding_needed = 1;
1471
                ist->decoding_needed = 1;
1472
                break;
1473
            default:
1474
                av_abort();
1475
            }
1476
            /* two pass mode */
1477
            if (ost->encoding_needed && 
1478
                (codec->flags & (CODEC_FLAG_PASS1 | CODEC_FLAG_PASS2))) {
1479
                char logfilename[1024];
1480
                FILE *f;
1481
                int size;
1482
                char *logbuffer;
1483
                
1484
                snprintf(logfilename, sizeof(logfilename), "%s-%d.log", 
1485
                         pass_logfilename ? 
1486
                         pass_logfilename : DEFAULT_PASS_LOGFILENAME, i);
1487
                if (codec->flags & CODEC_FLAG_PASS1) {
1488
                    f = fopen(logfilename, "w");
1489
                    if (!f) {
1490
                        perror(logfilename);
1491
                        exit(1);
1492
                    }
1493
                    ost->logfile = f;
1494
                } else {
1495
                    /* read the log file */
1496
                    f = fopen(logfilename, "r");
1497
                    if (!f) {
1498
                        perror(logfilename);
1499
                        exit(1);
1500
                    }
1501
                    fseek(f, 0, SEEK_END);
1502
                    size = ftell(f);
1503
                    fseek(f, 0, SEEK_SET);
1504
                    logbuffer = av_malloc(size + 1);
1505
                    if (!logbuffer) {
1506
                        fprintf(stderr, "Could not allocate log buffer\n");
1507
                        exit(1);
1508
                    }
1509
                    size = fread(logbuffer, 1, size, f);
1510
                    fclose(f);
1511
                    logbuffer[size] = '\0';
1512
                    codec->stats_in = logbuffer;
1513
                }
1514
            }
1515
        }
1516
    }
1517

    
1518
    /* dump the file output parameters - cannot be done before in case
1519
       of stream copy */
1520
    for(i=0;i<nb_output_files;i++) {
1521
        dump_format(output_files[i], i, output_files[i]->filename, 1);
1522
    }
1523

    
1524
    /* dump the stream mapping */
1525
    if (verbose >= 0) {
1526
        fprintf(stderr, "Stream mapping:\n");
1527
        for(i=0;i<nb_ostreams;i++) {
1528
            ost = ost_table[i];
1529
            fprintf(stderr, "  Stream #%d.%d -> #%d.%d\n",
1530
                    ist_table[ost->source_index]->file_index,
1531
                    ist_table[ost->source_index]->index,
1532
                    ost->file_index, 
1533
                    ost->index);
1534
        }
1535
    }
1536

    
1537
    /* open each encoder */
1538
    for(i=0;i<nb_ostreams;i++) {
1539
        ost = ost_table[i];
1540
        if (ost->encoding_needed) {
1541
            AVCodec *codec;
1542
            codec = avcodec_find_encoder(ost->st->codec.codec_id);
1543
            if (!codec) {
1544
                fprintf(stderr, "Unsupported codec for output stream #%d.%d\n", 
1545
                        ost->file_index, ost->index);
1546
                exit(1);
1547
            }
1548
            if (avcodec_open(&ost->st->codec, codec) < 0) {
1549
                fprintf(stderr, "Error while opening codec for stream #%d.%d - maybe incorrect parameters such as bit_rate, rate, width or height\n", 
1550
                        ost->file_index, ost->index);
1551
                exit(1);
1552
            }
1553
            extra_size += ost->st->codec.extradata_size;
1554
        }
1555
    }
1556

    
1557
    /* open each decoder */
1558
    for(i=0;i<nb_istreams;i++) {
1559
        ist = ist_table[i];
1560
        if (ist->decoding_needed) {
1561
            AVCodec *codec;
1562
            codec = avcodec_find_decoder(ist->st->codec.codec_id);
1563
            if (!codec) {
1564
                fprintf(stderr, "Unsupported codec (id=%d) for input stream #%d.%d\n", 
1565
                        ist->st->codec.codec_id, ist->file_index, ist->index);
1566
                exit(1);
1567
            }
1568
            if (avcodec_open(&ist->st->codec, codec) < 0) {
1569
                fprintf(stderr, "Error while opening codec for input stream #%d.%d\n", 
1570
                        ist->file_index, ist->index);
1571
                exit(1);
1572
            }
1573
            //if (ist->st->codec.codec_type == CODEC_TYPE_VIDEO)
1574
            //    ist->st->codec.flags |= CODEC_FLAG_REPEAT_FIELD;
1575
        }
1576
    }
1577

    
1578
    /* init pts */
1579
    for(i=0;i<nb_istreams;i++) {
1580
        ist = ist_table[i];
1581
        is = input_files[ist->file_index];
1582
        ist->pts = 0;
1583
        ist->next_pts = 0;
1584
    }
1585
    
1586
    /* compute buffer size max (should use a complete heuristic) */
1587
    for(i=0;i<nb_input_files;i++) {
1588
        file_table[i].buffer_size_max = 2048;
1589
    }
1590

    
1591
    /* open files and write file headers */
1592
    for(i=0;i<nb_output_files;i++) {
1593
        os = output_files[i];
1594
        if (av_write_header(os) < 0) {
1595
            fprintf(stderr, "Could not write header for output file #%d (incorrect codec paramters ?)\n", i);
1596
            ret = -EINVAL;
1597
            goto fail;
1598
        }
1599
    }
1600

    
1601
#ifndef CONFIG_WIN32
1602
    if ( !using_stdin && verbose >= 0) {
1603
        fprintf(stderr, "Press [q] to stop encoding\n");
1604
        url_set_interrupt_cb(decode_interrupt_cb);
1605
    }
1606
#endif
1607
    term_init();
1608

    
1609
    stream_no_data = 0;
1610
    key = -1;
1611

    
1612
    for(; received_sigterm == 0;) {
1613
        int file_index, ist_index;
1614
        AVPacket pkt;
1615
        double pts_min;
1616
        
1617
    redo:
1618
        /* if 'q' pressed, exits */
1619
        if (!using_stdin) {
1620
            if (q_pressed)
1621
                break;
1622
            /* read_key() returns 0 on EOF */
1623
            key = read_key();
1624
            if (key == 'q')
1625
                break;
1626
        }
1627

    
1628
        /* select the stream that we must read now by looking at the
1629
           smallest output pts */
1630
        file_index = -1;
1631
        pts_min = 1e10;
1632
        for(i=0;i<nb_ostreams;i++) {
1633
            double pts;
1634
            ost = ost_table[i];
1635
            os = output_files[ost->file_index];
1636
            ist = ist_table[ost->source_index];
1637
            if(ost->st->codec.codec_type == CODEC_TYPE_VIDEO)
1638
                pts = (double)ost->sync_opts * ost->st->codec.frame_rate_base / ost->st->codec.frame_rate;
1639
            else
1640
                pts = (double)ost->st->pts.val * ost->st->time_base.num / ost->st->time_base.den;
1641
            if (!file_table[ist->file_index].eof_reached && 
1642
                pts < pts_min) {
1643
                pts_min = pts;
1644
                file_index = ist->file_index;
1645
            }
1646
        }
1647
        /* if none, if is finished */
1648
        if (file_index < 0) {
1649
            break;
1650
        }
1651

    
1652
        /* finish if recording time exhausted */
1653
        if (recording_time > 0 && pts_min >= (recording_time / 1000000.0))
1654
            break;
1655

    
1656
        /* read a frame from it and output it in the fifo */
1657
        is = input_files[file_index];
1658
        if (av_read_frame(is, &pkt) < 0) {
1659
            file_table[file_index].eof_reached = 1;
1660
            continue;
1661
        }
1662

    
1663
        if (!pkt.size) {
1664
            stream_no_data = is;
1665
        } else {
1666
            stream_no_data = 0;
1667
        }
1668
        if (do_pkt_dump) {
1669
            av_pkt_dump(stdout, &pkt, do_hex_dump);
1670
        }
1671
        /* the following test is needed in case new streams appear
1672
           dynamically in stream : we ignore them */
1673
        if (pkt.stream_index >= file_table[file_index].nb_streams)
1674
            goto discard_packet;
1675
        ist_index = file_table[file_index].ist_index + pkt.stream_index;
1676
        ist = ist_table[ist_index];
1677
        if (ist->discard)
1678
            goto discard_packet;
1679

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

    
1683
            if (verbose >= 0)
1684
                fprintf(stderr, "Error while decoding stream #%d.%d\n",
1685
                        ist->file_index, ist->index);
1686

    
1687
            av_free_packet(&pkt);
1688
            goto redo;
1689
        }
1690
        
1691
    discard_packet:
1692
        av_free_packet(&pkt);
1693
        
1694
        /* dump report by using the output first video and audio streams */
1695
        print_report(output_files, ost_table, nb_ostreams, 0);
1696
    }
1697

    
1698
    /* at the end of stream, we must flush the decoder buffers */
1699
    for(i=0;i<nb_istreams;i++) {
1700
        ist = ist_table[i];
1701
        if (ist->decoding_needed) {
1702
            output_packet(ist, i, ost_table, nb_ostreams, NULL);
1703
        }
1704
    }
1705

    
1706
    term_exit();
1707

    
1708
    /* write the trailer if needed and close file */
1709
    for(i=0;i<nb_output_files;i++) {
1710
        os = output_files[i];
1711
        av_write_trailer(os);
1712
    }
1713

    
1714
    /* dump report by using the first video and audio streams */
1715
    print_report(output_files, ost_table, nb_ostreams, 1);
1716

    
1717
    /* close each encoder */
1718
    for(i=0;i<nb_ostreams;i++) {
1719
        ost = ost_table[i];
1720
        if (ost->encoding_needed) {
1721
            av_freep(&ost->st->codec.stats_in);
1722
            avcodec_close(&ost->st->codec);
1723
        }
1724
    }
1725
    
1726
    /* close each decoder */
1727
    for(i=0;i<nb_istreams;i++) {
1728
        ist = ist_table[i];
1729
        if (ist->decoding_needed) {
1730
            avcodec_close(&ist->st->codec);
1731
        }
1732
    }
1733

    
1734
    /* finished ! */
1735
    
1736
    ret = 0;
1737
 fail1:
1738
    av_free(file_table);
1739

    
1740
    if (ist_table) {
1741
        for(i=0;i<nb_istreams;i++) {
1742
            ist = ist_table[i];
1743
            av_free(ist);
1744
        }
1745
        av_free(ist_table);
1746
    }
1747
    if (ost_table) {
1748
        for(i=0;i<nb_ostreams;i++) {
1749
            ost = ost_table[i];
1750
            if (ost) {
1751
                if (ost->logfile) {
1752
                    fclose(ost->logfile);
1753
                    ost->logfile = NULL;
1754
                }
1755
                fifo_free(&ost->fifo); /* works even if fifo is not
1756
                                          initialized but set to zero */
1757
                av_free(ost->pict_tmp.data[0]);
1758
                if (ost->video_resample)
1759
                    img_resample_close(ost->img_resample_ctx);
1760
                if (ost->audio_resample)
1761
                    audio_resample_close(ost->resample);
1762
                av_free(ost);
1763
            }
1764
        }
1765
        av_free(ost_table);
1766
    }
1767
    return ret;
1768
 fail:
1769
    ret = -ENOMEM;
1770
    goto fail1;
1771
}
1772

    
1773
#if 0
1774
int file_read(const char *filename)
1775
{
1776
    URLContext *h;
1777
    unsigned char buffer[1024];
1778
    int len, i;
1779

1780
    if (url_open(&h, filename, O_RDONLY) < 0) {
1781
        printf("could not open '%s'\n", filename);
1782
        return -1;
1783
    }
1784
    for(;;) {
1785
        len = url_read(h, buffer, sizeof(buffer));
1786
        if (len <= 0)
1787
            break;
1788
        for(i=0;i<len;i++) putchar(buffer[i]);
1789
    }
1790
    url_close(h);
1791
    return 0;
1792
}
1793
#endif
1794

    
1795
static void opt_image_format(const char *arg)
1796
{
1797
    AVImageFormat *f;
1798
    
1799
    for(f = first_image_format; f != NULL; f = f->next) {
1800
        if (!strcmp(arg, f->name))
1801
            break;
1802
    }
1803
    if (!f) {
1804
        fprintf(stderr, "Unknown image format: '%s'\n", arg);
1805
        exit(1);
1806
    }
1807
    image_format = f;
1808
}
1809

    
1810
static void opt_format(const char *arg)
1811
{
1812
    /* compatibility stuff for pgmyuv */
1813
    if (!strcmp(arg, "pgmyuv")) {
1814
        opt_image_format(arg);
1815
        arg = "image";
1816
    }
1817

    
1818
    file_iformat = av_find_input_format(arg);
1819
    file_oformat = guess_format(arg, NULL, NULL);
1820
    if (!file_iformat && !file_oformat) {
1821
        fprintf(stderr, "Unknown input or output format: %s\n", arg);
1822
        exit(1);
1823
    }
1824
}
1825

    
1826
static void opt_video_bitrate(const char *arg)
1827
{
1828
    video_bit_rate = atoi(arg) * 1000;
1829
}
1830

    
1831
static void opt_video_bitrate_tolerance(const char *arg)
1832
{
1833
    video_bit_rate_tolerance = atoi(arg) * 1000;
1834
}
1835

    
1836
static void opt_video_bitrate_max(const char *arg)
1837
{
1838
    video_rc_max_rate = atoi(arg) * 1000;
1839
}
1840

    
1841
static void opt_video_bitrate_min(const char *arg)
1842
{
1843
    video_rc_min_rate = atoi(arg) * 1000;
1844
}
1845

    
1846
static void opt_video_buffer_size(const char *arg)
1847
{
1848
    video_rc_buffer_size = atoi(arg) * 8*1024;
1849
}
1850

    
1851
static void opt_video_rc_eq(char *arg)
1852
{
1853
    video_rc_eq = arg;
1854
}
1855

    
1856
static void opt_video_rc_override_string(char *arg)
1857
{
1858
    video_rc_override_string = arg;
1859
}
1860

    
1861

    
1862
static void opt_workaround_bugs(const char *arg)
1863
{
1864
    workaround_bugs = atoi(arg);
1865
}
1866

    
1867
static void opt_dct_algo(const char *arg)
1868
{
1869
    dct_algo = atoi(arg);
1870
}
1871

    
1872
static void opt_idct_algo(const char *arg)
1873
{
1874
    idct_algo = atoi(arg);
1875
}
1876

    
1877
static void opt_me_threshold(const char *arg)
1878
{
1879
    me_threshold = atoi(arg);
1880
}
1881

    
1882
static void opt_mb_threshold(const char *arg)
1883
{
1884
    mb_threshold = atoi(arg);
1885
}
1886

    
1887
static void opt_error_resilience(const char *arg)
1888
{
1889
    error_resilience = atoi(arg);
1890
}
1891

    
1892
static void opt_error_concealment(const char *arg)
1893
{
1894
    error_concealment = atoi(arg);
1895
}
1896

    
1897
static void opt_debug(const char *arg)
1898
{
1899
    debug = atoi(arg);
1900
}
1901

    
1902
static void opt_vismv(const char *arg)
1903
{
1904
    debug_mv = atoi(arg);
1905
}
1906
    
1907
static void opt_verbose(const char *arg)
1908
{
1909
    verbose = atoi(arg);
1910
    av_log_set_level(atoi(arg));
1911
}
1912

    
1913
static void opt_sync_method(const char *arg)
1914
{
1915
    sync_method = atoi(arg);
1916
}
1917

    
1918
static void opt_frame_rate(const char *arg)
1919
{
1920
    if (parse_frame_rate(&frame_rate, &frame_rate_base, arg) < 0) {
1921
        fprintf(stderr, "Incorrect frame rate\n");
1922
        exit(1);
1923
    }
1924
}
1925

    
1926
static void opt_frame_crop_top(const char *arg)
1927
{
1928
    frame_topBand = atoi(arg); 
1929
    if (frame_topBand < 0) {
1930
        fprintf(stderr, "Incorrect top crop size\n");
1931
        exit(1);
1932
    }
1933
    if ((frame_topBand % 2) != 0) {
1934
        fprintf(stderr, "Top crop size must be a multiple of 2\n");
1935
        exit(1);
1936
    }
1937
    if ((frame_topBand) >= frame_height){
1938
            fprintf(stderr, "Vertical crop dimensions are outside the range of the original image.\nRemember to crop first and scale second.\n");
1939
        exit(1);
1940
    }
1941
    frame_height -= frame_topBand;
1942
}
1943

    
1944
static void opt_frame_crop_bottom(const char *arg)
1945
{
1946
    frame_bottomBand = atoi(arg);
1947
    if (frame_bottomBand < 0) {
1948
        fprintf(stderr, "Incorrect bottom crop size\n");
1949
        exit(1);
1950
    }
1951
    if ((frame_bottomBand % 2) != 0) {
1952
        fprintf(stderr, "Bottom crop size must be a multiple of 2\n");
1953
        exit(1);        
1954
    }
1955
    if ((frame_bottomBand) >= frame_height){
1956
            fprintf(stderr, "Vertical crop dimensions are outside the range of the original image.\nRemember to crop first and scale second.\n");
1957
        exit(1);
1958
    }
1959
    frame_height -= frame_bottomBand;
1960
}
1961

    
1962
static void opt_frame_crop_left(const char *arg)
1963
{
1964
    frame_leftBand = atoi(arg);
1965
    if (frame_leftBand < 0) {
1966
        fprintf(stderr, "Incorrect left crop size\n");
1967
        exit(1);
1968
    }
1969
    if ((frame_leftBand % 2) != 0) {
1970
        fprintf(stderr, "Left crop size must be a multiple of 2\n");
1971
        exit(1);
1972
    }
1973
    if ((frame_leftBand) >= frame_width){
1974
            fprintf(stderr, "Horizontal crop dimensions are outside the range of the original image.\nRemember to crop first and scale second.\n");
1975
        exit(1);
1976
    }
1977
    frame_width -= frame_leftBand;
1978
}
1979

    
1980
static void opt_frame_crop_right(const char *arg)
1981
{
1982
    frame_rightBand = atoi(arg);
1983
    if (frame_rightBand < 0) {
1984
        fprintf(stderr, "Incorrect right crop size\n");
1985
        exit(1);
1986
    }
1987
    if ((frame_rightBand % 2) != 0) {
1988
        fprintf(stderr, "Right crop size must be a multiple of 2\n");
1989
        exit(1);        
1990
    }
1991
    if ((frame_rightBand) >= frame_width){
1992
            fprintf(stderr, "Horizontal crop dimensions are outside the range of the original image.\nRemember to crop first and scale second.\n");
1993
        exit(1);
1994
    }
1995
    frame_width -= frame_rightBand;
1996
}
1997

    
1998
static void opt_frame_size(const char *arg)
1999
{
2000
    if (parse_image_size(&frame_width, &frame_height, arg) < 0) {
2001
        fprintf(stderr, "Incorrect frame size\n");
2002
        exit(1);
2003
    }
2004
    if ((frame_width % 2) != 0 || (frame_height % 2) != 0) {
2005
        fprintf(stderr, "Frame size must be a multiple of 2\n");
2006
        exit(1);
2007
    }
2008
}
2009

    
2010

    
2011
#define SCALEBITS 10
2012
#define ONE_HALF  (1 << (SCALEBITS - 1))
2013
#define FIX(x)          ((int) ((x) * (1<<SCALEBITS) + 0.5))
2014

    
2015
#define RGB_TO_Y(r, g, b) \
2016
((FIX(0.29900) * (r) + FIX(0.58700) * (g) + \
2017
  FIX(0.11400) * (b) + ONE_HALF) >> SCALEBITS)
2018

    
2019
#define RGB_TO_U(r1, g1, b1, shift)\
2020
(((- FIX(0.16874) * r1 - FIX(0.33126) * g1 +         \
2021
     FIX(0.50000) * b1 + (ONE_HALF << shift) - 1) >> (SCALEBITS + shift)) + 128)
2022

    
2023
#define RGB_TO_V(r1, g1, b1, shift)\
2024
(((FIX(0.50000) * r1 - FIX(0.41869) * g1 -           \
2025
   FIX(0.08131) * b1 + (ONE_HALF << shift) - 1) >> (SCALEBITS + shift)) + 128)
2026

    
2027
static void opt_pad_color(const char *arg) {
2028
    /* Input is expected to be six hex digits similar to
2029
       how colors are expressed in html tags (but without the #) */
2030
    int rgb = strtol(arg, NULL, 16);
2031
    int r,g,b;
2032
    
2033
    r = (rgb >> 16); 
2034
    g = ((rgb >> 8) & 255);
2035
    b = (rgb & 255);
2036

    
2037
    padcolor[0] = RGB_TO_Y(r,g,b);
2038
    padcolor[1] = RGB_TO_U(r,g,b,0);
2039
    padcolor[2] = RGB_TO_V(r,g,b,0);
2040
}
2041

    
2042
static void opt_frame_pad_top(const char *arg)
2043
{
2044
    frame_padtop = atoi(arg); 
2045
    if (frame_padtop < 0) {
2046
        fprintf(stderr, "Incorrect top pad size\n");
2047
        exit(1);
2048
    }
2049
    if ((frame_padtop % 2) != 0) {
2050
        fprintf(stderr, "Top pad size must be a multiple of 2\n");
2051
        exit(1);
2052
    }
2053
}
2054

    
2055
static void opt_frame_pad_bottom(const char *arg)
2056
{
2057
    frame_padbottom = atoi(arg); 
2058
    if (frame_padbottom < 0) {
2059
        fprintf(stderr, "Incorrect bottom pad size\n");
2060
        exit(1);
2061
    }
2062
    if ((frame_padbottom % 2) != 0) {
2063
        fprintf(stderr, "Bottom pad size must be a multiple of 2\n");
2064
        exit(1);
2065
    }
2066
}
2067

    
2068

    
2069
static void opt_frame_pad_left(const char *arg)
2070
{
2071
    frame_padleft = atoi(arg); 
2072
    if (frame_padleft < 0) {
2073
        fprintf(stderr, "Incorrect left pad size\n");
2074
        exit(1);
2075
    }
2076
    if ((frame_padleft % 2) != 0) {
2077
        fprintf(stderr, "Left pad size must be a multiple of 2\n");
2078
        exit(1);
2079
    }
2080
}
2081

    
2082

    
2083
static void opt_frame_pad_right(const char *arg)
2084
{
2085
    frame_padright = atoi(arg); 
2086
    if (frame_padright < 0) {
2087
        fprintf(stderr, "Incorrect right pad size\n");
2088
        exit(1);
2089
    }
2090
    if ((frame_padright % 2) != 0) {
2091
        fprintf(stderr, "Right pad size must be a multiple of 2\n");
2092
        exit(1);
2093
    }
2094
}
2095

    
2096

    
2097
static void opt_frame_pix_fmt(const char *arg)
2098
{
2099
    frame_pix_fmt = avcodec_get_pix_fmt(arg);
2100
}
2101

    
2102
static void opt_frame_aspect_ratio(const char *arg)
2103
{
2104
    int x = 0, y = 0;
2105
    double ar = 0;
2106
    const char *p;
2107
    
2108
    p = strchr(arg, ':');
2109
    if (p) {
2110
        x = strtol(arg, (char **)&arg, 10);
2111
        if (arg == p)
2112
            y = strtol(arg+1, (char **)&arg, 10);
2113
        if (x > 0 && y > 0)
2114
            ar = (double)x / (double)y;
2115
    } else
2116
        ar = strtod(arg, (char **)&arg);
2117

    
2118
    if (!ar) {
2119
        fprintf(stderr, "Incorrect aspect ratio specification.\n");
2120
        exit(1);
2121
    }
2122
    frame_aspect_ratio = ar;
2123
}
2124

    
2125
static void opt_gop_size(const char *arg)
2126
{
2127
    gop_size = atoi(arg);
2128
}
2129

    
2130
static void opt_b_frames(const char *arg)
2131
{
2132
    b_frames = atoi(arg);
2133
    if (b_frames > FF_MAX_B_FRAMES) {
2134
        fprintf(stderr, "\nCannot have more than %d B frames, increase FF_MAX_B_FRAMES.\n", FF_MAX_B_FRAMES);
2135
        exit(1);
2136
    } else if (b_frames < 1) {
2137
        fprintf(stderr, "\nNumber of B frames must be higher than 0\n");
2138
        exit(1);
2139
    }
2140
}
2141

    
2142
static void opt_mb_decision(const char *arg)
2143
{
2144
    mb_decision = atoi(arg);
2145
}
2146

    
2147
static void opt_mb_cmp(const char *arg)
2148
{
2149
    mb_cmp = atoi(arg);
2150
}
2151

    
2152
static void opt_ildct_cmp(const char *arg)
2153
{
2154
    ildct_cmp = atoi(arg);
2155
}
2156

    
2157
static void opt_sub_cmp(const char *arg)
2158
{
2159
    sub_cmp = atoi(arg);
2160
}
2161

    
2162
static void opt_cmp(const char *arg)
2163
{
2164
    cmp = atoi(arg);
2165
}
2166

    
2167
static void opt_pre_cmp(const char *arg)
2168
{
2169
    pre_cmp = atoi(arg);
2170
}
2171

    
2172
static void opt_pre_me(const char *arg)
2173
{
2174
    pre_me = atoi(arg);
2175
}
2176

    
2177
static void opt_lumi_mask(const char *arg)
2178
{
2179
    lumi_mask = atof(arg);
2180
}
2181

    
2182
static void opt_dark_mask(const char *arg)
2183
{
2184
    dark_mask = atof(arg);
2185
}
2186

    
2187
static void opt_scplx_mask(const char *arg)
2188
{
2189
    scplx_mask = atof(arg);
2190
}
2191

    
2192
static void opt_tcplx_mask(const char *arg)
2193
{
2194
    tcplx_mask = atof(arg);
2195
}
2196

    
2197
static void opt_p_mask(const char *arg)
2198
{
2199
    p_mask = atof(arg);
2200
}
2201

    
2202
static void opt_qscale(const char *arg)
2203
{
2204
    video_qscale = atof(arg);
2205
    if (video_qscale < 0.01 ||
2206
        video_qscale > 255) {
2207
        fprintf(stderr, "qscale must be >= 0.01 and <= 255\n");
2208
        exit(1);
2209
    }
2210
}
2211

    
2212
static void opt_lmax(const char *arg)
2213
{
2214
    video_lmax = atof(arg)*FF_QP2LAMBDA;
2215
}
2216

    
2217
static void opt_lmin(const char *arg)
2218
{
2219
    video_lmin = atof(arg)*FF_QP2LAMBDA;
2220
}
2221

    
2222
static void opt_qmin(const char *arg)
2223
{
2224
    video_qmin = atoi(arg);
2225
    if (video_qmin < 0 ||
2226
        video_qmin > 31) {
2227
        fprintf(stderr, "qmin must be >= 1 and <= 31\n");
2228
        exit(1);
2229
    }
2230
}
2231

    
2232
static void opt_qmax(const char *arg)
2233
{
2234
    video_qmax = atoi(arg);
2235
    if (video_qmax < 0 ||
2236
        video_qmax > 31) {
2237
        fprintf(stderr, "qmax must be >= 1 and <= 31\n");
2238
        exit(1);
2239
    }
2240
}
2241

    
2242
static void opt_mb_qmin(const char *arg)
2243
{
2244
    video_mb_qmin = atoi(arg);
2245
    if (video_mb_qmin < 0 ||
2246
        video_mb_qmin > 31) {
2247
        fprintf(stderr, "qmin must be >= 1 and <= 31\n");
2248
        exit(1);
2249
    }
2250
}
2251

    
2252
static void opt_mb_qmax(const char *arg)
2253
{
2254
    video_mb_qmax = atoi(arg);
2255
    if (video_mb_qmax < 0 ||
2256
        video_mb_qmax > 31) {
2257
        fprintf(stderr, "qmax must be >= 1 and <= 31\n");
2258
        exit(1);
2259
    }
2260
}
2261

    
2262
static void opt_qdiff(const char *arg)
2263
{
2264
    video_qdiff = atoi(arg);
2265
    if (video_qdiff < 0 ||
2266
        video_qdiff > 31) {
2267
        fprintf(stderr, "qdiff must be >= 1 and <= 31\n");
2268
        exit(1);
2269
    }
2270
}
2271

    
2272
static void opt_qblur(const char *arg)
2273
{
2274
    video_qblur = atof(arg);
2275
}
2276

    
2277
static void opt_qcomp(const char *arg)
2278
{
2279
    video_qcomp = atof(arg);
2280
}
2281

    
2282
static void opt_rc_initial_cplx(const char *arg)
2283
{
2284
    video_rc_initial_cplx = atof(arg);
2285
}
2286
static void opt_b_qfactor(const char *arg)
2287
{
2288
    video_b_qfactor = atof(arg);
2289
}
2290
static void opt_i_qfactor(const char *arg)
2291
{
2292
    video_i_qfactor = atof(arg);
2293
}
2294
static void opt_b_qoffset(const char *arg)
2295
{
2296
    video_b_qoffset = atof(arg);
2297
}
2298
static void opt_i_qoffset(const char *arg)
2299
{
2300
    video_i_qoffset = atof(arg);
2301
}
2302

    
2303
static void opt_ibias(const char *arg)
2304
{
2305
    video_intra_quant_bias = atoi(arg);
2306
}
2307
static void opt_pbias(const char *arg)
2308
{
2309
    video_inter_quant_bias = atoi(arg);
2310
}
2311

    
2312
static void opt_packet_size(const char *arg)
2313
{
2314
    packet_size= atoi(arg);
2315
}
2316

    
2317
static void opt_error_rate(const char *arg)
2318
{
2319
    error_rate= atoi(arg);
2320
}
2321

    
2322
static void opt_strict(const char *arg)
2323
{
2324
    strict= atoi(arg);
2325
}
2326

    
2327
static void opt_top_field_first(const char *arg)
2328
{
2329
    top_field_first= atoi(arg);
2330
}
2331

    
2332
static void opt_noise_reduction(const char *arg)
2333
{
2334
    noise_reduction= atoi(arg);
2335
}
2336

    
2337
static void opt_qns(const char *arg)
2338
{
2339
    qns= atoi(arg);
2340
}
2341

    
2342
static void opt_sc_threshold(const char *arg)
2343
{
2344
    sc_threshold= atoi(arg);
2345
}
2346

    
2347
static void opt_me_range(const char *arg)
2348
{
2349
    me_range = atoi(arg);
2350
}
2351

    
2352
static void opt_thread_count(const char *arg)
2353
{
2354
    thread_count= atoi(arg);
2355
#if !defined(HAVE_PTHREADS) && !defined(HAVE_W32THREADS)
2356
    if (verbose >= 0)
2357
        fprintf(stderr, "Warning: not compiled with thread support, using thread emulation\n");
2358
#endif
2359
}
2360

    
2361
static void opt_audio_bitrate(const char *arg)
2362
{
2363
    audio_bit_rate = atoi(arg) * 1000;
2364
}
2365

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

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

    
2376
static void opt_video_device(const char *arg)
2377
{
2378
    video_device = av_strdup(arg);
2379
}
2380

    
2381
static void opt_video_channel(const char *arg)
2382
{
2383
    video_channel = strtol(arg, NULL, 0);
2384
}
2385

    
2386
static void opt_video_standard(const char *arg)
2387
{
2388
    video_standard = av_strdup(arg);
2389
}
2390

    
2391
static void opt_audio_device(const char *arg)
2392
{
2393
    audio_device = av_strdup(arg);
2394
}
2395

    
2396
static void opt_dv1394(const char *arg)
2397
{
2398
    video_grab_format = "dv1394";
2399
    audio_grab_format = NULL;
2400
}
2401

    
2402
static void opt_audio_codec(const char *arg)
2403
{
2404
    AVCodec *p;
2405

    
2406
    if (!strcmp(arg, "copy")) {
2407
        audio_stream_copy = 1;
2408
    } else {
2409
        p = first_avcodec;
2410
        while (p) {
2411
            if (!strcmp(p->name, arg) && p->type == CODEC_TYPE_AUDIO)
2412
                break;
2413
            p = p->next;
2414
        }
2415
        if (p == NULL) {
2416
            fprintf(stderr, "Unknown audio codec '%s'\n", arg);
2417
            exit(1);
2418
        } else {
2419
            audio_codec_id = p->id;
2420
        }
2421
    }
2422
}
2423

    
2424
static void add_frame_hooker(const char *arg)
2425
{
2426
    int argc = 0;
2427
    char *argv[64];
2428
    int i;
2429
    char *args = av_strdup(arg);
2430

    
2431
    using_vhook = 1;
2432

    
2433
    argv[0] = strtok(args, " ");
2434
    while (argc < 62 && (argv[++argc] = strtok(NULL, " "))) {
2435
    }
2436

    
2437
    i = frame_hook_add(argc, argv);
2438

    
2439
    if (i != 0) {
2440
        fprintf(stderr, "Failed to add video hook function: %s\n", arg);
2441
        exit(1);
2442
    }
2443
}
2444

    
2445
const char *motion_str[] = {
2446
    "zero",
2447
    "full",
2448
    "log",
2449
    "phods",
2450
    "epzs",
2451
    "x1",
2452
    NULL,
2453
};
2454

    
2455
static void opt_motion_estimation(const char *arg)
2456
{
2457
    const char **p;
2458
    p = motion_str;
2459
    for(;;) {
2460
        if (!*p) {
2461
            fprintf(stderr, "Unknown motion estimation method '%s'\n", arg);
2462
            exit(1);
2463
        }
2464
        if (!strcmp(*p, arg))
2465
            break;
2466
        p++;
2467
    }
2468
    me_method = (p - motion_str) + 1;
2469
}
2470

    
2471
static void opt_video_codec(const char *arg)
2472
{
2473
    AVCodec *p;
2474

    
2475
    if (!strcmp(arg, "copy")) {
2476
        video_stream_copy = 1;
2477
    } else {
2478
        p = first_avcodec;
2479
        while (p) {
2480
            if (!strcmp(p->name, arg) && p->type == CODEC_TYPE_VIDEO)
2481
                break;
2482
            p = p->next;
2483
        }
2484
        if (p == NULL) {
2485
            fprintf(stderr, "Unknown video codec '%s'\n", arg);
2486
            exit(1);
2487
        } else {
2488
            video_codec_id = p->id;
2489
        }
2490
    }
2491
}
2492

    
2493
static void opt_map(const char *arg)
2494
{
2495
    AVStreamMap *m;
2496
    const char *p;
2497

    
2498
    p = arg;
2499
    m = &stream_maps[nb_stream_maps++];
2500

    
2501
    m->file_index = strtol(arg, (char **)&p, 0);
2502
    if (*p)
2503
        p++;
2504

    
2505
    m->stream_index = strtol(p, (char **)&p, 0);
2506
}
2507

    
2508
static void opt_recording_time(const char *arg)
2509
{
2510
    recording_time = parse_date(arg, 1);
2511
}
2512

    
2513
static void opt_start_time(const char *arg)
2514
{
2515
    start_time = parse_date(arg, 1);
2516
}
2517

    
2518
static void opt_rec_timestamp(const char *arg)
2519
{
2520
    rec_timestamp = parse_date(arg, 0) / 1000000;
2521
}
2522

    
2523
static void opt_input_file(const char *filename)
2524
{
2525
    AVFormatContext *ic;
2526
    AVFormatParameters params, *ap = &params;
2527
    int err, i, ret, rfps, rfps_base;
2528

    
2529
    if (!strcmp(filename, "-"))
2530
        filename = "pipe:";
2531

    
2532
    using_stdin |= !strcmp(filename, "pipe:" ) || 
2533
                   !strcmp( filename, "/dev/stdin" );
2534

    
2535
    /* get default parameters from command line */
2536
    memset(ap, 0, sizeof(*ap));
2537
    ap->sample_rate = audio_sample_rate;
2538
    ap->channels = audio_channels;
2539
    ap->frame_rate = frame_rate;
2540
    ap->frame_rate_base = frame_rate_base;
2541
    ap->width = frame_width + frame_padleft + frame_padright;
2542
    ap->height = frame_height + frame_padtop + frame_padbottom;
2543
    ap->image_format = image_format;
2544
    ap->pix_fmt = frame_pix_fmt;
2545

    
2546
    /* open the input file with generic libav function */
2547
    err = av_open_input_file(&ic, filename, file_iformat, 0, ap);
2548
    if (err < 0) {
2549
        print_error(filename, err);
2550
        exit(1);
2551
    }
2552
    
2553
    /* If not enough info to get the stream parameters, we decode the
2554
       first frames to get it. (used in mpeg case for example) */
2555
    ret = av_find_stream_info(ic);
2556
    if (ret < 0 && verbose >= 0) {
2557
        fprintf(stderr, "%s: could not find codec parameters\n", filename);
2558
        exit(1);
2559
    }
2560

    
2561
    /* if seeking requested, we execute it */
2562
    if (start_time != 0) {
2563
        int64_t timestamp;
2564

    
2565
        timestamp = start_time;
2566
        /* add the stream start time */
2567
        if (ic->start_time != AV_NOPTS_VALUE)
2568
            timestamp += ic->start_time;
2569
        ret = av_seek_frame(ic, -1, timestamp);
2570
        if (ret < 0) {
2571
            fprintf(stderr, "%s: could not seek to position %0.3f\n", 
2572
                    filename, (double)timestamp / AV_TIME_BASE);
2573
        }
2574
        /* reset seek info */
2575
        start_time = 0;
2576
    }
2577

    
2578
    /* update the current parameters so that they match the one of the input stream */
2579
    for(i=0;i<ic->nb_streams;i++) {
2580
        AVCodecContext *enc = &ic->streams[i]->codec;
2581
#if defined(HAVE_PTHREADS) || defined(HAVE_W32THREADS)
2582
        if(thread_count>1)
2583
            avcodec_thread_init(enc, thread_count);
2584
#endif
2585
        enc->thread_count= thread_count;
2586
        switch(enc->codec_type) {
2587
        case CODEC_TYPE_AUDIO:
2588
            //fprintf(stderr, "\nInput Audio channels: %d", enc->channels);
2589
            audio_channels = enc->channels;
2590
            audio_sample_rate = enc->sample_rate;
2591
            break;
2592
        case CODEC_TYPE_VIDEO:
2593
            frame_height = enc->height;
2594
            frame_width = enc->width;
2595
            frame_aspect_ratio = av_q2d(enc->sample_aspect_ratio) * enc->width / enc->height;
2596
            frame_pix_fmt = enc->pix_fmt;
2597
            rfps      = ic->streams[i]->r_frame_rate;
2598
            rfps_base = ic->streams[i]->r_frame_rate_base;
2599
            enc->workaround_bugs = workaround_bugs;
2600
            enc->error_resilience = error_resilience; 
2601
            enc->error_concealment = error_concealment; 
2602
            enc->idct_algo = idct_algo;
2603
            enc->debug = debug;
2604
            enc->debug_mv = debug_mv;            
2605
            if(bitexact)
2606
                enc->flags|= CODEC_FLAG_BITEXACT;
2607
            if(me_threshold)
2608
                enc->debug |= FF_DEBUG_MV;
2609

    
2610
            assert(enc->frame_rate_base == rfps_base); // should be true for now
2611
            if (enc->frame_rate != rfps) { 
2612

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

    
2617
                    (float)rfps / rfps_base);
2618
            }
2619
            /* update the current frame rate to match the stream frame rate */
2620
            frame_rate      = rfps;
2621
            frame_rate_base = rfps_base;
2622

    
2623
            enc->rate_emu = rate_emu;
2624
            break;
2625
        case CODEC_TYPE_DATA:
2626
            break;
2627
        default:
2628
            av_abort();
2629
        }
2630
    }
2631
    
2632
    input_files[nb_input_files] = ic;
2633
    /* dump the file content */
2634
    if (verbose >= 0)
2635
        dump_format(ic, nb_input_files, filename, 0);
2636

    
2637
    nb_input_files++;
2638
    file_iformat = NULL;
2639
    file_oformat = NULL;
2640
    image_format = NULL;
2641

    
2642
    rate_emu = 0;
2643
}
2644

    
2645
static void check_audio_video_inputs(int *has_video_ptr, int *has_audio_ptr)
2646
{
2647
    int has_video, has_audio, i, j;
2648
    AVFormatContext *ic;
2649

    
2650
    has_video = 0;
2651
    has_audio = 0;
2652
    for(j=0;j<nb_input_files;j++) {
2653
        ic = input_files[j];
2654
        for(i=0;i<ic->nb_streams;i++) {
2655
            AVCodecContext *enc = &ic->streams[i]->codec;
2656
            switch(enc->codec_type) {
2657
            case CODEC_TYPE_AUDIO:
2658
                has_audio = 1;
2659
                break;
2660
            case CODEC_TYPE_VIDEO:
2661
                has_video = 1;
2662
                break;
2663
            case CODEC_TYPE_DATA:
2664
                break;
2665
            default:
2666
                av_abort();
2667
            }
2668
        }
2669
    }
2670
    *has_video_ptr = has_video;
2671
    *has_audio_ptr = has_audio;
2672
}
2673

    
2674
static void opt_output_file(const char *filename)
2675
{
2676
    AVStream *st;
2677
    AVFormatContext *oc;
2678
    int use_video, use_audio, nb_streams, input_has_video, input_has_audio;
2679
    int codec_id;
2680
    AVFormatParameters params, *ap = &params;
2681

    
2682
    if (!strcmp(filename, "-"))
2683
        filename = "pipe:";
2684

    
2685
    oc = av_alloc_format_context();
2686

    
2687
    if (!file_oformat) {
2688
        file_oformat = guess_format(NULL, filename, NULL);
2689
        if (!file_oformat) {
2690
            fprintf(stderr, "Unable for find a suitable output format for '%s'\n",
2691
                    filename);
2692
            exit(1);
2693
        }
2694
    }
2695
    
2696
    oc->oformat = file_oformat;
2697

    
2698
    if (!strcmp(file_oformat->name, "ffm") && 
2699
        strstart(filename, "http:", NULL)) {
2700
        /* special case for files sent to ffserver: we get the stream
2701
           parameters from ffserver */
2702
        if (read_ffserver_streams(oc, filename) < 0) {
2703
            fprintf(stderr, "Could not read stream parameters from '%s'\n", filename);
2704
            exit(1);
2705
        }
2706
    } else {
2707
        use_video = file_oformat->video_codec != CODEC_ID_NONE || video_stream_copy;
2708
        use_audio = file_oformat->audio_codec != CODEC_ID_NONE || audio_stream_copy;
2709

    
2710
        /* disable if no corresponding type found and at least one
2711
           input file */
2712
        if (nb_input_files > 0) {
2713
            check_audio_video_inputs(&input_has_video, &input_has_audio);
2714
            if (!input_has_video)
2715
                use_video = 0;
2716
            if (!input_has_audio)
2717
                use_audio = 0;
2718
        }
2719

    
2720
        /* manual disable */
2721
        if (audio_disable) {
2722
            use_audio = 0;
2723
        }
2724
        if (video_disable) {
2725
            use_video = 0;
2726
        }
2727
        
2728
        nb_streams = 0;
2729
        if (use_video) {
2730
            AVCodecContext *video_enc;
2731
            
2732
            st = av_new_stream(oc, nb_streams++);
2733
            if (!st) {
2734
                fprintf(stderr, "Could not alloc stream\n");
2735
                exit(1);
2736
            }
2737
#if defined(HAVE_PTHREADS) || defined(HAVE_W32THREADS)
2738
            if(thread_count>1)
2739
                avcodec_thread_init(&st->codec, thread_count);
2740
#endif
2741

    
2742
            video_enc = &st->codec;
2743
            
2744
            if(!strcmp(file_oformat->name, "mp4") || !strcmp(file_oformat->name, "mov") || !strcmp(file_oformat->name, "3gp"))
2745
                video_enc->flags |= CODEC_FLAG_GLOBAL_HEADER;
2746
            if (video_stream_copy) {
2747
                st->stream_copy = 1;
2748
                video_enc->codec_type = CODEC_TYPE_VIDEO;
2749
            } else {
2750
                char *p;
2751
                int i;
2752
                AVCodec *codec;
2753
            
2754
                codec_id = file_oformat->video_codec;
2755
                if (video_codec_id != CODEC_ID_NONE)
2756
                    codec_id = video_codec_id;
2757
                
2758
                video_enc->codec_id = codec_id;
2759
                codec = avcodec_find_encoder(codec_id);
2760
                
2761
                video_enc->bit_rate = video_bit_rate;
2762
                video_enc->bit_rate_tolerance = video_bit_rate_tolerance;
2763
                video_enc->frame_rate = frame_rate; 
2764
                video_enc->frame_rate_base = frame_rate_base; 
2765
                if(codec && codec->supported_framerates){
2766
                    const AVRational *p= codec->supported_framerates;
2767
                    AVRational req= (AVRational){frame_rate, frame_rate_base};
2768
                    const AVRational *best=NULL;
2769
                    AVRational best_error= (AVRational){INT_MAX, 1};
2770
                    for(; p->den!=0; p++){
2771
                        AVRational error= av_sub_q(req, *p);
2772
                        if(error.num <0) error.num *= -1;
2773
                        if(av_cmp_q(error, best_error) < 0){
2774
                            best_error= error;
2775
                            best= p;
2776
                        }
2777
                    }
2778
                    video_enc->frame_rate     = best->num;
2779
                    video_enc->frame_rate_base= best->den;
2780
                }
2781
                
2782
                video_enc->width = frame_width + frame_padright + frame_padleft;
2783
                video_enc->height = frame_height + frame_padtop + frame_padbottom;
2784
                video_enc->sample_aspect_ratio = av_d2q(frame_aspect_ratio*frame_height/frame_width, 255);
2785
                video_enc->pix_fmt = frame_pix_fmt;
2786

    
2787
                if(codec && codec->pix_fmts){
2788
                    const enum PixelFormat *p= codec->pix_fmts;
2789
                    for(; *p!=-1; p++){
2790
                        if(*p == video_enc->pix_fmt)
2791
                            break;
2792
                    }
2793
                    if(*p == -1)
2794
                        video_enc->pix_fmt = codec->pix_fmts[0];
2795
                }
2796

    
2797
                if (!intra_only)
2798
                    video_enc->gop_size = gop_size;
2799
                else
2800
                    video_enc->gop_size = 0;
2801
                if (video_qscale || same_quality) {
2802
                    video_enc->flags |= CODEC_FLAG_QSCALE;
2803
                    st->quality = FF_QP2LAMBDA * video_qscale;
2804
                }
2805

    
2806
                if(intra_matrix)
2807
                    video_enc->intra_matrix = intra_matrix;
2808
                if(inter_matrix)
2809
                    video_enc->inter_matrix = inter_matrix;
2810

    
2811
                if(bitexact)
2812
                    video_enc->flags |= CODEC_FLAG_BITEXACT;
2813

    
2814
                video_enc->mb_decision = mb_decision;
2815
                video_enc->mb_cmp = mb_cmp;
2816
                video_enc->ildct_cmp = ildct_cmp;
2817
                video_enc->me_sub_cmp = sub_cmp;
2818
                video_enc->me_cmp = cmp;
2819
                video_enc->me_pre_cmp = pre_cmp;
2820
                video_enc->pre_me = pre_me;
2821
                video_enc->lumi_masking = lumi_mask;
2822
                video_enc->dark_masking = dark_mask;
2823
                video_enc->spatial_cplx_masking = scplx_mask;
2824
                video_enc->temporal_cplx_masking = tcplx_mask;
2825
                video_enc->p_masking = p_mask;
2826
                video_enc->quantizer_noise_shaping= qns;
2827
                
2828
                if (use_umv) {
2829
                    video_enc->flags |= CODEC_FLAG_H263P_UMV;
2830
                }
2831
                if (use_ss) {
2832
                    video_enc->flags |= CODEC_FLAG_H263P_SLICE_STRUCT;
2833
                }
2834
                   if (use_aic) {
2835
                    video_enc->flags |= CODEC_FLAG_H263P_AIC;
2836
                }
2837
                   if (use_aiv) {
2838
                    video_enc->flags |= CODEC_FLAG_H263P_AIV;
2839
                }
2840
                if (use_4mv) {
2841
                    video_enc->flags |= CODEC_FLAG_4MV;
2842
                }
2843
                if (use_obmc) {
2844
                    video_enc->flags |= CODEC_FLAG_OBMC;
2845
                }
2846
                if (use_loop) {
2847
                    video_enc->flags |= CODEC_FLAG_LOOP_FILTER;
2848
                }
2849
            
2850
                if(use_part) {
2851
                    video_enc->flags |= CODEC_FLAG_PART;
2852
                }
2853
                   if (use_alt_scan) {
2854
                    video_enc->flags |= CODEC_FLAG_ALT_SCAN;
2855
                }
2856
                   if (use_trell) {
2857
                    video_enc->flags |= CODEC_FLAG_TRELLIS_QUANT;
2858
                }
2859
                   if (use_scan_offset) {
2860
                    video_enc->flags |= CODEC_FLAG_SVCD_SCAN_OFFSET;
2861
                }
2862
                   if (closed_gop) {
2863
                    video_enc->flags |= CODEC_FLAG_CLOSED_GOP;
2864
                }
2865
                   if (use_qpel) {
2866
                    video_enc->flags |= CODEC_FLAG_QPEL;
2867
                }
2868
                if (b_frames) {
2869
                    video_enc->max_b_frames = b_frames;
2870
                    video_enc->b_frame_strategy = 0;
2871
                    video_enc->b_quant_factor = 2.0;
2872
                }
2873
                if (do_interlace_dct) {
2874
                    video_enc->flags |= CODEC_FLAG_INTERLACED_DCT;
2875
                }
2876
                if (do_interlace_me) {
2877
                    video_enc->flags |= CODEC_FLAG_INTERLACED_ME;
2878
                }
2879
                video_enc->qmin = video_qmin;
2880
                video_enc->qmax = video_qmax;
2881
                video_enc->lmin = video_lmin;
2882
                video_enc->lmax = video_lmax;
2883
                video_enc->mb_qmin = video_mb_qmin;
2884
                video_enc->mb_qmax = video_mb_qmax;
2885
                video_enc->max_qdiff = video_qdiff;
2886
                video_enc->qblur = video_qblur;
2887
                video_enc->qcompress = video_qcomp;
2888
                video_enc->rc_eq = video_rc_eq;
2889
                video_enc->debug = debug;
2890
                video_enc->debug_mv = debug_mv;
2891
                video_enc->thread_count = thread_count;
2892
                p= video_rc_override_string;
2893
                for(i=0; p; i++){
2894
                    int start, end, q;
2895
                    int e=sscanf(p, "%d,%d,%d", &start, &end, &q);
2896
                    if(e!=3){
2897
                        fprintf(stderr, "error parsing rc_override\n");
2898
                        exit(1);
2899
                    }
2900
                    video_enc->rc_override= 
2901
                        av_realloc(video_enc->rc_override, 
2902
                                   sizeof(RcOverride)*(i+1));
2903
                    video_enc->rc_override[i].start_frame= start;
2904
                    video_enc->rc_override[i].end_frame  = end;
2905
                    if(q>0){
2906
                        video_enc->rc_override[i].qscale= q;
2907
                        video_enc->rc_override[i].quality_factor= 1.0;
2908
                    }
2909
                    else{
2910
                        video_enc->rc_override[i].qscale= 0;
2911
                        video_enc->rc_override[i].quality_factor= -q/100.0;
2912
                    }
2913
                    p= strchr(p, '/');
2914
                    if(p) p++;
2915
                }
2916
                video_enc->rc_override_count=i;
2917

    
2918
                video_enc->rc_max_rate = video_rc_max_rate;
2919
                video_enc->rc_min_rate = video_rc_min_rate;
2920
                video_enc->rc_buffer_size = video_rc_buffer_size;
2921
                video_enc->rc_buffer_aggressivity= video_rc_buffer_aggressivity;
2922
                video_enc->rc_initial_cplx= video_rc_initial_cplx;
2923
                video_enc->i_quant_factor = video_i_qfactor;
2924
                video_enc->b_quant_factor = video_b_qfactor;
2925
                video_enc->i_quant_offset = video_i_qoffset;
2926
                video_enc->b_quant_offset = video_b_qoffset;
2927
                video_enc->intra_quant_bias = video_intra_quant_bias;
2928
                video_enc->inter_quant_bias = video_inter_quant_bias;
2929
                video_enc->dct_algo = dct_algo;
2930
                video_enc->idct_algo = idct_algo;
2931
                video_enc->me_threshold= me_threshold;
2932
                video_enc->mb_threshold= mb_threshold;
2933
                video_enc->intra_dc_precision= intra_dc_precision;
2934
                video_enc->strict_std_compliance = strict;
2935
                video_enc->error_rate = error_rate;
2936
                video_enc->noise_reduction= noise_reduction;
2937
                video_enc->scenechange_threshold= sc_threshold;
2938
                video_enc->me_range = me_range;
2939
                video_enc->coder_type= coder;
2940
                video_enc->context_model= context;
2941
                video_enc->prediction_method= predictor;
2942

    
2943
                if(packet_size){
2944
                    video_enc->rtp_mode= 1;
2945
                    video_enc->rtp_payload_size= packet_size;
2946
                }
2947
            
2948
                if (do_psnr)
2949
                    video_enc->flags|= CODEC_FLAG_PSNR;
2950
            
2951
                video_enc->me_method = me_method;
2952

    
2953
                /* two pass mode */
2954
                if (do_pass) {
2955
                    if (do_pass == 1) {
2956
                        video_enc->flags |= CODEC_FLAG_PASS1;
2957
                    } else {
2958
                        video_enc->flags |= CODEC_FLAG_PASS2;
2959
                    }
2960
                }
2961
            }
2962
        }
2963
    
2964
        if (use_audio) {
2965
            AVCodecContext *audio_enc;
2966

    
2967
            st = av_new_stream(oc, nb_streams++);
2968
            if (!st) {
2969
                fprintf(stderr, "Could not alloc stream\n");
2970
                exit(1);
2971
            }
2972
#if defined(HAVE_PTHREADS) || defined(HAVE_W32THREADS)
2973
            if(thread_count>1)
2974
                avcodec_thread_init(&st->codec, thread_count);
2975
#endif
2976

    
2977
            audio_enc = &st->codec;
2978
            audio_enc->codec_type = CODEC_TYPE_AUDIO;
2979

    
2980
            if(!strcmp(file_oformat->name, "mp4") || !strcmp(file_oformat->name, "mov") || !strcmp(file_oformat->name, "3gp"))
2981
                audio_enc->flags |= CODEC_FLAG_GLOBAL_HEADER;
2982
            if (audio_stream_copy) {
2983
                st->stream_copy = 1;
2984
            } else {
2985
                codec_id = file_oformat->audio_codec;
2986
                if (audio_codec_id != CODEC_ID_NONE)
2987
                    codec_id = audio_codec_id;
2988
                audio_enc->codec_id = codec_id;
2989
                
2990
                audio_enc->bit_rate = audio_bit_rate;
2991
                audio_enc->sample_rate = audio_sample_rate;
2992
                audio_enc->strict_std_compliance = strict;
2993
                audio_enc->thread_count = thread_count;
2994
                /* For audio codecs other than AC3 we limit */
2995
                /* the number of coded channels to stereo   */
2996
                if (audio_channels > 2 && codec_id != CODEC_ID_AC3) {
2997
                    audio_enc->channels = 2;
2998
                } else
2999
                    audio_enc->channels = audio_channels;
3000
            }
3001
        }
3002

    
3003
        oc->nb_streams = nb_streams;
3004

    
3005
        if (!nb_streams) {
3006
            fprintf(stderr, "No audio or video streams available\n");
3007
            exit(1);
3008
        }
3009

    
3010
        oc->timestamp = rec_timestamp;
3011
            
3012
        if (str_title)
3013
            pstrcpy(oc->title, sizeof(oc->title), str_title);
3014
        if (str_author)
3015
            pstrcpy(oc->author, sizeof(oc->author), str_author);
3016
        if (str_copyright)
3017
            pstrcpy(oc->copyright, sizeof(oc->copyright), str_copyright);
3018
        if (str_comment)
3019
            pstrcpy(oc->comment, sizeof(oc->comment), str_comment);
3020
    }
3021

    
3022
    output_files[nb_output_files++] = oc;
3023

    
3024
    strcpy(oc->filename, filename);
3025

    
3026
    /* check filename in case of an image number is expected */
3027
    if (oc->oformat->flags & AVFMT_NEEDNUMBER) {
3028
        if (filename_number_test(oc->filename) < 0) {
3029
            print_error(oc->filename, AVERROR_NUMEXPECTED);
3030
            exit(1);
3031
        }
3032
    }
3033

    
3034
    if (!(oc->oformat->flags & AVFMT_NOFILE)) {
3035
        /* test if it already exists to avoid loosing precious files */
3036
        if (!file_overwrite && 
3037
            (strchr(filename, ':') == NULL ||
3038
             strstart(filename, "file:", NULL))) {
3039
            if (url_exist(filename)) {
3040
                int c;
3041
                
3042
                if ( !using_stdin ) {
3043
                    fprintf(stderr,"File '%s' already exists. Overwrite ? [y/N] ", filename);
3044
                    fflush(stderr);
3045
                    c = getchar();
3046
                    if (toupper(c) != 'Y') {
3047
                        fprintf(stderr, "Not overwriting - exiting\n");
3048
                        exit(1);
3049
                    }
3050
                                }
3051
                                else {
3052
                    fprintf(stderr,"File '%s' already exists. Exiting.\n", filename);
3053
                    exit(1);
3054
                                }
3055
            }
3056
        }
3057
        
3058
        /* open the file */
3059
        if (url_fopen(&oc->pb, filename, URL_WRONLY) < 0) {
3060
            fprintf(stderr, "Could not open '%s'\n", filename);
3061
            exit(1);
3062
        }
3063
    }
3064

    
3065
    memset(ap, 0, sizeof(*ap));
3066
    ap->image_format = image_format;
3067
    if (av_set_parameters(oc, ap) < 0) {
3068
        fprintf(stderr, "%s: Invalid encoding parameters\n",
3069
                oc->filename);
3070
        exit(1);
3071
    }
3072

    
3073
    /* reset some options */
3074
    file_oformat = NULL;
3075
    file_iformat = NULL;
3076
    image_format = NULL;
3077
    audio_disable = 0;
3078
    video_disable = 0;
3079
    audio_codec_id = CODEC_ID_NONE;
3080
    video_codec_id = CODEC_ID_NONE;
3081
    audio_stream_copy = 0;
3082
    video_stream_copy = 0;
3083
}
3084

    
3085
/* prepare dummy protocols for grab */
3086
static void prepare_grab(void)
3087
{
3088
    int has_video, has_audio, i, j;
3089
    AVFormatContext *oc;
3090
    AVFormatContext *ic;
3091
    AVFormatParameters vp1, *vp = &vp1;
3092
    AVFormatParameters ap1, *ap = &ap1;
3093
    
3094
    /* see if audio/video inputs are needed */
3095
    has_video = 0;
3096
    has_audio = 0;
3097
    memset(ap, 0, sizeof(*ap));
3098
    memset(vp, 0, sizeof(*vp));
3099
    for(j=0;j<nb_output_files;j++) {
3100
        oc = output_files[j];
3101
        for(i=0;i<oc->nb_streams;i++) {
3102
            AVCodecContext *enc = &oc->streams[i]->codec;
3103
            switch(enc->codec_type) {
3104
            case CODEC_TYPE_AUDIO:
3105
                if (enc->sample_rate > ap->sample_rate)
3106
                    ap->sample_rate = enc->sample_rate;
3107
                if (enc->channels > ap->channels)
3108
                    ap->channels = enc->channels;
3109
                has_audio = 1;
3110
                break;
3111
            case CODEC_TYPE_VIDEO:
3112
                if (enc->width > vp->width)
3113
                    vp->width = enc->width;
3114
                if (enc->height > vp->height)
3115
                    vp->height = enc->height;
3116
                
3117
                assert(enc->frame_rate_base == DEFAULT_FRAME_RATE_BASE);
3118
                if (enc->frame_rate > vp->frame_rate){
3119
                    vp->frame_rate      = enc->frame_rate;
3120
                    vp->frame_rate_base = enc->frame_rate_base;
3121
                }
3122
                has_video = 1;
3123
                break;
3124
            default:
3125
                av_abort();
3126
            }
3127
        }
3128
    }
3129
    
3130
    if (has_video == 0 && has_audio == 0) {
3131
        fprintf(stderr, "Output file must have at least one audio or video stream\n");
3132
        exit(1);
3133
    }
3134
    
3135
    if (has_video) {
3136
        AVInputFormat *fmt1;
3137
        fmt1 = av_find_input_format(video_grab_format);
3138
        vp->device  = video_device;
3139
        vp->channel = video_channel;
3140
        vp->standard = video_standard;
3141
        if (av_open_input_file(&ic, "", fmt1, 0, vp) < 0) {
3142
            fprintf(stderr, "Could not find video grab device\n");
3143
            exit(1);
3144
        }
3145
        /* If not enough info to get the stream parameters, we decode the
3146
           first frames to get it. */
3147
        if ((ic->ctx_flags & AVFMTCTX_NOHEADER) && av_find_stream_info(ic) < 0) {
3148
            fprintf(stderr, "Could not find video grab parameters\n");
3149
            exit(1);
3150
        }
3151
        /* by now video grab has one stream */
3152
        ic->streams[0]->r_frame_rate      = vp->frame_rate;
3153
        ic->streams[0]->r_frame_rate_base = vp->frame_rate_base;
3154
        input_files[nb_input_files] = ic;
3155

    
3156
        if (verbose >= 0)
3157
            dump_format(ic, nb_input_files, "", 0);
3158

    
3159
        nb_input_files++;
3160
    }
3161
    if (has_audio && audio_grab_format) {
3162
        AVInputFormat *fmt1;
3163
        fmt1 = av_find_input_format(audio_grab_format);
3164
        ap->device = audio_device;
3165
        if (av_open_input_file(&ic, "", fmt1, 0, ap) < 0) {
3166
            fprintf(stderr, "Could not find audio grab device\n");
3167
            exit(1);
3168
        }
3169
        input_files[nb_input_files] = ic;
3170

    
3171
        if (verbose >= 0)
3172
            dump_format(ic, nb_input_files, "", 0);
3173

    
3174
        nb_input_files++;
3175
    }
3176
}
3177

    
3178
/* same option as mencoder */
3179
static void opt_pass(const char *pass_str)
3180
{
3181
    int pass;
3182
    pass = atoi(pass_str);
3183
    if (pass != 1 && pass != 2) {
3184
        fprintf(stderr, "pass number can be only 1 or 2\n");
3185
        exit(1);
3186
    }
3187
    do_pass = pass;
3188
}
3189

    
3190
#if defined(CONFIG_WIN32) || defined(CONFIG_OS2)
3191
static int64_t getutime(void)
3192
{
3193
  return av_gettime();
3194
}
3195
#else
3196
static int64_t getutime(void)
3197
{
3198
    struct rusage rusage;
3199

    
3200
    getrusage(RUSAGE_SELF, &rusage);
3201
    return (rusage.ru_utime.tv_sec * 1000000LL) + rusage.ru_utime.tv_usec;
3202
}
3203
#endif
3204

    
3205
extern int ffm_nopts;
3206

    
3207
static void opt_bitexact(void)
3208
{
3209
    bitexact=1;
3210
    /* disable generate of real time pts in ffm (need to be supressed anyway) */
3211
    ffm_nopts = 1;
3212
}
3213

    
3214
static void show_formats(void)
3215
{
3216
    AVInputFormat *ifmt;
3217
    AVOutputFormat *ofmt;
3218
    AVImageFormat *image_fmt;
3219
    URLProtocol *up;
3220
    AVCodec *p, *p2;
3221
    const char **pp, *last_name;
3222

    
3223
    printf("File formats:\n");
3224
    last_name= "000";
3225
    for(;;){
3226
        int decode=0;
3227
        int encode=0;
3228
        const char *name=NULL;
3229

    
3230
        for(ofmt = first_oformat; ofmt != NULL; ofmt = ofmt->next) {
3231
            if((name == NULL || strcmp(ofmt->name, name)<0) &&
3232
                strcmp(ofmt->name, last_name)>0){
3233
                name= ofmt->name;
3234
                encode=1;
3235
            }
3236
        }
3237
        for(ifmt = first_iformat; ifmt != NULL; ifmt = ifmt->next) {
3238
            if((name == NULL || strcmp(ifmt->name, name)<0) &&
3239
                strcmp(ifmt->name, last_name)>0){
3240
                name= ifmt->name;
3241
                encode=0;
3242
            }
3243
            if(name && strcmp(ifmt->name, name)==0)
3244
                decode=1;
3245
        }
3246
        if(name==NULL)
3247
            break;
3248
        last_name= name;
3249
        
3250
        printf(
3251
            " %s%s %s\n", 
3252
            decode ? "D":" ", 
3253
            encode ? "E":" ", 
3254
            name);
3255
    }
3256
    printf("\n");
3257

    
3258
    printf("Image formats:\n");
3259
    for(image_fmt = first_image_format; image_fmt != NULL; 
3260
        image_fmt = image_fmt->next) {
3261
        printf(
3262
            " %s%s %s\n",
3263
            image_fmt->img_read  ? "D":" ",
3264
            image_fmt->img_write ? "E":" ",
3265
            image_fmt->name);
3266
    }
3267
    printf("\n");
3268

    
3269
    printf("Codecs:\n");
3270
    last_name= "000";
3271
    for(;;){
3272
        int decode=0;
3273
        int encode=0;
3274
        int cap=0;
3275

    
3276
        p2=NULL;
3277
        for(p = first_avcodec; p != NULL; p = p->next) {
3278
            if((p2==NULL || strcmp(p->name, p2->name)<0) &&
3279
                strcmp(p->name, last_name)>0){
3280
                p2= p;
3281
                decode= encode= cap=0;
3282
            }
3283
            if(p2 && strcmp(p->name, p2->name)==0){
3284
                if(p->decode) decode=1;
3285
                if(p->encode) encode=1;
3286
                cap |= p->capabilities;
3287
            }
3288
        }
3289
        if(p2==NULL)
3290
            break;
3291
        last_name= p2->name;
3292
        
3293
        printf(
3294
            " %s%s%s%s%s%s %s", 
3295
            decode ? "D": (/*p2->decoder ? "d":*/" "), 
3296
            encode ? "E":" ", 
3297
            p2->type == CODEC_TYPE_AUDIO ? "A":"V",
3298
            cap & CODEC_CAP_DRAW_HORIZ_BAND ? "S":" ",
3299
            cap & CODEC_CAP_DR1 ? "D":" ",
3300
            cap & CODEC_CAP_TRUNCATED ? "T":" ",
3301
            p2->name);
3302
       /* if(p2->decoder && decode==0)
3303
            printf(" use %s for decoding", p2->decoder->name);*/
3304
        printf("\n");
3305
    }
3306
    printf("\n");
3307

    
3308
    printf("Supported file protocols:\n");
3309
    for(up = first_protocol; up != NULL; up = up->next)
3310
        printf(" %s:", up->name);
3311
    printf("\n");
3312
    
3313
    printf("Frame size, frame rate abbreviations:\n ntsc pal qntsc qpal sntsc spal film ntsc-film sqcif qcif cif 4cif\n");
3314
    printf("Motion estimation methods:\n");
3315
    pp = motion_str;
3316
    while (*pp) {
3317
        printf(" %s", *pp);
3318
        if ((pp - motion_str + 1) == ME_ZERO) 
3319
            printf("(fastest)");
3320
        else if ((pp - motion_str + 1) == ME_FULL) 
3321
            printf("(slowest)");
3322
        else if ((pp - motion_str + 1) == ME_EPZS) 
3323
            printf("(default)");
3324
        pp++;
3325
    }
3326
    printf("\n\n");
3327
    printf(
3328
"Note, the names of encoders and decoders dont always match, so there are\n"
3329
"several cases where the above table shows encoder only or decoder only entries\n"
3330
"even though both encoding and decoding are supported for example, the h263\n"
3331
"decoder corresponds to the h263 and h263p encoders, for file formats its even\n"
3332
"worse\n");
3333
    exit(1);
3334
}
3335

    
3336
void parse_matrix_coeffs(uint16_t *dest, const char *str)
3337
{
3338
    int i;
3339
    const char *p = str;
3340
    for(i = 0;; i++) {
3341
        dest[i] = atoi(p);
3342
        if(i == 63)
3343
            break;
3344
        p = strchr(p, ',');
3345
        if(!p) {
3346
            fprintf(stderr, "Syntax error in matrix \"%s\" at coeff %d\n", str, i);
3347
            exit(1);
3348
        }
3349
        p++;
3350
    }
3351
}
3352

    
3353
void opt_inter_matrix(const char *arg)
3354
{
3355
    inter_matrix = av_mallocz(sizeof(uint16_t) * 64);
3356
    parse_matrix_coeffs(inter_matrix, arg);
3357
}
3358

    
3359
void opt_intra_matrix(const char *arg)
3360
{
3361
    intra_matrix = av_mallocz(sizeof(uint16_t) * 64);
3362
    parse_matrix_coeffs(intra_matrix, arg);
3363
}
3364

    
3365
static void opt_target(const char *arg)
3366
{
3367
    int norm = -1;
3368

    
3369
    if(!strncmp(arg, "pal-", 4)) {
3370
        norm = 0;
3371
        arg += 4;
3372
    } else if(!strncmp(arg, "ntsc-", 5)) {
3373
        norm = 1;
3374
        arg += 5;
3375
    } else {
3376
        int fr;
3377
        /* Calculate FR via float to avoid int overflow */
3378
        fr = (int)(frame_rate * 1000.0 / frame_rate_base);
3379
        if(fr == 25000) {
3380
            norm = 0;
3381
        } else if((fr == 29970) || (fr == 23976)) {
3382
            norm = 1;
3383
        } else {
3384
            /* Try to determine PAL/NTSC by peeking in the input files */
3385
            if(nb_input_files) {
3386
                int i, j;
3387
                for(j = 0; j < nb_input_files; j++) {
3388
                    for(i = 0; i < input_files[j]->nb_streams; i++) {
3389
                        AVCodecContext *c = &input_files[j]->streams[i]->codec;
3390
                        if(c->codec_type != CODEC_TYPE_VIDEO)
3391
                            continue;
3392
                        fr = c->frame_rate * 1000 / c->frame_rate_base;
3393
                        if(fr == 25000) {
3394
                            norm = 0;
3395
                            break;
3396
                        } else if((fr == 29970) || (fr == 23976)) {
3397
                            norm = 1;
3398
                            break;
3399
                        }
3400
                    }
3401
                    if(norm >= 0)
3402
                        break;
3403
                }
3404
            }
3405
        }
3406
        if(verbose && norm >= 0)
3407
            printf("Assuming %s for target.\n", norm ? "NTSC" : "PAL");
3408
    }
3409

    
3410
    if(norm < 0) {
3411
        fprintf(stderr, "Could not determine norm (PAL/NTSC) for target.\n");
3412
        fprintf(stderr, "Please prefix target with \"pal-\" or \"ntsc-\",\n");
3413
        fprintf(stderr, "or set a framerate with \"-r xxx\".\n");
3414
        exit(1);
3415
    }
3416

    
3417
    if(!strcmp(arg, "vcd")) {
3418

    
3419
        opt_video_codec("mpeg1video");
3420
        opt_audio_codec("mp2");
3421
        opt_format("vcd");
3422

    
3423
        opt_frame_size(norm ? "352x240" : "352x288");
3424

    
3425
        video_bit_rate = 1150000;
3426
        video_rc_max_rate = 1150000;
3427
        video_rc_min_rate = 1150000;
3428
        video_rc_buffer_size = 40*1024*8;
3429

    
3430
        audio_bit_rate = 224000;
3431
        audio_sample_rate = 44100;
3432

    
3433
    } else if(!strcmp(arg, "svcd")) {
3434

    
3435
        opt_video_codec("mpeg2video");
3436
        opt_audio_codec("mp2");
3437
        opt_format("svcd");
3438

    
3439
        opt_frame_size(norm ? "480x480" : "480x576");
3440
        opt_gop_size(norm ? "18" : "15");
3441

    
3442
        video_bit_rate = 2040000;
3443
        video_rc_max_rate = 2516000;
3444
        video_rc_min_rate = 0; //1145000;
3445
        video_rc_buffer_size = 224*1024*8;
3446
        use_scan_offset = 1;
3447

    
3448
        audio_bit_rate = 224000;
3449
        audio_sample_rate = 44100;
3450

    
3451
    } else if(!strcmp(arg, "dvd")) {
3452

    
3453
        opt_video_codec("mpeg2video");
3454
        opt_audio_codec("ac3");
3455
        opt_format("vob");
3456

    
3457
        opt_frame_size(norm ? "720x480" : "720x576");
3458
        opt_gop_size(norm ? "18" : "15");
3459

    
3460
        video_bit_rate = 6000000;
3461
        video_rc_max_rate = 9000000;
3462
        video_rc_min_rate = 0; //1500000;
3463
        video_rc_buffer_size = 224*1024*8;
3464

    
3465
        audio_bit_rate = 448000;
3466
        audio_sample_rate = 48000;
3467

    
3468
    } else {
3469
        fprintf(stderr, "Unknown target: %s\n", arg);
3470
        exit(1);
3471
    }
3472
}
3473

    
3474
static void show_version(void)
3475
{
3476
    printf("ffmpeg      " FFMPEG_VERSION "\n"
3477
           "libavcodec  %d\n"
3478
           "libavformat %d\n", 
3479
           avcodec_build(), LIBAVFORMAT_BUILD);
3480
    exit(1);
3481
}
3482

    
3483
const OptionDef options[] = {
3484
    /* main options */
3485
    { "L", 0, {(void*)show_license}, "show license" },
3486
    { "h", 0, {(void*)show_help}, "show help" },
3487
    { "version", 0, {(void*)show_version}, "show version" },
3488
    { "formats", 0, {(void*)show_formats}, "show available formats, codecs, protocols, ..." },
3489
    { "f", HAS_ARG, {(void*)opt_format}, "force format", "fmt" },
3490
    { "img", HAS_ARG, {(void*)opt_image_format}, "force image format", "img_fmt" },
3491
    { "i", HAS_ARG, {(void*)opt_input_file}, "input file name", "filename" },
3492
    { "y", OPT_BOOL, {(void*)&file_overwrite}, "overwrite output files" },
3493
    { "map", HAS_ARG | OPT_EXPERT, {(void*)opt_map}, "set input stream mapping", "file:stream" },
3494
    { "t", HAS_ARG, {(void*)opt_recording_time}, "set the recording time", "duration" },
3495
    { "ss", HAS_ARG, {(void*)opt_start_time}, "set the start time offset", "time_off" },
3496
    { "title", HAS_ARG | OPT_STRING, {(void*)&str_title}, "set the title", "string" },
3497
    { "timestamp", HAS_ARG, {(void*)&opt_rec_timestamp}, "set the timestamp", "time" },
3498
    { "author", HAS_ARG | OPT_STRING, {(void*)&str_author}, "set the author", "string" },
3499
    { "copyright", HAS_ARG | OPT_STRING, {(void*)&str_copyright}, "set the copyright", "string" },
3500
    { "comment", HAS_ARG | OPT_STRING, {(void*)&str_comment}, "set the comment", "string" },
3501
    { "debug", HAS_ARG | OPT_EXPERT, {(void*)opt_debug}, "print specific debug info", "" },
3502
    { "vismv", HAS_ARG | OPT_EXPERT, {(void*)opt_vismv}, "visualize motion vectors", "" },
3503
    { "benchmark", OPT_BOOL | OPT_EXPERT, {(void*)&do_benchmark}, 
3504
      "add timings for benchmarking" },
3505
    { "dump", OPT_BOOL | OPT_EXPERT, {(void*)&do_pkt_dump}, 
3506
      "dump each input packet" },
3507
    { "hex", OPT_BOOL | OPT_EXPERT, {(void*)&do_hex_dump}, 
3508
      "when dumping packets, also dump the payload" },
3509
    { "bitexact", OPT_EXPERT, {(void*)opt_bitexact}, "only use bit exact algorithms (for codec testing)" }, 
3510
    { "re", OPT_BOOL | OPT_EXPERT, {(void*)&rate_emu}, "read input at native frame rate", "" },
3511
    { "loop", OPT_BOOL | OPT_EXPERT, {(void*)&loop_input}, "loop (current only works with images)" },
3512
    { "v", HAS_ARG, {(void*)opt_verbose}, "control amount of logging", "verbose" },
3513
    { "target", HAS_ARG, {(void*)opt_target}, "specify target file type (\"vcd\", \"svcd\" or \"dvd\")", "type" },
3514
    { "threads", HAS_ARG | OPT_EXPERT, {(void*)opt_thread_count}, "thread count", "count" },
3515
    { "sync", HAS_ARG | OPT_EXPERT, {(void*)opt_sync_method}, "sync method", "" },
3516

    
3517
    /* video options */
3518
    { "b", HAS_ARG | OPT_VIDEO, {(void*)opt_video_bitrate}, "set video bitrate (in kbit/s)", "bitrate" },
3519
    { "r", HAS_ARG | OPT_VIDEO, {(void*)opt_frame_rate}, "set frame rate (Hz value, fraction or abbreviation)", "rate" },
3520
    { "s", HAS_ARG | OPT_VIDEO, {(void*)opt_frame_size}, "set frame size (WxH or abbreviation)", "size" },
3521
    { "aspect", HAS_ARG | OPT_VIDEO, {(void*)opt_frame_aspect_ratio}, "set aspect ratio (4:3, 16:9 or 1.3333, 1.7777)", "aspect" },
3522
    { "pix_fmt", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_frame_pix_fmt}, "set pixel format", "format" },
3523
    { "croptop", HAS_ARG | OPT_VIDEO, {(void*)opt_frame_crop_top}, "set top crop band size (in pixels)", "size" },
3524
    { "cropbottom", HAS_ARG | OPT_VIDEO, {(void*)opt_frame_crop_bottom}, "set bottom crop band size (in pixels)", "size" },
3525
    { "cropleft", HAS_ARG | OPT_VIDEO, {(void*)opt_frame_crop_left}, "set left crop band size (in pixels)", "size" },
3526
    { "cropright", HAS_ARG | OPT_VIDEO, {(void*)opt_frame_crop_right}, "set right crop band size (in pixels)", "size" },
3527
    { "padtop", HAS_ARG | OPT_VIDEO, {(void*)opt_frame_pad_top}, "set top pad band size (in pixels)", "size" },
3528
    { "padbottom", HAS_ARG | OPT_VIDEO, {(void*)opt_frame_pad_bottom}, "set bottom pad band size (in pixels)", "size" },
3529
    { "padleft", HAS_ARG | OPT_VIDEO, {(void*)opt_frame_pad_left}, "set left pad band size (in pixels)", "size" },
3530
    { "padright", HAS_ARG | OPT_VIDEO, {(void*)opt_frame_pad_right}, "set right pad band size (in pixels)", "size" },
3531
    { "padcolor", HAS_ARG | OPT_VIDEO, {(void*)opt_pad_color}, "set color of pad bands (Hex 000000 thru FFFFFF)", "color" },
3532
    { "g", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_gop_size}, "set the group of picture size", "gop_size" },
3533
    { "intra", OPT_BOOL | OPT_EXPERT | OPT_VIDEO, {(void*)&intra_only}, "use only intra frames"},
3534
    { "vn", OPT_BOOL | OPT_VIDEO, {(void*)&video_disable}, "disable video" },
3535
    { "qscale", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_qscale}, "use fixed video quantiser scale (VBR)", "q" },
3536
    { "qmin", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_qmin}, "min video quantiser scale (VBR)", "q" },
3537
    { "qmax", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_qmax}, "max video quantiser scale (VBR)", "q" },
3538
    { "lmin", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_lmin}, "min video lagrange factor (VBR)", "lambda" },
3539
    { "lmax", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_lmax}, "max video lagrange factor (VBR)", "lambda" },
3540
    { "mbqmin", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_mb_qmin}, "min macroblock quantiser scale (VBR)", "q" },
3541
    { "mbqmax", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_mb_qmax}, "max macroblock quantiser scale (VBR)", "q" },
3542
    { "qdiff", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_qdiff}, "max difference between the quantiser scale (VBR)", "q" },
3543
    { "qblur", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_qblur}, "video quantiser scale blur (VBR)", "blur" },
3544
    { "qcomp", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_qcomp}, "video quantiser scale compression (VBR)", "compression" },
3545
    { "rc_init_cplx", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_rc_initial_cplx}, "initial complexity for 1-pass encoding", "complexity" },
3546
    { "b_qfactor", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_b_qfactor}, "qp factor between p and b frames", "factor" },
3547
    { "i_qfactor", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_i_qfactor}, "qp factor between p and i frames", "factor" },
3548
    { "b_qoffset", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_b_qoffset}, "qp offset between p and b frames", "offset" },
3549
    { "i_qoffset", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_i_qoffset}, "qp offset between p and i frames", "offset" },
3550
    { "ibias", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_ibias}, "intra quant bias", "bias" },
3551
    { "pbias", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_pbias}, "inter quant bias", "bias" },
3552
//    { "b_strategy", HAS_ARG | OPT_EXPERT, {(void*)opt_b_strategy}, "dynamic b frame selection strategy", "strategy" },
3553
    { "rc_eq", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_video_rc_eq}, "set rate control equation", "equation" },
3554
    { "rc_override", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_video_rc_override_string}, "rate control override for specific intervals", "override" },
3555
    { "bt", HAS_ARG | OPT_VIDEO, {(void*)opt_video_bitrate_tolerance}, "set video bitrate tolerance (in kbit/s)", "tolerance" },
3556
    { "maxrate", HAS_ARG | OPT_VIDEO, {(void*)opt_video_bitrate_max}, "set max video bitrate tolerance (in kbit/s)", "bitrate" },
3557
    { "minrate", HAS_ARG | OPT_VIDEO, {(void*)opt_video_bitrate_min}, "set min video bitrate tolerance (in kbit/s)", "bitrate" },
3558
    { "bufsize", HAS_ARG | OPT_VIDEO, {(void*)opt_video_buffer_size}, "set ratecontrol buffere size (in kByte)", "size" },
3559
    { "vcodec", HAS_ARG | OPT_VIDEO, {(void*)opt_video_codec}, "force video codec ('copy' to copy stream)", "codec" },
3560
    { "me", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_motion_estimation}, "set motion estimation method", 
3561
      "method" },
3562
    { "dct_algo", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_dct_algo}, "set dct algo",  "algo" },
3563
    { "idct_algo", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_idct_algo}, "set idct algo",  "algo" },
3564
    { "me_threshold", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_me_threshold}, "motion estimaton threshold",  "" },
3565
    { "mb_threshold", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_mb_threshold}, "macroblock threshold",  "" },
3566
    { "er", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_error_resilience}, "set error resilience",  "n" },
3567
    { "ec", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_error_concealment}, "set error concealment",  "bit_mask" },
3568
    { "bf", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_b_frames}, "use 'frames' B frames", "frames" },
3569
    { "hq", OPT_BOOL, {(void*)&mb_decision}, "activate high quality settings" },
3570
    { "mbd", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_mb_decision}, "macroblock decision", "mode" },
3571
    { "mbcmp", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_mb_cmp}, "macroblock compare function", "cmp function" },
3572
    { "ildctcmp", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_ildct_cmp}, "ildct compare function", "cmp function" },
3573
    { "subcmp", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_sub_cmp}, "subpel compare function", "cmp function" },
3574
    { "cmp", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_cmp}, "fullpel compare function", "cmp function" },
3575
    { "precmp", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_pre_cmp}, "pre motion estimation compare function", "cmp function" },
3576
    { "preme", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_pre_me}, "pre motion estimation", "" },
3577
    { "lumi_mask", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_lumi_mask}, "luminance masking", "" },
3578
    { "dark_mask", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_dark_mask}, "darkness masking", "" },
3579
    { "scplx_mask", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_scplx_mask}, "spatial complexity masking", "" },
3580
    { "tcplx_mask", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_tcplx_mask}, "teporal complexity masking", "" },
3581
    { "p_mask", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_p_mask}, "inter masking", "" },
3582
    { "4mv", OPT_BOOL | OPT_EXPERT | OPT_VIDEO, {(void*)&use_4mv}, "use four motion vector by macroblock (MPEG4)" },
3583
    { "obmc", OPT_BOOL | OPT_EXPERT | OPT_VIDEO, {(void*)&use_obmc}, "use overlapped block motion compensation (h263+)" },
3584
    { "lf", OPT_BOOL | OPT_EXPERT | OPT_VIDEO, {(void*)&use_loop}, "use loop filter (h263+)" },
3585
    { "part", OPT_BOOL | OPT_EXPERT | OPT_VIDEO, {(void*)&use_part}, "use data partitioning (MPEG4)" },
3586
    { "bug", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_workaround_bugs}, "workaround not auto detected encoder bugs", "param" },
3587
    { "ps", HAS_ARG | OPT_EXPERT, {(void*)opt_packet_size}, "set packet size in bits", "size" },
3588
    { "error", HAS_ARG | OPT_EXPERT, {(void*)opt_error_rate}, "error rate", "rate" },
3589
    { "strict", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_strict}, "how strictly to follow the standards", "strictness" },
3590
    { "sameq", OPT_BOOL | OPT_VIDEO, {(void*)&same_quality}, 
3591
      "use same video quality as source (implies VBR)" },
3592
    { "pass", HAS_ARG | OPT_VIDEO, {(void*)&opt_pass}, "select the pass number (1 or 2)", "n" },
3593
    { "passlogfile", HAS_ARG | OPT_STRING | OPT_VIDEO, {(void*)&pass_logfilename}, "select two pass log file name", "file" },
3594
    { "deinterlace", OPT_BOOL | OPT_EXPERT | OPT_VIDEO, {(void*)&do_deinterlace}, 
3595
      "deinterlace pictures" },
3596
    { "ildct", OPT_BOOL | OPT_EXPERT | OPT_VIDEO, {(void*)&do_interlace_dct}, 
3597
      "force interlaced dct support in encoder (MPEG2/MPEG4)" },
3598
    { "ilme", OPT_BOOL | OPT_EXPERT | OPT_VIDEO, {(void*)&do_interlace_me}, 
3599
      "force interlaced me support in encoder (MPEG2/MPEG4)" },
3600
    { "psnr", OPT_BOOL | OPT_EXPERT | OPT_VIDEO, {(void*)&do_psnr}, "calculate PSNR of compressed frames" },
3601
    { "vstats", OPT_BOOL | OPT_EXPERT | OPT_VIDEO, {(void*)&do_vstats}, "dump video coding statistics to file" }, 
3602
    { "vhook", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)add_frame_hooker}, "insert video processing module", "module" },
3603
    { "aic", OPT_BOOL | OPT_EXPERT | OPT_VIDEO, {(void*)&use_aic}, "enable Advanced intra coding (h263+)" },
3604
    { "aiv", OPT_BOOL | OPT_EXPERT | OPT_VIDEO, {(void*)&use_aiv}, "enable Alternative inter vlc (h263+)" },
3605
    { "umv", OPT_BOOL | OPT_EXPERT | OPT_VIDEO, {(void*)&use_umv}, "enable Unlimited Motion Vector (h263+)" },
3606
    { "ssm", OPT_BOOL | OPT_EXPERT | OPT_VIDEO, {(void*)&use_ss}, "enable Slice Structured mode (h263+)" },
3607
    { "alt", OPT_BOOL | OPT_EXPERT | OPT_VIDEO, {(void*)&use_alt_scan}, "enable alternate scantable (MPEG2/MPEG4)" },
3608
    { "trell", OPT_BOOL | OPT_EXPERT | OPT_VIDEO, {(void*)&use_trell}, "enable trellis quantization" },
3609
    { "cgop", OPT_BOOL | OPT_EXPERT | OPT_VIDEO, {(void*)&closed_gop}, "closed gop" },
3610
    { "scan_offset", OPT_BOOL | OPT_EXPERT | OPT_VIDEO, {(void*)&use_scan_offset}, "enable SVCD Scan Offset placeholder" },
3611
    { "qpel", OPT_BOOL | OPT_EXPERT | OPT_VIDEO, {(void*)&use_qpel}, "enable 1/4-pel" },
3612
    { "intra_matrix", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_intra_matrix}, "specify intra matrix coeffs", "matrix" },
3613
    { "inter_matrix", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_inter_matrix}, "specify inter matrix coeffs", "matrix" },
3614
    { "top", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_top_field_first}, "top=1/bottom=0/auto=-1 field first", "" },
3615
    { "nr", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_noise_reduction}, "noise reduction", "" },
3616
    { "qns", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_qns}, "quantization noise shaping", "" },
3617
    { "sc_threshold", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_sc_threshold}, "scene change threshold", "threshold" },
3618
    { "me_range", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_me_range}, "limit motion vectors range (1023 for DivX player)", "range" },
3619
    { "dc", OPT_INT | HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)&intra_dc_precision}, "intra_dc_precision", "precision" },
3620
    { "coder", OPT_INT | HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)&coder}, "coder type", "" },
3621
    { "context", OPT_INT | HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)&context}, "context model", "" },
3622
    { "pred", OPT_INT | HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)&predictor}, "prediction method", "" },
3623

    
3624
    /* audio options */
3625
    { "ab", HAS_ARG | OPT_AUDIO, {(void*)opt_audio_bitrate}, "set audio bitrate (in kbit/s)", "bitrate", },
3626
    { "ar", HAS_ARG | OPT_AUDIO, {(void*)opt_audio_rate}, "set audio sampling rate (in Hz)", "rate" },
3627
    { "ac", HAS_ARG | OPT_AUDIO, {(void*)opt_audio_channels}, "set number of audio channels", "channels" },
3628
    { "an", OPT_BOOL | OPT_AUDIO, {(void*)&audio_disable}, "disable audio" },
3629
    { "acodec", HAS_ARG | OPT_AUDIO, {(void*)opt_audio_codec}, "force audio codec ('copy' to copy stream)", "codec" },
3630

    
3631
    /* grab options */
3632
    { "vd", HAS_ARG | OPT_EXPERT | OPT_VIDEO | OPT_GRAB, {(void*)opt_video_device}, "set video grab device", "device" },
3633
    { "vc", HAS_ARG | OPT_EXPERT | OPT_VIDEO | OPT_GRAB, {(void*)opt_video_channel}, "set video grab channel (DV1394 only)", "channel" },
3634
    { "tvstd", HAS_ARG | OPT_EXPERT | OPT_VIDEO | OPT_GRAB, {(void*)opt_video_standard}, "set television standard (NTSC, PAL (SECAM))", "standard" },
3635
    { "dv1394", OPT_EXPERT | OPT_GRAB, {(void*)opt_dv1394}, "set DV1394 grab", "" },
3636
    { "ad", HAS_ARG | OPT_EXPERT | OPT_AUDIO | OPT_GRAB, {(void*)opt_audio_device}, "set audio device", "device" },
3637
    { NULL, },
3638
};
3639

    
3640
static void show_banner(void)
3641
{
3642
    printf("ffmpeg version " FFMPEG_VERSION ", Copyright (c) 2000-2003 Fabrice Bellard\n");
3643
}
3644

    
3645
static void show_license(void)
3646
{
3647
    show_banner();
3648
#ifdef CONFIG_GPL
3649
    printf(
3650
    "This program is free software; you can redistribute it and/or modify\n"   
3651
    "it under the terms of the GNU General Public License as published by\n"
3652
    "the Free Software Foundation; either version 2 of the License, or\n"
3653
    "(at your option) any later version.\n"
3654
    "\n"
3655
    "This program is distributed in the hope that it will be useful,\n"
3656
    "but WITHOUT ANY WARRANTY; without even the implied warranty of\n"
3657
    "MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n"
3658
    "GNU General Public License for more details.\n"
3659
    "\n"
3660
    "You should have received a copy of the GNU General Public License\n"
3661
    "along with this program; if not, write to the Free Software\n"
3662
    "Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA\n"
3663
    );
3664
#else
3665
    printf(
3666
    "This library is free software; you can redistribute it and/or\n"
3667
    "modify it under the terms of the GNU Lesser General Public\n"
3668
    "License as published by the Free Software Foundation; either\n"
3669
    "version 2 of the License, or (at your option) any later version.\n"
3670
    "\n"
3671
    "This library is distributed in the hope that it will be useful,\n"
3672
    "but WITHOUT ANY WARRANTY; without even the implied warranty of\n"
3673
    "MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n"
3674
    "Lesser General Public License for more details.\n"
3675
    "\n"
3676
    "You should have received a copy of the GNU Lesser General Public\n"
3677
    "License along with this library; if not, write to the Free Software\n"
3678
    "Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA\n"
3679
    );
3680
#endif
3681
    exit(1);
3682
}
3683

    
3684
static void show_help(void)
3685
{
3686
    show_banner();
3687
    printf("usage: ffmpeg [[options] -i input_file]... {[options] outfile}...\n"
3688
           "Hyper fast Audio and Video encoder\n");
3689
    printf("\n");
3690
    show_help_options(options, "Main options:\n",
3691
                      OPT_EXPERT | OPT_AUDIO | OPT_VIDEO, 0);
3692
    show_help_options(options, "\nVideo options:\n",
3693
                      OPT_EXPERT | OPT_AUDIO | OPT_VIDEO | OPT_GRAB, 
3694
                      OPT_VIDEO);
3695
    show_help_options(options, "\nAdvanced Video options:\n",
3696
                      OPT_EXPERT | OPT_AUDIO | OPT_VIDEO | OPT_GRAB, 
3697
                      OPT_VIDEO | OPT_EXPERT);
3698
    show_help_options(options, "\nAudio options:\n",
3699
                      OPT_EXPERT | OPT_AUDIO | OPT_VIDEO | OPT_GRAB, 
3700
                      OPT_AUDIO);
3701
    show_help_options(options, "\nAdvanced Audio options:\n",
3702
                      OPT_EXPERT | OPT_AUDIO | OPT_VIDEO | OPT_GRAB, 
3703
                      OPT_AUDIO | OPT_EXPERT);
3704
    show_help_options(options, "\nAudio/Video grab options:\n",
3705
                      OPT_GRAB, 
3706
                      OPT_GRAB);
3707
    show_help_options(options, "\nAdvanced options:\n",
3708
                      OPT_EXPERT | OPT_AUDIO | OPT_VIDEO | OPT_GRAB, 
3709
                      OPT_EXPERT);
3710
    exit(1);
3711
}
3712

    
3713
void parse_arg_file(const char *filename)
3714
{
3715
    opt_output_file(filename);
3716
}
3717

    
3718
int main(int argc, char **argv)
3719
{
3720
    int i;
3721
    int64_t ti;
3722

    
3723
    av_register_all();
3724

    
3725
    if (argc <= 1)
3726
        show_help();
3727
    
3728
    /* parse options */
3729
    parse_options(argc, argv, options);
3730

    
3731
    /* file converter / grab */
3732
    if (nb_output_files <= 0) {
3733
        fprintf(stderr, "Must supply at least one output file\n");
3734
        exit(1);
3735
    }
3736
    
3737
    if (nb_input_files == 0) {
3738
        prepare_grab();
3739
    }
3740

    
3741
    ti = getutime();
3742
    av_encode(output_files, nb_output_files, input_files, nb_input_files, 
3743
              stream_maps, nb_stream_maps);
3744
    ti = getutime() - ti;
3745
    if (do_benchmark) {
3746
        printf("bench: utime=%0.3fs\n", ti / 1000000.0);
3747
    }
3748

    
3749
    /* close files */
3750
    for(i=0;i<nb_output_files;i++) {
3751
        /* maybe av_close_output_file ??? */
3752
        AVFormatContext *s = output_files[i];
3753
        int j;
3754
        if (!(s->oformat->flags & AVFMT_NOFILE))
3755
            url_fclose(&s->pb);
3756
        for(j=0;j<s->nb_streams;j++)
3757
            av_free(s->streams[j]);
3758
        av_free(s);
3759
    }
3760
    for(i=0;i<nb_input_files;i++)
3761
        av_close_input_file(input_files[i]);
3762

    
3763
    av_free_static();
3764

    
3765
    if(intra_matrix)
3766
        av_free(intra_matrix);
3767
    if(inter_matrix)
3768
        av_free(inter_matrix);
3769
    
3770
#ifdef POWERPC_PERFORMANCE_REPORT
3771
    extern void powerpc_display_perf_report(void);
3772
    powerpc_display_perf_report();
3773
#endif /* POWERPC_PERFORMANCE_REPORT */
3774

    
3775
#ifndef CONFIG_WIN32
3776
    if (received_sigterm) {
3777
        fprintf(stderr,
3778
            "Received signal %d: terminating.\n",
3779
            (int) received_sigterm);
3780
        exit (255);
3781
    }
3782
#endif
3783
    exit(0); /* not all OS-es handle main() return value */
3784
    return 0;
3785
}