Statistics
| Branch: | Revision:

ffmpeg / ffmpeg.c @ f20f8a8b

History | View | Annotate | Download (124 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_mb_qmin = 2;
92
static int video_mb_qmax = 31;
93
static int video_qdiff = 3;
94
static float video_qblur = 0.5;
95
static float video_qcomp = 0.5;
96
static uint16_t *intra_matrix = NULL;
97
static uint16_t *inter_matrix = NULL;
98
#if 0 //experimental, (can be removed)
99
static float video_rc_qsquish=1.0;
100
static float video_rc_qmod_amp=0;
101
static int video_rc_qmod_freq=0;
102
#endif
103
static char *video_rc_override_string=NULL;
104
static char *video_rc_eq="tex^qComp";
105
static int video_rc_buffer_size=0;
106
static float video_rc_buffer_aggressivity=1.0;
107
static int video_rc_max_rate=0;
108
static int video_rc_min_rate=0;
109
static float video_rc_initial_cplx=0;
110
static float video_b_qfactor = 1.25;
111
static float video_b_qoffset = 1.25;
112
static float video_i_qfactor = -0.8;
113
static float video_i_qoffset = 0.0;
114
static int video_intra_quant_bias= FF_DEFAULT_QUANT_BIAS;
115
static int video_inter_quant_bias= FF_DEFAULT_QUANT_BIAS;
116
static int me_method = ME_EPZS;
117
static int video_disable = 0;
118
static int video_codec_id = CODEC_ID_NONE;
119
static int same_quality = 0;
120
static int b_frames = 0;
121
static int mb_decision = FF_MB_DECISION_SIMPLE;
122
static int ildct_cmp = FF_CMP_VSAD;
123
static int mb_cmp = FF_CMP_SAD;
124
static int sub_cmp = FF_CMP_SAD;
125
static int cmp = FF_CMP_SAD;
126
static int pre_cmp = FF_CMP_SAD;
127
static int pre_me = 0;
128
static float lumi_mask = 0;
129
static float dark_mask = 0;
130
static float scplx_mask = 0;
131
static float tcplx_mask = 0;
132
static float p_mask = 0;
133
static int use_4mv = 0;
134
static int use_obmc = 0;
135
static int use_loop = 0;
136
static int use_aic = 0;
137
static int use_aiv = 0;
138
static int use_umv = 0;
139
static int use_ss = 0;
140
static int use_alt_scan = 0;
141
static int use_trell = 0;
142
static int use_scan_offset = 0;
143
static int use_qpel = 0;
144
static int qns = 0;
145
static int closed_gop = 0;
146
static int do_deinterlace = 0;
147
static int do_interlace_dct = 0;
148
static int do_interlace_me = 0;
149
static int workaround_bugs = FF_BUG_AUTODETECT;
150
static int error_resilience = 2;
151
static int error_concealment = 3;
152
static int dct_algo = 0;
153
static int idct_algo = 0;
154
static int use_part = 0;
155
static int packet_size = 0;
156
static int error_rate = 0;
157
static int strict = 0;
158
static int top_field_first = -1;
159
static int noise_reduction = 0;
160
static int sc_threshold = 0;
161
static int debug = 0;
162
static int debug_mv = 0;
163
static int me_threshold = 0;
164
static int mb_threshold = 0;
165
extern int loop_input; /* currently a hack */
166

    
167
static int gop_size = 12;
168
static int intra_only = 0;
169
static int audio_sample_rate = 44100;
170
static int audio_bit_rate = 64000;
171
static int audio_disable = 0;
172
static int audio_channels = 1;
173
static int audio_codec_id = CODEC_ID_NONE;
174

    
175
static int64_t recording_time = 0;
176
static int64_t start_time = 0;
177
static int64_t rec_timestamp = 0;
178
static int file_overwrite = 0;
179
static char *str_title = NULL;
180
static char *str_author = NULL;
181
static char *str_copyright = NULL;
182
static char *str_comment = NULL;
183
static int do_benchmark = 0;
184
static int do_hex_dump = 0;
185
static int do_pkt_dump = 0;
186
static int do_psnr = 0;
187
static int do_vstats = 0;
188
static int do_pass = 0;
189
static int bitexact = 0;
190
static char *pass_logfilename = NULL;
191
static int audio_stream_copy = 0;
192
static int video_stream_copy = 0;
193
static int sync_method= 1;
194

    
195
static int rate_emu = 0;
196

    
197
static char *video_grab_format = "video4linux";
198
static char *video_device = NULL;
199
static int  video_channel = 0;
200
static char *video_standard = "ntsc";
201

    
202
static char *audio_grab_format = "audio_device";
203
static char *audio_device = NULL;
204

    
205
static int using_stdin = 0;
206
static int using_vhook = 0;
207
static int verbose = 1;
208
static int thread_count= 1;
209
static int q_pressed = 0;
210
static int me_range = 0;
211
static int64_t video_size = 0;
212
static int64_t audio_size = 0;
213
static int64_t extra_size = 0;
214

    
215
#define DEFAULT_PASS_LOGFILENAME "ffmpeg2pass"
216

    
217
typedef struct AVOutputStream {
218
    int file_index;          /* file index */
219
    int index;               /* stream index in the output file */
220
    int source_index;        /* AVInputStream index */
221
    AVStream *st;            /* stream in the output file */
222
    int encoding_needed;     /* true if encoding needed for this stream */
223
    int frame_number;
224
    /* input pts and corresponding output pts
225
       for A/V sync */
226
    double sync_ipts;
227
    double sync_ipts_offset;
228
    int64_t sync_opts;
229
    /* video only */
230
    int video_resample;      /* video_resample and video_crop are mutually exclusive */
231
    AVFrame pict_tmp;      /* temporary image for resampling */
232
    ImgReSampleContext *img_resample_ctx; /* for image resampling */
233

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

    
251
typedef struct AVInputStream {
252
    int file_index;
253
    int index;
254
    AVStream *st;
255
    int discard;             /* true if stream data should be discarded */
256
    int decoding_needed;     /* true if the packets must be decoded in 'raw_fifo' */
257
    int64_t sample_index;      /* current sample */
258

    
259
    int64_t       start;     /* time when read started */
260
    unsigned long frame;     /* current frame */
261
    int64_t       next_pts;  /* synthetic pts for cases where pkt.pts
262
                                is not defined */
263
    int64_t       pts;       /* current pts */
264
} AVInputStream;
265

    
266
typedef struct AVInputFile {
267
    int eof_reached;      /* true if eof reached */
268
    int ist_index;        /* index of first stream in ist_table */
269
    int buffer_size;      /* current total buffer size */
270
    int buffer_size_max;  /* buffer size at which we consider we can stop
271
                             buffering */
272
    int nb_streams;       /* nb streams we are aware of */
273
} AVInputFile;
274

    
275
#ifndef CONFIG_WIN32
276

    
277
/* init terminal so that we can grab keys */
278
static struct termios oldtty;
279

    
280
static void term_exit(void)
281
{
282
    tcsetattr (0, TCSANOW, &oldtty);
283
}
284

    
285
static volatile sig_atomic_t received_sigterm = 0;
286

    
287
static void
288
sigterm_handler(int sig)
289
{
290
    received_sigterm = sig;
291
    term_exit();
292
}
293

    
294
static void term_init(void)
295
{
296
    struct termios tty;
297

    
298
    tcgetattr (0, &tty);
299
    oldtty = tty;
300

    
301
    tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
302
                          |INLCR|IGNCR|ICRNL|IXON);
303
    tty.c_oflag |= OPOST;
304
    tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
305
    tty.c_cflag &= ~(CSIZE|PARENB);
306
    tty.c_cflag |= CS8;
307
    tty.c_cc[VMIN] = 1;
308
    tty.c_cc[VTIME] = 0;
309
    
310
    tcsetattr (0, TCSANOW, &tty);
311

    
312
    signal(SIGINT , sigterm_handler); /* Interrupt (ANSI).  */
313
    signal(SIGQUIT, sigterm_handler); /* Quit (POSIX).  */
314
    signal(SIGTERM, sigterm_handler); /* Termination (ANSI).  */
315
    /*
316
    register a function to be called at normal program termination
317
    */
318
    atexit(term_exit);
319
#ifdef CONFIG_BEOS_NETSERVER
320
    fcntl(0, F_SETFL, fcntl(0, F_GETFL) | O_NONBLOCK);
321
#endif
322
}
323

    
324
/* read a key without blocking */
325
static int read_key(void)
326
{
327
    int n = 1;
328
    unsigned char ch;
329
#ifndef CONFIG_BEOS_NETSERVER
330
    struct timeval tv;
331
    fd_set rfds;
332

    
333
    FD_ZERO(&rfds);
334
    FD_SET(0, &rfds);
335
    tv.tv_sec = 0;
336
    tv.tv_usec = 0;
337
    n = select(1, &rfds, NULL, NULL, &tv);
338
#endif
339
    if (n > 0) {
340
        n = read(0, &ch, 1);
341
        if (n == 1)
342
            return ch;
343

    
344
        return n;
345
    }
346
    return -1;
347
}
348

    
349
static int decode_interrupt_cb(void)
350
{
351
    return q_pressed || (q_pressed = read_key() == 'q');
352
}
353

    
354
#else
355

    
356
static volatile int received_sigterm = 0;
357

    
358
/* no interactive support */
359
static void term_exit(void)
360
{
361
}
362

    
363
static void term_init(void)
364
{
365
}
366

    
367
static int read_key(void)
368
{
369
    return 0;
370
}
371

    
372
#endif
373

    
374
static int read_ffserver_streams(AVFormatContext *s, const char *filename)
375
{
376
    int i, err;
377
    AVFormatContext *ic;
378

    
379
    err = av_open_input_file(&ic, filename, NULL, FFM_PACKET_SIZE, NULL);
380
    if (err < 0)
381
        return err;
382
    /* copy stream format */
383
    s->nb_streams = ic->nb_streams;
384
    for(i=0;i<ic->nb_streams;i++) {
385
        AVStream *st;
386

    
387
        st = av_mallocz(sizeof(AVStream));
388
        memcpy(st, ic->streams[i], sizeof(AVStream));
389
        s->streams[i] = st;
390
    }
391

    
392
    av_close_input_file(ic);
393
    return 0;
394
}
395

    
396
#define MAX_AUDIO_PACKET_SIZE (128 * 1024)
397

    
398
static void do_audio_out(AVFormatContext *s, 
399
                         AVOutputStream *ost, 
400
                         AVInputStream *ist,
401
                         unsigned char *buf, int size)
402
{
403
    uint8_t *buftmp;
404
    static uint8_t *audio_buf = NULL;
405
    static uint8_t *audio_out = NULL;
406
    const int audio_out_size= 4*MAX_AUDIO_PACKET_SIZE;
407

    
408
    int size_out, frame_bytes, ret;
409
    AVCodecContext *enc;
410

    
411
    /* SC: dynamic allocation of buffers */
412
    if (!audio_buf)
413
        audio_buf = av_malloc(2*MAX_AUDIO_PACKET_SIZE);
414
    if (!audio_out)
415
        audio_out = av_malloc(audio_out_size);
416
    if (!audio_buf || !audio_out)
417
        return;               /* Should signal an error ! */
418

    
419
    
420
    enc = &ost->st->codec;
421

    
422
    if (ost->audio_resample) {
423
        buftmp = audio_buf;
424
        size_out = audio_resample(ost->resample, 
425
                                  (short *)buftmp, (short *)buf,
426
                                  size / (ist->st->codec.channels * 2));
427
        size_out = size_out * enc->channels * 2;
428
    } else {
429
        buftmp = buf;
430
        size_out = size;
431
    }
432

    
433
    /* now encode as many frames as possible */
434
    if (enc->frame_size > 1) {
435
        /* output resampled raw samples */
436
        fifo_write(&ost->fifo, buftmp, size_out, 
437
                   &ost->fifo.wptr);
438

    
439
        frame_bytes = enc->frame_size * 2 * enc->channels;
440
        
441
        while (fifo_read(&ost->fifo, audio_buf, frame_bytes, 
442
                     &ost->fifo.rptr) == 0) {
443
            ret = avcodec_encode_audio(enc, audio_out, audio_out_size, 
444
                                       (short *)audio_buf);
445
            audio_size += ret;
446
            av_write_frame(s, ost->index, audio_out, ret);
447
        }
448
    } else {
449
        /* output a pcm frame */
450
        /* XXX: change encoding codec API to avoid this ? */
451
        switch(enc->codec->id) {
452
        case CODEC_ID_PCM_S16LE:
453
        case CODEC_ID_PCM_S16BE:
454
        case CODEC_ID_PCM_U16LE:
455
        case CODEC_ID_PCM_U16BE:
456
            break;
457
        default:
458
            size_out = size_out >> 1;
459
            break;
460
        }
461
        ret = avcodec_encode_audio(enc, audio_out, size_out, 
462
                                   (short *)buftmp);
463
        audio_size += ret;
464
        av_write_frame(s, ost->index, audio_out, ret);
465
    }
466
}
467

    
468
static void pre_process_video_frame(AVInputStream *ist, AVPicture *picture, void **bufp)
469
{
470
    AVCodecContext *dec;
471
    AVPicture *picture2;
472
    AVPicture picture_tmp;
473
    uint8_t *buf = 0;
474

    
475
    dec = &ist->st->codec;
476

    
477
    /* deinterlace : must be done before any resize */
478
    if (do_deinterlace || using_vhook) {
479
        int size;
480

    
481
        /* create temporary picture */
482
        size = avpicture_get_size(dec->pix_fmt, dec->width, dec->height);
483
        buf = av_malloc(size);
484
        if (!buf)
485
            return;
486
        
487
        picture2 = &picture_tmp;
488
        avpicture_fill(picture2, buf, dec->pix_fmt, dec->width, dec->height);
489

    
490
        if (do_deinterlace){
491
            if(avpicture_deinterlace(picture2, picture, 
492
                                     dec->pix_fmt, dec->width, dec->height) < 0) {
493
                /* if error, do not deinterlace */
494
                av_free(buf);
495
                buf = NULL;
496
                picture2 = picture;
497
            }
498
        } else {
499
            if (img_convert(picture2, dec->pix_fmt, picture, 
500
                            dec->pix_fmt, dec->width, dec->height) < 0) {
501
                /* if error, do not copy */
502
                av_free(buf);
503
                buf = NULL;
504
                picture2 = picture;
505
            }
506
        }
507
    } else {
508
        picture2 = picture;
509
    }
510

    
511
    frame_hook_process(picture2, dec->pix_fmt, dec->width, dec->height);
512

    
513
    if (picture != picture2)
514
        *picture = *picture2;
515
    *bufp = buf;
516
}
517

    
518
/* we begin to correct av delay at this threshold */
519
#define AV_DELAY_MAX 0.100
520

    
521

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

    
537
        if (padleft || padright) {
538
            optr = img->data[i] + (img->linesize[i] * (padtop >> shift)) +
539
                (img->linesize[i] - (padright >> shift));
540

    
541
            for (y = 0; y < ((height - (padtop + padbottom)) >> shift); y++) {
542
                memset(optr, color[i], (padleft + padright) >> shift);
543
                optr += img->linesize[i];
544
            }
545
        }
546
      
547
        if (padbottom) {
548
            optr = img->data[i] + (img->linesize[i] * ((height - padbottom) >> shift));
549
            memset(optr, color[i], ((img->linesize[i] * padbottom) >> shift));
550
        }
551
    }
