Statistics
| Branch: | Revision:

ffmpeg / ffmpeg.c @ fcee0164

History | View | Annotate | Download (126 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 "avformat.h"
21
#include "framehook.h"
22

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

    
40
#include "cmdutils.h"
41

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

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

    
52
extern const OptionDef options[];
53

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

    
57
#define MAX_FILES 20
58

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

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

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

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

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

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

    
201
static int rate_emu = 0;
202

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

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

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

    
221
#define DEFAULT_PASS_LOGFILENAME "ffmpeg2pass"
222

    
223
typedef struct AVOutputStream {
224
    int file_index;          /* file index */
225
    int index;               /* stream index in the output file */
226
    int source_index;        /* AVInputStream index */
227
    AVStream *st;            /* stream in the output file */
228
    int encoding_needed;     /* true if encoding needed for this stream */
229
    int frame_number;
230
    /* input pts and corresponding output pts
231
       for A/V sync */
232
    double sync_ipts;
233
    double sync_ipts_offset;
234
    int64_t sync_opts;
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
            ret = avcodec_encode_audio(enc, audio_out, audio_out_size, 
450
                                       (short *)audio_buf);
451
            audio_size += ret;
452
            av_write_frame(s, ost->index, audio_out, ret);
453
        }
454
    } else {
455
        /* output a pcm frame */
456
        /* XXX: change encoding codec API to avoid this ? */
457
        switch(enc->codec->id) {
458
        case CODEC_ID_PCM_S16LE:
459
        case CODEC_ID_PCM_S16BE:
460
        case CODEC_ID_PCM_U16LE:
461
        case CODEC_ID_PCM_U16BE:
462
            break;
463
        default:
464
            size_out = size_out >> 1;
465
            break;
466
        }
467
        ret = avcodec_encode_audio(enc, audio_out, size_out, 
468
                                   (short *)buftmp);
469
        audio_size += ret;
470
        av_write_frame(s, ost->index, audio_out, ret);
471
    }
472
}
473

    
474
static void pre_process_video_frame(AVInputStream *ist, AVPicture *picture, void **bufp)
475
{
476
    AVCodecContext *dec;
477
    AVPicture *picture2;
478
    AVPicture picture_tmp;
479
    uint8_t *buf = 0;
480

    
481
    dec = &ist->st->codec;
482

    
483
    /* deinterlace : must be done before any resize */
484
    if (do_deinterlace || using_vhook) {
485
        int size;
486

    
487
        /* create temporary picture */
488
        size = avpicture_get_size(dec->pix_fmt, dec->width, dec->height);
489
        buf = av_malloc(size);
490
        if (!buf)
491
            return;
492
        
493
        picture2 = &picture_tmp;
494
        avpicture_fill(picture2, buf, dec->pix_fmt, dec->width, dec->height);
495

    
496
        if (do_deinterlace){
497
            if(avpicture_deinterlace(picture2, picture, 
498
                                     dec->pix_fmt, dec->width, dec->height) < 0) {
499
                /* if error, do not deinterlace */
500
                av_free(buf);
501
                buf = NULL;
502
                picture2 = picture;
503
            }
504
        } else {
505
            if (img_convert(picture2, dec->pix_fmt, picture, 
506
                            dec->pix_fmt, dec->width, dec->height) < 0) {
507
                /* if error, do not copy */
508
                av_free(buf);
509
                buf = NULL;
510
                picture2 = picture;
511
            }
512
        }
513
    } else {
514
        picture2 = picture;
515
    }
516

    
517
    frame_hook_process(picture2, dec->pix_fmt, dec->width, dec->height);
518

    
519
    if (picture != picture2)
520
        *picture = *picture2;
521
    *bufp = buf;
522
}
523

    
524
/* we begin to correct av delay at this threshold */
525
#define AV_DELAY_MAX 0.100
526

    
527

    
528
/* Expects img to be yuv420 */
529
static void fill_pad_region(AVPicture* img, int height, int width,
530
        int padtop, int padbottom, int padleft, int padright, int *color) {
531
  
532
    int i, y, shift;
533
    uint8_t *optr;
534
    
535
    for (i = 0; i < 3; i++) {
536
        shift = (i == 0) ? 0 : 1;
537
        
538
        if (padtop || padleft) {
539
            memset(img->data[i], color[i], (((img->linesize[i] * padtop) + 
540
                            padleft) >> shift));
541
        }
542

    
543
        if (padleft || padright) {
544
            optr = img->data[i] + (img->linesize[i] * (padtop >> shift)) +
545
                (img->linesize[i] - (padright >> shift));
546

    
547
            for (y = 0; y < ((height - (padtop + padbottom)) >> shift); y++) {
548
                memset(optr, color[i], (padleft + padright) >> shift);
549
                optr += img->linesize[i];
550
            }
551
        }
552
      
553
        if (padbottom) {
554
            optr = img->data[i] + (img->linesize[i] * ((height - padbottom) >> shift));
555
            memset(optr, color[i], ((img->linesize[i] * padbottom) >> shift));
556
        }
557
    }
558
}
559

    
560

    
561
static void do_video_out(AVFormatContext *s, 
562
                         AVOutputStream *ost, 
563
                         AVInputStream *ist,
564
                         AVFrame *in_picture,
565
                         int *frame_size, AVOutputStream *audio_sync)
566
{
567
    int nb_frames, i, ret;
568
    AVFrame *final_picture, *formatted_picture;
569
    AVFrame picture_format_temp, picture_crop_temp;
570
    static uint8_t *video_buffer= NULL;
571
    uint8_t *buf = NULL, *buf1 = NULL;
572
    AVCodecContext *enc, *dec;
573
    enum PixelFormat target_pixfmt;
574
    
575
#define VIDEO_BUFFER_SIZE (1024*1024)
576

    
577
    avcodec_get_frame_defaults(&picture_format_temp);
578
    avcodec_get_frame_defaults(&picture_crop_temp);
579

    
580
    enc = &ost->st->codec;
581
    dec = &ist->st->codec;
582

    
583
    /* by default, we output a single frame */
584
    nb_frames = 1;
585

    
586
    *frame_size = 0;
587

    
588
    /* NOTE: the A/V sync is always done by considering the audio is
589
       the master clock. It is suffisant for transcoding or playing,
590
       but not for the general case */
591
  if(sync_method){
592
    if (audio_sync) {
593
        /* compute the A-V delay and duplicate/remove frames if needed */
594
        double adelta, vdelta, av_delay;
595

    
596
        adelta = audio_sync->sync_ipts - ((double)audio_sync->sync_opts * 
597
            s->pts_num / s->pts_den);
598

    
599
        vdelta = ost->sync_ipts - ((double)ost->sync_opts *
600
            s->pts_num / s->pts_den);
601

    
602
        av_delay = adelta - vdelta;
603
        if (av_delay < -AV_DELAY_MAX)
604
            nb_frames = 2;
605
        else if (av_delay > AV_DELAY_MAX)
606
            nb_frames = 0;
607
//        printf("adelta=%f vdelta=%f delay=%f nb=%d (A)\n", adelta, vdelta, av_delay, nb_frames);
608
    } else {
609
        double vdelta;
610

    
611
        vdelta = (double)(ost->st->pts.val) * s->pts_num / s->pts_den - (ost->sync_ipts - ost->sync_ipts_offset);
612
        if (vdelta < 100 && vdelta > -100 && ost->sync_ipts_offset) {
613
            if (vdelta < -AV_DELAY_MAX)
614
                nb_frames = 2;
615
            else if (vdelta > AV_DELAY_MAX)
616
                nb_frames = 0;
617
        } else {
618
            ost->sync_ipts_offset -= vdelta;
619
            if (!ost->sync_ipts_offset)
620
                ost->sync_ipts_offset = 0.000001; /* one microsecond */
621
        }
622
//        printf("delay=%f nb=%d (V)\n",vdelta, nb_frames);
623
    }
624
  }
625
    
626
#if defined(AVSYNC_DEBUG)
627
    {
628
        static char *action[] = { "drop frame", "copy frame", "dup frame" };
629
        if (audio_sync && verbose >=0) {
630
            fprintf(stderr, "Input APTS %12.6f, output APTS %12.6f, ",
631
                    (double) audio_sync->sync_ipts, 
632
                    (double) audio_sync->st->pts.val * s->pts_num / s->pts_den);
633
            fprintf(stderr, "Input VPTS %12.6f, output VPTS %12.6f: %s\n",
634
                    (double) ost->sync_ipts, 
635
                    (double) ost->st->pts.val * s->pts_num / s->pts_den,
636
                    action[nb_frames]);
637
        }
638
    }
639
#endif
640

    
641
    if (nb_frames <= 0) 
642
        return;
643

    
644
    if (!video_buffer)
645
        video_buffer = av_malloc(VIDEO_BUFFER_SIZE);
646
    if (!video_buffer)
647
        return;
648

    
649
    /* convert pixel format if needed */
650
    target_pixfmt = ost->video_resample || ost->video_pad
651
        ? PIX_FMT_YUV420P : enc->pix_fmt;
652
    if (dec->pix_fmt != target_pixfmt) {
653
        int size;
654

    
655
        /* create temporary picture */
656
        size = avpicture_get_size(target_pixfmt, dec->width, dec->height);
657
        buf = av_malloc(size);
658
        if (!buf)
659
            return;
660
        formatted_picture = &picture_format_temp;
661
        avpicture_fill((AVPicture*)formatted_picture, buf, target_pixfmt, dec->width, dec->height);
662
        
663
        if (img_convert((AVPicture*)formatted_picture, target_pixfmt, 
664
                        (AVPicture *)in_picture, dec->pix_fmt, 
665
                        dec->width, dec->height) < 0) {
666

    
667
            if (verbose >= 0)
668
                fprintf(stderr, "pixel format conversion not handled\n");
669

    
670
            goto the_end;
671
        }
672
    } else {
673
        formatted_picture = in_picture;
674
    }
675

    
676
    /* XXX: resampling could be done before raw format conversion in
677
       some cases to go faster */
678
    /* XXX: only works for YUV420P */
679
    if (ost->video_resample) {
680
        final_picture = &ost->pict_tmp;
681
        img_resample(ost->img_resample_ctx, (AVPicture*)final_picture, (AVPicture*)formatted_picture);
682
       
683
        if (ost->padtop || ost->padbottom || ost->padleft || ost->padright) {
684
            fill_pad_region((AVPicture*)final_picture, enc->height, enc->width,
685
                    ost->padtop, ost->padbottom, ost->padleft, ost->padright,
686
                    padcolor);
687
        }
688
        
689
        if (enc->pix_fmt != PIX_FMT_YUV420P) {
690
            int size;
691
            
692
            av_free(buf);
693
            /* create temporary picture */
694
            size = avpicture_get_size(enc->pix_fmt, enc->width, enc->height);
695
            buf = av_malloc(size);
696
            if (!buf)
697
                return;
698
            final_picture = &picture_format_temp;
699
            avpicture_fill((AVPicture*)final_picture, buf, enc->pix_fmt, enc->width, enc->height);
700
        
701
            if (img_convert((AVPicture*)final_picture, enc->pix_fmt, 
702
                            (AVPicture*)&ost->pict_tmp, PIX_FMT_YUV420P, 
703
                            enc->width, enc->height) < 0) {
704

    
705
                if (verbose >= 0)
706
                    fprintf(stderr, "pixel format conversion not handled\n");
707

    
708
                goto the_end;
709
            }
710
        }
711
    } else if (ost->video_crop) {
712
        picture_crop_temp.data[0] = formatted_picture->data[0] +
713
                (ost->topBand * formatted_picture->linesize[0]) + ost->leftBand;
714

    
715
        picture_crop_temp.data[1] = formatted_picture->data[1] +
716
                ((ost->topBand >> 1) * formatted_picture->linesize[1]) +
717
                (ost->leftBand >> 1);
718

    
719
        picture_crop_temp.data[2] = formatted_picture->data[2] +
720
                ((ost->topBand >> 1) * formatted_picture->linesize[2]) +
721
                (ost->leftBand >> 1);
722

    
723
        picture_crop_temp.linesize[0] = formatted_picture->linesize[0];
724
        picture_crop_temp.linesize[1] = formatted_picture->linesize[1];
725
        picture_crop_temp.linesize[2] = formatted_picture->linesize[2];
726
        final_picture = &picture_crop_temp;
727
    } else if (ost->video_pad) {
728
        final_picture = &ost->pict_tmp;
729

    
730
        for (i = 0; i < 3; i++) {
731
            uint8_t *optr, *iptr;
732
            int shift = (i == 0) ? 0 : 1;
733
            int y, yheight;
734
            
735
            /* set offset to start writing image into */
736
            optr = final_picture->data[i] + (((final_picture->linesize[i] * 
737
                            ost->padtop) + ost->padleft) >> shift);
738
            iptr = formatted_picture->data[i];
739

    
740
            yheight = (enc->height - ost->padtop - ost->padbottom) >> shift;
741
            for (y = 0; y < yheight; y++) {
742
                /* copy unpadded image row into padded image row */
743
                memcpy(optr, iptr, formatted_picture->linesize[i]);
744
                optr += final_picture->linesize[i];
745
                iptr += formatted_picture->linesize[i];
746
            }
747
        }
748

    
749
        fill_pad_region((AVPicture*)final_picture, enc->height, enc->width,
750
                ost->padtop, ost->padbottom, ost->padleft, ost->padright,
751
                padcolor);
752
        
753
        if (enc->pix_fmt != PIX_FMT_YUV420P) {
754
            int size;
755

    
756
            av_free(buf);
757
            /* create temporary picture */
758
            size = avpicture_get_size(enc->pix_fmt, enc->width, enc->height);
759
            buf = av_malloc(size);
760
            if (!buf)
761
                return;
762
            final_picture = &picture_format_temp;
763
            avpicture_fill((AVPicture*)final_picture, buf, enc->pix_fmt, enc->width, enc->height);
764

    
765
            if (img_convert((AVPicture*)final_picture, enc->pix_fmt, 
766
                        (AVPicture*)&ost->pict_tmp, PIX_FMT_YUV420P, 
767
                        enc->width, enc->height) < 0) {
768

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

    
772
                goto the_end;
773
            }
774
        }
775
    } else {
776
        final_picture = formatted_picture;
777
    }
778
    /* duplicates frame if needed */
779
    /* XXX: pb because no interleaving */
780
    for(i=0;i<nb_frames;i++) {
781
        if (s->oformat->flags & AVFMT_RAWPICTURE) {
782
            /* raw pictures are written as AVPicture structure to
783
               avoid any copies. We support temorarily the older
784
               method. */
785
            AVFrame* old_frame = enc->coded_frame;
786
            enc->coded_frame = dec->coded_frame;
787
            av_write_frame(s, ost->index, 
788
                           (uint8_t *)final_picture, sizeof(AVPicture));
789
            enc->coded_frame = old_frame;
790
        } else {
791
            AVFrame big_picture;
792

    
793
            big_picture= *final_picture;
794
            /* better than nothing: use input picture interlaced
795
               settings */
796
            big_picture.interlaced_frame = in_picture->interlaced_frame;
797
            if(do_interlace_me || do_interlace_dct){
798
                if(top_field_first == -1)
799
                    big_picture.top_field_first = in_picture->top_field_first;
800
                else
801
                    big_picture.top_field_first = 1;
802
            }
803

    
804
            /* handles sameq here. This is not correct because it may
805
               not be a global option */
806
            if (same_quality) {
807
                big_picture.quality = ist->st->quality;
808
            }else
809
                big_picture.quality = ost->st->quality;
810
            if(!me_threshold)
811
                big_picture.pict_type = 0;
812
            big_picture.pts = AV_NOPTS_VALUE; //FIXME
813
            ret = avcodec_encode_video(enc, 
814
                                       video_buffer, VIDEO_BUFFER_SIZE,
815
                                       &big_picture);
816
            //enc->frame_number = enc->real_pict_num;
817
            av_write_frame(s, ost->index, video_buffer, ret);
818
            *frame_size = ret;
819
            //fprintf(stderr,"\nFrame: %3d %3d size: %5d type: %d",
820
            //        enc->frame_number-1, enc->real_pict_num, ret,
821
            //        enc->pict_type);
822
            /* if two pass, output log */
823
            if (ost->logfile && enc->stats_out) {
824
                fprintf(ost->logfile, "%s", enc->stats_out);
825
            }
826
        }
827
        ost->frame_number++;
828
    }
829
 the_end:
830
    av_free(buf);
831
    av_free(buf1);
832
}
833

    
834
static double psnr(double d){
835
    if(d==0) return INFINITY;
836
    return -10.0*log(d)/log(10.0);
837
}
838

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

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

    
912

    
913
    oc = output_files[0];
914

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

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

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

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

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

    
1077
            buffer_to_free = NULL;
1078
            if (ist->st->codec.codec_type == CODEC_TYPE_VIDEO) {
1079
                pre_process_video_frame(ist, (AVPicture *)&picture, 
1080
                                        &buffer_to_free);
1081
            }
1082

    
1083
            /* frame rate emulation */
1084
            if (ist->st->codec.rate_emu) {
1085
                int64_t pts = av_rescale((int64_t) ist->frame * ist->st->codec.frame_rate_base, 1000000, ist->st->codec.frame_rate);
1086
                int64_t now = av_gettime() - ist->start;
1087
                if (pts > now)
1088
                    usleep(pts - now);
1089

    
1090
                ist->frame++;
1091
            }
1092

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

    
1112
                    ost = ost_table[i];