552
}
553

    
554

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

    
571
    avcodec_get_frame_defaults(&picture_format_temp);
572
    avcodec_get_frame_defaults(&picture_crop_temp);
573

    
574
    enc = &ost->st->codec;
575
    dec = &ist->st->codec;
576

    
577
    /* by default, we output a single frame */
578
    nb_frames = 1;
579

    
580
    *frame_size = 0;
581

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

    
590
        adelta = audio_sync->sync_ipts - ((double)audio_sync->sync_opts * 
591
            s->pts_num / s->pts_den);
592

    
593
        vdelta = ost->sync_ipts - ((double)ost->sync_opts *
594
            s->pts_num / s->pts_den);
595

    
596
        av_delay = adelta - vdelta;
597
        if (av_delay < -AV_DELAY_MAX)
598
            nb_frames = 2;
599
        else if (av_delay > AV_DELAY_MAX)
600
            nb_frames = 0;
601
//        printf("delay=%f nb=%d (A)\n", av_delay, nb_frames);
602
    } else {
603
        double vdelta;
604

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

    
635
    if (nb_frames <= 0) 
636
        return;
637

    
638
    if (!video_buffer)
639
        video_buffer = av_malloc(VIDEO_BUFFER_SIZE);
640
    if (!video_buffer)
641
        return;
642

    
643
    /* convert pixel format if needed */
644
    target_pixfmt = ost->video_resample || ost->video_pad
645
        ? PIX_FMT_YUV420P : enc->pix_fmt;
646
    if (dec->pix_fmt != target_pixfmt) {
647
        int size;
648

    
649
        /* create temporary picture */
650
        size = avpicture_get_size(target_pixfmt, dec->width, dec->height);
651
        buf = av_malloc(size);
652
        if (!buf)
653
            return;
654
        formatted_picture = &picture_format_temp;
655
        avpicture_fill((AVPicture*)formatted_picture, buf, target_pixfmt, dec->width, dec->height);
656
        
657
        if (img_convert((AVPicture*)formatted_picture, target_pixfmt, 
658
                        (AVPicture *)in_picture, dec->pix_fmt, 
659
                        dec->width, dec->height) < 0) {
660

    
661
            if (verbose >= 0)
662
                fprintf(stderr, "pixel format conversion not handled\n");
663

    
664
            goto the_end;
665
        }
666
    } else {
667
        formatted_picture = in_picture;
668
    }
669

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

    
699
                if (verbose >= 0)
700
                    fprintf(stderr, "pixel format conversion not handled\n");
701

    
702
                goto the_end;
703
            }
704
        }
705
    } else if (ost->video_crop) {
706
        picture_crop_temp.data[0] = formatted_picture->data[0] +
707
                (ost->topBand * formatted_picture->linesize[0]) + ost->leftBand;
708

    
709
        picture_crop_temp.data[1] = formatted_picture->data[1] +
710
                ((ost->topBand >> 1) * formatted_picture->linesize[1]) +
711
                (ost->leftBand >> 1);
712

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

    
717
        picture_crop_temp.linesize[0] = formatted_picture->linesize[0];
718
        picture_crop_temp.linesize[1] = formatted_picture->linesize[1];
719
        picture_crop_temp.linesize[2] = formatted_picture->linesize[2];
720
        final_picture = &picture_crop_temp;
721
    } else if (ost->video_pad) {
722
        final_picture = &ost->pict_tmp;
723

    
724
        for (i = 0; i < 3; i++) {
725
            uint8_t *optr, *iptr;
726
            int shift = (i == 0) ? 0 : 1;
727
            int y, yheight;
728
            
729
            /* set offset to start writing image into */
730
            optr = final_picture->data[i] + (((final_picture->linesize[i] * 
731
                            ost->padtop) + ost->padleft) >> shift);
732
            iptr = formatted_picture->data[i];
733

    
734
            yheight = (enc->height - ost->padtop - ost->padbottom) >> shift;
735
            for (y = 0; y < yheight; y++) {
736
                /* copy unpadded image row into padded image row */
737
                memcpy(optr, iptr, formatted_picture->linesize[i]);
738
                optr += final_picture->linesize[i];
739
                iptr += formatted_picture->linesize[i];
740
            }
741
        }
742

    
743
        fill_pad_region((AVPicture*)final_picture, enc->height, enc->width,
744
                ost->padtop, ost->padbottom, ost->padleft, ost->padright,
745
                padcolor);
746
        
747
        if (enc->pix_fmt != PIX_FMT_YUV420P) {
748
            int size;
749

    
750
            av_free(buf);
751
            /* create temporary picture */
752
            size = avpicture_get_size(enc->pix_fmt, enc->width, enc->height);
753
            buf = av_malloc(size);
754
            if (!buf)
755
                return;
756
            final_picture = &picture_format_temp;
757
            avpicture_fill((AVPicture*)final_picture, buf, enc->pix_fmt, enc->width, enc->height);
758

    
759
            if (img_convert((AVPicture*)final_picture, enc->pix_fmt, 
760
                        (AVPicture*)&ost->pict_tmp, PIX_FMT_YUV420P, 
761
                        enc->width, enc->height) < 0) {
762

    
763
                if (verbose >= 0)
764
                    fprintf(stderr, "pixel format conversion not handled\n");
765

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

    
787
            big_picture= *final_picture;
788
            /* better than nothing: use input picture interlaced
789
               settings */
790
            big_picture.interlaced_frame = in_picture->interlaced_frame;
791
            if(do_interlace_me || do_interlace_dct){
792
                if(top_field_first == -1)
793
                    big_picture.top_field_first = in_picture->top_field_first;
794
                else
795
                    big_picture.top_field_first = 1;
796
            }
797

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

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

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

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

    
906

    
907
    oc = output_files[0];
908

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

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

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

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

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

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

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

    
1084
                ist->frame++;
1085
            }
1086

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

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

    
1110
#if 0
1111
                        printf("%d: got pts=%0.3f %0.3f\n", i, 
1112
                               (double)pkt->pts / AV_TIME_BASE, 
1113
                               ((double)ist->pts / AV_TIME_BASE) - 
1114
                               ((double)ost->st->pts.val * os->pts_num / os->pts_den));
1115
#endif
1116
                        /* set the input output pts pairs */
1117
                        ost->sync_ipts = (double)ist->pts / AV_TIME_BASE;
1118
                        /* XXX: take into account the various fifos,
1119
                           in particular for audio */
1120
                        ost->sync_opts = ost->st->pts.val;
1121
                        //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); 
1122

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

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

    
1163
                            av_write_frame(os, ost->index, data_buf, data_size);
1164
                            ost->st->codec.frame_number++;
1165
                            ost->frame_number++;
1166
                        }
1167
                    }
1168
                }
1169
            av_free(buffer_to_free);
1170
        }
1171
 discard_packet:
1172
    return 0;
1173
 fail_decode:
1174
    return -1;
1175
}
1176

    
1177

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

    
1196
    file_table= (AVInputFile*) av_mallocz(nb_input_files * sizeof(AVInputFile));
1197
    if (!file_table)
1198
        goto fail;
1199

    
1200
    /* input stream init */
1201
    j = 0;
1202
    for(i=0;i<nb_input_files;i++) {
1203
        is = input_files[i];
1204
        file_table[i].ist_index = j;
1205
        file_table[i].nb_streams = is->nb_streams;
1206
        j += is->nb_streams;
1207
    }
1208
    nb_istreams = j;
1209

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

    
1231
            if (ist->st->codec.rate_emu) {
1232
                ist->start = av_gettime();
1233
                ist->frame = 0;
1234
            }
1235
        }
1236
    }
1237

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

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

    
1325
    /* for each output stream, we compute the right encoding parameters */