1113
                    if (ost->source_index == ist_index) {
1114
                        os = output_files[ost->file_index];
1115

    
1116
#if 0
1117
                        printf("%d: got pts=%0.3f %0.3f\n", i, 
1118
                               (double)pkt->pts / AV_TIME_BASE, 
1119
                               ((double)ist->pts / AV_TIME_BASE) - 
1120
                               ((double)ost->st->pts.val * os->pts_num / os->pts_den));
1121
#endif
1122
                        /* set the input output pts pairs */
1123
                        ost->sync_ipts = (double)ist->pts / AV_TIME_BASE;
1124
                        /* XXX: take into account the various fifos,
1125
                           in particular for audio */
1126
                        ost->sync_opts = ost->st->pts.val;
1127
                        //printf("ipts=%lld sync_ipts=%f sync_opts=%lld pts.val=%lld pkt->pts=%lld\n", ist->pts, ost->sync_ipts, ost->sync_opts, ost->st->pts.val, pkt->pts); 
1128

    
1129
                        if (ost->encoding_needed) {
1130
                            switch(ost->st->codec.codec_type) {
1131
                            case CODEC_TYPE_AUDIO:
1132
                                do_audio_out(os, ost, ist, data_buf, data_size);
1133
                                break;
1134
                            case CODEC_TYPE_VIDEO:
1135
                                /* find an audio stream for synchro */
1136
                                {
1137
                                    int i;
1138
                                    AVOutputStream *audio_sync, *ost1;
1139
                                    audio_sync = NULL;
1140
                                    for(i=0;i<nb_ostreams;i++) {
1141
                                        ost1 = ost_table[i];
1142
                                        if (ost1->file_index == ost->file_index &&
1143
                                            ost1->st->codec.codec_type == CODEC_TYPE_AUDIO) {
1144
                                            audio_sync = ost1;
1145
                                            break;
1146
                                        }
1147
                                    }
1148

    
1149
                                    do_video_out(os, ost, ist, &picture, &frame_size, audio_sync);
1150
                                    video_size += frame_size;
1151
                                    if (do_vstats && frame_size)
1152
                                        do_video_stats(os, ost, frame_size);
1153
                                }
1154
                                break;
1155
                            default:
1156
                                av_abort();
1157
                            }
1158
                        } else {
1159
                            AVFrame avframe;
1160
                                                
1161
                            /* no reencoding needed : output the packet directly */
1162
                            /* force the input stream PTS */
1163
                        
1164
                            avcodec_get_frame_defaults(&avframe);
1165
                            ost->st->codec.coded_frame= &avframe;
1166
                            avframe.key_frame = pkt->flags & PKT_FLAG_KEY; 
1167
                            ost->st->pts.val= av_rescale(ist->pts, os->pts_den, os->pts_num*AV_TIME_BASE);
1168

    
1169
                            av_write_frame(os, ost->index, data_buf, data_size);
1170
                            ost->st->codec.frame_number++;
1171
                            ost->frame_number++;
1172
                        }
1173
                    }
1174
                }
1175
            av_free(buffer_to_free);
1176
        }
1177
 discard_packet:
1178
    return 0;
1179
 fail_decode:
1180
    return -1;
1181
}
1182

    
1183

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

    
1202
    file_table= (AVInputFile*) av_mallocz(nb_input_files * sizeof(AVInputFile));
1203
    if (!file_table)
1204
        goto fail;
1205

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

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

    
1237
            if (ist->st->codec.rate_emu) {
1238
                ist->start = av_gettime();
1239
                ist->frame = 0;
1240
            }
1241
        }
1242
    }
1243

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

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

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

    
1336
        codec = &ost->st->codec;
1337
        icodec = &ist->st->codec;
1338

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

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

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

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

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

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

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

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

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

    
1606
    stream_no_data = 0;
1607
    key = -1;
1608

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

    
1625
        /* select the stream that we must read now by looking at the
1626
           smallest output pts */
1627
        file_index = -1;
1628
        pts_min = 1e10;
1629
        for(i=0;i<nb_ostreams;i++) {
1630
            double pts;
1631
            ost = ost_table[i];
1632
            os = output_files[ost->file_index];
1633
            ist = ist_table[ost->source_index];
1634
            pts = (double)ost->st->pts.val * os->pts_num / os->pts_den;
1635
            if (!file_table[ist->file_index].eof_reached && 
1636
                pts < pts_min) {
1637
                pts_min = pts;
1638
                file_index = ist->file_index;
1639
            }
1640
        }
1641
        /* if none, if is finished */
1642
        if (file_index < 0) {
1643
            break;
1644
        }
1645

    
1646
        /* finish if recording time exhausted */
1647
        if (recording_time > 0 && pts_min >= (recording_time / 1000000.0))
1648
            break;
1649

    
1650
        /* read a frame from it and output it in the fifo */
1651
        is = input_files[file_index];
1652
        if (av_read_frame(is, &pkt) < 0) {
1653
            file_table[file_index].eof_reached = 1;
1654
            continue;
1655
        }
1656

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

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

    
1677
            if (verbose >= 0)
1678
                fprintf(stderr, "Error while decoding stream #%d.%d\n",
1679
                        ist->file_index, ist->index);
1680

    
1681
            av_free_packet(&pkt);
1682
            goto redo;
1683
        }
1684
        
1685
    discard_packet:
1686
        av_free_packet(&pkt);
1687
        
1688
        /* dump report by using the output first video and audio streams */
1689
        print_report(output_files, ost_table, nb_ostreams, 0);
1690
    }
1691

    
1692
    /* at the end of stream, we must flush the decoder buffers */
1693
    for(i=0;i<nb_istreams;i++) {
1694
        ist = ist_table[i];
1695
        if (ist->decoding_needed) {
1696
            output_packet(ist, i, ost_table, nb_ostreams, NULL);
1697
        }
1698
    }
1699

    
1700
    term_exit();
1701

    
1702
    /* write the trailer if needed and close file */
1703
    for(i=0;i<nb_output_files;i++) {
1704
        os = output_files[i];
1705
        av_write_trailer(os);
1706
    }
1707

    
1708
    /* dump report by using the first video and audio streams */
1709
    print_report(output_files, ost_table, nb_ostreams, 1);
1710

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

    
1728
    /* finished ! */
1729
    
1730
    ret = 0;
1731
 fail1:
1732
    av_free(file_table);
1733

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

    
1767
#if 0
1768
int file_read(const char *filename)
1769
{
1770
    URLContext *h;
1771
    unsigned char buffer[1024];
1772
    int len, i;
1773

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

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

    
1804
static void opt_format(const char *arg)
1805
{
1806
    /* compatibility stuff for pgmyuv */
1807
    if (!strcmp(arg, "pgmyuv")) {
1808
        opt_image_format(arg);
1809
        arg = "image";
1810
    }
1811

    
1812
    file_iformat = av_find_input_format(arg);
1813
    file_oformat = guess_format(arg, NULL, NULL);
1814
    if (!file_iformat && !file_oformat) {
1815
        fprintf(stderr, "Unknown input or output format: %s\n", arg);
1816
        exit(1);
1817
    }
1818
}
1819

    
1820
static void opt_video_bitrate(const char *arg)
1821
{
1822
    video_bit_rate = atoi(arg) * 1000;
1823
}
1824

    
1825
static void opt_video_bitrate_tolerance(const char *arg)
1826
{
1827
    video_bit_rate_tolerance = atoi(arg) * 1000;
1828
}
1829

    
1830
static void opt_video_bitrate_max(const char *arg)
1831
{
1832
    video_rc_max_rate = atoi(arg) * 1000;
1833
}
1834

    
1835
static void opt_video_bitrate_min(const char *arg)
1836
{
1837
    video_rc_min_rate = atoi(arg) * 1000;
1838
}
1839

    
1840
static void opt_video_buffer_size(const char *arg)
1841
{
1842
    video_rc_buffer_size = atoi(arg) * 8*1024;
1843
}
1844

    
1845
static void opt_video_rc_eq(char *arg)
1846
{
1847
    video_rc_eq = arg;
1848
}
1849

    
1850
static void opt_video_rc_override_string(char *arg)
1851
{
1852
    video_rc_override_string = arg;
1853
}
1854

    
1855

    
1856
static void opt_workaround_bugs(const char *arg)
1857
{
1858
    workaround_bugs = atoi(arg);
1859
}
1860

    
1861
static void opt_dct_algo(const char *arg)
1862
{
1863
    dct_algo = atoi(arg);
1864
}
1865

    
1866
static void opt_idct_algo(const char *arg)
1867
{
1868
    idct_algo = atoi(arg);
1869
}
1870

    
1871
static void opt_me_threshold(const char *arg)
1872
{
1873
    me_threshold = atoi(arg);
1874
}
1875

    
1876
static void opt_mb_threshold(const char *arg)
1877
{
1878
    mb_threshold = atoi(arg);
1879
}
1880

    
1881
static void opt_error_resilience(const char *arg)
1882
{
1883
    error_resilience = atoi(arg);
1884
}
1885

    
1886
static void opt_error_concealment(const char *arg)
1887
{
1888
    error_concealment = atoi(arg);
1889
}
1890

    
1891
static void opt_debug(const char *arg)
1892
{
1893
    debug = atoi(arg);
1894
}
1895

    
1896
static void opt_vismv(const char *arg)
1897
{
1898
    debug_mv = atoi(arg);
1899
}
1900
    
1901
static void opt_verbose(const char *arg)
1902
{
1903
    verbose = atoi(arg);
1904
    av_log_set_level(atoi(arg));
1905
}
1906

    
1907
static void opt_sync_method(const char *arg)
1908
{
1909
    sync_method = atoi(arg);
1910
}
1911

    
1912
static void opt_frame_rate(const char *arg)
1913
{
1914
    if (parse_frame_rate(&frame_rate, &frame_rate_base, arg) < 0) {
1915
        fprintf(stderr, "Incorrect frame rate\n");
1916
        exit(1);
1917
    }
1918
}
1919

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

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

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

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

    
1992
static void opt_frame_size(const char *arg)
1993
{
1994
    if (parse_image_size(&frame_width, &frame_height, arg) < 0) {
1995
        fprintf(stderr, "Incorrect frame size\n");
1996
        exit(1);
1997
    }
1998
    if ((frame_width % 2) != 0 || (frame_height % 2) != 0) {
1999
        fprintf(stderr, "Frame size must be a multiple of 2\n");
2000
        exit(1);
2001
    }
2002
}
2003

    
2004

    
2005
#define SCALEBITS 10
2006
#define ONE_HALF  (1 << (SCALEBITS - 1))
2007
#define FIX(x)          ((int) ((x) * (1<<SCALEBITS) + 0.5))
2008

    
2009
#define RGB_TO_Y(r, g, b) \
2010
((FIX(0.29900) * (r) + FIX(0.58700) * (g) + \
2011
  FIX(0.11400) * (b) + ONE_HALF) >> SCALEBITS)
2012

    
2013
#define RGB_TO_U(r1, g1, b1, shift)\
2014
(((- FIX(0.16874) * r1 - FIX(0.33126) * g1 +         \
2015
     FIX(0.50000) * b1 + (ONE_HALF << shift) - 1) >> (SCALEBITS + shift)) + 128)
2016

    
2017
#define RGB_TO_V(r1, g1, b1, shift)\
2018
(((FIX(0.50000) * r1 - FIX(0.41869) * g1 -           \
2019
   FIX(0.08131) * b1 + (ONE_HALF << shift) - 1) >> (SCALEBITS + shift)) + 128)
2020

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

    
2031
    padcolor[0] = RGB_TO_Y(r,g,b);
2032
    padcolor[1] = RGB_TO_U(r,g,b,0);
2033
    padcolor[2] = RGB_TO_V(r,g,b,0);
2034
}
2035

    
2036
static void opt_frame_pad_top(const char *arg)
2037
{
2038
    frame_padtop = atoi(arg); 
2039
    if (frame_padtop < 0) {
2040
        fprintf(stderr, "Incorrect top pad size\n");
2041
        exit(1);
2042
    }
2043
    if ((frame_padtop % 2) != 0) {
2044
        fprintf(stderr, "Top pad size must be a multiple of 2\n");
2045
        exit(1);
2046
    }
2047
}
2048

    
2049
static void opt_frame_pad_bottom(const char *arg)
2050
{
2051
    frame_padbottom = atoi(arg); 
2052
    if (frame_padbottom < 0) {
2053
        fprintf(stderr, "Incorrect bottom pad size\n");
2054
        exit(1);
2055
    }
2056
    if ((frame_padbottom % 2) != 0) {
2057
        fprintf(stderr, "Bottom pad size must be a multiple of 2\n");
2058
        exit(1);
2059
    }
2060
}
2061

    
2062

    
2063
static void opt_frame_pad_left(const char *arg)
2064
{
2065
    frame_padleft = atoi(arg); 
2066
    if (frame_padleft < 0) {
2067
        fprintf(stderr, "Incorrect left pad size\n");
2068
        exit(1);
2069
    }
2070
    if ((frame_padleft % 2) != 0) {
2071
        fprintf(stderr, "Left pad size must be a multiple of 2\n");
2072
        exit(1);
2073
    }
2074
}
2075

    
2076

    
2077
static void opt_frame_pad_right(const char *arg)
2078
{
2079
    frame_padright = atoi(arg); 
2080
    if (frame_padright < 0) {
2081
        fprintf(stderr, "Incorrect right pad size\n");
2082
        exit(1);
2083
    }
2084
    if ((frame_padright % 2) != 0) {
2085
        fprintf(stderr, "Right pad size must be a multiple of 2\n");
2086
        exit(1);
2087
    }
2088
}
2089

    
2090

    
2091
static void opt_frame_pix_fmt(const char *arg)
2092
{
2093
    frame_pix_fmt = avcodec_get_pix_fmt(arg);
2094
}
2095

    
2096
static void opt_frame_aspect_ratio(const char *arg)
2097
{
2098
    int x = 0, y = 0;
2099
    double ar = 0;
2100
    const char *p;
2101
    
2102
    p = strchr(arg, ':');
2103
    if (p) {
2104
        x = strtol(arg, (char **)&arg, 10);
2105
        if (arg == p)
2106
            y = strtol(arg+1, (char **)&arg, 10);
2107
        if (x > 0 && y > 0)
2108
            ar = (double)x / (double)y;
2109
    } else
2110
        ar = strtod(arg, (char **)&arg);
2111

    
2112
    if (!ar) {
2113
        fprintf(stderr, "Incorrect aspect ratio specification.\n");
2114
        exit(1);
2115
    }
2116
    frame_aspect_ratio = ar;
2117
}
2118

    
2119
static void opt_gop_size(const char *arg)
2120
{
2121
    gop_size = atoi(arg);
2122
}
2123

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

    
2136
static void opt_mb_decision(const char *arg)
2137
{
2138
    mb_decision = atoi(arg);
2139
}
2140

    
2141
static void opt_mb_cmp(const char *arg)
2142
{
2143
    mb_cmp = atoi(arg);
2144
}
2145

    
2146
static void opt_ildct_cmp(const char *arg)
2147
{
2148
    ildct_cmp = atoi(arg);
2149
}
2150

    
2151
static void opt_sub_cmp(const char *arg)
2152
{
2153
    sub_cmp = atoi(arg);
2154
}
2155

    
2156
static void opt_cmp(const char *arg)
2157
{
2158
    cmp = atoi(arg);
2159
}
2160

    
2161
static void opt_pre_cmp(const char *arg)
2162
{
2163
    pre_cmp = atoi(arg);
2164
}
2165

    
2166
static void opt_pre_me(const char *arg)
2167
{
2168
    pre_me = atoi(arg);
2169
}
2170

    
2171
static void opt_lumi_mask(const char *arg)
2172
{
2173
    lumi_mask = atof(arg);
2174
}
2175

    
2176
static void opt_dark_mask(const char *arg)
2177
{
2178
    dark_mask = atof(arg);
2179
}
2180

    
2181
static void opt_scplx_mask(const char *arg)
2182
{
2183
    scplx_mask = atof(arg);
2184
}
2185

    
2186
static void opt_tcplx_mask(const char *arg)
2187
{
2188
    tcplx_mask = atof(arg);
2189
}
2190

    
2191
static void opt_p_mask(const char *arg)
2192
{
2193
    p_mask = atof(arg);
2194
}
2195

    
2196
static void opt_qscale(const char *arg)
2197
{
2198
    video_qscale = atof(arg);
2199
    if (video_qscale < 0.01 ||
2200
        video_qscale > 255) {
2201
        fprintf(stderr, "qscale must be >= 0.01 and <= 255\n");
2202
        exit(1);
2203
    }
2204
}
2205

    
2206
static void opt_lmax(const char *arg)
2207
{
2208
    video_lmax = atof(arg)*FF_QP2LAMBDA;
2209
}
2210

    
2211
static void opt_lmin(const char *arg)
2212
{
2213
    video_lmin = atof(arg)*FF_QP2LAMBDA;
2214
}
2215

    
2216
static void opt_qmin(const char *arg)
2217
{
2218
    video_qmin = atoi(arg);
2219
    if (video_qmin < 0 ||
2220
        video_qmin > 31) {
2221
        fprintf(stderr, "qmin must be >= 1 and <= 31\n");
2222
        exit(1);
2223
    }
2224
}
2225

    
2226
static void opt_qmax(const char *arg)
2227
{
2228
    video_qmax = atoi(arg);
2229
    if (video_qmax < 0 ||
2230
        video_qmax > 31) {
2231
        fprintf(stderr, "qmax must be >= 1 and <= 31\n");
2232
        exit(1);
2233
    }
2234
}
2235

    
2236
static void opt_mb_qmin(const char *arg)
2237
{
2238
    video_mb_qmin = atoi(arg);
2239
    if (video_mb_qmin < 0 ||
2240
        video_mb_qmin > 31) {
2241
        fprintf(stderr, "qmin must be >= 1 and <= 31\n");
2242
        exit(1);
2243
    }
2244
}
2245

    
2246
static void opt_mb_qmax(const char *arg)
2247
{
2248
    video_mb_qmax = atoi(arg);
2249
    if (video_mb_qmax < 0 ||
2250
        video_mb_qmax > 31) {
2251
        fprintf(stderr, "qmax must be >= 1 and <= 31\n");
2252
        exit(1);
2253
    }
2254
}
2255

    
2256
static void opt_qdiff(const char *arg)
2257
{
2258
    video_qdiff = atoi(arg);
2259
    if (video_qdiff < 0 ||
2260
        video_qdiff > 31) {
2261
        fprintf(stderr, "qdiff must be >= 1 and <= 31\n");
2262
        exit(1);
2263
    }
2264
}
2265

    
2266
static void opt_qblur(const char *arg)
2267
{
2268
    video_qblur = atof(arg);
2269
}
2270

    
2271
static void opt_qcomp(const char *arg)
2272
{
2273
    video_qcomp = atof(arg);
2274
}
2275

    
2276
static void opt_rc_initial_cplx(const char *arg)
2277
{
2278
    video_rc_initial_cplx = atof(arg);
2279
}
2280
static void opt_b_qfactor(const char *arg)
2281
{
2282
    video_b_qfactor = atof(arg);
2283
}
2284
static void opt_i_qfactor(const char *arg)
2285
{
2286
    video_i_qfactor = atof(arg);
2287
}
2288
static void opt_b_qoffset(const char *arg)
2289
{
2290
    video_b_qoffset = atof(arg);
2291
}
2292
static void opt_i_qoffset(const char *arg)
2293
{
2294
    video_i_qoffset = atof(arg);
2295
}
2296

    
2297
static void opt_ibias(const char *arg)
2298
{
2299
    video_intra_quant_bias = atoi(arg);
2300
}
2301
static void opt_pbias(const char *arg)
2302
{
2303
    video_inter_quant_bias = atoi(arg);
2304
}
2305

    
2306
static void opt_packet_size(const char *arg)
2307
{
2308
    packet_size= atoi(arg);
2309
}
2310

    
2311
static void opt_error_rate(const char *arg)
2312
{
2313
    error_rate= atoi(arg);
2314
}
2315

    
2316
static void opt_strict(const char *arg)
2317
{
2318
    strict= atoi(arg);
2319
}
2320

    
2321
static void opt_top_field_first(const char *arg)
2322
{
2323
    top_field_first= atoi(arg);
2324
}
2325

    
2326
static void opt_noise_reduction(const char *arg)
2327
{
2328
    noise_reduction= atoi(arg);
2329
}
2330

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

    
2336
static void opt_sc_threshold(const char *arg)
2337
{
2338
    sc_threshold= atoi(arg);
2339
}
2340

    
2341
static void opt_me_range(const char *arg)
2342
{
2343
    me_range = atoi(arg);
2344
}
2345

    
2346
static void opt_thread_count(const char *arg)
2347
{
2348
    thread_count= atoi(arg);
2349
#if !defined(HAVE_PTHREADS) && !defined(HAVE_W32THREADS)
2350
    if (verbose >= 0)
2351
        fprintf(stderr, "Warning: not compiled with thread support, using thread emulation\n");
2352
#endif
2353
}
2354

    
2355
static void opt_audio_bitrate(const char *arg)
2356
{
2357
    audio_bit_rate = atoi(arg) * 1000;
2358
}
2359

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

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

    
2370
static void opt_video_device(const char *arg)
2371
{
2372
    video_device = av_strdup(arg);
2373
}
2374

    
2375
static void opt_video_channel(const char *arg)
2376
{
2377
    video_channel = strtol(arg, NULL, 0);
2378
}
2379

    
2380
static void opt_video_standard(const char *arg)
2381
{
2382
    video_standard = av_strdup(arg);
2383
}
2384

    
2385
static void opt_audio_device(const char *arg)
2386
{
2387
    audio_device = av_strdup(arg);
2388
}
2389

    
2390
static void opt_dv1394(const char *arg)
2391
{
2392
    video_grab_format = "dv1394";
2393
    audio_grab_format = NULL;
2394
}
2395

    
2396
static void opt_audio_codec(const char *arg)
2397
{
2398
    AVCodec *p;
2399

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

    
2418
static void add_frame_hooker(const char *arg)
2419
{
2420
    int argc = 0;
2421
    char *argv[64];
2422
    int i;
2423
    char *args = av_strdup(arg);
2424

    
2425
    using_vhook = 1;
2426

    
2427
    argv[0] = strtok(args, " ");
2428
    while (argc < 62 && (argv[++argc] = strtok(NULL, " "))) {
2429
    }
2430

    
2431
    i = frame_hook_add(argc, argv);
2432

    
2433
    if (i != 0) {
2434
        fprintf(stderr, "Failed to add video hook function: %s\n", arg);
2435
        exit(1);
2436
    }
2437
}
2438

    
2439
const char *motion_str[] = {
2440
    "zero",
2441
    "full",
2442
    "log",
2443
    "phods",
2444
    "epzs",
2445
    "x1",
2446
    NULL,
2447
};
2448

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

    
2465
static void opt_video_codec(const char *arg)
2466
{
2467
    AVCodec *p;
2468

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

    
2487
static void opt_map(const char *arg)
2488
{
2489
    AVStreamMap *m;
2490
    const char *p;
2491

    
2492
    p = arg;
2493
    m = &stream_maps[nb_stream_maps++];
2494

    
2495
    m->file_index = strtol(arg, (char **)&p, 0);
2496
    if (*p)
2497
        p++;
2498

    
2499
    m->stream_index = strtol(p, (char **)&p, 0);
2500
}
2501

    
2502
static void opt_recording_time(const char *arg)
2503
{
2504
    recording_time = parse_date(arg, 1);
2505
}
2506

    
2507
static void opt_start_time(const char *arg)
2508
{
2509
    start_time = parse_date(arg, 1);
2510
}
2511

    
2512
static void opt_rec_timestamp(const char *arg)
2513
{
2514
    rec_timestamp = parse_date(arg, 0) / 1000000;
2515
}
2516

    
2517
static void opt_input_file(const char *filename)
2518
{
2519
    AVFormatContext *ic;
2520
    AVFormatParameters params, *ap = &params;
2521
    int err, i, ret, rfps, rfps_base;
2522

    
2523
    if (!strcmp(filename, "-"))
2524
        filename = "pipe:";
2525

    
2526
    using_stdin |= !strcmp(filename, "pipe:" ) || 
2527
                   !strcmp( filename, "/dev/stdin" );
2528

    
2529
    /* get default parameters from command line */
2530
    memset(ap, 0, sizeof(*ap));
2531
    ap->sample_rate = audio_sample_rate;
2532
    ap->channels = audio_channels;
2533
    ap->frame_rate = frame_rate;
2534
    ap->frame_rate_base = frame_rate_base;
2535
    ap->width = frame_width + frame_padleft + frame_padright;
2536
    ap->height = frame_height + frame_padtop + frame_padbottom;
2537
    ap->image_format = image_format;
2538
    ap->pix_fmt = frame_pix_fmt;
2539

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

    
2555
    /* if seeking requested, we execute it */
2556
    if (start_time != 0) {
2557
        int64_t timestamp;
2558

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

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

    
2604
            assert(enc->frame_rate_base == rfps_base); // should be true for now
2605
            if (enc->frame_rate != rfps) { 
2606

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

    
2611
                    (float)rfps / rfps_base);
2612
            }
2613
            /* update the current frame rate to match the stream frame rate */
2614
            frame_rate      = rfps;
2615
            frame_rate_base = rfps_base;
2616

    
2617
            enc->rate_emu = rate_emu;
2618
            break;
2619
        case CODEC_TYPE_DATA:
2620
            break;
2621
        default:
2622
            av_abort();
2623
        }
2624
    }
2625
    
2626
    input_files[nb_input_files] = ic;
2627
    /* dump the file content */
2628
    if (verbose >= 0)
2629
        dump_format(ic, nb_input_files, filename, 0);
2630

    
2631
    nb_input_files++;
2632
    file_iformat = NULL;
2633
    file_oformat = NULL;
2634
    image_format = NULL;
2635

    
2636
    rate_emu = 0;
2637
}
2638

    
2639
static void check_audio_video_inputs(int *has_video_ptr, int *has_audio_ptr)
2640
{
2641
    int has_video, has_audio, i, j;
2642
    AVFormatContext *ic;
2643

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

    
2668
static void opt_output_file(const char *filename)
2669
{
2670
    AVStream *st;
2671
    AVFormatContext *oc;
2672
    int use_video, use_audio, nb_streams, input_has_video, input_has_audio;
2673
    int codec_id;
2674
    AVFormatParameters params, *ap = &params;
2675

    
2676
    if (!strcmp(filename, "-"))
2677
        filename = "pipe:";
2678

    
2679
    oc = av_alloc_format_context();
2680

    
2681
    if (!file_oformat) {
2682
        file_oformat = guess_format(NULL, filename, NULL);
2683
        if (!file_oformat) {
2684
            fprintf(stderr, "Unable for find a suitable output format for '%s'\n",
2685
                    filename);
2686
            exit(1);
2687
        }
2688
    }
2689
    
2690
    oc->oformat = file_oformat;
2691

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

    
2704
        /* disable if no corresponding type found and at least one
2705
           input file */
2706
        if (nb_input_files > 0) {
2707
            check_audio_video_inputs(&input_has_video, &input_has_audio);
2708
            if (!input_has_video)
2709
                use_video = 0;
2710
            if (!input_has_audio)
2711
                use_audio = 0;
2712
        }
2713

    
2714
        /* manual disable */
2715
        if (audio_disable) {
2716
            use_audio = 0;
2717
        }
2718
        if (video_disable) {
2719
            use_video = 0;
2720
        }
2721
        
2722
        nb_streams = 0;
2723
        if (use_video) {
2724
            AVCodecContext *video_enc;
2725
            
2726
            st = av_mallocz(sizeof(AVStream));
2727
            if (!st) {
2728
                fprintf(stderr, "Could not alloc stream\n");
2729
                exit(1);
2730
            }
2731
            avcodec_get_context_defaults(&st->codec);
2732
#if defined(HAVE_PTHREADS) || defined(HAVE_W32THREADS)
2733
            if(thread_count>1)
2734
                avcodec_thread_init(&st->codec, thread_count);
2735
#endif
2736

    
2737
            video_enc = &st->codec;
2738
            
2739
            if(!strcmp(file_oformat->name, "mp4") || !strcmp(file_oformat->name, "mov") || !strcmp(file_oformat->name, "3gp"))
2740
                video_enc->flags |= CODEC_FLAG_GLOBAL_HEADER;
2741
            if (video_stream_copy) {
2742
                st->stream_copy = 1;
2743
                video_enc->codec_type = CODEC_TYPE_VIDEO;
2744
            } else {
2745
                char *p;
2746
                int i;
2747
                AVCodec *codec;
2748
            
2749
                codec_id = file_oformat->video_codec;
2750
                if (video_codec_id != CODEC_ID_NONE)
2751
                    codec_id = video_codec_id;
2752
                
2753
                video_enc->codec_id = codec_id;
2754
                
2755
                video_enc->bit_rate = video_bit_rate;
2756
                video_enc->bit_rate_tolerance = video_bit_rate_tolerance;
2757
                video_enc->frame_rate = frame_rate; 
2758
                video_enc->frame_rate_base = frame_rate_base; 
2759
                
2760
                video_enc->width = frame_width + frame_padright + frame_padleft;
2761
                video_enc->height = frame_height + frame_padtop + frame_padbottom;
2762
                video_enc->sample_aspect_ratio = av_d2q(frame_aspect_ratio*frame_height/frame_width, 255);
2763
                video_enc->pix_fmt = frame_pix_fmt;
2764

    
2765
                codec = avcodec_find_encoder(codec_id);
2766
                if(codec && codec->pix_fmts){
2767
                    const enum PixelFormat *p= codec->pix_fmts;
2768
                    for(; *p!=-1; p++){
2769
                        if(*p == video_enc->pix_fmt)
2770
                            break;
2771
                    }
2772
                    if(*p == -1)
2773
                        video_enc->pix_fmt = codec->pix_fmts[0];
2774
                }
2775

    
2776
                if (!intra_only)
2777
                    video_enc->gop_size = gop_size;
2778
                else
2779
                    video_enc->gop_size = 0;
2780
                if (video_qscale || same_quality) {
2781
                    video_enc->flags |= CODEC_FLAG_QSCALE;
2782
                    st->quality = FF_QP2LAMBDA * video_qscale;
2783
                }
2784

    
2785
                if(intra_matrix)
2786
                    video_enc->intra_matrix = intra_matrix;
2787
                if(inter_matrix)
2788
                    video_enc->inter_matrix = inter_matrix;
2789

    
2790
                if(bitexact)
2791
                    video_enc->flags |= CODEC_FLAG_BITEXACT;
2792

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

    
2897
                video_enc->rc_max_rate = video_rc_max_rate;
2898
                video_enc->rc_min_rate = video_rc_min_rate;
2899
                video_enc->rc_buffer_size = video_rc_buffer_size;
2900
                video_enc->rc_buffer_aggressivity= video_rc_buffer_aggressivity;
2901
                video_enc->rc_initial_cplx= video_rc_initial_cplx;
2902
                video_enc->i_quant_factor = video_i_qfactor;
2903
                video_enc->b_quant_factor = video_b_qfactor;
2904
                video_enc->i_quant_offset = video_i_qoffset;
2905
                video_enc->b_quant_offset = video_b_qoffset;
2906
                video_enc->intra_quant_bias = video_intra_quant_bias;
2907
                video_enc->inter_quant_bias = video_inter_quant_bias;
2908
                video_enc->dct_algo = dct_algo;
2909
                video_enc->idct_algo = idct_algo;
2910
                video_enc->me_threshold= me_threshold;
2911
                video_enc->mb_threshold= mb_threshold;
2912
                video_enc->intra_dc_precision= intra_dc_precision;
2913
                video_enc->strict_std_compliance = strict;
2914
                video_enc->error_rate = error_rate;
2915
                video_enc->noise_reduction= noise_reduction;
2916
                video_enc->scenechange_threshold= sc_threshold;
2917
                video_enc->me_range = me_range;
2918
                video_enc->coder_type= coder;
2919
                video_enc->context_model= context;
2920
                video_enc->prediction_method= predictor;
2921

    
2922
                if(packet_size){
2923
                    video_enc->rtp_mode= 1;
2924
                    video_enc->rtp_payload_size= packet_size;
2925
                }
2926
            
2927
                if (do_psnr)
2928
                    video_enc->flags|= CODEC_FLAG_PSNR;
2929
            
2930
                video_enc->me_method = me_method;
2931

    
2932
                /* two pass mode */
2933
                if (do_pass) {
2934
                    if (do_pass == 1) {
2935
                        video_enc->flags |= CODEC_FLAG_PASS1;
2936
                    } else {
2937
                        video_enc->flags |= CODEC_FLAG_PASS2;
2938
                    }
2939
                }
2940
            }
2941
            oc->streams[nb_streams] = st;
2942
            nb_streams++;
2943
        }
2944
    
2945
        if (use_audio) {
2946
            AVCodecContext *audio_enc;
2947

    
2948
            st = av_mallocz(sizeof(AVStream));
2949
            if (!st) {
2950
                fprintf(stderr, "Could not alloc stream\n");
2951
                exit(1);
2952
            }
2953
            avcodec_get_context_defaults(&st->codec);
2954
#if defined(HAVE_PTHREADS) || defined(HAVE_W32THREADS)
2955
            if(thread_count>1)
2956
                avcodec_thread_init(&st->codec, thread_count);
2957
#endif
2958

    
2959
            audio_enc = &st->codec;
2960
            audio_enc->codec_type = CODEC_TYPE_AUDIO;
2961

    
2962
            if(!strcmp(file_oformat->name, "mp4") || !strcmp(file_oformat->name, "mov") || !strcmp(file_oformat->name, "3gp"))
2963
                audio_enc->flags |= CODEC_FLAG_GLOBAL_HEADER;
2964
            if (audio_stream_copy) {
2965
                st->stream_copy = 1;
2966
            } else {
2967
                codec_id = file_oformat->audio_codec;
2968
                if (audio_codec_id != CODEC_ID_NONE)
2969
                    codec_id = audio_codec_id;
2970
                audio_enc->codec_id = codec_id;
2971
                
2972
                audio_enc->bit_rate = audio_bit_rate;
2973
                audio_enc->sample_rate = audio_sample_rate;
2974
                audio_enc->strict_std_compliance = strict;
2975
                audio_enc->thread_count = thread_count;
2976
                /* For audio codecs other than AC3 we limit */
2977
                /* the number of coded channels to stereo   */
2978
                if (audio_channels > 2 && codec_id != CODEC_ID_AC3) {
2979
                    audio_enc->channels = 2;
2980
                } else
2981
                    audio_enc->channels = audio_channels;
2982
            }
2983
            oc->streams[nb_streams] = st;
2984
            nb_streams++;
2985
        }
2986

    
2987
        oc->nb_streams = nb_streams;
2988

    
2989
        if (!nb_streams) {
2990
            fprintf(stderr, "No audio or video streams available\n");
2991
            exit(1);
2992
        }
2993

    
2994
        oc->timestamp = rec_timestamp;
2995
            
2996
        if (str_title)
2997
            pstrcpy(oc->title, sizeof(oc->title), str_title);
2998
        if (str_author)
2999
            pstrcpy(oc->author, sizeof(oc->author), str_author);
3000
        if (str_copyright)
3001
            pstrcpy(oc->copyright, sizeof(oc->copyright), str_copyright);
3002
        if (str_comment)
3003
            pstrcpy(oc->comment, sizeof(oc->comment), str_comment);
3004
    }
3005

    
3006
    output_files[nb_output_files++] = oc;
3007

    
3008
    strcpy(oc->filename, filename);
3009

    
3010
    /* check filename in case of an image number is expected */
3011
    if (oc->oformat->flags & AVFMT_NEEDNUMBER) {
3012
        if (filename_number_test(oc->filename) < 0) {
3013
            print_error(oc->filename, AVERROR_NUMEXPECTED);
3014
            exit(1);
3015
        }
3016
    }
3017

    
3018
    if (!(oc->oformat->flags & AVFMT_NOFILE)) {
3019
        /* test if it already exists to avoid loosing precious files */
3020
        if (!file_overwrite && 
3021
            (strchr(filename, ':') == NULL ||
3022
             strstart(filename, "file:", NULL))) {
3023
            if (url_exist(filename)) {
3024
                int c;
3025
                
3026
                if ( !using_stdin ) {
3027
                    fprintf(stderr,"File '%s' already exists. Overwrite ? [y/N] ", filename);
3028
                    fflush(stderr);
3029
                    c = getchar();
3030
                    if (toupper(c) != 'Y') {
3031
                        fprintf(stderr, "Not overwriting - exiting\n");
3032
                        exit(1);
3033
                    }
3034
                                }
3035
                                else {
3036
                    fprintf(stderr,"File '%s' already exists. Exiting.\n", filename);
3037
                    exit(1);
3038
                                }
3039
            }
3040
        }
3041
        
3042
        /* open the file */
3043
        if (url_fopen(&oc->pb, filename, URL_WRONLY) < 0) {
3044
            fprintf(stderr, "Could not open '%s'\n", filename);
3045
            exit(1);
3046
        }
3047
    }
3048

    
3049
    memset(ap, 0, sizeof(*ap));
3050
    ap->image_format = image_format;
3051
    if (av_set_parameters(oc, ap) < 0) {
3052
        fprintf(stderr, "%s: Invalid encoding parameters\n",
3053
                oc->filename);
3054
        exit(1);
3055
    }
3056

    
3057
    /* reset some options */
3058
    file_oformat = NULL;
3059
    file_iformat = NULL;
3060
    image_format = NULL;
3061
    audio_disable = 0;
3062
    video_disable = 0;
3063
    audio_codec_id = CODEC_ID_NONE;
3064
    video_codec_id = CODEC_ID_NONE;
3065
    audio_stream_copy = 0;
3066
    video_stream_copy = 0;
3067
}
3068

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

    
3140
        if (verbose >= 0)