1326
    for(i=0;i<nb_ostreams;i++) {
1327
        ost = ost_table[i];
1328
        ist = ist_table[ost->source_index];
1329

    
1330
        codec = &ost->st->codec;
1331
        icodec = &ist->st->codec;
1332

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

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

    
1509
    /* dump the file output parameters - cannot be done before in case
1510
       of stream copy */
1511
    for(i=0;i<nb_output_files;i++) {
1512
        dump_format(output_files[i], i, output_files[i]->filename, 1);
1513
    }
1514

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

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

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

    
1569
    /* init pts */
1570
    for(i=0;i<nb_istreams;i++) {
1571
        ist = ist_table[i];
1572
        is = input_files[ist->file_index];
1573
        ist->pts = 0;
1574
        ist->next_pts = 0;
1575
    }
1576
    
1577
    /* compute buffer size max (should use a complete heuristic) */
1578
    for(i=0;i<nb_input_files;i++) {
1579
        file_table[i].buffer_size_max = 2048;
1580
    }
1581

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

    
1592
#ifndef CONFIG_WIN32
1593
    if ( !using_stdin && verbose >= 0) {
1594
        fprintf(stderr, "Press [q] to stop encoding\n");
1595
        url_set_interrupt_cb(decode_interrupt_cb);
1596
    }
1597
#endif
1598
    term_init();
1599

    
1600
    stream_no_data = 0;
1601
    key = -1;
1602

    
1603
    for(; received_sigterm == 0;) {
1604
        int file_index, ist_index;
1605
        AVPacket pkt;
1606
        double pts_min;
1607
        
1608
    redo:
1609
        /* if 'q' pressed, exits */
1610
        if (!using_stdin) {
1611
            if (q_pressed)
1612
                break;
1613
            /* read_key() returns 0 on EOF */
1614
            key = read_key();
1615
            if (key == 'q')
1616
                break;
1617
        }
1618

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

    
1640
        /* finish if recording time exhausted */
1641
        if (recording_time > 0 && pts_min >= (recording_time / 1000000.0))
1642
            break;
1643

    
1644
        /* read a frame from it and output it in the fifo */
1645
        is = input_files[file_index];
1646
        if (av_read_frame(is, &pkt) < 0) {
1647
            file_table[file_index].eof_reached = 1;
1648
            continue;
1649
        }
1650

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

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

    
1671
            if (verbose >= 0)
1672
                fprintf(stderr, "Error while decoding stream #%d.%d\n",
1673
                        ist->file_index, ist->index);
1674

    
1675
            av_free_packet(&pkt);
1676
            goto redo;
1677
        }
1678
        
1679
    discard_packet:
1680
        av_free_packet(&pkt);
1681
        
1682
        /* dump report by using the output first video and audio streams */
1683
        print_report(output_files, ost_table, nb_ostreams, 0);
1684
    }
1685

    
1686
    /* at the end of stream, we must flush the decoder buffers */
1687
    for(i=0;i<nb_istreams;i++) {
1688
        ist = ist_table[i];
1689
        if (ist->decoding_needed) {
1690
            output_packet(ist, i, ost_table, nb_ostreams, NULL);
1691
        }
1692
    }
1693

    
1694
    term_exit();
1695

    
1696
    /* write the trailer if needed and close file */
1697
    for(i=0;i<nb_output_files;i++) {
1698
        os = output_files[i];
1699
        av_write_trailer(os);
1700
    }
1701

    
1702
    /* dump report by using the first video and audio streams */
1703
    print_report(output_files, ost_table, nb_ostreams, 1);
1704

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

    
1722
    /* finished ! */
1723
    
1724
    ret = 0;
1725
 fail1:
1726
    av_free(file_table);