3141
            dump_format(ic, nb_input_files, "", 0);
3142

    
3143
        nb_input_files++;
3144
    }
3145
    if (has_audio && audio_grab_format) {
3146
        AVInputFormat *fmt1;
3147
        fmt1 = av_find_input_format(audio_grab_format);
3148
        ap->device = audio_device;
3149
        if (av_open_input_file(&ic, "", fmt1, 0, ap) < 0) {
3150
            fprintf(stderr, "Could not find audio grab device\n");
3151
            exit(1);
3152
        }
3153
        input_files[nb_input_files] = ic;
3154

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

    
3158
        nb_input_files++;
3159
    }
3160
}
3161

    
3162
/* same option as mencoder */
3163
static void opt_pass(const char *pass_str)
3164
{
3165
    int pass;
3166
    pass = atoi(pass_str);
3167
    if (pass != 1 && pass != 2) {
3168
        fprintf(stderr, "pass number can be only 1 or 2\n");
3169
        exit(1);
3170
    }
3171
    do_pass = pass;
3172
}
3173

    
3174
#if defined(CONFIG_WIN32) || defined(CONFIG_OS2)
3175
static int64_t getutime(void)
3176
{
3177
  return av_gettime();
3178
}
3179
#else
3180
static int64_t getutime(void)
3181
{
3182
    struct rusage rusage;
3183

    
3184
    getrusage(RUSAGE_SELF, &rusage);
3185
    return (rusage.ru_utime.tv_sec * 1000000LL) + rusage.ru_utime.tv_usec;
3186
}
3187
#endif
3188

    
3189
extern int ffm_nopts;
3190

    
3191
static void opt_bitexact(void)
3192
{
3193
    bitexact=1;
3194
    /* disable generate of real time pts in ffm (need to be supressed anyway) */
3195
    ffm_nopts = 1;
3196
}
3197

    
3198
static void show_formats(void)
3199
{
3200
    AVInputFormat *ifmt;
3201
    AVOutputFormat *ofmt;
3202
    AVImageFormat *image_fmt;
3203
    URLProtocol *up;
3204
    AVCodec *p, *p2;
3205
    const char **pp, *last_name;
3206

    
3207
    printf("File formats:\n");
3208
    last_name= "000";
3209
    for(;;){
3210
        int decode=0;
3211
        int encode=0;
3212
        const char *name=NULL;
3213

    
3214
        for(ofmt = first_oformat; ofmt != NULL; ofmt = ofmt->next) {
3215
            if((name == NULL || strcmp(ofmt->name, name)<0) &&
3216
                strcmp(ofmt->name, last_name)>0){
3217
                name= ofmt->name;
3218
                encode=1;
3219
            }
3220
        }
3221
        for(ifmt = first_iformat; ifmt != NULL; ifmt = ifmt->next) {
3222
            if((name == NULL || strcmp(ifmt->name, name)<0) &&
3223
                strcmp(ifmt->name, last_name)>0){
3224
                name= ifmt->name;
3225
                encode=0;
3226
            }
3227
            if(name && strcmp(ifmt->name, name)==0)
3228
                decode=1;
3229
        }
3230
        if(name==NULL)
3231
            break;
3232
        last_name= name;
3233
        
3234
        printf(
3235
            " %s%s %s\n", 
3236
            decode ? "D":" ", 
3237
            encode ? "E":" ", 
3238
            name);
3239
    }
3240
    printf("\n");
3241

    
3242
    printf("Image formats:\n");
3243
    for(image_fmt = first_image_format; image_fmt != NULL; 
3244
        image_fmt = image_fmt->next) {
3245
        printf(
3246
            " %s%s %s\n",
3247
            image_fmt->img_read  ? "D":" ",
3248
            image_fmt->img_write ? "E":" ",
3249
            image_fmt->name);
3250
    }
3251
    printf("\n");
3252

    
3253
    printf("Codecs:\n");
3254
    last_name= "000";
3255
    for(;;){
3256
        int decode=0;
3257
        int encode=0;
3258
        int cap=0;
3259

    
3260
        p2=NULL;
3261
        for(p = first_avcodec; p != NULL; p = p->next) {
3262
            if((p2==NULL || strcmp(p->name, p2->name)<0) &&
3263
                strcmp(p->name, last_name)>0){
3264
                p2= p;
3265
                decode= encode= cap=0;
3266
            }
3267
            if(p2 && strcmp(p->name, p2->name)==0){
3268
                if(p->decode) decode=1;
3269
                if(p->encode) encode=1;
3270
                cap |= p->capabilities;
3271
            }
3272
        }
3273
        if(p2==NULL)
3274
            break;
3275
        last_name= p2->name;
3276
        
3277
        printf(
3278
            " %s%s%s%s%s%s %s", 
3279
            decode ? "D": (/*p2->decoder ? "d":*/" "), 
3280
            encode ? "E":" ", 
3281
            p2->type == CODEC_TYPE_AUDIO ? "A":"V",
3282
            cap & CODEC_CAP_DRAW_HORIZ_BAND ? "S":" ",
3283
            cap & CODEC_CAP_DR1 ? "D":" ",
3284
            cap & CODEC_CAP_TRUNCATED ? "T":" ",
3285
            p2->name);
3286
       /* if(p2->decoder && decode==0)
3287
            printf(" use %s for decoding", p2->decoder->name);*/
3288
        printf("\n");
3289
    }
3290
    printf("\n");
3291

    
3292
    printf("Supported file protocols:\n");
3293
    for(up = first_protocol; up != NULL; up = up->next)
3294
        printf(" %s:", up->name);
3295
    printf("\n");
3296
    
3297
    printf("Frame size, frame rate abbreviations:\n ntsc pal qntsc qpal sntsc spal film ntsc-film sqcif qcif cif 4cif\n");
3298
    printf("Motion estimation methods:\n");
3299
    pp = motion_str;
3300
    while (*pp) {
3301
        printf(" %s", *pp);
3302
        if ((pp - motion_str + 1) == ME_ZERO) 
3303
            printf("(fastest)");
3304
        else if ((pp - motion_str + 1) == ME_FULL) 
3305
            printf("(slowest)");
3306
        else if ((pp - motion_str + 1) == ME_EPZS) 
3307
            printf("(default)");
3308
        pp++;
3309
    }
3310
    printf("\n\n");
3311
    printf(
3312
"Note, the names of encoders and decoders dont always match, so there are\n"
3313
"several cases where the above table shows encoder only or decoder only entries\n"
3314
"even though both encoding and decoding are supported for example, the h263\n"
3315
"decoder corresponds to the h263 and h263p encoders, for file formats its even\n"
3316
"worse\n");
3317
    exit(1);
3318
}
3319

    
3320
void parse_matrix_coeffs(uint16_t *dest, const char *str)
3321
{
3322
    int i;
3323
    const char *p = str;
3324
    for(i = 0;; i++) {
3325
        dest[i] = atoi(p);
3326
        if(i == 63)
3327
            break;
3328
        p = strchr(p, ',');
3329
        if(!p) {
3330
            fprintf(stderr, "Syntax error in matrix \"%s\" at coeff %d\n", str, i);
3331
            exit(1);
3332
        }
3333
        p++;
3334
    }
3335
}
3336

    
3337
void opt_inter_matrix(const char *arg)
3338
{
3339
    inter_matrix = av_mallocz(sizeof(uint16_t) * 64);
3340
    parse_matrix_coeffs(inter_matrix, arg);
3341
}
3342

    
3343
void opt_intra_matrix(const char *arg)
3344
{
3345
    intra_matrix = av_mallocz(sizeof(uint16_t) * 64);
3346
    parse_matrix_coeffs(intra_matrix, arg);
3347
}
3348

    
3349
static void opt_target(const char *arg)
3350
{
3351
    int norm = -1;
3352

    
3353
    if(!strncmp(arg, "pal-", 4)) {
3354
        norm = 0;
3355
        arg += 4;
3356
    } else if(!strncmp(arg, "ntsc-", 5)) {
3357
        norm = 1;
3358
        arg += 5;
3359
    } else {
3360
        int fr;
3361
        /* Calculate FR via float to avoid int overflow */
3362
        fr = (int)(frame_rate * 1000.0 / frame_rate_base);
3363
        if(fr == 25000) {
3364
            norm = 0;
3365
        } else if((fr == 29970) || (fr == 23976)) {
3366
            norm = 1;
3367
        } else {
3368
            /* Try to determine PAL/NTSC by peeking in the input files */
3369
            if(nb_input_files) {
3370
                int i, j;
3371
                for(j = 0; j < nb_input_files; j++) {
3372
                    for(i = 0; i < input_files[j]->nb_streams; i++) {
3373
                        AVCodecContext *c = &input_files[j]->streams[i]->codec;
3374
                        if(c->codec_type != CODEC_TYPE_VIDEO)
3375
                            continue;
3376
                        fr = c->frame_rate * 1000 / c->frame_rate_base;
3377
                        if(fr == 25000) {
3378
                            norm = 0;
3379
                            break;
3380
                        } else if((fr == 29970) || (fr == 23976)) {
3381
                            norm = 1;
3382
                            break;
3383
                        }
3384
                    }
3385
                    if(norm >= 0)
3386
                        break;
3387
                }
3388
            }
3389
        }
3390
        if(verbose && norm >= 0)
3391
            printf("Assuming %s for target.\n", norm ? "NTSC" : "PAL");
3392
    }
3393

    
3394
    if(norm < 0) {
3395
        fprintf(stderr, "Could not determine norm (PAL/NTSC) for target.\n");
3396
        fprintf(stderr, "Please prefix target with \"pal-\" or \"ntsc-\",\n");
3397
        fprintf(stderr, "or set a framerate with \"-r xxx\".\n");
3398
        exit(1);
3399
    }
3400

    
3401
    if(!strcmp(arg, "vcd")) {
3402

    
3403
        opt_video_codec("mpeg1video");
3404
        opt_audio_codec("mp2");
3405
        opt_format("vcd");
3406

    
3407
        opt_frame_size(norm ? "352x240" : "352x288");
3408

    
3409
        video_bit_rate = 1150000;
3410
        video_rc_max_rate = 1150000;
3411
        video_rc_min_rate = 1150000;
3412
        video_rc_buffer_size = 40*1024*8;
3413

    
3414
        audio_bit_rate = 224000;
3415
        audio_sample_rate = 44100;
3416

    
3417
    } else if(!strcmp(arg, "svcd")) {
3418

    
3419
        opt_video_codec("mpeg2video");
3420
        opt_audio_codec("mp2");
3421
        opt_format("svcd");
3422

    
3423
        opt_frame_size(norm ? "480x480" : "480x576");
3424
        opt_gop_size(norm ? "18" : "15");
3425

    
3426
        video_bit_rate = 2040000;
3427
        video_rc_max_rate = 2516000;
3428
        video_rc_min_rate = 0; //1145000;
3429
        video_rc_buffer_size = 224*1024*8;
3430
        use_scan_offset = 1;
3431

    
3432
        audio_bit_rate = 224000;
3433
        audio_sample_rate = 44100;
3434

    
3435
    } else if(!strcmp(arg, "dvd")) {
3436

    
3437
        opt_video_codec("mpeg2video");
3438
        opt_audio_codec("ac3");
3439
        opt_format("vob");
3440

    
3441
        opt_frame_size(norm ? "720x480" : "720x576");
3442
        opt_gop_size(norm ? "18" : "15");
3443

    
3444
        video_bit_rate = 6000000;
3445
        video_rc_max_rate = 9000000;
3446
        video_rc_min_rate = 0; //1500000;
3447
        video_rc_buffer_size = 224*1024*8;
3448

    
3449
        audio_bit_rate = 448000;
3450
        audio_sample_rate = 48000;
3451

    
3452
    } else {
3453
        fprintf(stderr, "Unknown target: %s\n", arg);
3454
        exit(1);
3455
    }
3456
}
3457

    
3458
static void show_version(void)
3459
{
3460
    printf("ffmpeg      " FFMPEG_VERSION "\n"
3461
           "libavcodec  %d\n"
3462
           "libavformat %d\n", 
3463
           avcodec_build(), LIBAVFORMAT_BUILD);
3464
    exit(1);
3465
}
3466

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

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

    
3608
    /* audio options */
3609
    { "ab", HAS_ARG | OPT_AUDIO, {(void*)opt_audio_bitrate}, "set audio bitrate (in kbit/s)", "bitrate", },
3610
    { "ar", HAS_ARG | OPT_AUDIO, {(void*)opt_audio_rate}, "set audio sampling rate (in Hz)", "rate" },
3611
    { "ac", HAS_ARG | OPT_AUDIO, {(void*)opt_audio_channels}, "set number of audio channels", "channels" },
3612
    { "an", OPT_BOOL | OPT_AUDIO, {(void*)&audio_disable}, "disable audio" },
3613
    { "acodec", HAS_ARG | OPT_AUDIO, {(void*)opt_audio_codec}, "force audio codec ('copy' to copy stream)", "codec" },
3614

    
3615
    /* grab options */
3616
    { "vd", HAS_ARG | OPT_EXPERT | OPT_VIDEO | OPT_GRAB, {(void*)opt_video_device}, "set video grab device", "device" },
3617
    { "vc", HAS_ARG | OPT_EXPERT | OPT_VIDEO | OPT_GRAB, {(void*)opt_video_channel}, "set video grab channel (DV1394 only)", "channel" },
3618
    { "tvstd", HAS_ARG | OPT_EXPERT | OPT_VIDEO | OPT_GRAB, {(void*)opt_video_standard}, "set television standard (NTSC, PAL (SECAM))", "standard" },