1727

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

    
1761
#if 0
1762
int file_read(const char *filename)
1763
{
1764
    URLContext *h;
1765
    unsigned char buffer[1024];
1766
    int len, i;
1767

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

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

    
1798
static void opt_format(const char *arg)
1799
{
1800
    /* compatibility stuff for pgmyuv */
1801
    if (!strcmp(arg, "pgmyuv")) {
1802
        opt_image_format(arg);
1803
        arg = "image";
1804
    }
1805

    
1806
    file_iformat = av_find_input_format(arg);
1807
    file_oformat = guess_format(arg, NULL, NULL);
1808
    if (!file_iformat && !file_oformat) {
1809
        fprintf(stderr, "Unknown input or output format: %s\n", arg);
1810
        exit(1);
1811
    }
1812
}
1813

    
1814
static void opt_video_bitrate(const char *arg)
1815
{
1816
    video_bit_rate = atoi(arg) * 1000;
1817
}
1818

    
1819
static void opt_video_bitrate_tolerance(const char *arg)
1820
{
1821
    video_bit_rate_tolerance = atoi(arg) * 1000;
1822
}
1823

    
1824
static void opt_video_bitrate_max(const char *arg)
1825
{
1826
    video_rc_max_rate = atoi(arg) * 1000;
1827
}
1828

    
1829
static void opt_video_bitrate_min(const char *arg)
1830
{
1831
    video_rc_min_rate = atoi(arg) * 1000;
1832
}
1833

    
1834
static void opt_video_buffer_size(const char *arg)
1835
{
1836
    video_rc_buffer_size = atoi(arg) * 8*1024;
1837
}
1838

    
1839
static void opt_video_rc_eq(char *arg)
1840
{
1841
    video_rc_eq = arg;
1842
}
1843

    
1844
static void opt_video_rc_override_string(char *arg)
1845
{
1846
    video_rc_override_string = arg;
1847
}
1848

    
1849

    
1850
static void opt_workaround_bugs(const char *arg)
1851
{
1852
    workaround_bugs = atoi(arg);
1853
}
1854

    
1855
static void opt_dct_algo(const char *arg)
1856
{
1857
    dct_algo = atoi(arg);
1858
}
1859

    
1860
static void opt_idct_algo(const char *arg)
1861
{
1862
    idct_algo = atoi(arg);
1863
}
1864

    
1865
static void opt_me_threshold(const char *arg)
1866
{
1867
    me_threshold = atoi(arg);
1868
}
1869

    
1870
static void opt_mb_threshold(const char *arg)
1871
{
1872
    mb_threshold = atoi(arg);
1873
}
1874

    
1875
static void opt_error_resilience(const char *arg)
1876
{
1877
    error_resilience = atoi(arg);
1878
}
1879

    
1880
static void opt_error_concealment(const char *arg)
1881
{
1882
    error_concealment = atoi(arg);
1883
}
1884

    
1885
static void opt_debug(const char *arg)
1886
{
1887
    debug = atoi(arg);
1888
}
1889

    
1890
static void opt_vismv(const char *arg)
1891
{
1892
    debug_mv = atoi(arg);
1893
}
1894
    
1895
static void opt_verbose(const char *arg)
1896
{
1897
    verbose = atoi(arg);
1898
    av_log_set_level(atoi(arg));
1899
}
1900

    
1901
static void opt_sync_method(const char *arg)
1902
{
1903
    sync_method = atoi(arg);
1904
}
1905

    
1906
static void opt_frame_rate(const char *arg)
1907
{
1908
    if (parse_frame_rate(&frame_rate, &frame_rate_base, arg) < 0) {
1909
        fprintf(stderr, "Incorrect frame rate\n");
1910
        exit(1);
1911
    }
1912
}
1913

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

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

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

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

    
1986
static void opt_frame_size(const char *arg)
1987
{
1988
    if (parse_image_size(&frame_width, &frame_height, arg) < 0) {
1989
        fprintf(stderr, "Incorrect frame size\n");
1990
        exit(1);
1991
    }
1992
    if ((frame_width % 2) != 0 || (frame_height % 2) != 0) {
1993
        fprintf(stderr, "Frame size must be a multiple of 2\n");
1994
        exit(1);
1995
    }
1996
}
1997

    
1998

    
1999
#define SCALEBITS 10
2000
#define ONE_HALF  (1 << (SCALEBITS - 1))
2001
#define FIX(x)          ((int) ((x) * (1<<SCALEBITS) + 0.5))
2002

    
2003
#define RGB_TO_Y(r, g, b) \
2004
((FIX(0.29900) * (r) + FIX(0.58700) * (g) + \
2005
  FIX(0.11400) * (b) + ONE_HALF) >> SCALEBITS)
2006

    
2007
#define RGB_TO_U(r1, g1, b1, shift)\
2008
(((- FIX(0.16874) * r1 - FIX(0.33126) * g1 +         \
2009
     FIX(0.50000) * b1 + (ONE_HALF << shift) - 1) >> (SCALEBITS + shift)) + 128)
2010

    
2011
#define RGB_TO_V(r1, g1, b1, shift)\
2012
(((FIX(0.50000) * r1 - FIX(0.41869) * g1 -           \
2013
   FIX(0.08131) * b1 + (ONE_HALF << shift) - 1) >> (SCALEBITS + shift)) + 128)
2014

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

    
2025
    padcolor[0] = RGB_TO_Y(r,g,b);
2026
    padcolor[1] = RGB_TO_U(r,g,b,0);
2027
    padcolor[2] = RGB_TO_V(r,g,b,0);
2028
}
2029

    
2030
static void opt_frame_pad_top(const char *arg)
2031
{
2032
    frame_padtop = atoi(arg); 
2033
    if (frame_padtop < 0) {
2034
        fprintf(stderr, "Incorrect top pad size\n");
2035
        exit(1);
2036
    }
2037
    if ((frame_padtop % 2) != 0) {
2038
        fprintf(stderr, "Top pad size must be a multiple of 2\n");
2039
        exit(1);
2040
    }
2041
}
2042

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

    
2056

    
2057
static void opt_frame_pad_left(const char *arg)
2058
{
2059
    frame_padleft = atoi(arg); 
2060
    if (frame_padleft < 0) {
2061
        fprintf(stderr, "Incorrect left pad size\n");
2062
        exit(1);
2063
    }
2064
    if ((frame_padleft % 2) != 0) {
2065
        fprintf(stderr, "Left pad size must be a multiple of 2\n");
2066
        exit(1);
2067
    }
2068
}
2069

    
2070

    
2071
static void opt_frame_pad_right(const char *arg)
2072
{
2073
    frame_padright = atoi(arg); 
2074
    if (frame_padright < 0) {
2075
        fprintf(stderr, "Incorrect right pad size\n");
2076
        exit(1);
2077
    }
2078
    if ((frame_padright % 2) != 0) {
2079
        fprintf(stderr, "Right pad size must be a multiple of 2\n");
2080
        exit(1);
2081
    }
2082
}
2083

    
2084

    
2085
static void opt_frame_pix_fmt(const char *arg)
2086
{
2087
    frame_pix_fmt = avcodec_get_pix_fmt(arg);
2088
}
2089

    
2090
static void opt_frame_aspect_ratio(const char *arg)
2091
{
2092
    int x = 0, y = 0;
2093
    double ar = 0;
2094
    const char *p;
2095
    
2096
    p = strchr(arg, ':');
2097
    if (p) {
2098
        x = strtol(arg, (char **)&arg, 10);
2099
        if (arg == p)
2100
            y = strtol(arg+1, (char **)&arg, 10);
2101
        if (x > 0 && y > 0)
2102
            ar = (double)x / (double)y;
2103
    } else
2104
        ar = strtod(arg, (char **)&arg);
2105

    
2106
    if (!ar) {
2107
        fprintf(stderr, "Incorrect aspect ratio specification.\n");
2108
        exit(1);
2109
    }
2110
    frame_aspect_ratio = ar;
2111
}
2112

    
2113
static void opt_gop_size(const char *arg)
2114
{
2115
    gop_size = atoi(arg);
2116
}
2117

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

    
2130
static void opt_mb_decision(const char *arg)
2131
{
2132
    mb_decision = atoi(arg);
2133
}
2134

    
2135
static void opt_mb_cmp(const char *arg)
2136
{
2137
    mb_cmp = atoi(arg);
2138
}
2139

    
2140
static void opt_ildct_cmp(const char *arg)
2141
{
2142
    ildct_cmp = atoi(arg);
2143
}
2144

    
2145
static void opt_sub_cmp(const char *arg)
2146
{
2147
    sub_cmp = atoi(arg);
2148
}
2149

    
2150
static void opt_cmp(const char *arg)
2151
{
2152
    cmp = atoi(arg);
2153
}
2154

    
2155
static void opt_pre_cmp(const char *arg)
2156
{
2157
    pre_cmp = atoi(arg);
2158
}
2159

    
2160
static void opt_pre_me(const char *arg)
2161
{
2162
    pre_me = atoi(arg);
2163
}
2164

    
2165
static void opt_lumi_mask(const char *arg)
2166
{
2167
    lumi_mask = atof(arg);
2168
}
2169

    
2170
static void opt_dark_mask(const char *arg)
2171
{
2172
    dark_mask = atof(arg);
2173
}
2174

    
2175
static void opt_scplx_mask(const char *arg)
2176
{
2177
    scplx_mask = atof(arg);
2178
}
2179

    
2180
static void opt_tcplx_mask(const char *arg)
2181
{
2182
    tcplx_mask = atof(arg);
2183
}
2184

    
2185
static void opt_p_mask(const char *arg)
2186
{
2187
    p_mask = atof(arg);
2188
}
2189

    
2190
static void opt_qscale(const char *arg)
2191
{
2192
    video_qscale = atof(arg);
2193
    if (video_qscale < 0.01 ||
2194
        video_qscale > 255) {
2195
        fprintf(stderr, "qscale must be >= 0.01 and <= 255\n");
2196
        exit(1);
2197
    }
2198
}
2199

    
2200
static void opt_qmin(const char *arg)
2201
{
2202
    video_qmin = atoi(arg);
2203
    if (video_qmin < 0 ||
2204
        video_qmin > 31) {
2205
        fprintf(stderr, "qmin must be >= 1 and <= 31\n");
2206
        exit(1);
2207
    }
2208
}
2209

    
2210
static void opt_qmax(const char *arg)
2211
{
2212
    video_qmax = atoi(arg);
2213
    if (video_qmax < 0 ||
2214
        video_qmax > 31) {
2215
        fprintf(stderr, "qmax must be >= 1 and <= 31\n");
2216
        exit(1);
2217
    }
2218
}
2219

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

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

    
2240
static void opt_qdiff(const char *arg)
2241
{
2242
    video_qdiff = atoi(arg);
2243
    if (video_qdiff < 0 ||
2244
        video_qdiff > 31) {
2245
        fprintf(stderr, "qdiff must be >= 1 and <= 31\n");
2246
        exit(1);
2247
    }
2248
}
2249

    
2250
static void opt_qblur(const char *arg)
2251
{
2252
    video_qblur = atof(arg);
2253
}
2254

    
2255
static void opt_qcomp(const char *arg)
2256
{
2257
    video_qcomp = atof(arg);
2258
}
2259

    
2260
static void opt_rc_initial_cplx(const char *arg)
2261
{
2262
    video_rc_initial_cplx = atof(arg);
2263
}
2264
static void opt_b_qfactor(const char *arg)
2265
{
2266
    video_b_qfactor = atof(arg);
2267
}
2268
static void opt_i_qfactor(const char *arg)
2269
{
2270
    video_i_qfactor = atof(arg);
2271
}
2272
static void opt_b_qoffset(const char *arg)
2273
{
2274
    video_b_qoffset = atof(arg);
2275
}
2276
static void opt_i_qoffset(const char *arg)
2277
{
2278
    video_i_qoffset = atof(arg);
2279
}
2280

    
2281
static void opt_ibias(const char *arg)
2282
{
2283
    video_intra_quant_bias = atoi(arg);
2284
}
2285
static void opt_pbias(const char *arg)
2286
{
2287
    video_inter_quant_bias = atoi(arg);
2288
}
2289

    
2290
static void opt_packet_size(const char *arg)
2291
{
2292
    packet_size= atoi(arg);
2293
}
2294

    
2295
static void opt_error_rate(const char *arg)
2296
{
2297
    error_rate= atoi(arg);
2298
}
2299

    
2300
static void opt_strict(const char *arg)
2301
{
2302
    strict= atoi(arg);
2303
}
2304

    
2305
static void opt_top_field_first(const char *arg)
2306
{
2307
    top_field_first= atoi(arg);
2308
}
2309

    
2310
static void opt_noise_reduction(const char *arg)
2311
{
2312
    noise_reduction= atoi(arg);
2313
}
2314

    
2315
static void opt_qns(const char *arg)
2316
{
2317
    qns= atoi(arg);
2318
}
2319

    
2320
static void opt_sc_threshold(const char *arg)
2321
{
2322
    sc_threshold= atoi(arg);
2323
}
2324

    
2325
static void opt_me_range(const char *arg)
2326
{
2327
    me_range = atoi(arg);
2328
}
2329

    
2330
static void opt_thread_count(const char *arg)
2331
{
2332
    thread_count= atoi(arg);
2333
#if !defined(HAVE_PTHREADS) && !defined(HAVE_W32THREADS)
2334
    if (verbose >= 0)
2335
        fprintf(stderr, "Warning: not compiled with thread support, using thread emulation\n");
2336
#endif
2337
}
2338

    
2339
static void opt_audio_bitrate(const char *arg)
2340
{
2341
    audio_bit_rate = atoi(arg) * 1000;
2342
}
2343

    
2344
static void opt_audio_rate(const char *arg)
2345
{
2346
    audio_sample_rate = atoi(arg);
2347
}
2348

    
2349
static void opt_audio_channels(const char *arg)
2350
{
2351
    audio_channels = atoi(arg);
2352
}
2353

    
2354
static void opt_video_device(const char *arg)
2355
{
2356
    video_device = av_strdup(arg);
2357
}
2358

    
2359
static void opt_video_channel(const char *arg)
2360
{
2361
    video_channel = strtol(arg, NULL, 0);
2362
}
2363

    
2364
static void opt_video_standard(const char *arg)
2365
{
2366
    video_standard = av_strdup(arg);
2367
}
2368

    
2369
static void opt_audio_device(const char *arg)
2370
{
2371
    audio_device = av_strdup(arg);
2372
}
2373

    
2374
static void opt_dv1394(const char *arg)
2375
{
2376
    video_grab_format = "dv1394";
2377
    audio_grab_format = NULL;
2378
}
2379

    
2380
static void opt_audio_codec(const char *arg)
2381
{
2382
    AVCodec *p;
2383

    
2384
    if (!strcmp(arg, "copy")) {
2385
        audio_stream_copy = 1;
2386
    } else {
2387
        p = first_avcodec;
2388
        while (p) {
2389
            if (!strcmp(p->name, arg) && p->type == CODEC_TYPE_AUDIO)
2390
                break;
2391
            p = p->next;
2392
        }
2393
        if (p == NULL) {
2394
            fprintf(stderr, "Unknown audio codec '%s'\n", arg);
2395
            exit(1);
2396
        } else {
2397
            audio_codec_id = p->id;
2398
        }
2399
    }
2400
}
2401

    
2402
static void add_frame_hooker(const char *arg)
2403
{
2404
    int argc = 0;
2405
    char *argv[64];
2406
    int i;
2407
    char *args = av_strdup(arg);
2408

    
2409
    using_vhook = 1;
2410

    
2411
    argv[0] = strtok(args, " ");
2412
    while (argc < 62 && (argv[++argc] = strtok(NULL, " "))) {
2413
    }
2414

    
2415
    i = frame_hook_add(argc, argv);
2416

    
2417
    if (i != 0) {
2418
        fprintf(stderr, "Failed to add video hook function: %s\n", arg);
2419
        exit(1);
2420
    }
2421
}
2422

    
2423
const char *motion_str[] = {
2424
    "zero",
2425
    "full",
2426
    "log",
2427
    "phods",
2428
    "epzs",
2429
    "x1",
2430
    NULL,
2431
};
2432

    
2433
static void opt_motion_estimation(const char *arg)
2434
{
2435
    const char **p;
2436
    p = motion_str;
2437
    for(;;) {
2438
        if (!*p) {
2439
            fprintf(stderr, "Unknown motion estimation method '%s'\n", arg);
2440
            exit(1);
2441
        }
2442
        if (!strcmp(*p, arg))
2443
            break;
2444
        p++;
2445
    }
2446
    me_method = (p - motion_str) + 1;
2447
}
2448

    
2449
static void opt_video_codec(const char *arg)
2450
{
2451
    AVCodec *p;
2452

    
2453
    if (!strcmp(arg, "copy")) {
2454
        video_stream_copy = 1;
2455
    } else {
2456
        p = first_avcodec;
2457
        while (p) {
2458
            if (!strcmp(p->name, arg) && p->type == CODEC_TYPE_VIDEO)
2459
                break;
2460
            p = p->next;
2461
        }
2462
        if (p == NULL) {
2463
            fprintf(stderr, "Unknown video codec '%s'\n", arg);
2464
            exit(1);
2465
        } else {
2466
            video_codec_id = p->id;
2467
        }
2468
    }
2469
}
2470

    
2471
static void opt_map(const char *arg)
2472
{
2473
    AVStreamMap *m;
2474
    const char *p;
2475

    
2476
    p = arg;
2477
    m = &stream_maps[nb_stream_maps++];
2478

    
2479
    m->file_index = strtol(arg, (char **)&p, 0);
2480
    if (*p)
2481
        p++;
2482

    
2483
    m->stream_index = strtol(p, (char **)&p, 0);
2484
}
2485

    
2486
static void opt_recording_time(const char *arg)
2487
{
2488
    recording_time = parse_date(arg, 1);
2489
}
2490

    
2491
static void opt_start_time(const char *arg)
2492
{
2493
    start_time = parse_date(arg, 1);
2494
}
2495

    
2496
static void opt_rec_timestamp(const char *arg)
2497
{
2498
    rec_timestamp = parse_date(arg, 0) / 1000000;
2499
}
2500

    
2501
static void opt_input_file(const char *filename)
2502
{
2503
    AVFormatContext *ic;
2504
    AVFormatParameters params, *ap = &params;
2505
    int err, i, ret, rfps, rfps_base;
2506

    
2507
    if (!strcmp(filename, "-"))
2508
        filename = "pipe:";
2509

    
2510
    using_stdin |= !strcmp(filename, "pipe:" ) || 
2511
                   !strcmp( filename, "/dev/stdin" );
2512

    
2513
    /* get default parameters from command line */
2514
    memset(ap, 0, sizeof(*ap));
2515
    ap->sample_rate = audio_sample_rate;
2516
    ap->channels = audio_channels;
2517
    ap->frame_rate = frame_rate;
2518
    ap->frame_rate_base = frame_rate_base;
2519
    ap->width = frame_width + frame_padleft + frame_padright;
2520
    ap->height = frame_height + frame_padtop + frame_padbottom;
2521
    ap->image_format = image_format;
2522
    ap->pix_fmt = frame_pix_fmt;
2523

    
2524
    /* open the input file with generic libav function */
2525
    err = av_open_input_file(&ic, filename, file_iformat, 0, ap);
2526
    if (err < 0) {
2527
        print_error(filename, err);
2528
        exit(1);
2529
    }
2530
    
2531
    /* If not enough info to get the stream parameters, we decode the
2532
       first frames to get it. (used in mpeg case for example) */
2533
    ret = av_find_stream_info(ic);
2534
    if (ret < 0 && verbose >= 0) {
2535
        fprintf(stderr, "%s: could not find codec parameters\n", filename);
2536
        exit(1);
2537
    }
2538

    
2539
    /* if seeking requested, we execute it */
2540
    if (start_time != 0) {
2541
        int64_t timestamp;
2542

    
2543
        timestamp = start_time;
2544
        /* add the stream start time */
2545
        if (ic->start_time != AV_NOPTS_VALUE)
2546
            timestamp += ic->start_time;
2547
        ret = av_seek_frame(ic, -1, timestamp);
2548
        if (ret < 0) {
2549
            fprintf(stderr, "%s: could not seek to position %0.3f\n", 
2550
                    filename, (double)timestamp / AV_TIME_BASE);
2551
        }
2552
        /* reset seek info */
2553
        start_time = 0;
2554
    }
2555

    
2556
    /* update the current parameters so that they match the one of the input stream */
2557
    for(i=0;i<ic->nb_streams;i++) {
2558
        AVCodecContext *enc = &ic->streams[i]->codec;
2559
#if defined(HAVE_PTHREADS) || defined(HAVE_W32THREADS)
2560
        if(thread_count>1)
2561
            avcodec_thread_init(enc, thread_count);
2562
#endif
2563
        enc->thread_count= thread_count;
2564
        switch(enc->codec_type) {
2565
        case CODEC_TYPE_AUDIO:
2566
            //fprintf(stderr, "\nInput Audio channels: %d", enc->channels);
2567
            audio_channels = enc->channels;
2568
            audio_sample_rate = enc->sample_rate;
2569
            break;
2570
        case CODEC_TYPE_VIDEO:
2571
            frame_height = enc->height;
2572
            frame_width = enc->width;
2573
            frame_aspect_ratio = av_q2d(enc->sample_aspect_ratio) * enc->width / enc->height;
2574
            frame_pix_fmt = enc->pix_fmt;
2575
            rfps      = ic->streams[i]->r_frame_rate;
2576
            rfps_base = ic->streams[i]->r_frame_rate_base;
2577
            enc->workaround_bugs = workaround_bugs;
2578
            enc->error_resilience = error_resilience; 
2579
            enc->error_concealment = error_concealment; 
2580
            enc->idct_algo = idct_algo;
2581
            enc->debug = debug;
2582
            enc->debug_mv = debug_mv;            
2583
            if(bitexact)
2584
                enc->flags|= CODEC_FLAG_BITEXACT;
2585
            if(me_threshold)
2586
                enc->debug |= FF_DEBUG_MV;
2587

    
2588
            assert(enc->frame_rate_base == rfps_base); // should be true for now
2589
            if (enc->frame_rate != rfps) { 
2590

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

    
2595
                    (float)rfps / rfps_base);
2596
            }
2597
            /* update the current frame rate to match the stream frame rate */
2598
            frame_rate      = rfps;
2599
            frame_rate_base = rfps_base;
2600

    
2601
            enc->rate_emu = rate_emu;
2602
            break;
2603
        case CODEC_TYPE_DATA:
2604
            break;
2605
        default:
2606
            av_abort();
2607
        }
2608
    }