3619
    { "dv1394", OPT_EXPERT | OPT_GRAB, {(void*)opt_dv1394}, "set DV1394 grab", "" },
3620
    { "ad", HAS_ARG | OPT_EXPERT | OPT_AUDIO | OPT_GRAB, {(void*)opt_audio_device}, "set audio device", "device" },
3621
    { NULL, },
3622
};
3623

    
3624
static void show_banner(void)
3625
{
3626
    printf("ffmpeg version " FFMPEG_VERSION ", Copyright (c) 2000-2003 Fabrice Bellard\n");
3627
}
3628

    
3629
static void show_license(void)
3630
{
3631
    show_banner();
3632
#ifdef CONFIG_GPL
3633
    printf(
3634
    "This program is free software; you can redistribute it and/or modify\n"   
3635
    "it under the terms of the GNU General Public License as published by\n"
3636
    "the Free Software Foundation; either version 2 of the License, or\n"
3637
    "(at your option) any later version.\n"
3638
    "\n"
3639
    "This program is distributed in the hope that it will be useful,\n"
3640
    "but WITHOUT ANY WARRANTY; without even the implied warranty of\n"
3641
    "MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n"
3642
    "GNU General Public License for more details.\n"
3643
    "\n"
3644
    "You should have received a copy of the GNU General Public License\n"
3645
    "along with this program; if not, write to the Free Software\n"
3646
    "Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA\n"
3647
    );
3648
#else
3649
    printf(
3650
    "This library is free software; you can redistribute it and/or\n"
3651
    "modify it under the terms of the GNU Lesser General Public\n"
3652
    "License as published by the Free Software Foundation; either\n"
3653
    "version 2 of the License, or (at your option) any later version.\n"
3654
    "\n"
3655
    "This library 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 GNU\n"
3658
    "Lesser General Public License for more details.\n"
3659
    "\n"
3660
    "You should have received a copy of the GNU Lesser General Public\n"
3661
    "License along with this library; if not, write to the Free Software\n"
3662
    "Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA\n"
3663
    );
3664
#endif
3665
    exit(1);
3666
}
3667

    
3668
static void show_help(void)
3669
{
3670
    show_banner();
3671
    printf("usage: ffmpeg [[options] -i input_file]... {[options] outfile}...\n"
3672
           "Hyper fast Audio and Video encoder\n");
3673
    printf("\n");
3674
    show_help_options(options, "Main options:\n",
3675
                      OPT_EXPERT | OPT_AUDIO | OPT_VIDEO, 0);
3676
    show_help_options(options, "\nVideo options:\n",
3677
                      OPT_EXPERT | OPT_AUDIO | OPT_VIDEO | OPT_GRAB, 
3678
                      OPT_VIDEO);
3679
    show_help_options(options, "\nAdvanced Video options:\n",
3680
                      OPT_EXPERT | OPT_AUDIO | OPT_VIDEO | OPT_GRAB, 
3681
                      OPT_VIDEO | OPT_EXPERT);
3682
    show_help_options(options, "\nAudio options:\n",
3683
                      OPT_EXPERT | OPT_AUDIO | OPT_VIDEO | OPT_GRAB, 
3684
                      OPT_AUDIO);
3685
    show_help_options(options, "\nAdvanced Audio options:\n",
3686
                      OPT_EXPERT | OPT_AUDIO | OPT_VIDEO | OPT_GRAB, 
3687
                      OPT_AUDIO | OPT_EXPERT);
3688
    show_help_options(options, "\nAudio/Video grab options:\n",
3689
                      OPT_GRAB, 
3690
                      OPT_GRAB);
3691
    show_help_options(options, "\nAdvanced options:\n",
3692
                      OPT_EXPERT | OPT_AUDIO | OPT_VIDEO | OPT_GRAB, 
3693
                      OPT_EXPERT);
3694
    exit(1);
3695
}
3696

    
3697
void parse_arg_file(const char *filename)
3698
{
3699
    opt_output_file(filename);
3700
}
3701

    
3702
int main(int argc, char **argv)
3703
{
3704
    int i;
3705
    int64_t ti;
3706

    
3707
    av_register_all();
3708

    
3709
    if (argc <= 1)
3710
        show_help();
3711
    
3712
    /* parse options */
3713
    parse_options(argc, argv, options);
3714

    
3715
    /* file converter / grab */
3716
    if (nb_output_files <= 0) {
3717
        fprintf(stderr, "Must supply at least one output file\n");
3718
        exit(1);
3719
    }
3720
    
3721
    if (nb_input_files == 0) {
3722
        prepare_grab();
3723
    }
3724

    
3725
    ti = getutime();
3726
    av_encode(output_files, nb_output_files, input_files, nb_input_files, 
3727
              stream_maps, nb_stream_maps);
3728
    ti = getutime() - ti;
3729
    if (do_benchmark) {
3730
        printf("bench: utime=%0.3fs\n", ti / 1000000.0);
3731
    }
3732

    
3733
    /* close files */
3734
    for(i=0;i<nb_output_files;i++) {
3735
        /* maybe av_close_output_file ??? */
3736
        AVFormatContext *s = output_files[i];
3737
        int j;
3738
        if (!(s->oformat->flags & AVFMT_NOFILE))
3739
            url_fclose(&s->pb);
3740
        for(j=0;j<s->nb_streams;j++)
3741
            av_free(s->streams[j]);
3742
        av_free(s);
3743
    }
3744
    for(i=0;i<nb_input_files;i++)
3745
        av_close_input_file(input_files[i]);
3746

    
3747
    av_free_static();
3748

    
3749
    if(intra_matrix)
3750
        av_free(intra_matrix);
3751
    if(inter_matrix)
3752
        av_free(inter_matrix);
3753
    
3754
#ifdef POWERPC_PERFORMANCE_REPORT
3755
    extern void powerpc_display_perf_report(void);
3756
    powerpc_display_perf_report();
3757
#endif /* POWERPC_PERFORMANCE_REPORT */
3758

    
3759
#ifndef CONFIG_WIN32
3760
    if (received_sigterm) {
3761
        fprintf(stderr,
3762
            "Received signal %d: terminating.\n",
3763
            (int) received_sigterm);
3764
        exit (255);
3765
    }
3766
#endif
3767
    exit(0); /* not all OS-es handle main() return value */
3768
    return 0;
3769
}