2609
    
2610
    input_files[nb_input_files] = ic;
2611
    /* dump the file content */
2612
    if (verbose >= 0)
2613
        dump_format(ic, nb_input_files, filename, 0);
2614

    
2615
    nb_input_files++;
2616
    file_iformat = NULL;
2617
    file_oformat = NULL;
2618
    image_format = NULL;
2619

    
2620
    rate_emu = 0;
2621
}
2622

    
2623
static void check_audio_video_inputs(int *has_video_ptr, int *has_audio_ptr)
2624
{
2625
    int has_video, has_audio, i, j;
2626
    AVFormatContext *ic;
2627

    
2628
    has_video = 0;
2629
    has_audio = 0;
2630
    for(j=0;j<nb_input_files;j++) {
2631
        ic = input_files[j];
2632
        for(i=0;i<ic->nb_streams;i++) {
2633
            AVCodecContext *enc = &ic->streams[i]->codec;
2634
            switch(enc->codec_type) {
2635
            case CODEC_TYPE_AUDIO:
2636
                has_audio = 1;
2637
                break;
2638
            case CODEC_TYPE_VIDEO:
2639
                has_video = 1;
2640
                break;
2641
            case CODEC_TYPE_DATA:
2642
                break;
2643
            default:
2644
                av_abort();
2645
            }
2646
        }
2647
    }
2648
    *has_video_ptr = has_video;
2649
    *has_audio_ptr = has_audio;
2650
}
2651

    
2652
static void opt_output_file(const char *filename)
2653
{
2654
    AVStream *st;
2655
    AVFormatContext *oc;
2656
    int use_video, use_audio, nb_streams, input_has_video, input_has_audio;
2657
    int codec_id;
2658
    AVFormatParameters params, *ap = &params;
2659

    
2660
    if (!strcmp(filename, "-"))
2661
        filename = "pipe:";
2662

    
2663
    oc = av_alloc_format_context();
2664

    
2665
    if (!file_oformat) {
2666
        file_oformat = guess_format(NULL, filename, NULL);
2667
        if (!file_oformat) {
2668
            fprintf(stderr, "Unable for find a suitable output format for '%s'\n",
2669
                    filename);
2670
            exit(1);
2671
        }
2672
    }
2673
    
2674
    oc->oformat = file_oformat;
2675

    
2676
    if (!strcmp(file_oformat->name, "ffm") && 
2677
        strstart(filename, "http:", NULL)) {
2678
        /* special case for files sent to ffserver: we get the stream
2679
           parameters from ffserver */
2680
        if (read_ffserver_streams(oc, filename) < 0) {
2681
            fprintf(stderr, "Could not read stream parameters from '%s'\n", filename);
2682
            exit(1);
2683
        }
2684
    } else {
2685
        use_video = file_oformat->video_codec != CODEC_ID_NONE || video_stream_copy;
2686
        use_audio = file_oformat->audio_codec != CODEC_ID_NONE || audio_stream_copy;
2687

    
2688
        /* disable if no corresponding type found and at least one
2689
           input file */
2690
        if (nb_input_files > 0) {
2691
            check_audio_video_inputs(&input_has_video, &input_has_audio);
2692
            if (!input_has_video)
2693
                use_video = 0;
2694
            if (!input_has_audio)
2695
                use_audio = 0;
2696
        }
2697

    
2698
        /* manual disable */
2699
        if (audio_disable) {
2700
            use_audio = 0;
2701
        }
2702
        if (video_disable) {
2703
            use_video = 0;
2704
        }
2705
        
2706
        nb_streams = 0;
2707
        if (use_video) {
2708
            AVCodecContext *video_enc;
2709
            
2710
            st = av_mallocz(sizeof(AVStream));
2711
            if (!st) {
2712
                fprintf(stderr, "Could not alloc stream\n");
2713
                exit(1);
2714
            }
2715
            avcodec_get_context_defaults(&st->codec);
2716
#if defined(HAVE_PTHREADS) || defined(HAVE_W32THREADS)
2717
            if(thread_count>1)
2718
                avcodec_thread_init(&st->codec, thread_count);
2719
#endif
2720

    
2721
            video_enc = &st->codec;
2722
            
2723
            if(!strcmp(file_oformat->name, "mp4") || !strcmp(file_oformat->name, "mov") || !strcmp(file_oformat->name, "3gp"))
2724
                video_enc->flags |= CODEC_FLAG_GLOBAL_HEADER;
2725
            if (video_stream_copy) {
2726
                st->stream_copy = 1;
2727
                video_enc->codec_type = CODEC_TYPE_VIDEO;
2728
            } else {
2729
                char *p;
2730
                int i;
2731
            
2732
                codec_id = file_oformat->video_codec;
2733
                if (video_codec_id != CODEC_ID_NONE)
2734
                    codec_id = video_codec_id;
2735
                
2736
                video_enc->codec_id = codec_id;
2737
                
2738
                video_enc->bit_rate = video_bit_rate;
2739
                video_enc->bit_rate_tolerance = video_bit_rate_tolerance;
2740
                video_enc->frame_rate = frame_rate; 
2741
                video_enc->frame_rate_base = frame_rate_base; 
2742
                
2743
                video_enc->width = frame_width + frame_padright + frame_padleft;
2744
                video_enc->height = frame_height + frame_padtop + frame_padbottom;
2745
                video_enc->sample_aspect_ratio = av_d2q(frame_aspect_ratio*frame_height/frame_width, 255);
2746
                video_enc->pix_fmt = frame_pix_fmt;
2747

    
2748
                if (!intra_only)
2749
                    video_enc->gop_size = gop_size;
2750
                else
2751
                    video_enc->gop_size = 0;
2752
                if (video_qscale || same_quality) {
2753
                    video_enc->flags |= CODEC_FLAG_QSCALE;
2754
                    st->quality = FF_QP2LAMBDA * video_qscale;
2755
                }
2756

    
2757
                if(intra_matrix)
2758
                    video_enc->intra_matrix = intra_matrix;
2759
                if(inter_matrix)
2760
                    video_enc->inter_matrix = inter_matrix;
2761

    
2762
                if(bitexact)
2763
                    video_enc->flags |= CODEC_FLAG_BITEXACT;
2764

    
2765
                video_enc->mb_decision = mb_decision;
2766
                video_enc->mb_cmp = mb_cmp;
2767
                video_enc->ildct_cmp = ildct_cmp;
2768
                video_enc->me_sub_cmp = sub_cmp;
2769
                video_enc->me_cmp = cmp;
2770
                video_enc->me_pre_cmp = pre_cmp;
2771
                video_enc->pre_me = pre_me;
2772
                video_enc->lumi_masking = lumi_mask;
2773
                video_enc->dark_masking = dark_mask;
2774
                video_enc->spatial_cplx_masking = scplx_mask;
2775
                video_enc->temporal_cplx_masking = tcplx_mask;
2776
                video_enc->p_masking = p_mask;
2777
                video_enc->quantizer_noise_shaping= qns;
2778
                
2779
                if (use_umv) {
2780
                    video_enc->flags |= CODEC_FLAG_H263P_UMV;
2781
                }
2782
                if (use_ss) {
2783
                    video_enc->flags |= CODEC_FLAG_H263P_SLICE_STRUCT;
2784
                }
2785
                   if (use_aic) {
2786
                    video_enc->flags |= CODEC_FLAG_H263P_AIC;
2787
                }
2788
                   if (use_aiv) {
2789
                    video_enc->flags |= CODEC_FLAG_H263P_AIV;
2790
                }
2791
                if (use_4mv) {
2792
                    video_enc->flags |= CODEC_FLAG_4MV;
2793
                }
2794
                if (use_obmc) {
2795
                    video_enc->flags |= CODEC_FLAG_OBMC;
2796
                }
2797
                if (use_loop) {
2798
                    video_enc->flags |= CODEC_FLAG_LOOP_FILTER;
2799
                }
2800
            
2801
                if(use_part) {
2802
                    video_enc->flags |= CODEC_FLAG_PART;
2803
                }
2804
                   if (use_alt_scan) {
2805
                    video_enc->flags |= CODEC_FLAG_ALT_SCAN;
2806
                }
2807
                   if (use_trell) {
2808
                    video_enc->flags |= CODEC_FLAG_TRELLIS_QUANT;
2809
                }
2810
                   if (use_scan_offset) {
2811
                    video_enc->flags |= CODEC_FLAG_SVCD_SCAN_OFFSET;
2812
                }
2813
                   if (closed_gop) {
2814
                    video_enc->flags |= CODEC_FLAG_CLOSED_GOP;
2815
                }
2816
                   if (use_qpel) {
2817
                    video_enc->flags |= CODEC_FLAG_QPEL;
2818
                }
2819
                if (b_frames) {
2820
                    video_enc->max_b_frames = b_frames;
2821
                    video_enc->b_frame_strategy = 0;
2822
                    video_enc->b_quant_factor = 2.0;
2823
                }
2824
                if (do_interlace_dct) {
2825
                    video_enc->flags |= CODEC_FLAG_INTERLACED_DCT;
2826
                }
2827
                if (do_interlace_me) {
2828
                    video_enc->flags |= CODEC_FLAG_INTERLACED_ME;
2829
                }
2830
                video_enc->qmin = video_qmin;
2831
                video_enc->qmax = video_qmax;
2832
                video_enc->mb_qmin = video_mb_qmin;
2833
                video_enc->mb_qmax = video_mb_qmax;
2834
                video_enc->max_qdiff = video_qdiff;
2835
                video_enc->qblur = video_qblur;
2836
                video_enc->qcompress = video_qcomp;
2837
                video_enc->rc_eq = video_rc_eq;
2838
                video_enc->debug = debug;
2839
                video_enc->debug_mv = debug_mv;
2840
                video_enc->thread_count = thread_count;
2841
                p= video_rc_override_string;
2842
                for(i=0; p; i++){
2843
                    int start, end, q;
2844
                    int e=sscanf(p, "%d,%d,%d", &start, &end, &q);
2845
                    if(e!=3){
2846
                        fprintf(stderr, "error parsing rc_override\n");
2847
                        exit(1);
2848
                    }
2849
                    video_enc->rc_override= 
2850
                        av_realloc(video_enc->rc_override, 
2851
                                   sizeof(RcOverride)*(i+1));
2852
                    video_enc->rc_override[i].start_frame= start;
2853
                    video_enc->rc_override[i].end_frame  = end;
2854
                    if(q>0){
2855
                        video_enc->rc_override[i].qscale= q;
2856
                        video_enc->rc_override[i].quality_factor= 1.0;
2857
                    }
2858
                    else{
2859
                        video_enc->rc_override[i].qscale= 0;
2860
                        video_enc->rc_override[i].quality_factor= -q/100.0;
2861
                    }
2862
                    p= strchr(p, '/');
2863
                    if(p) p++;
2864
                }
2865
                video_enc->rc_override_count=i;
2866

    
2867
                video_enc->rc_max_rate = video_rc_max_rate;
2868
                video_enc->rc_min_rate = video_rc_min_rate;
2869
                video_enc->rc_buffer_size = video_rc_buffer_size;
2870
                video_enc->rc_buffer_aggressivity= video_rc_buffer_aggressivity;
2871
                video_enc->rc_initial_cplx= video_rc_initial_cplx;
2872
                video_enc->i_quant_factor = video_i_qfactor;
2873
                video_enc->b_quant_factor = video_b_qfactor;
2874
                video_enc->i_quant_offset = video_i_qoffset;
2875
                video_enc->b_quant_offset = video_b_qoffset;
2876
                video_enc->intra_quant_bias = video_intra_quant_bias;
2877
                video_enc->inter_quant_bias = video_inter_quant_bias;
2878
                video_enc->dct_algo = dct_algo;
2879
                video_enc->idct_algo = idct_algo;
2880
                video_enc->me_threshold= me_threshold;
2881
                video_enc->mb_threshold= mb_threshold;
2882
                video_enc->strict_std_compliance = strict;
2883
                video_enc->error_rate = error_rate;
2884
                video_enc->noise_reduction= noise_reduction;
2885
                video_enc->scenechange_threshold= sc_threshold;
2886
                video_enc->me_range = me_range;
2887

    
2888
                if(packet_size){
2889
                    video_enc->rtp_mode= 1;
2890
                    video_enc->rtp_payload_size= packet_size;
2891
                }
2892
            
2893
                if (do_psnr)
2894
                    video_enc->flags|= CODEC_FLAG_PSNR;
2895
            
2896
                video_enc->me_method = me_method;
2897

    
2898
                /* two pass mode */
2899
                if (do_pass) {
2900
                    if (do_pass == 1) {
2901
                        video_enc->flags |= CODEC_FLAG_PASS1;
2902
                    } else {
2903
                        video_enc->flags |= CODEC_FLAG_PASS2;
2904
                    }
2905
                }
2906
            }
2907
            oc->streams[nb_streams] = st;
2908
            nb_streams++;
2909
        }
2910
    
2911
        if (use_audio) {
2912
            AVCodecContext *audio_enc;
2913

    
2914
            st = av_mallocz(sizeof(AVStream));
2915
            if (!st) {
2916
                fprintf(stderr, "Could not alloc stream\n");
2917
                exit(1);
2918
            }
2919
            avcodec_get_context_defaults(&st->codec);
2920
#if defined(HAVE_PTHREADS) || defined(HAVE_W32THREADS)
2921
            if(thread_count>1)
2922
                avcodec_thread_init(&st->codec, thread_count);
2923
#endif
2924

    
2925
            audio_enc = &st->codec;
2926
            audio_enc->codec_type = CODEC_TYPE_AUDIO;
2927

    
2928
            if(!strcmp(file_oformat->name, "mp4") || !strcmp(file_oformat->name, "mov") || !strcmp(file_oformat->name, "3gp"))
2929
                audio_enc->flags |= CODEC_FLAG_GLOBAL_HEADER;
2930
            if (audio_stream_copy) {
2931
                st->stream_copy = 1;
2932
            } else {
2933
                codec_id = file_oformat->audio_codec;
2934
                if (audio_codec_id != CODEC_ID_NONE)
2935
                    codec_id = audio_codec_id;
2936
                audio_enc->codec_id = codec_id;
2937
                
2938
                audio_enc->bit_rate = audio_bit_rate;
2939
                audio_enc->sample_rate = audio_sample_rate;
2940
                audio_enc->strict_std_compliance = strict;
2941
                audio_enc->thread_count = thread_count;
2942
                /* For audio codecs other than AC3 we limit */
2943
                /* the number of coded channels to stereo   */
2944
                if (audio_channels > 2 && codec_id != CODEC_ID_AC3) {
2945
                    audio_enc->channels = 2;
2946
                } else
2947
                    audio_enc->channels = audio_channels;
2948
            }
2949
            oc->streams[nb_streams] = st;
2950
            nb_streams++;
2951
        }
2952

    
2953
        oc->nb_streams = nb_streams;
2954

    
2955
        if (!nb_streams) {
2956
            fprintf(stderr, "No audio or video streams available\n");
2957
            exit(1);
2958
        }
2959

    
2960
        oc->timestamp = rec_timestamp;
2961
            
2962
        if (str_title)
2963
            pstrcpy(oc->title, sizeof(oc->title), str_title);
2964
        if (str_author)
2965
            pstrcpy(oc->author, sizeof(oc->author), str_author);
2966
        if (str_copyright)
2967
            pstrcpy(oc->copyright, sizeof(oc->copyright), str_copyright);
2968
        if (str_comment)
2969
            pstrcpy(oc->comment, sizeof(oc->comment), str_comment);
2970
    }
2971

    
2972
    output_files[nb_output_files++] = oc;
2973

    
2974
    strcpy(oc->filename, filename);
2975

    
2976
    /* check filename in case of an image number is expected */
2977
    if (oc->oformat->flags & AVFMT_NEEDNUMBER) {
2978
        if (filename_number_test(oc->filename) < 0) {
2979
            print_error(oc->filename, AVERROR_NUMEXPECTED);
2980
            exit(1);
2981
        }
2982
    }
2983

    
2984
    if (!(oc->oformat->flags & AVFMT_NOFILE)) {
2985
        /* test if it already exists to avoid loosing precious files */
2986
        if (!file_overwrite && 
2987
            (strchr(filename, ':') == NULL ||
2988
             strstart(filename, "file:", NULL))) {
2989
            if (url_exist(filename)) {
2990
                int c;
2991
                
2992
                if ( !using_stdin ) {
2993
                    fprintf(stderr,"File '%s' already exists. Overwrite ? [y/N] ", filename);
2994
                    fflush(stderr);
2995
                    c = getchar();
2996
                    if (toupper(c) != 'Y') {
2997
                        fprintf(stderr, "Not overwriting - exiting\n");
2998
                        exit(1);
2999
                    }
3000
                                }
3001
                                else {
3002
                    fprintf(stderr,"File '%s' already exists. Exiting.\n", filename);
3003
                    exit(1);
3004
                                }
3005
            }
3006
        }
3007
        
3008
        /* open the file */
3009
        if (url_fopen(&oc->pb, filename, URL_WRONLY) < 0) {
3010
            fprintf(stderr, "Could not open '%s'\n", filename);
3011
            exit(1);
3012
        }
3013
    }
3014

    
3015
    memset(ap, 0, sizeof(*ap));
3016
    ap->image_format = image_format;
3017
    if (av_set_parameters(oc, ap) < 0) {
3018
        fprintf(stderr, "%s: Invalid encoding parameters\n",
3019
                oc->filename);
3020
        exit(1);
3021
    }
3022

    
3023
    /* reset some options */
3024
    file_oformat = NULL;
3025
    file_iformat = NULL;
3026
    image_format = NULL;
3027
    audio_disable = 0;
3028
    video_disable = 0;
3029
    audio_codec_id = CODEC_ID_NONE;
3030
    video_codec_id = CODEC_ID_NONE;
3031
    audio_stream_copy = 0;
3032
    video_stream_copy = 0;
3033
}
3034

    
3035
/* prepare dummy protocols for grab */
3036
static void prepare_grab(void)
3037
{
3038
    int has_video, has_audio, i, j;
3039
    AVFormatContext *oc;
3040
    AVFormatContext *ic;
3041
    AVFormatParameters vp1, *vp = &vp1;
3042
    AVFormatParameters ap1, *ap = &ap1;
3043
    
3044
    /* see if audio/video inputs are needed */
3045
    has_video = 0;
3046
    has_audio = 0;
3047
    memset(ap, 0, sizeof(*ap));
3048
    memset(vp, 0, sizeof(*vp));
3049
    for(j=0;j<nb_output_files;j++) {
3050
        oc = output_files[j];
3051
        for(i=0;i<oc->nb_streams;i++) {
3052
            AVCodecContext *enc = &oc->streams[i]->codec;
3053
            switch(enc->codec_type) {
3054
            case CODEC_TYPE_AUDIO:
3055
                if (enc->sample_rate > ap->sample_rate)
3056
                    ap->sample_rate = enc->sample_rate;
3057
                if (enc->channels > ap->channels)
3058
                    ap->channels = enc->channels;
3059
                has_audio = 1;
3060
                break;
3061
            case CODEC_TYPE_VIDEO:
3062
                if (enc->width > vp->width)
3063
                    vp->width = enc->width;
3064
                if (enc->height > vp->height)
3065
                    vp->height = enc->height;
3066
                
3067
                assert(enc->frame_rate_base == DEFAULT_FRAME_RATE_BASE);
3068
                if (enc->frame_rate > vp->frame_rate){
3069
                    vp->frame_rate      = enc->frame_rate;
3070
                    vp->frame_rate_base = enc->frame_rate_base;
3071
                }
3072
                has_video = 1;
3073
                break;
3074
            default:
3075
                av_abort();
3076
            }
3077
        }
3078
    }
3079
    
3080
    if (has_video == 0 && has_audio == 0) {
3081
        fprintf(stderr, "Output file must have at least one audio or video stream\n");
3082
        exit(1);
3083
    }
3084
    
3085
    if (has_video) {
3086
        AVInputFormat *fmt1;
3087
        fmt1 = av_find_input_format(video_grab_format);
3088
        vp->device  = video_device;
3089
        vp->channel = video_channel;
3090
        vp->standard = video_standard;
3091
        if (av_open_input_file(&ic, "", fmt1, 0, vp) < 0) {
3092
            fprintf(stderr, "Could not find video grab device\n");
3093
            exit(1);
3094
        }
3095
        /* If not enough info to get the stream parameters, we decode the
3096
           first frames to get it. */
3097
        if ((ic->ctx_flags & AVFMTCTX_NOHEADER) && av_find_stream_info(ic) < 0) {
3098
            fprintf(stderr, "Could not find video grab parameters\n");
3099
            exit(1);
3100
        }
3101
        /* by now video grab has one stream */
3102
        ic->streams[0]->r_frame_rate      = vp->frame_rate;
3103
        ic->streams[0]->r_frame_rate_base = vp->frame_rate_base;
3104
        input_files[nb_input_files] = ic;
3105

    
3106
        if (verbose >= 0)
3107
            dump_format(ic, nb_input_files, "", 0);
3108

    
3109
        nb_input_files++;
3110
    }
3111
    if (has_audio && audio_grab_format) {
3112
        AVInputFormat *fmt1;
3113
        fmt1 = av_find_input_format(audio_grab_format);
3114
        ap->device = audio_device;
3115
        if (av_open_input_file(&ic, "", fmt1, 0, ap) < 0) {
3116
            fprintf(stderr, "Could not find audio grab device\n");
3117
            exit(1);
3118
        }
3119
        input_files[nb_input_files] = ic;
3120

    
3121
        if (verbose >= 0)
3122
            dump_format(ic, nb_input_files, "", 0);
3123

    
3124
        nb_input_files++;
3125
    }
3126
}
3127

    
3128
/* same option as mencoder */
3129
static void opt_pass(const char *pass_str)
3130
{
3131
    int pass;
3132
    pass = atoi(pass_str);
3133
    if (pass != 1 && pass != 2) {
3134
        fprintf(stderr, "pass number can be only 1 or 2\n");
3135
        exit(1);
3136
    }
3137
    do_pass = pass;
3138
}
3139

    
3140
#if defined(CONFIG_WIN32) || defined(CONFIG_OS2)
3141
static int64_t getutime(void)
3142
{
3143
  return av_gettime();
3144
}
3145
#else
3146
static int64_t getutime(void)
3147
{
3148
    struct rusage rusage;
3149

    
3150
    getrusage(RUSAGE_SELF, &rusage);
3151
    return (rusage.ru_utime.tv_sec * 1000000LL) + rusage.ru_utime.tv_usec;
3152
}
3153
#endif
3154

    
3155
extern int ffm_nopts;
3156

    
3157
static void opt_bitexact(void)
3158
{
3159
    bitexact=1;
3160
    /* disable generate of real time pts in ffm (need to be supressed anyway) */
3161
    ffm_nopts = 1;
3162
}
3163

    
3164
static void show_formats(void)
3165
{
3166
    AVInputFormat *ifmt;
3167
    AVOutputFormat *ofmt;
3168
    AVImageFormat *image_fmt;
3169
    URLProtocol *up;
3170
    AVCodec *p, *p2;
3171
    const char **pp, *last_name;
3172

    
3173
    printf("File formats:\n");
3174
    last_name= "000";
3175
    for(;;){
3176
        int decode=0;
3177
        int encode=0;
3178
        const char *name=NULL;
3179

    
3180
        for(ofmt = first_oformat; ofmt != NULL; ofmt = ofmt->next) {
3181
            if((name == NULL || strcmp(ofmt->name, name)<0) &&
3182
                strcmp(ofmt->name, last_name)>0){
3183
                name= ofmt->name;
3184
                encode=1;
3185
            }
3186
        }
3187
        for(ifmt = first_iformat; ifmt != NULL; ifmt = ifmt->next) {
3188
            if((name == NULL || strcmp(ifmt->name, name)<0) &&
3189
                strcmp(ifmt->name, last_name)>0){
3190
                name= ifmt->name;
3191
                encode=0;
3192
            }
3193
            if(name && strcmp(ifmt->name, name)==0)
3194
                decode=1;
3195
        }
3196
        if(name==NULL)
3197
            break;
3198
        last_name= name;
3199
        
3200
        printf(
3201
            " %s%s %s\n", 
3202
            decode ? "D":" ", 
3203
            encode ? "E":" ", 
3204
            name);
3205
    }
3206
    printf("\n");
3207

    
3208
    printf("Image formats:\n");
3209
    for(image_fmt = first_image_format; image_fmt != NULL; 
3210
        image_fmt = image_fmt->next) {
3211
        printf(
3212
            " %s%s %s\n",
3213
            image_fmt->img_read  ? "D":" ",
3214
            image_fmt->img_write ? "E":" ",
3215
            image_fmt->name);
3216
    }
3217
    printf("\n");
3218

    
3219
    printf("Codecs:\n");
3220
    last_name= "000";
3221
    for(;;){
3222
        int decode=0;
3223
        int encode=0;
3224
        int cap=0;
3225

    
3226
        p2=NULL;
3227
        for(p = first_avcodec; p != NULL; p = p->next) {
3228
            if((p2==NULL || strcmp(p->name, p2->name)<0) &&
3229
                strcmp(p->name, last_name)>0){
3230
                p2= p;
3231
                decode= encode= cap=0;
3232
            }
3233
            if(p2 && strcmp(p->name, p2->name)==0){
3234
                if(p->decode) decode=1;
3235
                if(p->encode) encode=1;
3236
                cap |= p->capabilities;
3237
            }
3238
        }
3239
        if(p2==NULL)
3240
            break;
3241
        last_name= p2->name;
3242
        
3243
        printf(
3244
            " %s%s%s%s%s%s %s", 
3245
            decode ? "D": (/*p2->decoder ? "d":*/" "), 
3246
            encode ? "E":" ", 
3247
            p2->type == CODEC_TYPE_AUDIO ? "A":"V",
3248
            cap & CODEC_CAP_DRAW_HORIZ_BAND ? "S":" ",
3249
            cap & CODEC_CAP_DR1 ? "D":" ",
3250
            cap & CODEC_CAP_TRUNCATED ? "T":" ",
3251
            p2->name);
3252
       /* if(p2->decoder && decode==0)
3253
            printf(" use %s for decoding", p2->decoder->name);*/
3254
        printf("\n");
3255
    }
3256
    printf("\n");
3257

    
3258
    printf("Supported file protocols:\n");
3259
    for(up = first_protocol; up != NULL; up = up->next)
3260
        printf(" %s:", up->name);
3261
    printf("\n");
3262
    
3263
    printf("Frame size, frame rate abbreviations:\n ntsc pal qntsc qpal sntsc spal film ntsc-film sqcif qcif cif 4cif\n");
3264
    printf("Motion estimation methods:\n");
3265
    pp = motion_str;
3266
    while (*pp) {
3267
        printf(" %s", *pp);
3268
        if ((pp - motion_str + 1) == ME_ZERO) 
3269
            printf("(fastest)");
3270
        else if ((pp - motion_str + 1) == ME_FULL) 
3271
            printf("(slowest)");
3272
        else if ((pp - motion_str + 1) == ME_EPZS) 
3273
            printf("(default)");
3274
        pp++;
3275
    }
3276
    printf("\n\n");
3277
    printf(
3278
"Note, the names of encoders and decoders dont always match, so there are\n"
3279
"several cases where the above table shows encoder only or decoder only entries\n"
3280
"even though both encoding and decoding are supported for example, the h263\n"
3281
"decoder corresponds to the h263 and h263p encoders, for file formats its even\n"
3282
"worse\n");
3283
    exit(1);
3284
}
3285

    
3286
void parse_matrix_coeffs(uint16_t *dest, const char *str)
3287
{
3288
    int i;
3289
    const char *p = str;
3290
    for(i = 0;; i++) {
3291
        dest[i] = atoi(p);
3292
        if(i == 63)
3293
            break;
3294
        p = strchr(p, ',');
3295
        if(!p) {
3296
            fprintf(stderr, "Syntax error in matrix \"%s\" at coeff %d\n", str, i);
3297
            exit(1);
3298
        }
3299
        p++;
3300
    }
3301
}
3302

    
3303
void opt_inter_matrix(const char *arg)
3304
{
3305
    inter_matrix = av_mallocz(sizeof(uint16_t) * 64);
3306
    parse_matrix_coeffs(inter_matrix, arg);
3307
}
3308

    
3309
void opt_intra_matrix(const char *arg)
3310
{
3311
    intra_matrix = av_mallocz(sizeof(uint16_t) * 64);
3312
    parse_matrix_coeffs(intra_matrix, arg);
3313
}
3314

    
3315
static void opt_target(const char *arg)
3316
{
3317
    int norm = -1;
3318

    
3319
    if(!strncmp(arg, "pal-", 4)) {
3320
        norm = 0;
3321
        arg += 4;
3322
    } else if(!strncmp(arg, "ntsc-", 5)) {
3323
        norm = 1;
3324
        arg += 5;
3325
    } else {
3326
        int fr;
3327
        /* Calculate FR via float to avoid int overflow */
3328
        fr = (int)(frame_rate * 1000.0 / frame_rate_base);
3329
        if(fr == 25000) {
3330
            norm = 0;
3331
        } else if((fr == 29970) || (fr == 23976)) {
3332
            norm = 1;
3333
        } else {
3334
            /* Try to determine PAL/NTSC by peeking in the input files */
3335
            if(nb_input_files) {
3336
                int i, j;
3337
                for(j = 0; j < nb_input_files; j++) {
3338
                    for(i = 0; i < input_files[j]->nb_streams; i++) {
3339
                        AVCodecContext *c = &input_files[j]->streams[i]->codec;
3340
                        if(c->codec_type != CODEC_TYPE_VIDEO)
3341
                            continue;
3342
                        fr = c->frame_rate * 1000 / c->frame_rate_base;
3343
                        if(fr == 25000) {
3344
                            norm = 0;
3345
                            break;
3346
                        } else if((fr == 29970) || (fr == 23976)) {
3347
                            norm = 1;
3348
                            break;
3349
                        }
3350
                    }
3351
                    if(norm >= 0)
3352
                        break;
3353
                }
3354
            }
3355
        }
3356
        if(verbose && norm >= 0)
3357
            printf("Assuming %s for target.\n", norm ? "NTSC" : "PAL");
3358
    }
3359

    
3360
    if(norm < 0) {
3361
        fprintf(stderr, "Could not determine norm (PAL/NTSC) for target.\n");
3362
        fprintf(stderr, "Please prefix target with \"pal-\" or \"ntsc-\",\n");
3363
        fprintf(stderr, "or set a framerate with \"-r xxx\".\n");
3364
        exit(1);
3365
    }
3366

    
3367
    if(!strcmp(arg, "vcd")) {
3368

    
3369
        opt_video_codec("mpeg1video");
3370
        opt_audio_codec("mp2");
3371
        opt_format("vcd");
3372

    
3373
        opt_frame_size(norm ? "352x240" : "352x288");
3374

    
3375
        video_bit_rate = 1150000;
3376
        video_rc_max_rate = 1150000;
3377
        video_rc_min_rate = 1150000;
3378
        video_rc_buffer_size = 40*1024*8;
3379

    
3380
        audio_bit_rate = 224000;
3381
        audio_sample_rate = 44100;
3382

    
3383
    } else if(!strcmp(arg, "svcd")) {
3384

    
3385
        opt_video_codec("mpeg2video");
3386
        opt_audio_codec("mp2");
3387
        opt_format("svcd");
3388

    
3389
        opt_frame_size(norm ? "480x480" : "480x576");
3390
        opt_gop_size(norm ? "18" : "15");
3391

    
3392
        video_bit_rate = 2040000;
3393
        video_rc_max_rate = 2516000;
3394
        video_rc_min_rate = 0; //1145000;
3395
        video_rc_buffer_size = 224*1024*8;
3396
        use_scan_offset = 1;
3397

    
3398
        audio_bit_rate = 224000;
3399
        audio_sample_rate = 44100;
3400

    
3401
    } else if(!strcmp(arg, "dvd")) {
3402

    
3403
        opt_video_codec("mpeg2video");
3404
        opt_audio_codec("ac3");
3405
        opt_format("vob");
3406

    
3407
        opt_frame_size(norm ? "720x480" : "720x576");
3408
        opt_gop_size(norm ? "18" : "15");
3409

    
3410
        video_bit_rate = 6000000;
3411
        video_rc_max_rate = 9000000;
3412
        video_rc_min_rate = 0; //1500000;
3413
        video_rc_buffer_size = 224*1024*8;
3414

    
3415
        audio_bit_rate = 448000;
3416
        audio_sample_rate = 48000;
3417

    
3418
    } else {
3419
        fprintf(stderr, "Unknown target: %s\n", arg);
3420
        exit(1);
3421
    }
3422
}
3423

    
3424
const OptionDef options[] = {
3425
    /* main options */
3426
    { "L", 0, {(void*)show_license}, "show license" },
3427
    { "h", 0, {(void*)show_help}, "show help" },
3428
    { "formats", 0, {(void*)show_formats}, "show available formats, codecs, protocols, ..." },
3429
    { "f", HAS_ARG, {(void*)opt_format}, "force format", "fmt" },
3430
    { "img", HAS_ARG, {(void*)opt_image_format}, "force image format", "img_fmt" },
3431
    { "i", HAS_ARG, {(void*)opt_input_file}, "input file name", "filename" },
3432
    { "y", OPT_BOOL, {(void*)&file_overwrite}, "overwrite output files" },
3433
    { "map", HAS_ARG | OPT_EXPERT, {(void*)opt_map}, "set input stream mapping", "file:stream" },
3434
    { "t", HAS_ARG, {(void*)opt_recording_time}, "set the recording time", "duration" },
3435
    { "ss", HAS_ARG, {(void*)opt_start_time}, "set the start time offset", "time_off" },
3436
    { "title", HAS_ARG | OPT_STRING, {(void*)&str_title}, "set the title", "string" },
3437
    { "timestamp", HAS_ARG, {(void*)&opt_rec_timestamp}, "set the timestamp", "time" },
3438
    { "author", HAS_ARG | OPT_STRING, {(void*)&str_author}, "set the author", "string" },
3439
    { "copyright", HAS_ARG | OPT_STRING, {(void*)&str_copyright}, "set the copyright", "string" },
3440
    { "comment", HAS_ARG | OPT_STRING, {(void*)&str_comment}, "set the comment", "string" },
3441
    { "debug", HAS_ARG | OPT_EXPERT, {(void*)opt_debug}, "print specific debug info", "" },
3442
    { "vismv", HAS_ARG | OPT_EXPERT, {(void*)opt_vismv}, "visualize motion vectors", "" },
3443
    { "benchmark", OPT_BOOL | OPT_EXPERT, {(void*)&do_benchmark}, 
3444
      "add timings for benchmarking" },
3445
    { "dump", OPT_BOOL | OPT_EXPERT, {(void*)&do_pkt_dump}, 
3446
      "dump each input packet" },
3447
    { "hex", OPT_BOOL | OPT_EXPERT, {(void*)&do_hex_dump}, 
3448
      "when dumping packets, also dump the payload" },
3449
    { "bitexact", OPT_EXPERT, {(void*)opt_bitexact}, "only use bit exact algorithms (for codec testing)" }, 
3450
    { "re", OPT_BOOL | OPT_EXPERT, {(void*)&rate_emu}, "read input at native frame rate", "" },
3451
    { "loop", OPT_BOOL | OPT_EXPERT, {(void*)&loop_input}, "loop (current only works with images)" },
3452
    { "v", HAS_ARG, {(void*)opt_verbose}, "control amount of logging", "verbose" },
3453
    { "target", HAS_ARG, {(void*)opt_target}, "specify target file type (\"vcd\", \"svcd\" or \"dvd\")", "type" },
3454
    { "threads", HAS_ARG | OPT_EXPERT, {(void*)opt_thread_count}, "thread count", "count" },
3455
    { "sync", HAS_ARG | OPT_EXPERT, {(void*)opt_sync_method}, "sync method", "" },
3456

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

    
3558
    /* audio options */
3559
    { "ab", HAS_ARG | OPT_AUDIO, {(void*)opt_audio_bitrate}, "set audio bitrate (in kbit/s)", "bitrate", },
3560
    { "ar", HAS_ARG | OPT_AUDIO, {(void*)opt_audio_rate}, "set audio sampling rate (in Hz)", "rate" },
3561
    { "ac", HAS_ARG | OPT_AUDIO, {(void*)opt_audio_channels}, "set number of audio channels", "channels" },
3562
    { "an", OPT_BOOL | OPT_AUDIO, {(void*)&audio_disable}, "disable audio" },
3563
    { "acodec", HAS_ARG | OPT_AUDIO, {(void*)opt_audio_codec}, "force audio codec ('copy' to copy stream)", "codec" },
3564

    
3565
    /* grab options */
3566
    { "vd", HAS_ARG | OPT_EXPERT | OPT_VIDEO | OPT_GRAB, {(void*)opt_video_device}, "set video grab device", "device" },
3567
    { "vc", HAS_ARG | OPT_EXPERT | OPT_VIDEO | OPT_GRAB, {(void*)opt_video_channel}, "set video grab channel (DV1394 only)", "channel" },
3568
    { "tvstd", HAS_ARG | OPT_EXPERT | OPT_VIDEO | OPT_GRAB, {(void*)opt_video_standard}, "set television standard (NTSC, PAL (SECAM))", "standard" },
3569
    { "dv1394", OPT_EXPERT | OPT_GRAB, {(void*)opt_dv1394}, "set DV1394 grab", "" },
3570
    { "ad", HAS_ARG | OPT_EXPERT | OPT_AUDIO | OPT_GRAB, {(void*)opt_audio_device}, "set audio device", "device" },
3571
    { NULL, },
3572
};
3573

    
3574
static void show_banner(void)
3575
{
3576
    printf("ffmpeg version " FFMPEG_VERSION ", Copyright (c) 2000-2003 Fabrice Bellard\n");
3577
}
3578

    
3579
static void show_license(void)
3580
{
3581
    show_banner();
3582
#ifdef CONFIG_GPL
3583
    printf(
3584
    "This program is free software; you can redistribute it and/or modify\n"   
3585
    "it under the terms of the GNU General Public License as published by\n"
3586
    "the Free Software Foundation; either version 2 of the License, or\n"
3587
    "(at your option) any later version.\n"
3588
    "\n"
3589
    "This program is distributed in the hope that it will be useful,\n"
3590
    "but WITHOUT ANY WARRANTY; without even the implied warranty of\n"
3591
    "MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n"
3592
    "GNU General Public License for more details.\n"
3593
    "\n"
3594
    "You should have received a copy of the GNU General Public License\n"
3595
    "along with this program; if not, write to the Free Software\n"
3596
    "Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA\n"
3597
    );
3598
#else
3599
    printf(
3600
    "This library is free software; you can redistribute it and/or\n"
3601
    "modify it under the terms of the GNU Lesser General Public\n"
3602
    "License as published by the Free Software Foundation; either\n"
3603
    "version 2 of the License, or (at your option) any later version.\n"
3604
    "\n"
3605
    "This library is distributed in the hope that it will be useful,\n"
3606
    "but WITHOUT ANY WARRANTY; without even the implied warranty of\n"
3607
    "MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n"
3608
    "Lesser General Public License for more details.\n"
3609
    "\n"
3610
    "You should have received a copy of the GNU Lesser General Public\n"
3611
    "License along with this library; if not, write to the Free Software\n"
3612
    "Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA\n"
3613
    );
3614
#endif
3615
    exit(1);
3616
}
3617

    
3618
static void show_help(void)
3619
{
3620
    show_banner();
3621
    printf("usage: ffmpeg [[options] -i input_file]... {[options] outfile}...\n"
3622
           "Hyper fast Audio and Video encoder\n");
3623
    printf("\n");
3624
    show_help_options(options, "Main options:\n",
3625
                      OPT_EXPERT | OPT_AUDIO | OPT_VIDEO, 0);
3626
    show_help_options(options, "\nVideo options:\n",
3627
                      OPT_EXPERT | OPT_AUDIO | OPT_VIDEO | OPT_GRAB, 
3628
                      OPT_VIDEO);
3629
    show_help_options(options, "\nAdvanced Video options:\n",
3630
                      OPT_EXPERT | OPT_AUDIO | OPT_VIDEO | OPT_GRAB, 
3631
                      OPT_VIDEO | OPT_EXPERT);
3632
    show_help_options(options, "\nAudio options:\n",
3633
                      OPT_EXPERT | OPT_AUDIO | OPT_VIDEO | OPT_GRAB, 
3634
                      OPT_AUDIO);
3635
    show_help_options(options, "\nAdvanced Audio options:\n",
3636
                      OPT_EXPERT | OPT_AUDIO | OPT_VIDEO | OPT_GRAB, 
3637
                      OPT_AUDIO | OPT_EXPERT);
3638
    show_help_options(options, "\nAudio/Video grab options:\n",
3639
                      OPT_GRAB, 
3640
                      OPT_GRAB);
3641
    show_help_options(options, "\nAdvanced options:\n",
3642
                      OPT_EXPERT | OPT_AUDIO | OPT_VIDEO | OPT_GRAB, 
3643
                      OPT_EXPERT);
3644
    exit(1);
3645
}
3646

    
3647
void parse_arg_file(const char *filename)
3648
{
3649
    opt_output_file(filename);
3650
}
3651

    
3652
int main(int argc, char **argv)
3653
{
3654
    int i;
3655
    int64_t ti;
3656

    
3657
    av_register_all();
3658

    
3659
    if (argc <= 1)
3660
        show_help();
3661
    
3662
    /* parse options */
3663
    parse_options(argc, argv, options);
3664

    
3665
    /* file converter / grab */
3666
    if (nb_output_files <= 0) {
3667
        fprintf(stderr, "Must supply at least one output file\n");
3668
        exit(1);
3669
    }
3670
    
3671
    if (nb_input_files == 0) {
3672
        prepare_grab();
3673
    }
3674

    
3675
    ti = getutime();
3676
    av_encode(output_files, nb_output_files, input_files, nb_input_files, 
3677
              stream_maps, nb_stream_maps);
3678
    ti = getutime() - ti;
3679
    if (do_benchmark) {
3680
        printf("bench: utime=%0.3fs\n", ti / 1000000.0);
3681
    }
3682

    
3683
    /* close files */
3684
    for(i=0;i<nb_output_files;i++) {
3685
        /* maybe av_close_output_file ??? */
3686
        AVFormatContext *s = output_files[i];
3687
        int j;
3688
        if (!(s->oformat->flags & AVFMT_NOFILE))
3689
            url_fclose(&s->pb);
3690
        for(j=0;j<s->nb_streams;j++)
3691
            av_free(s->streams[j]);
3692
        av_free(s);
3693
    }
3694
    for(i=0;i<nb_input_files;i++)
3695
        av_close_input_file(input_files[i]);
3696

    
3697
    av_free_static();
3698

    
3699
    if(intra_matrix)
3700
        av_free(intra_matrix);
3701
    if(inter_matrix)
3702
        av_free(inter_matrix);
3703
    
3704
#ifdef POWERPC_PERFORMANCE_REPORT
3705
    extern void powerpc_display_perf_report(void);
3706
    powerpc_display_perf_report();
3707
#endif /* POWERPC_PERFORMANCE_REPORT */
3708

    
3709
#ifndef CONFIG_WIN32
3710
    if (received_sigterm) {
3711
        fprintf(stderr,
3712
            "Received signal %d: terminating.\n",
3713
            (int) received_sigterm);
3714
        exit (255);
3715
    }
3716
#endif
3717
    exit(0); /* not all OS-es handle main() return value */
3718
    return 0;
3719
}