Statistics
| Branch: | Revision:

ffmpeg / ffmpeg.c @ 986ebcdb

History | View | Annotate | Download (133 KB)

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

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

    
41
#include "cmdutils.h"
42

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

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

    
53
extern const OptionDef options[];
54

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

    
58
#define MAX_FILES 20
59

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

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

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

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

    
177
static int gop_size = 12;
178
static int intra_only = 0;
179
static int audio_sample_rate = 44100;
180
static int audio_bit_rate = 64000;
181
static int audio_disable = 0;
182
static int audio_channels = 1;
183
static int audio_codec_id = CODEC_ID_NONE;
184

    
185
static int64_t recording_time = 0;
186
static int64_t start_time = 0;
187
static int64_t rec_timestamp = 0;
188
static int64_t input_ts_offset = 0;
189
static int file_overwrite = 0;
190
static char *str_title = NULL;
191
static char *str_author = NULL;
192
static char *str_copyright = NULL;
193
static char *str_comment = NULL;
194
static int do_benchmark = 0;
195
static int do_hex_dump = 0;
196
static int do_pkt_dump = 0;
197
static int do_psnr = 0;
198
static int do_vstats = 0;
199
static int do_pass = 0;
200
static int bitexact = 0;
201
static char *pass_logfilename = NULL;
202
static int audio_stream_copy = 0;
203
static int video_stream_copy = 0;
204
static int video_sync_method= 1;
205
static int audio_sync_method= 0;
206
static int copy_ts= 0;
207

    
208
static int rate_emu = 0;
209

    
210
static char *video_grab_format = "video4linux";
211
static char *video_device = NULL;
212
static int  video_channel = 0;
213
static char *video_standard = "ntsc";
214

    
215
static char *audio_grab_format = "audio_device";
216
static char *audio_device = NULL;
217

    
218
static int using_stdin = 0;
219
static int using_vhook = 0;
220
static int verbose = 1;
221
static int thread_count= 1;
222
static int q_pressed = 0;
223
static int me_range = 0;
224
static int64_t video_size = 0;
225
static int64_t audio_size = 0;
226
static int64_t extra_size = 0;
227
static int nb_frames_dup = 0;
228
static int nb_frames_drop = 0;
229
static int input_sync;
230

    
231
#define DEFAULT_PASS_LOGFILENAME "ffmpeg2pass"
232

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

    
249
    int video_crop;          /* video_resample and video_crop are mutually exclusive */
250
    int topBand;             /* cropping area sizes */
251
    int leftBand;
252
    
253
    int video_pad;           /* video_resample and video_pad are mutually exclusive */
254
    int padtop;              /* padding area sizes */
255
    int padbottom;
256
    int padleft;
257
    int padright;
258
    
259
    /* audio only */
260
    int audio_resample;
261
    ReSampleContext *resample; /* for audio resampling */
262
    FifoBuffer fifo;     /* for compression: one audio fifo per codec */
263
    FILE *logfile;
264
} AVOutputStream;
265

    
266
typedef struct AVInputStream {
267
    int file_index;
268
    int index;
269
    AVStream *st;
270
    int discard;             /* true if stream data should be discarded */
271
    int decoding_needed;     /* true if the packets must be decoded in 'raw_fifo' */
272
    int64_t sample_index;      /* current sample */
273

    
274
    int64_t       start;     /* time when read started */
275
    unsigned long frame;     /* current frame */
276
    int64_t       next_pts;  /* synthetic pts for cases where pkt.pts
277
                                is not defined */
278
    int64_t       pts;       /* current pts */
279
} AVInputStream;
280

    
281
typedef struct AVInputFile {
282
    int eof_reached;      /* true if eof reached */
283
    int ist_index;        /* index of first stream in ist_table */
284
    int buffer_size;      /* current total buffer size */
285
    int buffer_size_max;  /* buffer size at which we consider we can stop
286
                             buffering */
287
    int nb_streams;       /* nb streams we are aware of */
288
} AVInputFile;
289

    
290
#ifndef CONFIG_WIN32
291

    
292
/* init terminal so that we can grab keys */
293
static struct termios oldtty;
294

    
295
static void term_exit(void)
296
{
297
    tcsetattr (0, TCSANOW, &oldtty);
298
}
299

    
300
static volatile sig_atomic_t received_sigterm = 0;
301

    
302
static void
303
sigterm_handler(int sig)
304
{
305
    received_sigterm = sig;
306
    term_exit();
307
}
308

    
309
static void term_init(void)
310
{
311
    struct termios tty;
312

    
313
    tcgetattr (0, &tty);
314
    oldtty = tty;
315

    
316
    tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
317
                          |INLCR|IGNCR|ICRNL|IXON);
318
    tty.c_oflag |= OPOST;
319
    tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
320
    tty.c_cflag &= ~(CSIZE|PARENB);
321
    tty.c_cflag |= CS8;
322
    tty.c_cc[VMIN] = 1;
323
    tty.c_cc[VTIME] = 0;
324
    
325
    tcsetattr (0, TCSANOW, &tty);
326

    
327
    signal(SIGINT , sigterm_handler); /* Interrupt (ANSI).  */
328
    signal(SIGQUIT, sigterm_handler); /* Quit (POSIX).  */
329
    signal(SIGTERM, sigterm_handler); /* Termination (ANSI).  */
330
    /*
331
    register a function to be called at normal program termination
332
    */
333
    atexit(term_exit);
334
#ifdef CONFIG_BEOS_NETSERVER
335
    fcntl(0, F_SETFL, fcntl(0, F_GETFL) | O_NONBLOCK);
336
#endif
337
}
338

    
339
/* read a key without blocking */
340
static int read_key(void)
341
{
342
    int n = 1;
343
    unsigned char ch;
344
#ifndef CONFIG_BEOS_NETSERVER
345
    struct timeval tv;
346
    fd_set rfds;
347

    
348
    FD_ZERO(&rfds);
349
    FD_SET(0, &rfds);
350
    tv.tv_sec = 0;
351
    tv.tv_usec = 0;
352
    n = select(1, &rfds, NULL, NULL, &tv);
353
#endif
354
    if (n > 0) {
355
        n = read(0, &ch, 1);
356
        if (n == 1)
357
            return ch;
358

    
359
        return n;
360
    }
361
    return -1;
362
}
363

    
364
static int decode_interrupt_cb(void)
365
{
366
    return q_pressed || (q_pressed = read_key() == 'q');
367
}
368

    
369
#else
370

    
371
static volatile int received_sigterm = 0;
372

    
373
/* no interactive support */
374
static void term_exit(void)
375
{
376
}
377

    
378
static void term_init(void)
379
{
380
}
381

    
382
static int read_key(void)
383
{
384
    return 0;
385
}
386

    
387
#endif
388

    
389
static int read_ffserver_streams(AVFormatContext *s, const char *filename)
390
{
391
    int i, err;
392
    AVFormatContext *ic;
393

    
394
    err = av_open_input_file(&ic, filename, NULL, FFM_PACKET_SIZE, NULL);
395
    if (err < 0)
396
        return err;
397
    /* copy stream format */
398
    s->nb_streams = ic->nb_streams;
399
    for(i=0;i<ic->nb_streams;i++) {
400
        AVStream *st;
401

    
402
        st = av_mallocz(sizeof(AVStream));
403
        memcpy(st, ic->streams[i], sizeof(AVStream));
404
        s->streams[i] = st;
405
    }
406

    
407
    av_close_input_file(ic);
408
    return 0;
409
}
410

    
411
#define MAX_AUDIO_PACKET_SIZE (128 * 1024)
412

    
413
static void do_audio_out(AVFormatContext *s, 
414
                         AVOutputStream *ost, 
415
                         AVInputStream *ist,
416
                         unsigned char *buf, int size)
417
{
418
    uint8_t *buftmp;
419
    static uint8_t *audio_buf = NULL;
420
    static uint8_t *audio_out = NULL;
421
    const int audio_out_size= 4*MAX_AUDIO_PACKET_SIZE;
422

    
423
    int size_out, frame_bytes, ret;
424
    AVCodecContext *enc;
425

    
426
    /* SC: dynamic allocation of buffers */
427
    if (!audio_buf)
428
        audio_buf = av_malloc(2*MAX_AUDIO_PACKET_SIZE);
429
    if (!audio_out)
430
        audio_out = av_malloc(audio_out_size);
431
    if (!audio_buf || !audio_out)
432
        return;               /* Should signal an error ! */
433

    
434
    
435
    enc = &ost->st->codec;
436
    
437
    if(audio_sync_method){
438
        double delta = ost->sync_ipts * enc->sample_rate - ost->sync_opts 
439
                - fifo_size(&ost->fifo, ost->fifo.rptr)/(ost->st->codec.channels * 2);
440
        //FIXME resample delay
441
        if(fabs(delta) > 50){
442
            int comp= clip(delta, -audio_sync_method, audio_sync_method);
443
            assert(ost->audio_resample);
444
            if(verbose > 2)
445
                fprintf(stderr, "compensating audio timestamp drift:%f compensation:%d in:%d\n", delta, comp, enc->sample_rate);
446
//            fprintf(stderr, "drift:%f len:%d opts:%lld ipts:%lld fifo:%d\n", delta, len/4, ost->sync_opts, (int64_t)(ost->sync_ipts * enc->sample_rate), fifo_size(&ost->fifo, ost->fifo.rptr)/(ost->st->codec.channels * 2));
447
            av_resample_compensate(*(struct AVResampleContext**)ost->resample, delta, enc->sample_rate);
448
        }
449
    }else
450
        ost->sync_opts= lrintf(ost->sync_ipts * enc->sample_rate)
451
                        - fifo_size(&ost->fifo, ost->fifo.rptr)/(ost->st->codec.channels * 2); //FIXME wrong
452

    
453
    if (ost->audio_resample) {
454
        buftmp = audio_buf;
455
        size_out = audio_resample(ost->resample, 
456
                                  (short *)buftmp, (short *)buf,
457
                                  size / (ist->st->codec.channels * 2));
458
        size_out = size_out * enc->channels * 2;
459
    } else {
460
        buftmp = buf;
461
        size_out = size;
462
    }
463

    
464
    /* now encode as many frames as possible */
465
    if (enc->frame_size > 1) {
466
        /* output resampled raw samples */
467
        fifo_write(&ost->fifo, buftmp, size_out, 
468
                   &ost->fifo.wptr);
469

    
470
        frame_bytes = enc->frame_size * 2 * enc->channels;
471
        
472
        while (fifo_read(&ost->fifo, audio_buf, frame_bytes, 
473
                     &ost->fifo.rptr) == 0) {
474
            AVPacket pkt;
475
            av_init_packet(&pkt);
476

    
477
            ret = avcodec_encode_audio(enc, audio_out, audio_out_size, 
478
                                       (short *)audio_buf);
479
            audio_size += ret;
480
            pkt.stream_index= ost->index;
481
            pkt.data= audio_out;
482
            pkt.size= ret;
483
            if(enc->coded_frame)
484
                pkt.pts= enc->coded_frame->pts;
485
            pkt.flags |= PKT_FLAG_KEY;
486
            av_interleaved_write_frame(s, &pkt);
487
            
488
            ost->sync_opts += enc->frame_size;
489
        }
490
    } else {
491
        AVPacket pkt;
492
        av_init_packet(&pkt);
493

    
494
        ost->sync_opts += size_out / enc->channels;
495

    
496
        /* output a pcm frame */
497
        /* XXX: change encoding codec API to avoid this ? */
498
        switch(enc->codec->id) {
499
        case CODEC_ID_PCM_S16LE:
500
        case CODEC_ID_PCM_S16BE:
501
        case CODEC_ID_PCM_U16LE:
502
        case CODEC_ID_PCM_U16BE:
503
            break;
504
        default:
505
            size_out = size_out >> 1;
506
            break;
507
        }
508
        ret = avcodec_encode_audio(enc, audio_out, size_out, 
509
                                   (short *)buftmp);
510
        audio_size += ret;
511
        pkt.stream_index= ost->index;
512
        pkt.data= audio_out;
513
        pkt.size= ret;
514
        if(enc->coded_frame)
515
            pkt.pts= enc->coded_frame->pts;
516
        pkt.flags |= PKT_FLAG_KEY;
517
        av_interleaved_write_frame(s, &pkt);
518
    }
519
}
520

    
521
static void pre_process_video_frame(AVInputStream *ist, AVPicture *picture, void **bufp)
522
{
523
    AVCodecContext *dec;
524
    AVPicture *picture2;
525
    AVPicture picture_tmp;
526
    uint8_t *buf = 0;
527

    
528
    dec = &ist->st->codec;
529

    
530
    /* deinterlace : must be done before any resize */
531
    if (do_deinterlace || using_vhook) {
532
        int size;
533

    
534
        /* create temporary picture */
535
        size = avpicture_get_size(dec->pix_fmt, dec->width, dec->height);
536
        buf = av_malloc(size);
537
        if (!buf)
538
            return;
539
        
540
        picture2 = &picture_tmp;
541
        avpicture_fill(picture2, buf, dec->pix_fmt, dec->width, dec->height);
542

    
543
        if (do_deinterlace){
544
            if(avpicture_deinterlace(picture2, picture, 
545
                                     dec->pix_fmt, dec->width, dec->height) < 0) {
546
                /* if error, do not deinterlace */
547
                av_free(buf);
548
                buf = NULL;
549
                picture2 = picture;
550
            }
551
        } else {
552
            if (img_convert(picture2, dec->pix_fmt, picture, 
553
                            dec->pix_fmt, dec->width, dec->height) < 0) {
554
                /* if error, do not copy */
555
                av_free(buf);
556
                buf = NULL;
557
                picture2 = picture;
558
            }
559
        }
560
    } else {
561
        picture2 = picture;
562
    }
563

    
564
    frame_hook_process(picture2, dec->pix_fmt, dec->width, dec->height);
565

    
566
    if (picture != picture2)
567
        *picture = *picture2;
568
    *bufp = buf;
569
}
570

    
571
/* we begin to correct av delay at this threshold */
572
#define AV_DELAY_MAX 0.100
573

    
574

    
575
/* Expects img to be yuv420 */
576
static void fill_pad_region(AVPicture* img, int height, int width,
577
        int padtop, int padbottom, int padleft, int padright, int *color) {
578
  
579
    int i, y, shift;
580
    uint8_t *optr;
581
    
582
    for (i = 0; i < 3; i++) {
583
        shift = (i == 0) ? 0 : 1;
584
        
585
        if (padtop || padleft) {
586
            memset(img->data[i], color[i], (((img->linesize[i] * padtop) + 
587
                            padleft) >> shift));
588
        }
589

    
590
        if (padleft || padright) {
591
            optr = img->data[i] + (img->linesize[i] * (padtop >> shift)) +
592
                (img->linesize[i] - (padright >> shift));
593

    
594
            for (y = 0; y < ((height - (padtop + padbottom)) >> shift); y++) {
595
                memset(optr, color[i], (padleft + padright) >> shift);
596
                optr += img->linesize[i];
597
            }
598
        }
599
      
600
        if (padbottom) {
601
            optr = img->data[i] + (img->linesize[i] * ((height - padbottom) >> shift));
602
            memset(optr, color[i], ((img->linesize[i] * padbottom) >> shift));
603
        }
604
    }
605
}
606

    
607
static uint8_t *bit_buffer= NULL;
608

    
609
static void do_video_out(AVFormatContext *s, 
610
                         AVOutputStream *ost, 
611
                         AVInputStream *ist,
612
                         AVFrame *in_picture,
613
                         int *frame_size)
614
{
615
    int nb_frames, i, ret;
616
    AVFrame *final_picture, *formatted_picture;
617
    AVFrame picture_format_temp, picture_crop_temp;
618
    uint8_t *buf = NULL, *buf1 = NULL;
619
    AVCodecContext *enc, *dec;
620
    enum PixelFormat target_pixfmt;
621
    
622
#define VIDEO_BUFFER_SIZE (1024*1024)
623

    
624
    avcodec_get_frame_defaults(&picture_format_temp);
625
    avcodec_get_frame_defaults(&picture_crop_temp);
626

    
627
    enc = &ost->st->codec;
628
    dec = &ist->st->codec;
629

    
630
    /* by default, we output a single frame */
631
    nb_frames = 1;
632

    
633
    *frame_size = 0;
634

    
635
    if(video_sync_method){
636
        double vdelta;
637
        vdelta = ost->sync_ipts * enc->frame_rate / enc->frame_rate_base - ost->sync_opts;
638
        //FIXME set to 0.5 after we fix some dts/pts bugs like in avidec.c
639
        if (vdelta < -1.1)
640
            nb_frames = 0;
641
        else if (vdelta > 1.1)
642
            nb_frames = 2;
643
//fprintf(stderr, "vdelta:%f, ost->sync_opts:%lld, ost->sync_ipts:%f nb_frames:%d\n", vdelta, ost->sync_opts, ost->sync_ipts, nb_frames);
644
        if (nb_frames == 0){
645
            ++nb_frames_drop;
646
            if (verbose>2)
647
                fprintf(stderr, "*** drop!\n");
648
        }else if (nb_frames == 2) {
649
            ++nb_frames_dup;
650
            if (verbose>2)
651
                fprintf(stderr, "*** dup!\n");
652
        }
653
    }else
654
        ost->sync_opts= lrintf(ost->sync_ipts * enc->frame_rate / enc->frame_rate_base);
655

    
656
    if (nb_frames <= 0) 
657
        return;
658

    
659
    /* convert pixel format if needed */
660
    target_pixfmt = ost->video_resample || ost->video_pad
661
        ? PIX_FMT_YUV420P : enc->pix_fmt;
662
    if (dec->pix_fmt != target_pixfmt) {
663
        int size;
664

    
665
        /* create temporary picture */
666
        size = avpicture_get_size(target_pixfmt, dec->width, dec->height);
667
        buf = av_malloc(size);
668
        if (!buf)
669
            return;
670
        formatted_picture = &picture_format_temp;
671
        avpicture_fill((AVPicture*)formatted_picture, buf, target_pixfmt, dec->width, dec->height);
672
        
673
        if (img_convert((AVPicture*)formatted_picture, target_pixfmt, 
674
                        (AVPicture *)in_picture, dec->pix_fmt, 
675
                        dec->width, dec->height) < 0) {
676

    
677
            if (verbose >= 0)
678
                fprintf(stderr, "pixel format conversion not handled\n");
679

    
680
            goto the_end;
681
        }
682
    } else {
683
        formatted_picture = in_picture;
684
    }
685

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

    
715
                if (verbose >= 0)
716
                    fprintf(stderr, "pixel format conversion not handled\n");
717

    
718
                goto the_end;
719
            }
720
        }
721
    } else if (ost->video_crop) {
722
        picture_crop_temp.data[0] = formatted_picture->data[0] +
723
                (ost->topBand * formatted_picture->linesize[0]) + ost->leftBand;
724

    
725
        picture_crop_temp.data[1] = formatted_picture->data[1] +
726
                ((ost->topBand >> 1) * formatted_picture->linesize[1]) +
727
                (ost->leftBand >> 1);
728

    
729
        picture_crop_temp.data[2] = formatted_picture->data[2] +
730
                ((ost->topBand >> 1) * formatted_picture->linesize[2]) +
731
                (ost->leftBand >> 1);
732

    
733
        picture_crop_temp.linesize[0] = formatted_picture->linesize[0];
734
        picture_crop_temp.linesize[1] = formatted_picture->linesize[1];
735
        picture_crop_temp.linesize[2] = formatted_picture->linesize[2];
736
        final_picture = &picture_crop_temp;
737
    } else if (ost->video_pad) {
738
        final_picture = &ost->pict_tmp;
739

    
740
        for (i = 0; i < 3; i++) {
741
            uint8_t *optr, *iptr;
742
            int shift = (i == 0) ? 0 : 1;
743
            int y, yheight;
744
            
745
            /* set offset to start writing image into */
746
            optr = final_picture->data[i] + (((final_picture->linesize[i] * 
747
                            ost->padtop) + ost->padleft) >> shift);
748
            iptr = formatted_picture->data[i];
749

    
750
            yheight = (enc->height - ost->padtop - ost->padbottom) >> shift;
751
            for (y = 0; y < yheight; y++) {
752
                /* copy unpadded image row into padded image row */
753
                memcpy(optr, iptr, formatted_picture->linesize[i]);
754
                optr += final_picture->linesize[i];
755
                iptr += formatted_picture->linesize[i];
756
            }
757
        }
758

    
759
        fill_pad_region((AVPicture*)final_picture, enc->height, enc->width,
760
                ost->padtop, ost->padbottom, ost->padleft, ost->padright,
761
                padcolor);
762
        
763
        if (enc->pix_fmt != PIX_FMT_YUV420P) {
764
            int size;
765

    
766
            av_free(buf);
767
            /* create temporary picture */
768
            size = avpicture_get_size(enc->pix_fmt, enc->width, enc->height);
769
            buf = av_malloc(size);
770
            if (!buf)
771
                return;
772
            final_picture = &picture_format_temp;
773
            avpicture_fill((AVPicture*)final_picture, buf, enc->pix_fmt, enc->width, enc->height);
774

    
775
            if (img_convert((AVPicture*)final_picture, enc->pix_fmt, 
776
                        (AVPicture*)&ost->pict_tmp, PIX_FMT_YUV420P, 
777
                        enc->width, enc->height) < 0) {
778

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

    
782
                goto the_end;
783
            }
784
        }
785
    } else {
786
        final_picture = formatted_picture;
787
    }
788
    /* duplicates frame if needed */
789
    /* XXX: pb because no interleaving */
790
    for(i=0;i<nb_frames;i++) {
791
        AVPacket pkt;
792
        av_init_packet(&pkt);
793
        pkt.stream_index= ost->index;
794

    
795
        if (s->oformat->flags & AVFMT_RAWPICTURE) {
796
            /* raw pictures are written as AVPicture structure to
797
               avoid any copies. We support temorarily the older
798
               method. */
799
            AVFrame* old_frame = enc->coded_frame;
800
            enc->coded_frame = dec->coded_frame; //FIXME/XXX remove this hack
801
            pkt.data= (uint8_t *)final_picture;
802
            pkt.size=  sizeof(AVPicture);
803
            if(dec->coded_frame)
804
                pkt.pts= dec->coded_frame->pts;
805
            if(dec->coded_frame && dec->coded_frame->key_frame)
806
                pkt.flags |= PKT_FLAG_KEY;
807

    
808
            av_interleaved_write_frame(s, &pkt);
809
            enc->coded_frame = old_frame;
810
        } else {
811
            AVFrame big_picture;
812

    
813
            big_picture= *final_picture;
814
            /* better than nothing: use input picture interlaced
815
               settings */
816
            big_picture.interlaced_frame = in_picture->interlaced_frame;
817
            if(do_interlace_me || do_interlace_dct){
818
                if(top_field_first == -1)
819
                    big_picture.top_field_first = in_picture->top_field_first;
820
                else
821
                    big_picture.top_field_first = top_field_first;
822
            }
823

    
824
            /* handles sameq here. This is not correct because it may
825
               not be a global option */
826
            if (same_quality) {
827
                big_picture.quality = ist->st->quality;
828
            }else
829
                big_picture.quality = ost->st->quality;
830
            if(!me_threshold)
831
                big_picture.pict_type = 0;
832
//            big_picture.pts = AV_NOPTS_VALUE;
833
            big_picture.pts= av_rescale(ost->sync_opts, AV_TIME_BASE*(int64_t)enc->frame_rate_base, enc->frame_rate);
834
//av_log(NULL, AV_LOG_DEBUG, "%lld -> encoder\n", ost->sync_opts);
835
            ret = avcodec_encode_video(enc, 
836
                                       bit_buffer, VIDEO_BUFFER_SIZE,
837
                                       &big_picture);
838
            //enc->frame_number = enc->real_pict_num;
839
            if(ret){
840
                pkt.data= bit_buffer;
841
                pkt.size= ret;
842
                if(enc->coded_frame)
843
                    pkt.pts= enc->coded_frame->pts;
844
/*av_log(NULL, AV_LOG_DEBUG, "encoder -> %lld/%lld\n", 
845
   pkt.pts != AV_NOPTS_VALUE ? av_rescale(pkt.pts, enc->frame_rate, AV_TIME_BASE*(int64_t)enc->frame_rate_base) : -1,
846
   pkt.dts != AV_NOPTS_VALUE ? av_rescale(pkt.dts, enc->frame_rate, AV_TIME_BASE*(int64_t)enc->frame_rate_base) : -1);*/
847

    
848
                if(enc->coded_frame && enc->coded_frame->key_frame)
849
                    pkt.flags |= PKT_FLAG_KEY;
850
                av_interleaved_write_frame(s, &pkt);
851
                *frame_size = ret;
852
                //fprintf(stderr,"\nFrame: %3d %3d size: %5d type: %d",
853
                //        enc->frame_number-1, enc->real_pict_num, ret,
854
                //        enc->pict_type);
855
                /* if two pass, output log */
856
                if (ost->logfile && enc->stats_out) {
857
                    fprintf(ost->logfile, "%s", enc->stats_out);
858
                }
859
            }
860
        }
861
        ost->sync_opts++;
862
        ost->frame_number++;
863
    }
864
 the_end:
865
    av_free(buf);
866
    av_free(buf1);
867
}
868

    
869
static double psnr(double d){
870
    if(d==0) return INFINITY;
871
    return -10.0*log(d)/log(10.0);
872
}
873

    
874
static void do_video_stats(AVFormatContext *os, AVOutputStream *ost, 
875
                           int frame_size)
876
{
877
    static FILE *fvstats=NULL;
878
    char filename[40];
879
    time_t today2;
880
    struct tm *today;
881
    AVCodecContext *enc;
882
    int frame_number;
883
    int64_t ti;
884
    double ti1, bitrate, avg_bitrate;
885
    
886
    if (!fvstats) {
887
        today2 = time(NULL);
888
        today = localtime(&today2);
889
        sprintf(filename, "vstats_%02d%02d%02d.log", today->tm_hour,
890
                                               today->tm_min,
891
                                               today->tm_sec);
892
        fvstats = fopen(filename,"w");
893
        if (!fvstats) {
894
            perror("fopen");
895
            exit(1);
896
        }
897
    }
898
    
899
    ti = MAXINT64;
900
    enc = &ost->st->codec;
901
    if (enc->codec_type == CODEC_TYPE_VIDEO) {
902
        frame_number = ost->frame_number;
903
        fprintf(fvstats, "frame= %5d q= %2.1f ", frame_number, enc->coded_frame->quality/(float)FF_QP2LAMBDA);
904
        if (enc->flags&CODEC_FLAG_PSNR)
905
            fprintf(fvstats, "PSNR= %6.2f ", psnr(enc->coded_frame->error[0]/(enc->width*enc->height*255.0*255.0)));
906
        
907
        fprintf(fvstats,"f_size= %6d ", frame_size);
908
        /* compute pts value */
909
        ti1 = (double)ost->sync_opts *enc->frame_rate_base / enc->frame_rate;
910
        if (ti1 < 0.01)
911
            ti1 = 0.01;
912
    
913
        bitrate = (double)(frame_size * 8) * enc->frame_rate / enc->frame_rate_base / 1000.0;
914
        avg_bitrate = (double)(video_size * 8) / ti1 / 1000.0;
915
        fprintf(fvstats, "s_size= %8.0fkB time= %0.3f br= %7.1fkbits/s avg_br= %7.1fkbits/s ",
916
            (double)video_size / 1024, ti1, bitrate, avg_bitrate);
917
        fprintf(fvstats,"type= %c\n", av_get_pict_type_char(enc->coded_frame->pict_type));        
918
    }
919
}
920

    
921
static void print_report(AVFormatContext **output_files,
922
                         AVOutputStream **ost_table, int nb_ostreams,
923
                         int is_last_report)
924
{
925
    char buf[1024];
926
    AVOutputStream *ost;
927
    AVFormatContext *oc, *os;
928
    int64_t total_size;
929
    AVCodecContext *enc;
930
    int frame_number, vid, i;
931
    double bitrate, ti1, pts;
932
    static int64_t last_time = -1;
933
    
934
    if (!is_last_report) {
935
        int64_t cur_time;
936
        /* display the report every 0.5 seconds */
937
        cur_time = av_gettime();
938
        if (last_time == -1) {
939
            last_time = cur_time;
940
            return;
941
        } 
942
        if ((cur_time - last_time) < 500000)
943
            return;
944
        last_time = cur_time;
945
    }
946

    
947

    
948
    oc = output_files[0];
949

    
950
    total_size = url_ftell(&oc->pb);
951
    
952
    buf[0] = '\0';
953
    ti1 = 1e10;
954
    vid = 0;
955
    for(i=0;i<nb_ostreams;i++) {
956
        ost = ost_table[i];
957
        os = output_files[ost->file_index];
958
        enc = &ost->st->codec;
959
        if (vid && enc->codec_type == CODEC_TYPE_VIDEO) {
960
            sprintf(buf + strlen(buf), "q=%2.1f ",
961
                    enc->coded_frame->quality/(float)FF_QP2LAMBDA);
962
        }
963
        if (!vid && enc->codec_type == CODEC_TYPE_VIDEO) {
964
            frame_number = ost->frame_number;
965
            sprintf(buf + strlen(buf), "frame=%5d q=%2.1f ",
966
                    frame_number, enc->coded_frame ? enc->coded_frame->quality/(float)FF_QP2LAMBDA : 0);
967
            if(is_last_report)
968
                sprintf(buf + strlen(buf), "L");
969
            if (enc->flags&CODEC_FLAG_PSNR){
970
                int j;
971
                double error, error_sum=0;
972
                double scale, scale_sum=0;
973
                char type[3]= {'Y','U','V'};
974
                sprintf(buf + strlen(buf), "PSNR=");
975
                for(j=0; j<3; j++){
976
                    if(is_last_report){
977
                        error= enc->error[j];
978
                        scale= enc->width*enc->height*255.0*255.0*frame_number;
979
                    }else{
980
                        error= enc->coded_frame->error[j];
981
                        scale= enc->width*enc->height*255.0*255.0;
982
                    }
983
                    if(j) scale/=4;
984
                    error_sum += error;
985
                    scale_sum += scale;
986
                    sprintf(buf + strlen(buf), "%c:%2.2f ", type[j], psnr(error/scale));
987
                }
988
                sprintf(buf + strlen(buf), "*:%2.2f ", psnr(error_sum/scale_sum));
989
            }
990
            vid = 1;
991
        }
992
        /* compute min output value */
993
        pts = (double)ost->st->pts.val * ost->st->time_base.num / ost->st->time_base.den;
994
        if ((pts < ti1) && (pts > 0))
995
            ti1 = pts;
996
    }
997
    if (ti1 < 0.01)
998
        ti1 = 0.01;
999
    
1000
    if (verbose || is_last_report) {
1001
        bitrate = (double)(total_size * 8) / ti1 / 1000.0;
1002
        
1003
        sprintf(buf + strlen(buf), 
1004
            "size=%8.0fkB time=%0.1f bitrate=%6.1fkbits/s",
1005
            (double)total_size / 1024, ti1, bitrate);
1006

    
1007
        if (verbose > 1)
1008
          sprintf(buf + strlen(buf), " dup=%d drop=%d",
1009
                  nb_frames_dup, nb_frames_drop);
1010
        
1011
        if (verbose >= 0)
1012
            fprintf(stderr, "%s    \r", buf);
1013

    
1014
        fflush(stderr);
1015
    }
1016
        
1017
    if (is_last_report && verbose >= 0){
1018
        int64_t raw= audio_size + video_size + extra_size;
1019
        fprintf(stderr, "\n");
1020
        fprintf(stderr, "video:%1.0fkB audio:%1.0fkB global headers:%1.0fkB muxing overhead %f%%\n",
1021
                video_size/1024.0,
1022
                audio_size/1024.0,
1023
                extra_size/1024.0,
1024
                100.0*(total_size - raw)/raw
1025
        );
1026
    }
1027
}
1028

    
1029
/* pkt = NULL means EOF (needed to flush decoder buffers) */
1030
static int output_packet(AVInputStream *ist, int ist_index,
1031
                         AVOutputStream **ost_table, int nb_ostreams,
1032
                         const AVPacket *pkt)
1033
{
1034
    AVFormatContext *os;
1035
    AVOutputStream *ost;
1036
    uint8_t *ptr;
1037
    int len, ret, i;
1038
    uint8_t *data_buf;
1039
    int data_size, got_picture;
1040
    AVFrame picture;
1041
    short samples[AVCODEC_MAX_AUDIO_FRAME_SIZE / 2];
1042
    void *buffer_to_free;
1043
//fprintf(stderr, "output_packet %d, dts:%lld\n", pkt->stream_index, pkt->dts);
1044
    if (pkt && pkt->dts != AV_NOPTS_VALUE) { //FIXME seems redundant, as libavformat does this too
1045
        ist->next_pts = ist->pts = pkt->dts;
1046
    } else {
1047
        assert(ist->pts == ist->next_pts);
1048
    }
1049

    
1050
    if (pkt == NULL) {
1051
        /* EOF handling */
1052
        ptr = NULL;
1053
        len = 0;
1054
        goto handle_eof;
1055
    }
1056

    
1057
    len = pkt->size;
1058
    ptr = pkt->data;
1059
    while (len > 0) {
1060
    handle_eof:
1061
        /* decode the packet if needed */
1062
        data_buf = NULL; /* fail safe */
1063
        data_size = 0;
1064
        if (ist->decoding_needed) {
1065
            switch(ist->st->codec.codec_type) {
1066
            case CODEC_TYPE_AUDIO:
1067
                    /* XXX: could avoid copy if PCM 16 bits with same
1068
                       endianness as CPU */
1069
                ret = avcodec_decode_audio(&ist->st->codec, samples, &data_size,
1070
                                           ptr, len);
1071
                if (ret < 0)
1072
                    goto fail_decode;
1073
                ptr += ret;
1074
                len -= ret;
1075
                /* Some bug in mpeg audio decoder gives */
1076
                /* data_size < 0, it seems they are overflows */
1077
                if (data_size <= 0) {
1078
                    /* no audio frame */
1079
                    continue;
1080
                }
1081
                data_buf = (uint8_t *)samples;
1082
                ist->next_pts += ((int64_t)AV_TIME_BASE/2 * data_size) / 
1083
                    (ist->st->codec.sample_rate * ist->st->codec.channels);
1084
                break;
1085
            case CODEC_TYPE_VIDEO:
1086
                    data_size = (ist->st->codec.width * ist->st->codec.height * 3) / 2;
1087
                    /* XXX: allocate picture correctly */
1088
                    avcodec_get_frame_defaults(&picture);
1089

    
1090
                    ret = avcodec_decode_video(&ist->st->codec, 
1091
                                               &picture, &got_picture, ptr, len);
1092
                    ist->st->quality= picture.quality;
1093
                    if (ret < 0) 
1094
                        goto fail_decode;
1095
                    if (!got_picture) {
1096
                        /* no picture yet */
1097
                        goto discard_packet;
1098
                    }
1099
                    if (ist->st->codec.frame_rate_base != 0) {
1100
                        ist->next_pts += ((int64_t)AV_TIME_BASE * 
1101
                                          ist->st->codec.frame_rate_base) /
1102
                            ist->st->codec.frame_rate;
1103
                    }
1104
                    len = 0;
1105
                    break;
1106
                default:
1107
                    goto fail_decode;
1108
                }
1109
            } else {
1110
                data_buf = ptr;
1111
                data_size = len;
1112
                ret = len;
1113
                len = 0;
1114
            }
1115

    
1116
            buffer_to_free = NULL;
1117
            if (ist->st->codec.codec_type == CODEC_TYPE_VIDEO) {
1118
                pre_process_video_frame(ist, (AVPicture *)&picture, 
1119
                                        &buffer_to_free);
1120
            }
1121

    
1122
            /* frame rate emulation */
1123
            if (ist->st->codec.rate_emu) {
1124
                int64_t pts = av_rescale((int64_t) ist->frame * ist->st->codec.frame_rate_base, 1000000, ist->st->codec.frame_rate);
1125
                int64_t now = av_gettime() - ist->start;
1126
                if (pts > now)
1127
                    usleep(pts - now);
1128

    
1129
                ist->frame++;
1130
            }
1131

    
1132
#if 0
1133
            /* mpeg PTS deordering : if it is a P or I frame, the PTS
1134
               is the one of the next displayed one */
1135
            /* XXX: add mpeg4 too ? */
1136
            if (ist->st->codec.codec_id == CODEC_ID_MPEG1VIDEO) {
1137
                if (ist->st->codec.pict_type != B_TYPE) {
1138
                    int64_t tmp;
1139
                    tmp = ist->last_ip_pts;
1140
                    ist->last_ip_pts  = ist->frac_pts.val;
1141
                    ist->frac_pts.val = tmp;
1142
                }
1143
            }
1144
#endif
1145
            /* if output time reached then transcode raw format, 
1146
               encode packets and output them */
1147
            if (start_time == 0 || ist->pts >= start_time)
1148
                for(i=0;i<nb_ostreams;i++) {
1149
                    int frame_size;
1150

    
1151
                    ost = ost_table[i];
1152
                    if (ost->source_index == ist_index) {
1153
                        os = output_files[ost->file_index];
1154

    
1155
#if 0
1156
                        printf("%d: got pts=%0.3f %0.3f\n", i, 
1157
                               (double)pkt->pts / AV_TIME_BASE, 
1158
                               ((double)ist->pts / AV_TIME_BASE) - 
1159
                               ((double)ost->st->pts.val * ost->st->time_base.num / ost->st->time_base.den));
1160
#endif
1161
                        /* set the input output pts pairs */
1162
                        ost->sync_ipts = (double)(ist->pts + input_files_ts_offset[ist->file_index])/ AV_TIME_BASE;
1163

    
1164
                        if (ost->encoding_needed) {
1165
                            switch(ost->st->codec.codec_type) {
1166
                            case CODEC_TYPE_AUDIO:
1167
                                do_audio_out(os, ost, ist, data_buf, data_size);
1168
                                break;
1169
                            case CODEC_TYPE_VIDEO:
1170
                                /* find an audio stream for synchro */
1171
                                {
1172
                                    int i;
1173
                                    AVOutputStream *audio_sync, *ost1;
1174
                                    audio_sync = NULL;
1175
                                    for(i=0;i<nb_ostreams;i++) {
1176
                                        ost1 = ost_table[i];
1177
                                        if (ost1->file_index == ost->file_index &&
1178
                                            ost1->st->codec.codec_type == CODEC_TYPE_AUDIO) {
1179
                                            audio_sync = ost1;
1180
                                            break;
1181
                                        }
1182
                                    }
1183

    
1184
                                    do_video_out(os, ost, ist, &picture, &frame_size);
1185
                                    video_size += frame_size;
1186
                                    if (do_vstats && frame_size)
1187
                                        do_video_stats(os, ost, frame_size);
1188
                                }
1189
                                break;
1190
                            default:
1191
                                av_abort();
1192
                            }
1193
                        } else {
1194
                            AVFrame avframe; //FIXME/XXX remove this
1195
                            AVPacket opkt;
1196
                            av_init_packet(&opkt);
1197

    
1198
                            /* no reencoding needed : output the packet directly */
1199
                            /* force the input stream PTS */
1200
                        
1201
                            avcodec_get_frame_defaults(&avframe);
1202
                            ost->st->codec.coded_frame= &avframe;
1203
                            avframe.key_frame = pkt->flags & PKT_FLAG_KEY; 
1204

    
1205
                            if(ost->st->codec.codec_type == CODEC_TYPE_AUDIO)
1206
                                audio_size += data_size;
1207
                            else if (ost->st->codec.codec_type == CODEC_TYPE_VIDEO)
1208
                                video_size += data_size;
1209

    
1210
                            opkt.stream_index= ost->index;
1211
                            opkt.data= data_buf;
1212
                            opkt.size= data_size;
1213
                            opkt.pts= pkt->pts + input_files_ts_offset[ist->file_index];
1214
                            opkt.dts= pkt->dts + input_files_ts_offset[ist->file_index];
1215
                            opkt.flags= pkt->flags;
1216
                            
1217
                            av_interleaved_write_frame(os, &opkt);
1218
                            ost->st->codec.frame_number++;
1219
                            ost->frame_number++;
1220
                        }
1221
                    }
1222
                }
1223
            av_free(buffer_to_free);
1224
        }
1225
 discard_packet:
1226
    if (pkt == NULL) {
1227
        /* EOF handling */
1228
  
1229
        for(i=0;i<nb_ostreams;i++) {
1230
            ost = ost_table[i];
1231
            if (ost->source_index == ist_index) {
1232
                AVCodecContext *enc= &ost->st->codec;
1233
                os = output_files[ost->file_index];
1234
                
1235
                if(ost->st->codec.codec_type == CODEC_TYPE_AUDIO && enc->frame_size <=1)
1236
                    continue;
1237
                if(ost->st->codec.codec_type == CODEC_TYPE_VIDEO && (os->oformat->flags & AVFMT_RAWPICTURE))
1238
                    continue;
1239

    
1240
                if (ost->encoding_needed) {
1241
                    for(;;) {
1242
                        AVPacket pkt;
1243
                        av_init_packet(&pkt);
1244
                        pkt.stream_index= ost->index;
1245
 
1246
                        switch(ost->st->codec.codec_type) {
1247
                        case CODEC_TYPE_AUDIO:        
1248
                            ret = avcodec_encode_audio(enc, bit_buffer, VIDEO_BUFFER_SIZE, NULL);
1249
                            audio_size += ret;
1250
                            pkt.flags |= PKT_FLAG_KEY;
1251
                            break;
1252
                        case CODEC_TYPE_VIDEO:
1253
                            ret = avcodec_encode_video(enc, bit_buffer, VIDEO_BUFFER_SIZE, NULL);
1254
                            video_size += ret;
1255
                            if(enc->coded_frame && enc->coded_frame->key_frame)
1256
                                pkt.flags |= PKT_FLAG_KEY;
1257
                            if (ost->logfile && enc->stats_out) {
1258
                                fprintf(ost->logfile, "%s", enc->stats_out);
1259
                            }
1260
                            break;
1261
                        default:
1262
                            ret=-1;
1263
                        }
1264
                            
1265
                        if(ret<=0)
1266
                            break;
1267
                        pkt.data= bit_buffer;
1268
                        pkt.size= ret;
1269
                        if(enc->coded_frame)
1270
                            pkt.pts= enc->coded_frame->pts;
1271
                        av_interleaved_write_frame(os, &pkt);
1272
                    }
1273
                }
1274
            }
1275
        }
1276
    }
1277
 
1278
    return 0;
1279
 fail_decode:
1280
    return -1;
1281
}
1282

    
1283

    
1284
/*
1285
 * The following code is the main loop of the file converter
1286
 */
1287
static int av_encode(AVFormatContext **output_files,
1288
                     int nb_output_files,
1289
                     AVFormatContext **input_files,
1290
                     int nb_input_files,
1291
                     AVStreamMap *stream_maps, int nb_stream_maps)
1292
{
1293
    int ret, i, j, k, n, nb_istreams = 0, nb_ostreams = 0;
1294
    AVFormatContext *is, *os;
1295
    AVCodecContext *codec, *icodec;
1296
    AVOutputStream *ost, **ost_table = NULL;
1297
    AVInputStream *ist, **ist_table = NULL;
1298
    AVInputFile *file_table;
1299
    AVFormatContext *stream_no_data;
1300
    int key;
1301

    
1302
    file_table= (AVInputFile*) av_mallocz(nb_input_files * sizeof(AVInputFile));
1303
    if (!file_table)
1304
        goto fail;
1305

    
1306
    if (!bit_buffer)
1307
        bit_buffer = av_malloc(VIDEO_BUFFER_SIZE);
1308
    if (!bit_buffer)
1309
        goto fail;
1310
        
1311
    /* input stream init */
1312
    j = 0;
1313
    for(i=0;i<nb_input_files;i++) {
1314
        is = input_files[i];
1315
        file_table[i].ist_index = j;
1316
        file_table[i].nb_streams = is->nb_streams;
1317
        j += is->nb_streams;
1318
    }
1319
    nb_istreams = j;
1320

    
1321
    ist_table = av_mallocz(nb_istreams * sizeof(AVInputStream *));
1322
    if (!ist_table)
1323
        goto fail;
1324
    
1325
    for(i=0;i<nb_istreams;i++) {
1326
        ist = av_mallocz(sizeof(AVInputStream));
1327
        if (!ist)
1328
            goto fail;
1329
        ist_table[i] = ist;
1330
    }
1331
    j = 0;
1332
    for(i=0;i<nb_input_files;i++) {
1333
        is = input_files[i];
1334
        for(k=0;k<is->nb_streams;k++) {
1335
            ist = ist_table[j++];
1336
            ist->st = is->streams[k];
1337
            ist->file_index = i;
1338
            ist->index = k;
1339
            ist->discard = 1; /* the stream is discarded by default
1340
                                 (changed later) */
1341

    
1342
            if (ist->st->codec.rate_emu) {
1343
                ist->start = av_gettime();
1344
                ist->frame = 0;
1345
            }
1346
        }
1347
    }
1348

    
1349
    /* output stream init */
1350
    nb_ostreams = 0;
1351
    for(i=0;i<nb_output_files;i++) {
1352
        os = output_files[i];
1353
        nb_ostreams += os->nb_streams;
1354
    }
1355
    if (nb_stream_maps > 0 && nb_stream_maps != nb_ostreams) {
1356
        fprintf(stderr, "Number of stream maps must match number of output streams\n");
1357
        exit(1);
1358
    }
1359

    
1360
    /* Sanity check the mapping args -- do the input files & streams exist? */
1361
    for(i=0;i<nb_stream_maps;i++) {
1362
        int fi = stream_maps[i].file_index;
1363
        int si = stream_maps[i].stream_index;
1364
        
1365
        if (fi < 0 || fi > nb_input_files - 1 ||
1366
            si < 0 || si > file_table[fi].nb_streams - 1) {
1367
            fprintf(stderr,"Could not find input stream #%d.%d\n", fi, si);
1368
            exit(1);
1369
        }
1370
    }
1371
    
1372
    ost_table = av_mallocz(sizeof(AVOutputStream *) * nb_ostreams);
1373
    if (!ost_table)
1374
        goto fail;
1375
    for(i=0;i<nb_ostreams;i++) {
1376
        ost = av_mallocz(sizeof(AVOutputStream));
1377
        if (!ost)
1378
            goto fail;
1379
        ost_table[i] = ost;
1380
    }
1381
    
1382
    n = 0;
1383
    for(k=0;k<nb_output_files;k++) {
1384
        os = output_files[k];
1385
        for(i=0;i<os->nb_streams;i++) {
1386
            int found;
1387
            ost = ost_table[n++];
1388
            ost->file_index = k;
1389
            ost->index = i;
1390
            ost->st = os->streams[i];
1391
            if (nb_stream_maps > 0) {
1392
                ost->source_index = file_table[stream_maps[n-1].file_index].ist_index + 
1393
                    stream_maps[n-1].stream_index;
1394
                    
1395
                /* Sanity check that the stream types match */
1396
                if (ist_table[ost->source_index]->st->codec.codec_type != ost->st->codec.codec_type) {
1397
                    fprintf(stderr, "Codec type mismatch for mapping #%d.%d -> #%d.%d\n",
1398
                        stream_maps[n-1].file_index, stream_maps[n-1].stream_index,
1399
                        ost->file_index, ost->index);
1400
                    exit(1);
1401
                }
1402
                
1403
            } else {
1404
                /* get corresponding input stream index : we select the first one with the right type */
1405
                found = 0;
1406
                for(j=0;j<nb_istreams;j++) {
1407
                    ist = ist_table[j];
1408
                    if (ist->discard && 
1409
                        ist->st->codec.codec_type == ost->st->codec.codec_type) {
1410
                        ost->source_index = j;
1411
                        found = 1;
1412
                    }
1413
                }
1414
                
1415
                if (!found) {
1416
                    /* try again and reuse existing stream */
1417
                    for(j=0;j<nb_istreams;j++) {
1418
                        ist = ist_table[j];
1419
                        if (ist->st->codec.codec_type == ost->st->codec.codec_type) {
1420
                            ost->source_index = j;
1421
                            found = 1;
1422
                        }
1423
                    }
1424
                    if (!found) {
1425
                        fprintf(stderr, "Could not find input stream matching output stream #%d.%d\n",
1426
                                ost->file_index, ost->index);
1427
                        exit(1);
1428
                    }
1429
                }
1430
            }
1431
            ist = ist_table[ost->source_index];
1432
            ist->discard = 0;
1433
        }
1434
    }
1435

    
1436
    /* for each output stream, we compute the right encoding parameters */
1437
    for(i=0;i<nb_ostreams;i++) {
1438
        ost = ost_table[i];
1439
        ist = ist_table[ost->source_index];
1440

    
1441
        codec = &ost->st->codec;
1442
        icodec = &ist->st->codec;
1443

    
1444
        if (ost->st->stream_copy) {
1445
            /* if stream_copy is selected, no need to decode or encode */
1446
            codec->codec_id = icodec->codec_id;
1447
            codec->codec_type = icodec->codec_type;
1448
            codec->codec_tag = icodec->codec_tag;
1449
            codec->bit_rate = icodec->bit_rate;
1450
            switch(codec->codec_type) {
1451
            case CODEC_TYPE_AUDIO:
1452
                codec->sample_rate = icodec->sample_rate;
1453
                codec->channels = icodec->channels;
1454
                codec->frame_size = icodec->frame_size;
1455
                break;
1456
            case CODEC_TYPE_VIDEO:
1457
                codec->frame_rate = icodec->frame_rate;
1458
                codec->frame_rate_base = icodec->frame_rate_base;
1459
                codec->width = icodec->width;
1460
                codec->height = icodec->height;
1461
                break;
1462
            default:
1463
                av_abort();
1464
            }
1465
        } else {
1466
            switch(codec->codec_type) {
1467
            case CODEC_TYPE_AUDIO:
1468
                if (fifo_init(&ost->fifo, 2 * MAX_AUDIO_PACKET_SIZE))
1469
                    goto fail;
1470
                
1471
                if (codec->channels == icodec->channels &&
1472
                    codec->sample_rate == icodec->sample_rate) {
1473
                    ost->audio_resample = 0;
1474
                } else {
1475
                    if (codec->channels != icodec->channels &&
1476
                        icodec->codec_id == CODEC_ID_AC3) {
1477
                        /* Special case for 5:1 AC3 input */
1478
                        /* and mono or stereo output      */
1479
                        /* Request specific number of channels */
1480
                        icodec->channels = codec->channels;
1481
                        if (codec->sample_rate == icodec->sample_rate)
1482
                            ost->audio_resample = 0;
1483
                        else {
1484
                            ost->audio_resample = 1;
1485
                        }
1486
                    } else {
1487
                        ost->audio_resample = 1; 
1488
                    }
1489
                }
1490
                if(audio_sync_method)
1491
                    ost->audio_resample = 1;
1492

    
1493
                if(ost->audio_resample){
1494
                    ost->resample = audio_resample_init(codec->channels, icodec->channels,
1495
                                                    codec->sample_rate, icodec->sample_rate);
1496
                    if(!ost->resample){
1497
                        printf("Can't resample.  Aborting.\n");
1498
                        av_abort();
1499
                    }
1500
                }
1501
                ist->decoding_needed = 1;
1502
                ost->encoding_needed = 1;
1503
                break;
1504
            case CODEC_TYPE_VIDEO:
1505
                if (codec->width == icodec->width &&
1506
                    codec->height == icodec->height &&
1507
                    frame_topBand == 0 &&
1508
                    frame_bottomBand == 0 &&
1509
                    frame_leftBand == 0 &&
1510
                    frame_rightBand == 0 && 
1511
                    frame_padtop == 0 &&
1512
                    frame_padbottom == 0 &&
1513
                    frame_padleft == 0 &&
1514
                    frame_padright == 0)
1515
                {
1516
                    ost->video_resample = 0;
1517
                    ost->video_crop = 0;
1518
                    ost->video_pad = 0;
1519
                } else if ((codec->width == icodec->width -
1520
                                (frame_leftBand + frame_rightBand)) &&
1521
                        (codec->height == icodec->height -
1522
                                (frame_topBand  + frame_bottomBand)))
1523
                {
1524
                    ost->video_resample = 0;
1525
                    ost->video_crop = 1;
1526
                    ost->topBand = frame_topBand;
1527
                    ost->leftBand = frame_leftBand;
1528
                } else if ((codec->width == icodec->width + 
1529
                                (frame_padleft + frame_padright)) &&
1530
                        (codec->height == icodec->height +
1531
                                (frame_padtop + frame_padbottom))) {
1532
                    ost->video_resample = 0;
1533
                    ost->video_crop = 0;
1534
                    ost->video_pad = 1;
1535
                    ost->padtop = frame_padtop;
1536
                    ost->padleft = frame_padleft;
1537
                    ost->padbottom = frame_padbottom;
1538
                    ost->padright = frame_padright;
1539
                    avcodec_get_frame_defaults(&ost->pict_tmp);
1540
                    if( avpicture_alloc( (AVPicture*)&ost->pict_tmp, PIX_FMT_YUV420P,
1541
                                codec->width, codec->height ) )
1542
                        goto fail;
1543
                } else {
1544
                    ost->video_resample = 1;
1545
                    ost->video_crop = 0; // cropping is handled as part of resample
1546
                    avcodec_get_frame_defaults(&ost->pict_tmp);
1547
                    if( avpicture_alloc( (AVPicture*)&ost->pict_tmp, PIX_FMT_YUV420P,
1548
                                         codec->width, codec->height ) )
1549
                        goto fail;
1550

    
1551
                    ost->img_resample_ctx = img_resample_full_init( 
1552
                                      ost->st->codec.width, ost->st->codec.height,
1553
                                      ist->st->codec.width, ist->st->codec.height,
1554
                                      frame_topBand, frame_bottomBand,
1555
                            frame_leftBand, frame_rightBand, 
1556
                            frame_padtop, frame_padbottom, 
1557
                            frame_padleft, frame_padright);
1558
                    
1559
                    ost->padtop = frame_padtop;
1560
                    ost->padleft = frame_padleft;
1561
                    ost->padbottom = frame_padbottom;
1562
                    ost->padright = frame_padright;
1563
                   
1564
                }
1565
                ost->encoding_needed = 1;
1566
                ist->decoding_needed = 1;
1567
                break;
1568
            default:
1569
                av_abort();
1570
            }
1571
            /* two pass mode */
1572
            if (ost->encoding_needed && 
1573
                (codec->flags & (CODEC_FLAG_PASS1 | CODEC_FLAG_PASS2))) {
1574
                char logfilename[1024];
1575
                FILE *f;
1576
                int size;
1577
                char *logbuffer;
1578
                
1579
                snprintf(logfilename, sizeof(logfilename), "%s-%d.log", 
1580
                         pass_logfilename ? 
1581
                         pass_logfilename : DEFAULT_PASS_LOGFILENAME, i);
1582
                if (codec->flags & CODEC_FLAG_PASS1) {
1583
                    f = fopen(logfilename, "w");
1584
                    if (!f) {
1585
                        perror(logfilename);
1586
                        exit(1);
1587
                    }
1588
                    ost->logfile = f;
1589
                } else {
1590
                    /* read the log file */
1591
                    f = fopen(logfilename, "r");
1592
                    if (!f) {
1593
                        perror(logfilename);
1594
                        exit(1);
1595
                    }
1596
                    fseek(f, 0, SEEK_END);
1597
                    size = ftell(f);
1598
                    fseek(f, 0, SEEK_SET);
1599
                    logbuffer = av_malloc(size + 1);
1600
                    if (!logbuffer) {
1601
                        fprintf(stderr, "Could not allocate log buffer\n");
1602
                        exit(1);
1603
                    }
1604
                    size = fread(logbuffer, 1, size, f);
1605
                    fclose(f);
1606
                    logbuffer[size] = '\0';
1607
                    codec->stats_in = logbuffer;
1608
                }
1609
            }
1610
        }
1611
    }
1612

    
1613
    /* dump the file output parameters - cannot be done before in case
1614
       of stream copy */
1615
    for(i=0;i<nb_output_files;i++) {
1616
        dump_format(output_files[i], i, output_files[i]->filename, 1);
1617
    }
1618

    
1619
    /* dump the stream mapping */
1620
    if (verbose >= 0) {
1621
        fprintf(stderr, "Stream mapping:\n");
1622
        for(i=0;i<nb_ostreams;i++) {
1623
            ost = ost_table[i];
1624
            fprintf(stderr, "  Stream #%d.%d -> #%d.%d\n",
1625
                    ist_table[ost->source_index]->file_index,
1626
                    ist_table[ost->source_index]->index,
1627
                    ost->file_index, 
1628
                    ost->index);
1629
        }
1630
    }
1631

    
1632
    /* open each encoder */
1633
    for(i=0;i<nb_ostreams;i++) {
1634
        ost = ost_table[i];
1635
        if (ost->encoding_needed) {
1636
            AVCodec *codec;
1637
            codec = avcodec_find_encoder(ost->st->codec.codec_id);
1638
            if (!codec) {
1639
                fprintf(stderr, "Unsupported codec for output stream #%d.%d\n", 
1640
                        ost->file_index, ost->index);
1641
                exit(1);
1642
            }
1643
            if (avcodec_open(&ost->st->codec, codec) < 0) {
1644
                fprintf(stderr, "Error while opening codec for stream #%d.%d - maybe incorrect parameters such as bit_rate, rate, width or height\n", 
1645
                        ost->file_index, ost->index);
1646
                exit(1);
1647
            }
1648
            extra_size += ost->st->codec.extradata_size;
1649
        }
1650
    }
1651

    
1652
    /* open each decoder */
1653
    for(i=0;i<nb_istreams;i++) {
1654
        ist = ist_table[i];
1655
        if (ist->decoding_needed) {
1656
            AVCodec *codec;
1657
            codec = avcodec_find_decoder(ist->st->codec.codec_id);
1658
            if (!codec) {
1659
                fprintf(stderr, "Unsupported codec (id=%d) for input stream #%d.%d\n", 
1660
                        ist->st->codec.codec_id, ist->file_index, ist->index);
1661
                exit(1);
1662
            }
1663
            if (avcodec_open(&ist->st->codec, codec) < 0) {
1664
                fprintf(stderr, "Error while opening codec for input stream #%d.%d\n", 
1665
                        ist->file_index, ist->index);
1666
                exit(1);
1667
            }
1668
            //if (ist->st->codec.codec_type == CODEC_TYPE_VIDEO)
1669
            //    ist->st->codec.flags |= CODEC_FLAG_REPEAT_FIELD;
1670
        }
1671
    }
1672

    
1673
    /* init pts */
1674
    for(i=0;i<nb_istreams;i++) {
1675
        ist = ist_table[i];
1676
        is = input_files[ist->file_index];
1677
        ist->pts = 0;
1678
        ist->next_pts = 0;
1679
    }
1680
    
1681
    /* compute buffer size max (should use a complete heuristic) */
1682
    for(i=0;i<nb_input_files;i++) {
1683
        file_table[i].buffer_size_max = 2048;
1684
    }
1685

    
1686
    /* open files and write file headers */
1687
    for(i=0;i<nb_output_files;i++) {
1688
        os = output_files[i];
1689
        if (av_write_header(os) < 0) {
1690
            fprintf(stderr, "Could not write header for output file #%d (incorrect codec paramters ?)\n", i);
1691
            ret = -EINVAL;
1692
            goto fail;
1693
        }
1694
    }
1695

    
1696
#ifndef CONFIG_WIN32
1697
    if ( !using_stdin && verbose >= 0) {
1698
        fprintf(stderr, "Press [q] to stop encoding\n");
1699
        url_set_interrupt_cb(decode_interrupt_cb);
1700
    }
1701
#endif
1702
    term_init();
1703

    
1704
    stream_no_data = 0;
1705
    key = -1;
1706

    
1707
    for(; received_sigterm == 0;) {
1708
        int file_index, ist_index;
1709
        AVPacket pkt;
1710
        double ipts_min= 1e100;
1711
        double opts_min= 1e100;
1712

    
1713
    redo:
1714
        /* if 'q' pressed, exits */
1715
        if (!using_stdin) {
1716
            if (q_pressed)
1717
                break;
1718
            /* read_key() returns 0 on EOF */
1719
            key = read_key();
1720
            if (key == 'q')
1721
                break;
1722
        }
1723

    
1724
        /* select the stream that we must read now by looking at the
1725
           smallest output pts */
1726
        file_index = -1;
1727
        for(i=0;i<nb_ostreams;i++) {
1728
            double ipts, opts;
1729
            ost = ost_table[i];
1730
            os = output_files[ost->file_index];
1731
            ist = ist_table[ost->source_index];
1732
            if(ost->st->codec.codec_type == CODEC_TYPE_VIDEO)
1733
                opts = (double)ost->sync_opts * ost->st->codec.frame_rate_base / ost->st->codec.frame_rate;
1734
            else
1735
                opts = (double)ost->st->pts.val * ost->st->time_base.num / ost->st->time_base.den;
1736
            ipts = (double)ist->pts;
1737
            if (!file_table[ist->file_index].eof_reached){
1738
                if(ipts < ipts_min) {
1739
                    ipts_min = ipts;
1740
                    if(input_sync ) file_index = ist->file_index;
1741
                }
1742
                if(opts < opts_min) {
1743
                    opts_min = opts;
1744
                    if(!input_sync) file_index = ist->file_index;
1745
                }
1746
            }
1747
        }
1748
        /* if none, if is finished */
1749
        if (file_index < 0) {
1750
            break;
1751
        }
1752

    
1753
        /* finish if recording time exhausted */
1754
        if (recording_time > 0 && opts_min >= (recording_time / 1000000.0))
1755
            break;
1756

    
1757
        /* read a frame from it and output it in the fifo */
1758
        is = input_files[file_index];
1759
        if (av_read_frame(is, &pkt) < 0) {
1760
            file_table[file_index].eof_reached = 1;
1761
            continue;
1762
        }
1763

    
1764
        if (!pkt.size) {
1765
            stream_no_data = is;
1766
        } else {
1767
            stream_no_data = 0;
1768
        }
1769
        if (do_pkt_dump) {
1770
            av_pkt_dump(stdout, &pkt, do_hex_dump);
1771
        }
1772
        /* the following test is needed in case new streams appear
1773
           dynamically in stream : we ignore them */
1774
        if (pkt.stream_index >= file_table[file_index].nb_streams)
1775
            goto discard_packet;
1776
        ist_index = file_table[file_index].ist_index + pkt.stream_index;
1777
        ist = ist_table[ist_index];
1778
        if (ist->discard)
1779
            goto discard_packet;
1780

    
1781
//        fprintf(stderr, "next:%lld dts:%lld off:%lld %d\n", ist->next_pts, pkt.dts, input_files_ts_offset[ist->file_index], ist->st->codec.codec_type);
1782
        if (pkt.dts != AV_NOPTS_VALUE) {
1783
            int64_t delta= pkt.dts - ist->next_pts;
1784
            if(ABS(delta) > 10LL*AV_TIME_BASE && !copy_ts){
1785
                input_files_ts_offset[ist->file_index]-= delta;
1786
                if (verbose > 2)
1787
                    fprintf(stderr, "timestamp discontinuity %lld, new offset= %lld\n", delta, input_files_ts_offset[ist->file_index]);
1788
                for(i=0; i<file_table[file_index].nb_streams; i++){
1789
                    int index= file_table[file_index].ist_index + i;
1790
                    ist_table[index]->next_pts += delta;
1791
                }
1792
            }
1793
        }
1794

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

    
1798
            if (verbose >= 0)
1799
                fprintf(stderr, "Error while decoding stream #%d.%d\n",
1800
                        ist->file_index, ist->index);
1801

    
1802
            av_free_packet(&pkt);
1803
            goto redo;
1804
        }
1805
        
1806
    discard_packet:
1807
        av_free_packet(&pkt);
1808
        
1809
        /* dump report by using the output first video and audio streams */
1810
        print_report(output_files, ost_table, nb_ostreams, 0);
1811
    }
1812

    
1813
    /* at the end of stream, we must flush the decoder buffers */
1814
    for(i=0;i<nb_istreams;i++) {
1815
        ist = ist_table[i];
1816
        if (ist->decoding_needed) {
1817
            output_packet(ist, i, ost_table, nb_ostreams, NULL);
1818
        }
1819
    }
1820

    
1821
    term_exit();
1822

    
1823
    /* write the trailer if needed and close file */
1824
    for(i=0;i<nb_output_files;i++) {
1825
        os = output_files[i];
1826
        av_write_trailer(os);
1827
    }
1828

    
1829
    /* dump report by using the first video and audio streams */
1830
    print_report(output_files, ost_table, nb_ostreams, 1);
1831

    
1832
    /* close each encoder */
1833
    for(i=0;i<nb_ostreams;i++) {
1834
        ost = ost_table[i];
1835
        if (ost->encoding_needed) {
1836
            av_freep(&ost->st->codec.stats_in);
1837
            avcodec_close(&ost->st->codec);
1838
        }
1839
    }
1840
    
1841
    /* close each decoder */
1842
    for(i=0;i<nb_istreams;i++) {
1843
        ist = ist_table[i];
1844
        if (ist->decoding_needed) {
1845
            avcodec_close(&ist->st->codec);
1846
        }
1847
    }
1848

    
1849
    /* finished ! */
1850
    
1851
    ret = 0;
1852
 fail1:
1853
    av_free(file_table);
1854

    
1855
    if (ist_table) {
1856
        for(i=0;i<nb_istreams;i++) {
1857
            ist = ist_table[i];
1858
            av_free(ist);
1859
        }
1860
        av_free(ist_table);
1861
    }
1862
    if (ost_table) {
1863
        for(i=0;i<nb_ostreams;i++) {
1864
            ost = ost_table[i];
1865
            if (ost) {
1866
                if (ost->logfile) {
1867
                    fclose(ost->logfile);
1868
                    ost->logfile = NULL;
1869
                }
1870
                fifo_free(&ost->fifo); /* works even if fifo is not
1871
                                          initialized but set to zero */
1872
                av_free(ost->pict_tmp.data[0]);
1873
                if (ost->video_resample)
1874
                    img_resample_close(ost->img_resample_ctx);
1875
                if (ost->audio_resample)
1876
                    audio_resample_close(ost->resample);
1877
                av_free(ost);
1878
            }
1879
        }
1880
        av_free(ost_table);
1881
    }
1882
    return ret;
1883
 fail:
1884
    ret = -ENOMEM;
1885
    goto fail1;
1886
}
1887

    
1888
#if 0
1889
int file_read(const char *filename)
1890
{
1891
    URLContext *h;
1892
    unsigned char buffer[1024];
1893
    int len, i;
1894

1895
    if (url_open(&h, filename, O_RDONLY) < 0) {
1896
        printf("could not open '%s'\n", filename);
1897
        return -1;
1898
    }
1899
    for(;;) {
1900
        len = url_read(h, buffer, sizeof(buffer));
1901
        if (len <= 0)
1902
            break;
1903
        for(i=0;i<len;i++) putchar(buffer[i]);
1904
    }
1905
    url_close(h);
1906
    return 0;
1907
}
1908
#endif
1909

    
1910
static void opt_image_format(const char *arg)
1911
{
1912
    AVImageFormat *f;
1913
    
1914
    for(f = first_image_format; f != NULL; f = f->next) {
1915
        if (!strcmp(arg, f->name))
1916
            break;
1917
    }
1918
    if (!f) {
1919
        fprintf(stderr, "Unknown image format: '%s'\n", arg);
1920
        exit(1);
1921
    }
1922
    image_format = f;
1923
}
1924

    
1925
static void opt_format(const char *arg)
1926
{
1927
    /* compatibility stuff for pgmyuv */
1928
    if (!strcmp(arg, "pgmyuv")) {
1929
        opt_image_format(arg);
1930
        arg = "image";
1931
    }
1932

    
1933
    file_iformat = av_find_input_format(arg);
1934
    file_oformat = guess_format(arg, NULL, NULL);
1935
    if (!file_iformat && !file_oformat) {
1936
        fprintf(stderr, "Unknown input or output format: %s\n", arg);
1937
        exit(1);
1938
    }
1939
}
1940

    
1941
static void opt_video_bitrate(const char *arg)
1942
{
1943
    video_bit_rate = atoi(arg) * 1000;
1944
}
1945

    
1946
static void opt_video_bitrate_tolerance(const char *arg)
1947
{
1948
    video_bit_rate_tolerance = atoi(arg) * 1000;
1949
}
1950

    
1951
static void opt_video_bitrate_max(const char *arg)
1952
{
1953
    video_rc_max_rate = atoi(arg) * 1000;
1954
}
1955

    
1956
static void opt_video_bitrate_min(const char *arg)
1957
{
1958
    video_rc_min_rate = atoi(arg) * 1000;
1959
}
1960

    
1961
static void opt_video_buffer_size(const char *arg)
1962
{
1963
    video_rc_buffer_size = atoi(arg) * 8*1024;
1964
}
1965

    
1966
static void opt_video_rc_eq(char *arg)
1967
{
1968
    video_rc_eq = arg;
1969
}
1970

    
1971
static void opt_video_rc_override_string(char *arg)
1972
{
1973
    video_rc_override_string = arg;
1974
}
1975

    
1976

    
1977
static void opt_workaround_bugs(const char *arg)
1978
{
1979
    workaround_bugs = atoi(arg);
1980
}
1981

    
1982
static void opt_dct_algo(const char *arg)
1983
{
1984
    dct_algo = atoi(arg);
1985
}
1986

    
1987
static void opt_idct_algo(const char *arg)
1988
{
1989
    idct_algo = atoi(arg);
1990
}
1991

    
1992
static void opt_me_threshold(const char *arg)
1993
{
1994
    me_threshold = atoi(arg);
1995
}
1996

    
1997
static void opt_mb_threshold(const char *arg)
1998
{
1999
    mb_threshold = atoi(arg);
2000
}
2001

    
2002
static void opt_error_resilience(const char *arg)
2003
{
2004
    error_resilience = atoi(arg);
2005
}
2006

    
2007
static void opt_error_concealment(const char *arg)
2008
{
2009
    error_concealment = atoi(arg);
2010
}
2011

    
2012
static void opt_debug(const char *arg)
2013
{
2014
    debug = atoi(arg);
2015
}
2016

    
2017
static void opt_vismv(const char *arg)
2018
{
2019
    debug_mv = atoi(arg);
2020
}
2021
    
2022
static void opt_verbose(const char *arg)
2023
{
2024
    verbose = atoi(arg);
2025
    av_log_set_level(atoi(arg));
2026
}
2027

    
2028
static void opt_frame_rate(const char *arg)
2029
{
2030
    if (parse_frame_rate(&frame_rate, &frame_rate_base, arg) < 0) {
2031
        fprintf(stderr, "Incorrect frame rate\n");
2032
        exit(1);
2033
    }
2034
}
2035

    
2036
static void opt_frame_crop_top(const char *arg)
2037
{
2038
    frame_topBand = atoi(arg); 
2039
    if (frame_topBand < 0) {
2040
        fprintf(stderr, "Incorrect top crop size\n");
2041
        exit(1);
2042
    }
2043
    if ((frame_topBand % 2) != 0) {
2044
        fprintf(stderr, "Top crop size must be a multiple of 2\n");
2045
        exit(1);
2046
    }
2047
    if ((frame_topBand) >= frame_height){
2048
            fprintf(stderr, "Vertical crop dimensions are outside the range of the original image.\nRemember to crop first and scale second.\n");
2049
        exit(1);
2050
    }
2051
    frame_height -= frame_topBand;
2052
}
2053

    
2054
static void opt_frame_crop_bottom(const char *arg)
2055
{
2056
    frame_bottomBand = atoi(arg);
2057
    if (frame_bottomBand < 0) {
2058
        fprintf(stderr, "Incorrect bottom crop size\n");
2059
        exit(1);
2060
    }
2061
    if ((frame_bottomBand % 2) != 0) {
2062
        fprintf(stderr, "Bottom crop size must be a multiple of 2\n");
2063
        exit(1);        
2064
    }
2065
    if ((frame_bottomBand) >= frame_height){
2066
            fprintf(stderr, "Vertical crop dimensions are outside the range of the original image.\nRemember to crop first and scale second.\n");
2067
        exit(1);
2068
    }
2069
    frame_height -= frame_bottomBand;
2070
}
2071

    
2072
static void opt_frame_crop_left(const char *arg)
2073
{
2074
    frame_leftBand = atoi(arg);
2075
    if (frame_leftBand < 0) {
2076
        fprintf(stderr, "Incorrect left crop size\n");
2077
        exit(1);
2078
    }
2079
    if ((frame_leftBand % 2) != 0) {
2080
        fprintf(stderr, "Left crop size must be a multiple of 2\n");
2081
        exit(1);
2082
    }
2083
    if ((frame_leftBand) >= frame_width){
2084
            fprintf(stderr, "Horizontal crop dimensions are outside the range of the original image.\nRemember to crop first and scale second.\n");
2085
        exit(1);
2086
    }
2087
    frame_width -= frame_leftBand;
2088
}
2089

    
2090
static void opt_frame_crop_right(const char *arg)
2091
{
2092
    frame_rightBand = atoi(arg);
2093
    if (frame_rightBand < 0) {
2094
        fprintf(stderr, "Incorrect right crop size\n");
2095
        exit(1);
2096
    }
2097
    if ((frame_rightBand % 2) != 0) {
2098
        fprintf(stderr, "Right crop size must be a multiple of 2\n");
2099
        exit(1);        
2100
    }
2101
    if ((frame_rightBand) >= frame_width){
2102
            fprintf(stderr, "Horizontal crop dimensions are outside the range of the original image.\nRemember to crop first and scale second.\n");
2103
        exit(1);
2104
    }
2105
    frame_width -= frame_rightBand;
2106
}
2107

    
2108
static void opt_frame_size(const char *arg)
2109
{
2110
    if (parse_image_size(&frame_width, &frame_height, arg) < 0) {
2111
        fprintf(stderr, "Incorrect frame size\n");
2112
        exit(1);
2113
    }
2114
    if ((frame_width % 2) != 0 || (frame_height % 2) != 0) {
2115
        fprintf(stderr, "Frame size must be a multiple of 2\n");
2116
        exit(1);
2117
    }
2118
}
2119

    
2120

    
2121
#define SCALEBITS 10
2122
#define ONE_HALF  (1 << (SCALEBITS - 1))
2123
#define FIX(x)          ((int) ((x) * (1<<SCALEBITS) + 0.5))
2124

    
2125
#define RGB_TO_Y(r, g, b) \
2126
((FIX(0.29900) * (r) + FIX(0.58700) * (g) + \
2127
  FIX(0.11400) * (b) + ONE_HALF) >> SCALEBITS)
2128

    
2129
#define RGB_TO_U(r1, g1, b1, shift)\
2130
(((- FIX(0.16874) * r1 - FIX(0.33126) * g1 +         \
2131
     FIX(0.50000) * b1 + (ONE_HALF << shift) - 1) >> (SCALEBITS + shift)) + 128)
2132

    
2133
#define RGB_TO_V(r1, g1, b1, shift)\
2134
(((FIX(0.50000) * r1 - FIX(0.41869) * g1 -           \
2135
   FIX(0.08131) * b1 + (ONE_HALF << shift) - 1) >> (SCALEBITS + shift)) + 128)
2136

    
2137
static void opt_pad_color(const char *arg) {
2138
    /* Input is expected to be six hex digits similar to
2139
       how colors are expressed in html tags (but without the #) */
2140
    int rgb = strtol(arg, NULL, 16);
2141
    int r,g,b;
2142
    
2143
    r = (rgb >> 16); 
2144
    g = ((rgb >> 8) & 255);
2145
    b = (rgb & 255);
2146

    
2147
    padcolor[0] = RGB_TO_Y(r,g,b);
2148
    padcolor[1] = RGB_TO_U(r,g,b,0);
2149
    padcolor[2] = RGB_TO_V(r,g,b,0);
2150
}
2151

    
2152
static void opt_frame_pad_top(const char *arg)
2153
{
2154
    frame_padtop = atoi(arg); 
2155
    if (frame_padtop < 0) {
2156
        fprintf(stderr, "Incorrect top pad size\n");
2157
        exit(1);
2158
    }
2159
    if ((frame_padtop % 2) != 0) {
2160
        fprintf(stderr, "Top pad size must be a multiple of 2\n");
2161
        exit(1);
2162
    }
2163
}
2164

    
2165
static void opt_frame_pad_bottom(const char *arg)
2166
{
2167
    frame_padbottom = atoi(arg); 
2168
    if (frame_padbottom < 0) {
2169
        fprintf(stderr, "Incorrect bottom pad size\n");
2170
        exit(1);
2171
    }
2172
    if ((frame_padbottom % 2) != 0) {
2173
        fprintf(stderr, "Bottom pad size must be a multiple of 2\n");
2174
        exit(1);
2175
    }
2176
}
2177

    
2178

    
2179
static void opt_frame_pad_left(const char *arg)
2180
{
2181
    frame_padleft = atoi(arg); 
2182
    if (frame_padleft < 0) {
2183
        fprintf(stderr, "Incorrect left pad size\n");
2184
        exit(1);
2185
    }
2186
    if ((frame_padleft % 2) != 0) {
2187
        fprintf(stderr, "Left pad size must be a multiple of 2\n");
2188
        exit(1);
2189
    }
2190
}
2191

    
2192

    
2193
static void opt_frame_pad_right(const char *arg)
2194
{
2195
    frame_padright = atoi(arg); 
2196
    if (frame_padright < 0) {
2197
        fprintf(stderr, "Incorrect right pad size\n");
2198
        exit(1);
2199
    }
2200
    if ((frame_padright % 2) != 0) {
2201
        fprintf(stderr, "Right pad size must be a multiple of 2\n");
2202
        exit(1);
2203
    }
2204
}
2205

    
2206

    
2207
static void opt_frame_pix_fmt(const char *arg)
2208
{
2209
    frame_pix_fmt = avcodec_get_pix_fmt(arg);
2210
}
2211

    
2212
static void opt_frame_aspect_ratio(const char *arg)
2213
{
2214
    int x = 0, y = 0;
2215
    double ar = 0;
2216
    const char *p;
2217
    
2218
    p = strchr(arg, ':');
2219
    if (p) {
2220
        x = strtol(arg, (char **)&arg, 10);
2221
        if (arg == p)
2222
            y = strtol(arg+1, (char **)&arg, 10);
2223
        if (x > 0 && y > 0)
2224
            ar = (double)x / (double)y;
2225
    } else
2226
        ar = strtod(arg, (char **)&arg);
2227

    
2228
    if (!ar) {
2229
        fprintf(stderr, "Incorrect aspect ratio specification.\n");
2230
        exit(1);
2231
    }
2232
    frame_aspect_ratio = ar;
2233
}
2234

    
2235
static void opt_gop_size(const char *arg)
2236
{
2237
    gop_size = atoi(arg);
2238
}
2239

    
2240
static void opt_b_frames(const char *arg)
2241
{
2242
    b_frames = atoi(arg);
2243
    if (b_frames > FF_MAX_B_FRAMES) {
2244
        fprintf(stderr, "\nCannot have more than %d B frames, increase FF_MAX_B_FRAMES.\n", FF_MAX_B_FRAMES);
2245
        exit(1);
2246
    } else if (b_frames < 1) {
2247
        fprintf(stderr, "\nNumber of B frames must be higher than 0\n");
2248
        exit(1);
2249
    }
2250
}
2251

    
2252
static void opt_mb_decision(const char *arg)
2253
{
2254
    mb_decision = atoi(arg);
2255
}
2256

    
2257
static void opt_mb_cmp(const char *arg)
2258
{
2259
    mb_cmp = atoi(arg);
2260
}
2261

    
2262
static void opt_ildct_cmp(const char *arg)
2263
{
2264
    ildct_cmp = atoi(arg);
2265
}
2266

    
2267
static void opt_sub_cmp(const char *arg)
2268
{
2269
    sub_cmp = atoi(arg);
2270
}
2271

    
2272
static void opt_cmp(const char *arg)
2273
{
2274
    cmp = atoi(arg);
2275
}
2276

    
2277
static void opt_pre_cmp(const char *arg)
2278
{
2279
    pre_cmp = atoi(arg);
2280
}
2281

    
2282
static void opt_pre_me(const char *arg)
2283
{
2284
    pre_me = atoi(arg);
2285
}
2286

    
2287
static void opt_lumi_mask(const char *arg)
2288
{
2289
    lumi_mask = atof(arg);
2290
}
2291

    
2292
static void opt_dark_mask(const char *arg)
2293
{
2294
    dark_mask = atof(arg);
2295
}
2296

    
2297
static void opt_scplx_mask(const char *arg)
2298
{
2299
    scplx_mask = atof(arg);
2300
}
2301

    
2302
static void opt_tcplx_mask(const char *arg)
2303
{
2304
    tcplx_mask = atof(arg);
2305
}
2306

    
2307
static void opt_p_mask(const char *arg)
2308
{
2309
    p_mask = atof(arg);
2310
}
2311

    
2312
static void opt_qscale(const char *arg)
2313
{
2314
    video_qscale = atof(arg);
2315
    if (video_qscale < 0.01 ||
2316
        video_qscale > 255) {
2317
        fprintf(stderr, "qscale must be >= 0.01 and <= 255\n");
2318
        exit(1);
2319
    }
2320
}
2321

    
2322
static void opt_lmax(const char *arg)
2323
{
2324
    video_lmax = atof(arg)*FF_QP2LAMBDA;
2325
}
2326

    
2327
static void opt_lmin(const char *arg)
2328
{
2329
    video_lmin = atof(arg)*FF_QP2LAMBDA;
2330
}
2331

    
2332
static void opt_qmin(const char *arg)
2333
{
2334
    video_qmin = atoi(arg);
2335
    if (video_qmin < 0 ||
2336
        video_qmin > 31) {
2337
        fprintf(stderr, "qmin must be >= 1 and <= 31\n");
2338
        exit(1);
2339
    }
2340
}
2341

    
2342
static void opt_qmax(const char *arg)
2343
{
2344
    video_qmax = atoi(arg);
2345
    if (video_qmax < 0 ||
2346
        video_qmax > 31) {
2347
        fprintf(stderr, "qmax must be >= 1 and <= 31\n");
2348
        exit(1);
2349
    }
2350
}
2351

    
2352
static void opt_mb_qmin(const char *arg)
2353
{
2354
    video_mb_qmin = atoi(arg);
2355
    if (video_mb_qmin < 0 ||
2356
        video_mb_qmin > 31) {
2357
        fprintf(stderr, "qmin must be >= 1 and <= 31\n");
2358
        exit(1);
2359
    }
2360
}
2361

    
2362
static void opt_mb_qmax(const char *arg)
2363
{
2364
    video_mb_qmax = atoi(arg);
2365
    if (video_mb_qmax < 0 ||
2366
        video_mb_qmax > 31) {
2367
        fprintf(stderr, "qmax must be >= 1 and <= 31\n");
2368
        exit(1);
2369
    }
2370
}
2371

    
2372
static void opt_qdiff(const char *arg)
2373
{
2374
    video_qdiff = atoi(arg);
2375
    if (video_qdiff < 0 ||
2376
        video_qdiff > 31) {
2377
        fprintf(stderr, "qdiff must be >= 1 and <= 31\n");
2378
        exit(1);
2379
    }
2380
}
2381

    
2382
static void opt_qblur(const char *arg)
2383
{
2384
    video_qblur = atof(arg);
2385
}
2386

    
2387
static void opt_qcomp(const char *arg)
2388
{
2389
    video_qcomp = atof(arg);
2390
}
2391

    
2392
static void opt_rc_initial_cplx(const char *arg)
2393
{
2394
    video_rc_initial_cplx = atof(arg);
2395
}
2396
static void opt_b_qfactor(const char *arg)
2397
{
2398
    video_b_qfactor = atof(arg);
2399
}
2400
static void opt_i_qfactor(const char *arg)
2401
{
2402
    video_i_qfactor = atof(arg);
2403
}
2404
static void opt_b_qoffset(const char *arg)
2405
{
2406
    video_b_qoffset = atof(arg);
2407
}
2408
static void opt_i_qoffset(const char *arg)
2409
{
2410
    video_i_qoffset = atof(arg);
2411
}
2412

    
2413
static void opt_ibias(const char *arg)
2414
{
2415
    video_intra_quant_bias = atoi(arg);
2416
}
2417
static void opt_pbias(const char *arg)
2418
{
2419
    video_inter_quant_bias = atoi(arg);
2420
}
2421

    
2422
static void opt_packet_size(const char *arg)
2423
{
2424
    packet_size= atoi(arg);
2425
}
2426

    
2427
static void opt_error_rate(const char *arg)
2428
{
2429
    error_rate= atoi(arg);
2430
}
2431

    
2432
static void opt_strict(const char *arg)
2433
{
2434
    strict= atoi(arg);
2435
}
2436

    
2437
static void opt_top_field_first(const char *arg)
2438
{
2439
    top_field_first= atoi(arg);
2440
}
2441

    
2442
static void opt_noise_reduction(const char *arg)
2443
{
2444
    noise_reduction= atoi(arg);
2445
}
2446

    
2447
static void opt_qns(const char *arg)
2448
{
2449
    qns= atoi(arg);
2450
}
2451

    
2452
static void opt_sc_threshold(const char *arg)
2453
{
2454
    sc_threshold= atoi(arg);
2455
}
2456

    
2457
static void opt_me_range(const char *arg)
2458
{
2459
    me_range = atoi(arg);
2460
}
2461

    
2462
static void opt_thread_count(const char *arg)
2463
{
2464
    thread_count= atoi(arg);
2465
#if !defined(HAVE_PTHREADS) && !defined(HAVE_W32THREADS)
2466
    if (verbose >= 0)
2467
        fprintf(stderr, "Warning: not compiled with thread support, using thread emulation\n");
2468
#endif
2469
}
2470

    
2471
static void opt_audio_bitrate(const char *arg)
2472
{
2473
    audio_bit_rate = atoi(arg) * 1000;
2474
}
2475

    
2476
static void opt_audio_rate(const char *arg)
2477
{
2478
    audio_sample_rate = atoi(arg);
2479
}
2480

    
2481
static void opt_audio_channels(const char *arg)
2482
{
2483
    audio_channels = atoi(arg);
2484
}
2485

    
2486
static void opt_video_device(const char *arg)
2487
{
2488
    video_device = av_strdup(arg);
2489
}
2490

    
2491
static void opt_video_channel(const char *arg)
2492
{
2493
    video_channel = strtol(arg, NULL, 0);
2494
}
2495

    
2496
static void opt_video_standard(const char *arg)
2497
{
2498
    video_standard = av_strdup(arg);
2499
}
2500

    
2501
static void opt_audio_device(const char *arg)
2502
{
2503
    audio_device = av_strdup(arg);
2504
}
2505

    
2506
static void opt_dv1394(const char *arg)
2507
{
2508
    video_grab_format = "dv1394";
2509
    audio_grab_format = NULL;
2510
}
2511

    
2512
static void opt_audio_codec(const char *arg)
2513
{
2514
    AVCodec *p;
2515

    
2516
    if (!strcmp(arg, "copy")) {
2517
        audio_stream_copy = 1;
2518
    } else {
2519
        p = first_avcodec;
2520
        while (p) {
2521
            if (!strcmp(p->name, arg) && p->type == CODEC_TYPE_AUDIO)
2522
                break;
2523
            p = p->next;
2524
        }
2525
        if (p == NULL) {
2526
            fprintf(stderr, "Unknown audio codec '%s'\n", arg);
2527
            exit(1);
2528
        } else {
2529
            audio_codec_id = p->id;
2530
        }
2531
    }
2532
}
2533

    
2534
static void add_frame_hooker(const char *arg)
2535
{
2536
    int argc = 0;
2537
    char *argv[64];
2538
    int i;
2539
    char *args = av_strdup(arg);
2540

    
2541
    using_vhook = 1;
2542

    
2543
    argv[0] = strtok(args, " ");
2544
    while (argc < 62 && (argv[++argc] = strtok(NULL, " "))) {
2545
    }
2546

    
2547
    i = frame_hook_add(argc, argv);
2548

    
2549
    if (i != 0) {
2550
        fprintf(stderr, "Failed to add video hook function: %s\n", arg);
2551
        exit(1);
2552
    }
2553
}
2554

    
2555
const char *motion_str[] = {
2556
    "zero",
2557
    "full",
2558
    "log",
2559
    "phods",
2560
    "epzs",
2561
    "x1",
2562
    NULL,
2563
};
2564

    
2565
static void opt_motion_estimation(const char *arg)
2566
{
2567
    const char **p;
2568
    p = motion_str;
2569
    for(;;) {
2570
        if (!*p) {
2571
            fprintf(stderr, "Unknown motion estimation method '%s'\n", arg);
2572
            exit(1);
2573
        }
2574
        if (!strcmp(*p, arg))
2575
            break;
2576
        p++;
2577
    }
2578
    me_method = (p - motion_str) + 1;
2579
}
2580

    
2581
static void opt_video_codec(const char *arg)
2582
{
2583
    AVCodec *p;
2584

    
2585
    if (!strcmp(arg, "copy")) {
2586
        video_stream_copy = 1;
2587
    } else {
2588
        p = first_avcodec;
2589
        while (p) {
2590
            if (!strcmp(p->name, arg) && p->type == CODEC_TYPE_VIDEO)
2591
                break;
2592
            p = p->next;
2593
        }
2594
        if (p == NULL) {
2595
            fprintf(stderr, "Unknown video codec '%s'\n", arg);
2596
            exit(1);
2597
        } else {
2598
            video_codec_id = p->id;
2599
        }
2600
    }
2601
}
2602

    
2603
static void opt_map(const char *arg)
2604
{
2605
    AVStreamMap *m;
2606
    const char *p;
2607

    
2608
    p = arg;
2609
    m = &stream_maps[nb_stream_maps++];
2610

    
2611
    m->file_index = strtol(arg, (char **)&p, 0);
2612
    if (*p)
2613
        p++;
2614

    
2615
    m->stream_index = strtol(p, (char **)&p, 0);
2616
}
2617

    
2618
static void opt_recording_time(const char *arg)
2619
{
2620
    recording_time = parse_date(arg, 1);
2621
}
2622

    
2623
static void opt_start_time(const char *arg)
2624
{
2625
    start_time = parse_date(arg, 1);
2626
}
2627

    
2628
static void opt_rec_timestamp(const char *arg)
2629
{
2630
    rec_timestamp = parse_date(arg, 0) / 1000000;
2631
}
2632

    
2633
static void opt_input_ts_offset(const char *arg)
2634
{
2635
    input_ts_offset = parse_date(arg, 1);
2636
}
2637

    
2638
static void opt_input_file(const char *filename)
2639
{
2640
    AVFormatContext *ic;
2641
    AVFormatParameters params, *ap = &params;
2642
    int err, i, ret, rfps, rfps_base;
2643

    
2644
    if (!strcmp(filename, "-"))
2645
        filename = "pipe:";
2646

    
2647
    using_stdin |= !strcmp(filename, "pipe:" ) || 
2648
                   !strcmp( filename, "/dev/stdin" );
2649

    
2650
    /* get default parameters from command line */
2651
    memset(ap, 0, sizeof(*ap));
2652
    ap->sample_rate = audio_sample_rate;
2653
    ap->channels = audio_channels;
2654
    ap->frame_rate = frame_rate;
2655
    ap->frame_rate_base = frame_rate_base;
2656
    ap->width = frame_width + frame_padleft + frame_padright;
2657
    ap->height = frame_height + frame_padtop + frame_padbottom;
2658
    ap->image_format = image_format;
2659
    ap->pix_fmt = frame_pix_fmt;
2660

    
2661
    /* open the input file with generic libav function */
2662
    err = av_open_input_file(&ic, filename, file_iformat, 0, ap);
2663
    if (err < 0) {
2664
        print_error(filename, err);
2665
        exit(1);
2666
    }
2667
    
2668
    /* If not enough info to get the stream parameters, we decode the
2669
       first frames to get it. (used in mpeg case for example) */
2670
    ret = av_find_stream_info(ic);
2671
    if (ret < 0 && verbose >= 0) {
2672
        fprintf(stderr, "%s: could not find codec parameters\n", filename);
2673
        exit(1);
2674
    }
2675

    
2676
    /* if seeking requested, we execute it */
2677
    if (start_time != 0) {
2678
        int64_t timestamp;
2679

    
2680
        timestamp = start_time;
2681
        /* add the stream start time */
2682
        if (ic->start_time != AV_NOPTS_VALUE)
2683
            timestamp += ic->start_time;
2684
        ret = av_seek_frame(ic, -1, timestamp);
2685
        if (ret < 0) {
2686
            fprintf(stderr, "%s: could not seek to position %0.3f\n", 
2687
                    filename, (double)timestamp / AV_TIME_BASE);
2688
        }
2689
        /* reset seek info */
2690
        start_time = 0;
2691
    }
2692

    
2693
    /* update the current parameters so that they match the one of the input stream */
2694
    for(i=0;i<ic->nb_streams;i++) {
2695
        AVCodecContext *enc = &ic->streams[i]->codec;
2696
#if defined(HAVE_PTHREADS) || defined(HAVE_W32THREADS)
2697
        if(thread_count>1)
2698
            avcodec_thread_init(enc, thread_count);
2699
#endif
2700
        enc->thread_count= thread_count;
2701
        switch(enc->codec_type) {
2702
        case CODEC_TYPE_AUDIO:
2703
            //fprintf(stderr, "\nInput Audio channels: %d", enc->channels);
2704
            audio_channels = enc->channels;
2705
            audio_sample_rate = enc->sample_rate;
2706
            break;
2707
        case CODEC_TYPE_VIDEO:
2708
            frame_height = enc->height;
2709
            frame_width = enc->width;
2710
            frame_aspect_ratio = av_q2d(enc->sample_aspect_ratio) * enc->width / enc->height;
2711
            frame_pix_fmt = enc->pix_fmt;
2712
            rfps      = ic->streams[i]->r_frame_rate;
2713
            rfps_base = ic->streams[i]->r_frame_rate_base;
2714
            enc->workaround_bugs = workaround_bugs;
2715
            enc->error_resilience = error_resilience; 
2716
            enc->error_concealment = error_concealment; 
2717
            enc->idct_algo = idct_algo;
2718
            enc->debug = debug;
2719
            enc->debug_mv = debug_mv;            
2720
            if(bitexact)
2721
                enc->flags|= CODEC_FLAG_BITEXACT;
2722
            if(me_threshold)
2723
                enc->debug |= FF_DEBUG_MV;
2724

    
2725
            assert(enc->frame_rate_base == rfps_base); // should be true for now
2726
            if (enc->frame_rate != rfps) { 
2727

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

    
2732
                    (float)rfps / rfps_base);
2733
            }
2734
            /* update the current frame rate to match the stream frame rate */
2735
            frame_rate      = rfps;
2736
            frame_rate_base = rfps_base;
2737

    
2738
            enc->rate_emu = rate_emu;
2739
            break;
2740
        case CODEC_TYPE_DATA:
2741
            break;
2742
        default:
2743
            av_abort();
2744
        }
2745
    }
2746
    
2747
    input_files[nb_input_files] = ic;
2748
    input_files_ts_offset[nb_input_files] = input_ts_offset;
2749
    /* dump the file content */
2750
    if (verbose >= 0)
2751
        dump_format(ic, nb_input_files, filename, 0);
2752

    
2753
    nb_input_files++;
2754
    file_iformat = NULL;
2755
    file_oformat = NULL;
2756
    image_format = NULL;
2757

    
2758
    rate_emu = 0;
2759
}
2760

    
2761
static void check_audio_video_inputs(int *has_video_ptr, int *has_audio_ptr)
2762
{
2763
    int has_video, has_audio, i, j;
2764
    AVFormatContext *ic;
2765

    
2766
    has_video = 0;
2767
    has_audio = 0;
2768
    for(j=0;j<nb_input_files;j++) {
2769
        ic = input_files[j];
2770
        for(i=0;i<ic->nb_streams;i++) {
2771
            AVCodecContext *enc = &ic->streams[i]->codec;
2772
            switch(enc->codec_type) {
2773
            case CODEC_TYPE_AUDIO:
2774
                has_audio = 1;
2775
                break;
2776
            case CODEC_TYPE_VIDEO:
2777
                has_video = 1;
2778
                break;
2779
            case CODEC_TYPE_DATA:
2780
                break;
2781
            default:
2782
                av_abort();
2783
            }
2784
        }
2785
    }
2786
    *has_video_ptr = has_video;
2787
    *has_audio_ptr = has_audio;
2788
}
2789

    
2790
static void opt_output_file(const char *filename)
2791
{
2792
    AVStream *st;
2793
    AVFormatContext *oc;
2794
    int use_video, use_audio, nb_streams, input_has_video, input_has_audio;
2795
    int codec_id;
2796
    AVFormatParameters params, *ap = &params;
2797

    
2798
    if (!strcmp(filename, "-"))
2799
        filename = "pipe:";
2800

    
2801
    oc = av_alloc_format_context();
2802

    
2803
    if (!file_oformat) {
2804
        file_oformat = guess_format(NULL, filename, NULL);
2805
        if (!file_oformat) {
2806
            fprintf(stderr, "Unable for find a suitable output format for '%s'\n",
2807
                    filename);
2808
            exit(1);
2809
        }
2810
    }
2811
    
2812
    oc->oformat = file_oformat;
2813

    
2814
    if (!strcmp(file_oformat->name, "ffm") && 
2815
        strstart(filename, "http:", NULL)) {
2816
        /* special case for files sent to ffserver: we get the stream
2817
           parameters from ffserver */
2818
        if (read_ffserver_streams(oc, filename) < 0) {
2819
            fprintf(stderr, "Could not read stream parameters from '%s'\n", filename);
2820
            exit(1);
2821
        }
2822
    } else {
2823
        use_video = file_oformat->video_codec != CODEC_ID_NONE || video_stream_copy;
2824
        use_audio = file_oformat->audio_codec != CODEC_ID_NONE || audio_stream_copy;
2825

    
2826
        /* disable if no corresponding type found and at least one
2827
           input file */
2828
        if (nb_input_files > 0) {
2829
            check_audio_video_inputs(&input_has_video, &input_has_audio);
2830
            if (!input_has_video)
2831
                use_video = 0;
2832
            if (!input_has_audio)
2833
                use_audio = 0;
2834
        }
2835

    
2836
        /* manual disable */
2837
        if (audio_disable) {
2838
            use_audio = 0;
2839
        }
2840
        if (video_disable) {
2841
            use_video = 0;
2842
        }
2843
        
2844
        nb_streams = 0;
2845
        if (use_video) {
2846
            AVCodecContext *video_enc;
2847
            
2848
            st = av_new_stream(oc, nb_streams++);
2849
            if (!st) {
2850
                fprintf(stderr, "Could not alloc stream\n");
2851
                exit(1);
2852
            }
2853
#if defined(HAVE_PTHREADS) || defined(HAVE_W32THREADS)
2854
            if(thread_count>1)
2855
                avcodec_thread_init(&st->codec, thread_count);
2856
#endif
2857

    
2858
            video_enc = &st->codec;
2859
            
2860
            if(!strcmp(file_oformat->name, "mp4") || !strcmp(file_oformat->name, "mov") || !strcmp(file_oformat->name, "3gp"))
2861
                video_enc->flags |= CODEC_FLAG_GLOBAL_HEADER;
2862
            if (video_stream_copy) {
2863
                st->stream_copy = 1;
2864
                video_enc->codec_type = CODEC_TYPE_VIDEO;
2865
            } else {
2866
                char *p;
2867
                int i;
2868
                AVCodec *codec;
2869
            
2870
                codec_id = file_oformat->video_codec;
2871
                if (video_codec_id != CODEC_ID_NONE)
2872
                    codec_id = video_codec_id;
2873
                
2874
                video_enc->codec_id = codec_id;
2875
                codec = avcodec_find_encoder(codec_id);
2876
                
2877
                video_enc->bit_rate = video_bit_rate;
2878
                video_enc->bit_rate_tolerance = video_bit_rate_tolerance;
2879
                video_enc->frame_rate = frame_rate; 
2880
                video_enc->frame_rate_base = frame_rate_base; 
2881
                if(codec && codec->supported_framerates){
2882
                    const AVRational *p= codec->supported_framerates;
2883
                    AVRational req= (AVRational){frame_rate, frame_rate_base};
2884
                    const AVRational *best=NULL;
2885
                    AVRational best_error= (AVRational){INT_MAX, 1};
2886
                    for(; p->den!=0; p++){
2887
                        AVRational error= av_sub_q(req, *p);
2888
                        if(error.num <0) error.num *= -1;
2889
                        if(av_cmp_q(error, best_error) < 0){
2890
                            best_error= error;
2891
                            best= p;
2892
                        }
2893
                    }
2894
                    video_enc->frame_rate     = best->num;
2895
                    video_enc->frame_rate_base= best->den;
2896
                }
2897
                
2898
                video_enc->width = frame_width + frame_padright + frame_padleft;
2899
                video_enc->height = frame_height + frame_padtop + frame_padbottom;
2900
                video_enc->sample_aspect_ratio = av_d2q(frame_aspect_ratio*frame_height/frame_width, 255);
2901
                video_enc->pix_fmt = frame_pix_fmt;
2902

    
2903
                if(codec && codec->pix_fmts){
2904
                    const enum PixelFormat *p= codec->pix_fmts;
2905
                    for(; *p!=-1; p++){
2906
                        if(*p == video_enc->pix_fmt)
2907
                            break;
2908
                    }
2909
                    if(*p == -1)
2910
                        video_enc->pix_fmt = codec->pix_fmts[0];
2911
                }
2912

    
2913
                if (!intra_only)
2914
                    video_enc->gop_size = gop_size;
2915
                else
2916
                    video_enc->gop_size = 0;
2917
                if (video_qscale || same_quality) {
2918
                    video_enc->flags |= CODEC_FLAG_QSCALE;
2919
                    st->quality = FF_QP2LAMBDA * video_qscale;
2920
                }
2921

    
2922
                if(intra_matrix)
2923
                    video_enc->intra_matrix = intra_matrix;
2924
                if(inter_matrix)
2925
                    video_enc->inter_matrix = inter_matrix;
2926

    
2927
                if(bitexact)
2928
                    video_enc->flags |= CODEC_FLAG_BITEXACT;
2929

    
2930
                video_enc->mb_decision = mb_decision;
2931
                video_enc->mb_cmp = mb_cmp;
2932
                video_enc->ildct_cmp = ildct_cmp;
2933
                video_enc->me_sub_cmp = sub_cmp;
2934
                video_enc->me_cmp = cmp;
2935
                video_enc->me_pre_cmp = pre_cmp;
2936
                video_enc->pre_me = pre_me;
2937
                video_enc->lumi_masking = lumi_mask;
2938
                video_enc->dark_masking = dark_mask;
2939
                video_enc->spatial_cplx_masking = scplx_mask;
2940
                video_enc->temporal_cplx_masking = tcplx_mask;
2941
                video_enc->p_masking = p_mask;
2942
                video_enc->quantizer_noise_shaping= qns;
2943
                
2944
                if (use_umv) {
2945
                    video_enc->flags |= CODEC_FLAG_H263P_UMV;
2946
                }
2947
                if (use_ss) {
2948
                    video_enc->flags |= CODEC_FLAG_H263P_SLICE_STRUCT;
2949
                }
2950
                   if (use_aic) {
2951
                    video_enc->flags |= CODEC_FLAG_H263P_AIC;
2952
                }
2953
                   if (use_aiv) {
2954
                    video_enc->flags |= CODEC_FLAG_H263P_AIV;
2955
                }
2956
                if (use_4mv) {
2957
                    video_enc->flags |= CODEC_FLAG_4MV;
2958
                }
2959
                if (use_obmc) {
2960
                    video_enc->flags |= CODEC_FLAG_OBMC;
2961
                }
2962
                if (use_loop) {
2963
                    video_enc->flags |= CODEC_FLAG_LOOP_FILTER;
2964
                }
2965
            
2966
                if(use_part) {
2967
                    video_enc->flags |= CODEC_FLAG_PART;
2968
                }
2969
                   if (use_alt_scan) {
2970
                    video_enc->flags |= CODEC_FLAG_ALT_SCAN;
2971
                }
2972
                   if (use_trell) {
2973
                    video_enc->flags |= CODEC_FLAG_TRELLIS_QUANT;
2974
                }
2975
                   if (use_scan_offset) {
2976
                    video_enc->flags |= CODEC_FLAG_SVCD_SCAN_OFFSET;
2977
                }
2978
                   if (closed_gop) {
2979
                    video_enc->flags |= CODEC_FLAG_CLOSED_GOP;
2980
                }
2981
                   if (use_qpel) {
2982
                    video_enc->flags |= CODEC_FLAG_QPEL;
2983
                }
2984
                   if (use_qprd) {
2985
                    video_enc->flags |= CODEC_FLAG_QP_RD;
2986
                }
2987
                   if (use_cbprd) {
2988
                    video_enc->flags |= CODEC_FLAG_CBP_RD;
2989
                }
2990
                if (b_frames) {
2991
                    video_enc->max_b_frames = b_frames;
2992
                    video_enc->b_frame_strategy = 0;
2993
                    video_enc->b_quant_factor = 2.0;
2994
                }
2995
                if (do_interlace_dct) {
2996
                    video_enc->flags |= CODEC_FLAG_INTERLACED_DCT;
2997
                }
2998
                if (do_interlace_me) {
2999
                    video_enc->flags |= CODEC_FLAG_INTERLACED_ME;
3000
                }
3001
                video_enc->qmin = video_qmin;
3002
                video_enc->qmax = video_qmax;
3003
                video_enc->lmin = video_lmin;
3004
                video_enc->lmax = video_lmax;
3005
                video_enc->mb_qmin = video_mb_qmin;
3006
                video_enc->mb_qmax = video_mb_qmax;
3007
                video_enc->max_qdiff = video_qdiff;
3008
                video_enc->qblur = video_qblur;
3009
                video_enc->qcompress = video_qcomp;
3010
                video_enc->rc_eq = video_rc_eq;
3011
                video_enc->debug = debug;
3012
                video_enc->debug_mv = debug_mv;
3013
                video_enc->thread_count = thread_count;
3014
                p= video_rc_override_string;
3015
                for(i=0; p; i++){
3016
                    int start, end, q;
3017
                    int e=sscanf(p, "%d,%d,%d", &start, &end, &q);
3018
                    if(e!=3){
3019
                        fprintf(stderr, "error parsing rc_override\n");
3020
                        exit(1);
3021
                    }
3022
                    video_enc->rc_override= 
3023
                        av_realloc(video_enc->rc_override, 
3024
                                   sizeof(RcOverride)*(i+1));
3025
                    video_enc->rc_override[i].start_frame= start;
3026
                    video_enc->rc_override[i].end_frame  = end;
3027
                    if(q>0){
3028
                        video_enc->rc_override[i].qscale= q;
3029
                        video_enc->rc_override[i].quality_factor= 1.0;
3030
                    }
3031
                    else{
3032
                        video_enc->rc_override[i].qscale= 0;
3033
                        video_enc->rc_override[i].quality_factor= -q/100.0;
3034
                    }
3035
                    p= strchr(p, '/');
3036
                    if(p) p++;
3037
                }
3038
                video_enc->rc_override_count=i;
3039

    
3040
                video_enc->rc_max_rate = video_rc_max_rate;
3041
                video_enc->rc_min_rate = video_rc_min_rate;
3042
                video_enc->rc_buffer_size = video_rc_buffer_size;
3043
                video_enc->rc_buffer_aggressivity= video_rc_buffer_aggressivity;
3044
                video_enc->rc_initial_cplx= video_rc_initial_cplx;
3045
                video_enc->i_quant_factor = video_i_qfactor;
3046
                video_enc->b_quant_factor = video_b_qfactor;
3047
                video_enc->i_quant_offset = video_i_qoffset;
3048
                video_enc->b_quant_offset = video_b_qoffset;
3049
                video_enc->intra_quant_bias = video_intra_quant_bias;
3050
                video_enc->inter_quant_bias = video_inter_quant_bias;
3051
                video_enc->dct_algo = dct_algo;
3052
                video_enc->idct_algo = idct_algo;
3053
                video_enc->me_threshold= me_threshold;
3054
                video_enc->mb_threshold= mb_threshold;
3055
                video_enc->intra_dc_precision= intra_dc_precision - 8;
3056
                video_enc->strict_std_compliance = strict;
3057
                video_enc->error_rate = error_rate;
3058
                video_enc->noise_reduction= noise_reduction;
3059
                video_enc->scenechange_threshold= sc_threshold;
3060
                video_enc->me_range = me_range;
3061
                video_enc->coder_type= coder;
3062
                video_enc->context_model= context;
3063
                video_enc->prediction_method= predictor;
3064

    
3065
                if(packet_size){
3066
                    video_enc->rtp_mode= 1;
3067
                    video_enc->rtp_payload_size= packet_size;
3068
                }
3069
            
3070
                if (do_psnr)
3071
                    video_enc->flags|= CODEC_FLAG_PSNR;
3072
            
3073
                video_enc->me_method = me_method;
3074

    
3075
                /* two pass mode */
3076
                if (do_pass) {
3077
                    if (do_pass == 1) {
3078
                        video_enc->flags |= CODEC_FLAG_PASS1;
3079
                    } else {
3080
                        video_enc->flags |= CODEC_FLAG_PASS2;
3081
                    }
3082
                }
3083
            }
3084
        }
3085
    
3086
        if (use_audio) {
3087
            AVCodecContext *audio_enc;
3088

    
3089
            st = av_new_stream(oc, nb_streams++);
3090
            if (!st) {
3091
                fprintf(stderr, "Could not alloc stream\n");
3092
                exit(1);
3093
            }
3094
#if defined(HAVE_PTHREADS) || defined(HAVE_W32THREADS)
3095
            if(thread_count>1)
3096
                avcodec_thread_init(&st->codec, thread_count);
3097
#endif
3098

    
3099
            audio_enc = &st->codec;
3100
            audio_enc->codec_type = CODEC_TYPE_AUDIO;
3101

    
3102
            if(!strcmp(file_oformat->name, "mp4") || !strcmp(file_oformat->name, "mov") || !strcmp(file_oformat->name, "3gp"))
3103
                audio_enc->flags |= CODEC_FLAG_GLOBAL_HEADER;
3104
            if (audio_stream_copy) {
3105
                st->stream_copy = 1;
3106
                audio_enc->channels = audio_channels;
3107
            } else {
3108
                codec_id = file_oformat->audio_codec;
3109
                if (audio_codec_id != CODEC_ID_NONE)
3110
                    codec_id = audio_codec_id;
3111
                audio_enc->codec_id = codec_id;
3112
                
3113
                audio_enc->bit_rate = audio_bit_rate;
3114
                audio_enc->strict_std_compliance = strict;
3115
                audio_enc->thread_count = thread_count;
3116
                /* For audio codecs other than AC3 we limit */
3117
                /* the number of coded channels to stereo   */
3118
                if (audio_channels > 2 && codec_id != CODEC_ID_AC3) {
3119
                    audio_enc->channels = 2;
3120
                } else
3121
                    audio_enc->channels = audio_channels;
3122
            }
3123
            audio_enc->sample_rate = audio_sample_rate;
3124
        }
3125

    
3126
        oc->nb_streams = nb_streams;
3127

    
3128
        if (!nb_streams) {
3129
            fprintf(stderr, "No audio or video streams available\n");
3130
            exit(1);
3131
        }
3132

    
3133
        oc->timestamp = rec_timestamp;
3134
            
3135
        if (str_title)
3136
            pstrcpy(oc->title, sizeof(oc->title), str_title);
3137
        if (str_author)
3138
            pstrcpy(oc->author, sizeof(oc->author), str_author);
3139
        if (str_copyright)
3140
            pstrcpy(oc->copyright, sizeof(oc->copyright), str_copyright);
3141
        if (str_comment)
3142
            pstrcpy(oc->comment, sizeof(oc->comment), str_comment);
3143
    }
3144

    
3145
    output_files[nb_output_files++] = oc;
3146

    
3147
    strcpy(oc->filename, filename);
3148

    
3149
    /* check filename in case of an image number is expected */
3150
    if (oc->oformat->flags & AVFMT_NEEDNUMBER) {
3151
        if (filename_number_test(oc->filename) < 0) {
3152
            print_error(oc->filename, AVERROR_NUMEXPECTED);
3153
            exit(1);
3154
        }
3155
    }
3156

    
3157
    if (!(oc->oformat->flags & AVFMT_NOFILE)) {
3158
        /* test if it already exists to avoid loosing precious files */
3159
        if (!file_overwrite && 
3160
            (strchr(filename, ':') == NULL ||
3161
             strstart(filename, "file:", NULL))) {
3162
            if (url_exist(filename)) {
3163
                int c;
3164
                
3165
                if ( !using_stdin ) {
3166
                    fprintf(stderr,"File '%s' already exists. Overwrite ? [y/N] ", filename);
3167
                    fflush(stderr);
3168
                    c = getchar();
3169
                    if (toupper(c) != 'Y') {
3170
                        fprintf(stderr, "Not overwriting - exiting\n");
3171
                        exit(1);
3172
                    }
3173
                                }
3174
                                else {
3175
                    fprintf(stderr,"File '%s' already exists. Exiting.\n", filename);
3176
                    exit(1);
3177
                                }
3178
            }
3179
        }
3180
        
3181
        /* open the file */
3182
        if (url_fopen(&oc->pb, filename, URL_WRONLY) < 0) {
3183
            fprintf(stderr, "Could not open '%s'\n", filename);
3184
            exit(1);
3185
        }
3186
    }
3187

    
3188
    memset(ap, 0, sizeof(*ap));
3189
    ap->image_format = image_format;
3190
    if (av_set_parameters(oc, ap) < 0) {
3191
        fprintf(stderr, "%s: Invalid encoding parameters\n",
3192
                oc->filename);
3193
        exit(1);
3194
    }
3195

    
3196
    /* reset some options */
3197
    file_oformat = NULL;
3198
    file_iformat = NULL;
3199
    image_format = NULL;
3200
    audio_disable = 0;
3201
    video_disable = 0;
3202
    audio_codec_id = CODEC_ID_NONE;
3203
    video_codec_id = CODEC_ID_NONE;
3204
    audio_stream_copy = 0;
3205
    video_stream_copy = 0;
3206
}
3207

    
3208
/* prepare dummy protocols for grab */
3209
static void prepare_grab(void)
3210
{
3211
    int has_video, has_audio, i, j;
3212
    AVFormatContext *oc;
3213
    AVFormatContext *ic;
3214
    AVFormatParameters vp1, *vp = &vp1;
3215
    AVFormatParameters ap1, *ap = &ap1;
3216
    
3217
    /* see if audio/video inputs are needed */
3218
    has_video = 0;
3219
    has_audio = 0;
3220
    memset(ap, 0, sizeof(*ap));
3221
    memset(vp, 0, sizeof(*vp));
3222
    for(j=0;j<nb_output_files;j++) {
3223
        oc = output_files[j];
3224
        for(i=0;i<oc->nb_streams;i++) {
3225
            AVCodecContext *enc = &oc->streams[i]->codec;
3226
            switch(enc->codec_type) {
3227
            case CODEC_TYPE_AUDIO:
3228
                if (enc->sample_rate > ap->sample_rate)
3229
                    ap->sample_rate = enc->sample_rate;
3230
                if (enc->channels > ap->channels)
3231
                    ap->channels = enc->channels;
3232
                has_audio = 1;
3233
                break;
3234
            case CODEC_TYPE_VIDEO:
3235
                if (enc->width > vp->width)
3236
                    vp->width = enc->width;
3237
                if (enc->height > vp->height)
3238
                    vp->height = enc->height;
3239
                
3240
                assert(enc->frame_rate_base == DEFAULT_FRAME_RATE_BASE);
3241
                if (enc->frame_rate > vp->frame_rate){
3242
                    vp->frame_rate      = enc->frame_rate;
3243
                    vp->frame_rate_base = enc->frame_rate_base;
3244
                }
3245
                has_video = 1;
3246
                break;
3247
            default:
3248
                av_abort();
3249
            }
3250
        }
3251
    }
3252
    
3253
    if (has_video == 0 && has_audio == 0) {
3254
        fprintf(stderr, "Output file must have at least one audio or video stream\n");
3255
        exit(1);
3256
    }
3257
    
3258
    if (has_video) {
3259
        AVInputFormat *fmt1;
3260
        fmt1 = av_find_input_format(video_grab_format);
3261
        vp->device  = video_device;
3262
        vp->channel = video_channel;
3263
        vp->standard = video_standard;
3264
        if (av_open_input_file(&ic, "", fmt1, 0, vp) < 0) {
3265
            fprintf(stderr, "Could not find video grab device\n");
3266
            exit(1);
3267
        }
3268
        /* If not enough info to get the stream parameters, we decode the
3269
           first frames to get it. */
3270
        if ((ic->ctx_flags & AVFMTCTX_NOHEADER) && av_find_stream_info(ic) < 0) {
3271
            fprintf(stderr, "Could not find video grab parameters\n");
3272
            exit(1);
3273
        }
3274
        /* by now video grab has one stream */
3275
        ic->streams[0]->r_frame_rate      = vp->frame_rate;
3276
        ic->streams[0]->r_frame_rate_base = vp->frame_rate_base;
3277
        input_files[nb_input_files] = ic;
3278

    
3279
        if (verbose >= 0)
3280
            dump_format(ic, nb_input_files, "", 0);
3281

    
3282
        nb_input_files++;
3283
    }
3284
    if (has_audio && audio_grab_format) {
3285
        AVInputFormat *fmt1;
3286
        fmt1 = av_find_input_format(audio_grab_format);
3287
        ap->device = audio_device;
3288
        if (av_open_input_file(&ic, "", fmt1, 0, ap) < 0) {
3289
            fprintf(stderr, "Could not find audio grab device\n");
3290
            exit(1);
3291
        }
3292
        input_files[nb_input_files] = ic;
3293

    
3294
        if (verbose >= 0)
3295
            dump_format(ic, nb_input_files, "", 0);
3296

    
3297
        nb_input_files++;
3298
    }
3299
}
3300

    
3301
/* same option as mencoder */
3302
static void opt_pass(const char *pass_str)
3303
{
3304
    int pass;
3305
    pass = atoi(pass_str);
3306
    if (pass != 1 && pass != 2) {
3307
        fprintf(stderr, "pass number can be only 1 or 2\n");
3308
        exit(1);
3309
    }
3310
    do_pass = pass;
3311
}
3312

    
3313
#if defined(CONFIG_WIN32) || defined(CONFIG_OS2)
3314
static int64_t getutime(void)
3315
{
3316
  return av_gettime();
3317
}
3318
#else
3319
static int64_t getutime(void)
3320
{
3321
    struct rusage rusage;
3322

    
3323
    getrusage(RUSAGE_SELF, &rusage);
3324
    return (rusage.ru_utime.tv_sec * 1000000LL) + rusage.ru_utime.tv_usec;
3325
}
3326
#endif
3327

    
3328
extern int ffm_nopts;
3329

    
3330
static void opt_bitexact(void)
3331
{
3332
    bitexact=1;
3333
    /* disable generate of real time pts in ffm (need to be supressed anyway) */
3334
    ffm_nopts = 1;
3335
}
3336

    
3337
static void show_formats(void)
3338
{
3339
    AVInputFormat *ifmt;
3340
    AVOutputFormat *ofmt;
3341
    AVImageFormat *image_fmt;
3342
    URLProtocol *up;
3343
    AVCodec *p, *p2;
3344
    const char **pp, *last_name;
3345

    
3346
    printf("File formats:\n");
3347
    last_name= "000";
3348
    for(;;){
3349
        int decode=0;
3350
        int encode=0;
3351
        const char *name=NULL;
3352

    
3353
        for(ofmt = first_oformat; ofmt != NULL; ofmt = ofmt->next) {
3354
            if((name == NULL || strcmp(ofmt->name, name)<0) &&
3355
                strcmp(ofmt->name, last_name)>0){
3356
                name= ofmt->name;
3357
                encode=1;
3358
            }
3359
        }
3360
        for(ifmt = first_iformat; ifmt != NULL; ifmt = ifmt->next) {
3361
            if((name == NULL || strcmp(ifmt->name, name)<0) &&
3362
                strcmp(ifmt->name, last_name)>0){
3363
                name= ifmt->name;
3364
                encode=0;
3365
            }
3366
            if(name && strcmp(ifmt->name, name)==0)
3367
                decode=1;
3368
        }
3369
        if(name==NULL)
3370
            break;
3371
        last_name= name;
3372
        
3373
        printf(
3374
            " %s%s %s\n", 
3375
            decode ? "D":" ", 
3376
            encode ? "E":" ", 
3377
            name);
3378
    }
3379
    printf("\n");
3380

    
3381
    printf("Image formats:\n");
3382
    for(image_fmt = first_image_format; image_fmt != NULL; 
3383
        image_fmt = image_fmt->next) {
3384
        printf(
3385
            " %s%s %s\n",
3386
            image_fmt->img_read  ? "D":" ",
3387
            image_fmt->img_write ? "E":" ",
3388
            image_fmt->name);
3389
    }
3390
    printf("\n");
3391

    
3392
    printf("Codecs:\n");
3393
    last_name= "000";
3394
    for(;;){
3395
        int decode=0;
3396
        int encode=0;
3397
        int cap=0;
3398

    
3399
        p2=NULL;
3400
        for(p = first_avcodec; p != NULL; p = p->next) {
3401
            if((p2==NULL || strcmp(p->name, p2->name)<0) &&
3402
                strcmp(p->name, last_name)>0){
3403
                p2= p;
3404
                decode= encode= cap=0;
3405
            }
3406
            if(p2 && strcmp(p->name, p2->name)==0){
3407
                if(p->decode) decode=1;
3408
                if(p->encode) encode=1;
3409
                cap |= p->capabilities;
3410
            }
3411
        }
3412
        if(p2==NULL)
3413
            break;
3414
        last_name= p2->name;
3415
        
3416
        printf(
3417
            " %s%s%s%s%s%s %s", 
3418
            decode ? "D": (/*p2->decoder ? "d":*/" "), 
3419
            encode ? "E":" ", 
3420
            p2->type == CODEC_TYPE_AUDIO ? "A":"V",
3421
            cap & CODEC_CAP_DRAW_HORIZ_BAND ? "S":" ",
3422
            cap & CODEC_CAP_DR1 ? "D":" ",
3423
            cap & CODEC_CAP_TRUNCATED ? "T":" ",
3424
            p2->name);
3425
       /* if(p2->decoder && decode==0)
3426
            printf(" use %s for decoding", p2->decoder->name);*/
3427
        printf("\n");
3428
    }
3429
    printf("\n");
3430

    
3431
    printf("Supported file protocols:\n");
3432
    for(up = first_protocol; up != NULL; up = up->next)
3433
        printf(" %s:", up->name);
3434
    printf("\n");
3435
    
3436
    printf("Frame size, frame rate abbreviations:\n ntsc pal qntsc qpal sntsc spal film ntsc-film sqcif qcif cif 4cif\n");
3437
    printf("Motion estimation methods:\n");
3438
    pp = motion_str;
3439
    while (*pp) {
3440
        printf(" %s", *pp);
3441
        if ((pp - motion_str + 1) == ME_ZERO) 
3442
            printf("(fastest)");
3443
        else if ((pp - motion_str + 1) == ME_FULL) 
3444
            printf("(slowest)");
3445
        else if ((pp - motion_str + 1) == ME_EPZS) 
3446
            printf("(default)");
3447
        pp++;
3448
    }
3449
    printf("\n\n");
3450
    printf(
3451
"Note, the names of encoders and decoders dont always match, so there are\n"
3452
"several cases where the above table shows encoder only or decoder only entries\n"
3453
"even though both encoding and decoding are supported for example, the h263\n"
3454
"decoder corresponds to the h263 and h263p encoders, for file formats its even\n"
3455
"worse\n");
3456
    exit(1);
3457
}
3458

    
3459
void parse_matrix_coeffs(uint16_t *dest, const char *str)
3460
{
3461
    int i;
3462
    const char *p = str;
3463
    for(i = 0;; i++) {
3464
        dest[i] = atoi(p);
3465
        if(i == 63)
3466
            break;
3467
        p = strchr(p, ',');
3468
        if(!p) {
3469
            fprintf(stderr, "Syntax error in matrix \"%s\" at coeff %d\n", str, i);
3470
            exit(1);
3471
        }
3472
        p++;
3473
    }
3474
}
3475

    
3476
void opt_inter_matrix(const char *arg)
3477
{
3478
    inter_matrix = av_mallocz(sizeof(uint16_t) * 64);
3479
    parse_matrix_coeffs(inter_matrix, arg);
3480
}
3481

    
3482
void opt_intra_matrix(const char *arg)
3483
{
3484
    intra_matrix = av_mallocz(sizeof(uint16_t) * 64);
3485
    parse_matrix_coeffs(intra_matrix, arg);
3486
}
3487

    
3488
static void opt_target(const char *arg)
3489
{
3490
    int norm = -1;
3491

    
3492
    if(!strncmp(arg, "pal-", 4)) {
3493
        norm = 0;
3494
        arg += 4;
3495
    } else if(!strncmp(arg, "ntsc-", 5)) {
3496
        norm = 1;
3497
        arg += 5;
3498
    } else {
3499
        int fr;
3500
        /* Calculate FR via float to avoid int overflow */
3501
        fr = (int)(frame_rate * 1000.0 / frame_rate_base);
3502
        if(fr == 25000) {
3503
            norm = 0;
3504
        } else if((fr == 29970) || (fr == 23976)) {
3505
            norm = 1;
3506
        } else {
3507
            /* Try to determine PAL/NTSC by peeking in the input files */
3508
            if(nb_input_files) {
3509
                int i, j;
3510
                for(j = 0; j < nb_input_files; j++) {
3511
                    for(i = 0; i < input_files[j]->nb_streams; i++) {
3512
                        AVCodecContext *c = &input_files[j]->streams[i]->codec;
3513
                        if(c->codec_type != CODEC_TYPE_VIDEO)
3514
                            continue;
3515
                        fr = c->frame_rate * 1000 / c->frame_rate_base;
3516
                        if(fr == 25000) {
3517
                            norm = 0;
3518
                            break;
3519
                        } else if((fr == 29970) || (fr == 23976)) {
3520
                            norm = 1;
3521
                            break;
3522
                        }
3523
                    }
3524
                    if(norm >= 0)
3525
                        break;
3526
                }
3527
            }
3528
        }
3529
        if(verbose && norm >= 0)
3530
            printf("Assuming %s for target.\n", norm ? "NTSC" : "PAL");
3531
    }
3532

    
3533
    if(norm < 0) {
3534
        fprintf(stderr, "Could not determine norm (PAL/NTSC) for target.\n");
3535
        fprintf(stderr, "Please prefix target with \"pal-\" or \"ntsc-\",\n");
3536
        fprintf(stderr, "or set a framerate with \"-r xxx\".\n");
3537
        exit(1);
3538
    }
3539

    
3540
    if(!strcmp(arg, "vcd")) {
3541

    
3542
        opt_video_codec("mpeg1video");
3543
        opt_audio_codec("mp2");
3544
        opt_format("vcd");
3545

    
3546
        opt_frame_size(norm ? "352x240" : "352x288");
3547

    
3548
        video_bit_rate = 1150000;
3549
        video_rc_max_rate = 1150000;
3550
        video_rc_min_rate = 1150000;
3551
        video_rc_buffer_size = 40*1024*8;
3552

    
3553
        audio_bit_rate = 224000;
3554
        audio_sample_rate = 44100;
3555

    
3556
    } else if(!strcmp(arg, "svcd")) {
3557

    
3558
        opt_video_codec("mpeg2video");
3559
        opt_audio_codec("mp2");
3560
        opt_format("svcd");
3561

    
3562
        opt_frame_size(norm ? "480x480" : "480x576");
3563
        opt_gop_size(norm ? "18" : "15");
3564

    
3565
        video_bit_rate = 2040000;
3566
        video_rc_max_rate = 2516000;
3567
        video_rc_min_rate = 0; //1145000;
3568
        video_rc_buffer_size = 224*1024*8;
3569
        use_scan_offset = 1;
3570

    
3571
        audio_bit_rate = 224000;
3572
        audio_sample_rate = 44100;
3573

    
3574
    } else if(!strcmp(arg, "dvd")) {
3575

    
3576
        opt_video_codec("mpeg2video");
3577
        opt_audio_codec("ac3");
3578
        opt_format("vob");
3579

    
3580
        opt_frame_size(norm ? "720x480" : "720x576");
3581
        opt_gop_size(norm ? "18" : "15");
3582

    
3583
        video_bit_rate = 6000000;
3584
        video_rc_max_rate = 9000000;
3585
        video_rc_min_rate = 0; //1500000;
3586
        video_rc_buffer_size = 224*1024*8;
3587

    
3588
        audio_bit_rate = 448000;
3589
        audio_sample_rate = 48000;
3590

    
3591
    } else {
3592
        fprintf(stderr, "Unknown target: %s\n", arg);
3593
        exit(1);
3594
    }
3595
}
3596

    
3597
static void show_version(void)
3598
{
3599
    printf("ffmpeg      " FFMPEG_VERSION "\n"
3600
           "libavcodec  %d\n"
3601
           "libavformat %d\n", 
3602
           avcodec_build(), LIBAVFORMAT_BUILD);
3603
    exit(1);
3604
}
3605

    
3606
const OptionDef options[] = {
3607
    /* main options */
3608
    { "L", 0, {(void*)show_license}, "show license" },
3609
    { "h", 0, {(void*)show_help}, "show help" },
3610
    { "version", 0, {(void*)show_version}, "show version" },
3611
    { "formats", 0, {(void*)show_formats}, "show available formats, codecs, protocols, ..." },
3612
    { "f", HAS_ARG, {(void*)opt_format}, "force format", "fmt" },
3613
    { "img", HAS_ARG, {(void*)opt_image_format}, "force image format", "img_fmt" },
3614
    { "i", HAS_ARG, {(void*)opt_input_file}, "input file name", "filename" },
3615
    { "y", OPT_BOOL, {(void*)&file_overwrite}, "overwrite output files" },
3616
    { "map", HAS_ARG | OPT_EXPERT, {(void*)opt_map}, "set input stream mapping", "file:stream" },
3617
    { "t", HAS_ARG, {(void*)opt_recording_time}, "set the recording time", "duration" },
3618
    { "ss", HAS_ARG, {(void*)opt_start_time}, "set the start time offset", "time_off" },
3619
    { "itsoffset", HAS_ARG, {(void*)opt_input_ts_offset}, "set the input ts offset", "time_off" },
3620
    { "title", HAS_ARG | OPT_STRING, {(void*)&str_title}, "set the title", "string" },
3621
    { "timestamp", HAS_ARG, {(void*)&opt_rec_timestamp}, "set the timestamp", "time" },
3622
    { "author", HAS_ARG | OPT_STRING, {(void*)&str_author}, "set the author", "string" },
3623
    { "copyright", HAS_ARG | OPT_STRING, {(void*)&str_copyright}, "set the copyright", "string" },
3624
    { "comment", HAS_ARG | OPT_STRING, {(void*)&str_comment}, "set the comment", "string" },
3625
    { "debug", HAS_ARG | OPT_EXPERT, {(void*)opt_debug}, "print specific debug info", "" },
3626
    { "vismv", HAS_ARG | OPT_EXPERT, {(void*)opt_vismv}, "visualize motion vectors", "" },
3627
    { "benchmark", OPT_BOOL | OPT_EXPERT, {(void*)&do_benchmark}, 
3628
      "add timings for benchmarking" },
3629
    { "dump", OPT_BOOL | OPT_EXPERT, {(void*)&do_pkt_dump}, 
3630
      "dump each input packet" },
3631
    { "hex", OPT_BOOL | OPT_EXPERT, {(void*)&do_hex_dump}, 
3632
      "when dumping packets, also dump the payload" },
3633
    { "bitexact", OPT_EXPERT, {(void*)opt_bitexact}, "only use bit exact algorithms (for codec testing)" }, 
3634
    { "re", OPT_BOOL | OPT_EXPERT, {(void*)&rate_emu}, "read input at native frame rate", "" },
3635
    { "loop", OPT_BOOL | OPT_EXPERT, {(void*)&loop_input}, "loop (current only works with images)" },
3636
    { "v", HAS_ARG, {(void*)opt_verbose}, "control amount of logging", "verbose" },
3637
    { "target", HAS_ARG, {(void*)opt_target}, "specify target file type (\"vcd\", \"svcd\" or \"dvd\")", "type" },
3638
    { "threads", HAS_ARG | OPT_EXPERT, {(void*)opt_thread_count}, "thread count", "count" },
3639
    { "vsync", HAS_ARG | OPT_INT | OPT_EXPERT, {(void*)&video_sync_method}, "video sync method", "" },
3640
    { "async", HAS_ARG | OPT_INT | OPT_EXPERT, {(void*)&audio_sync_method}, "audio sync method", "" },
3641
    { "copyts", OPT_BOOL | OPT_EXPERT, {(void*)&copy_ts}, "copy timestamps" },
3642

    
3643
    /* video options */
3644
    { "b", HAS_ARG | OPT_VIDEO, {(void*)opt_video_bitrate}, "set video bitrate (in kbit/s)", "bitrate" },
3645
    { "r", HAS_ARG | OPT_VIDEO, {(void*)opt_frame_rate}, "set frame rate (Hz value, fraction or abbreviation)", "rate" },
3646
    { "s", HAS_ARG | OPT_VIDEO, {(void*)opt_frame_size}, "set frame size (WxH or abbreviation)", "size" },
3647
    { "aspect", HAS_ARG | OPT_VIDEO, {(void*)opt_frame_aspect_ratio}, "set aspect ratio (4:3, 16:9 or 1.3333, 1.7777)", "aspect" },
3648
    { "pix_fmt", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_frame_pix_fmt}, "set pixel format", "format" },
3649
    { "croptop", HAS_ARG | OPT_VIDEO, {(void*)opt_frame_crop_top}, "set top crop band size (in pixels)", "size" },
3650
    { "cropbottom", HAS_ARG | OPT_VIDEO, {(void*)opt_frame_crop_bottom}, "set bottom crop band size (in pixels)", "size" },
3651
    { "cropleft", HAS_ARG | OPT_VIDEO, {(void*)opt_frame_crop_left}, "set left crop band size (in pixels)", "size" },
3652
    { "cropright", HAS_ARG | OPT_VIDEO, {(void*)opt_frame_crop_right}, "set right crop band size (in pixels)", "size" },
3653
    { "padtop", HAS_ARG | OPT_VIDEO, {(void*)opt_frame_pad_top}, "set top pad band size (in pixels)", "size" },
3654
    { "padbottom", HAS_ARG | OPT_VIDEO, {(void*)opt_frame_pad_bottom}, "set bottom pad band size (in pixels)", "size" },
3655
    { "padleft", HAS_ARG | OPT_VIDEO, {(void*)opt_frame_pad_left}, "set left pad band size (in pixels)", "size" },
3656
    { "padright", HAS_ARG | OPT_VIDEO, {(void*)opt_frame_pad_right}, "set right pad band size (in pixels)", "size" },
3657
    { "padcolor", HAS_ARG | OPT_VIDEO, {(void*)opt_pad_color}, "set color of pad bands (Hex 000000 thru FFFFFF)", "color" },
3658
    { "g", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_gop_size}, "set the group of picture size", "gop_size" },
3659
    { "intra", OPT_BOOL | OPT_EXPERT | OPT_VIDEO, {(void*)&intra_only}, "use only intra frames"},
3660
    { "vn", OPT_BOOL | OPT_VIDEO, {(void*)&video_disable}, "disable video" },
3661
    { "qscale", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_qscale}, "use fixed video quantiser scale (VBR)", "q" },
3662
    { "qmin", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_qmin}, "min video quantiser scale (VBR)", "q" },
3663
    { "qmax", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_qmax}, "max video quantiser scale (VBR)", "q" },
3664
    { "lmin", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_lmin}, "min video lagrange factor (VBR)", "lambda" },
3665
    { "lmax", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_lmax}, "max video lagrange factor (VBR)", "lambda" },
3666
    { "mbqmin", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_mb_qmin}, "min macroblock quantiser scale (VBR)", "q" },
3667
    { "mbqmax", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_mb_qmax}, "max macroblock quantiser scale (VBR)", "q" },
3668
    { "qdiff", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_qdiff}, "max difference between the quantiser scale (VBR)", "q" },
3669
    { "qblur", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_qblur}, "video quantiser scale blur (VBR)", "blur" },
3670
    { "qcomp", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_qcomp}, "video quantiser scale compression (VBR)", "compression" },
3671
    { "rc_init_cplx", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_rc_initial_cplx}, "initial complexity for 1-pass encoding", "complexity" },
3672
    { "b_qfactor", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_b_qfactor}, "qp factor between p and b frames", "factor" },
3673
    { "i_qfactor", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_i_qfactor}, "qp factor between p and i frames", "factor" },
3674
    { "b_qoffset", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_b_qoffset}, "qp offset between p and b frames", "offset" },
3675
    { "i_qoffset", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_i_qoffset}, "qp offset between p and i frames", "offset" },
3676
    { "ibias", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_ibias}, "intra quant bias", "bias" },
3677
    { "pbias", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_pbias}, "inter quant bias", "bias" },
3678
//    { "b_strategy", HAS_ARG | OPT_EXPERT, {(void*)opt_b_strategy}, "dynamic b frame selection strategy", "strategy" },
3679
    { "rc_eq", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_video_rc_eq}, "set rate control equation", "equation" },
3680
    { "rc_override", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_video_rc_override_string}, "rate control override for specific intervals", "override" },
3681
    { "bt", HAS_ARG | OPT_VIDEO, {(void*)opt_video_bitrate_tolerance}, "set video bitrate tolerance (in kbit/s)", "tolerance" },
3682
    { "maxrate", HAS_ARG | OPT_VIDEO, {(void*)opt_video_bitrate_max}, "set max video bitrate tolerance (in kbit/s)", "bitrate" },
3683
    { "minrate", HAS_ARG | OPT_VIDEO, {(void*)opt_video_bitrate_min}, "set min video bitrate tolerance (in kbit/s)", "bitrate" },
3684
    { "bufsize", HAS_ARG | OPT_VIDEO, {(void*)opt_video_buffer_size}, "set ratecontrol buffere size (in kByte)", "size" },
3685
    { "vcodec", HAS_ARG | OPT_VIDEO, {(void*)opt_video_codec}, "force video codec ('copy' to copy stream)", "codec" },
3686
    { "me", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_motion_estimation}, "set motion estimation method", 
3687
      "method" },
3688
    { "dct_algo", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_dct_algo}, "set dct algo",  "algo" },
3689
    { "idct_algo", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_idct_algo}, "set idct algo",  "algo" },
3690
    { "me_threshold", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_me_threshold}, "motion estimaton threshold",  "" },
3691
    { "mb_threshold", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_mb_threshold}, "macroblock threshold",  "" },
3692
    { "er", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_error_resilience}, "set error resilience",  "n" },
3693
    { "ec", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_error_concealment}, "set error concealment",  "bit_mask" },
3694
    { "bf", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_b_frames}, "use 'frames' B frames", "frames" },
3695
    { "hq", OPT_BOOL, {(void*)&mb_decision}, "activate high quality settings" },
3696
    { "mbd", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_mb_decision}, "macroblock decision", "mode" },
3697
    { "mbcmp", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_mb_cmp}, "macroblock compare function", "cmp function" },
3698
    { "ildctcmp", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_ildct_cmp}, "ildct compare function", "cmp function" },
3699
    { "subcmp", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_sub_cmp}, "subpel compare function", "cmp function" },
3700
    { "cmp", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_cmp}, "fullpel compare function", "cmp function" },
3701
    { "precmp", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_pre_cmp}, "pre motion estimation compare function", "cmp function" },
3702
    { "preme", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_pre_me}, "pre motion estimation", "" },
3703
    { "lumi_mask", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_lumi_mask}, "luminance masking", "" },
3704
    { "dark_mask", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_dark_mask}, "darkness masking", "" },
3705
    { "scplx_mask", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_scplx_mask}, "spatial complexity masking", "" },
3706
    { "tcplx_mask", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_tcplx_mask}, "teporal complexity masking", "" },
3707
    { "p_mask", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_p_mask}, "inter masking", "" },
3708
    { "4mv", OPT_BOOL | OPT_EXPERT | OPT_VIDEO, {(void*)&use_4mv}, "use four motion vector by macroblock (MPEG4)" },
3709
    { "obmc", OPT_BOOL | OPT_EXPERT | OPT_VIDEO, {(void*)&use_obmc}, "use overlapped block motion compensation (h263+)" },
3710
    { "lf", OPT_BOOL | OPT_EXPERT | OPT_VIDEO, {(void*)&use_loop}, "use loop filter (h263+)" },
3711
    { "part", OPT_BOOL | OPT_EXPERT | OPT_VIDEO, {(void*)&use_part}, "use data partitioning (MPEG4)" },
3712
    { "bug", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_workaround_bugs}, "workaround not auto detected encoder bugs", "param" },
3713
    { "ps", HAS_ARG | OPT_EXPERT, {(void*)opt_packet_size}, "set packet size in bits", "size" },
3714
    { "error", HAS_ARG | OPT_EXPERT, {(void*)opt_error_rate}, "error rate", "rate" },
3715
    { "strict", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_strict}, "how strictly to follow the standards", "strictness" },
3716
    { "sameq", OPT_BOOL | OPT_VIDEO, {(void*)&same_quality}, 
3717
      "use same video quality as source (implies VBR)" },
3718
    { "pass", HAS_ARG | OPT_VIDEO, {(void*)&opt_pass}, "select the pass number (1 or 2)", "n" },
3719
    { "passlogfile", HAS_ARG | OPT_STRING | OPT_VIDEO, {(void*)&pass_logfilename}, "select two pass log file name", "file" },
3720
    { "deinterlace", OPT_BOOL | OPT_EXPERT | OPT_VIDEO, {(void*)&do_deinterlace}, 
3721
      "deinterlace pictures" },
3722
    { "ildct", OPT_BOOL | OPT_EXPERT | OPT_VIDEO, {(void*)&do_interlace_dct}, 
3723
      "force interlaced dct support in encoder (MPEG2/MPEG4)" },
3724
    { "ilme", OPT_BOOL | OPT_EXPERT | OPT_VIDEO, {(void*)&do_interlace_me}, 
3725
      "force interlaced me support in encoder (MPEG2/MPEG4)" },
3726
    { "psnr", OPT_BOOL | OPT_EXPERT | OPT_VIDEO, {(void*)&do_psnr}, "calculate PSNR of compressed frames" },
3727
    { "vstats", OPT_BOOL | OPT_EXPERT | OPT_VIDEO, {(void*)&do_vstats}, "dump video coding statistics to file" }, 
3728
    { "vhook", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)add_frame_hooker}, "insert video processing module", "module" },
3729
    { "aic", OPT_BOOL | OPT_EXPERT | OPT_VIDEO, {(void*)&use_aic}, "enable Advanced intra coding (h263+)" },
3730
    { "aiv", OPT_BOOL | OPT_EXPERT | OPT_VIDEO, {(void*)&use_aiv}, "enable Alternative inter vlc (h263+)" },
3731
    { "umv", OPT_BOOL | OPT_EXPERT | OPT_VIDEO, {(void*)&use_umv}, "enable Unlimited Motion Vector (h263+)" },
3732
    { "ssm", OPT_BOOL | OPT_EXPERT | OPT_VIDEO, {(void*)&use_ss}, "enable Slice Structured mode (h263+)" },
3733
    { "alt", OPT_BOOL | OPT_EXPERT | OPT_VIDEO, {(void*)&use_alt_scan}, "enable alternate scantable (MPEG2/MPEG4)" },
3734
    { "qprd", OPT_BOOL | OPT_EXPERT | OPT_VIDEO, {(void*)&use_qprd}, "" },
3735
    { "cbp", OPT_BOOL | OPT_EXPERT | OPT_VIDEO, {(void*)&use_cbprd}, "" },
3736
    { "trell", OPT_BOOL | OPT_EXPERT | OPT_VIDEO, {(void*)&use_trell}, "enable trellis quantization" },
3737
    { "cgop", OPT_BOOL | OPT_EXPERT | OPT_VIDEO, {(void*)&closed_gop}, "closed gop" },
3738
    { "scan_offset", OPT_BOOL | OPT_EXPERT | OPT_VIDEO, {(void*)&use_scan_offset}, "enable SVCD Scan Offset placeholder" },
3739
    { "qpel", OPT_BOOL | OPT_EXPERT | OPT_VIDEO, {(void*)&use_qpel}, "enable 1/4-pel" },
3740
    { "intra_matrix", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_intra_matrix}, "specify intra matrix coeffs", "matrix" },
3741
    { "inter_matrix", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_inter_matrix}, "specify inter matrix coeffs", "matrix" },
3742
    { "top", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_top_field_first}, "top=1/bottom=0/auto=-1 field first", "" },
3743
    { "nr", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_noise_reduction}, "noise reduction", "" },
3744
    { "qns", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_qns}, "quantization noise shaping", "" },
3745
    { "sc_threshold", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_sc_threshold}, "scene change threshold", "threshold" },
3746
    { "me_range", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_me_range}, "limit motion vectors range (1023 for DivX player)", "range" },
3747
    { "dc", OPT_INT | HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)&intra_dc_precision}, "intra_dc_precision", "precision" },
3748
    { "coder", OPT_INT | HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)&coder}, "coder type", "" },
3749
    { "context", OPT_INT | HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)&context}, "context model", "" },
3750
    { "pred", OPT_INT | HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)&predictor}, "prediction method", "" },
3751

    
3752
    /* audio options */
3753
    { "ab", HAS_ARG | OPT_AUDIO, {(void*)opt_audio_bitrate}, "set audio bitrate (in kbit/s)", "bitrate", },
3754
    { "ar", HAS_ARG | OPT_AUDIO, {(void*)opt_audio_rate}, "set audio sampling rate (in Hz)", "rate" },
3755
    { "ac", HAS_ARG | OPT_AUDIO, {(void*)opt_audio_channels}, "set number of audio channels", "channels" },
3756
    { "an", OPT_BOOL | OPT_AUDIO, {(void*)&audio_disable}, "disable audio" },
3757
    { "acodec", HAS_ARG | OPT_AUDIO, {(void*)opt_audio_codec}, "force audio codec ('copy' to copy stream)", "codec" },
3758

    
3759
    /* grab options */
3760
    { "vd", HAS_ARG | OPT_EXPERT | OPT_VIDEO | OPT_GRAB, {(void*)opt_video_device}, "set video grab device", "device" },
3761
    { "vc", HAS_ARG | OPT_EXPERT | OPT_VIDEO | OPT_GRAB, {(void*)opt_video_channel}, "set video grab channel (DV1394 only)", "channel" },
3762
    { "tvstd", HAS_ARG | OPT_EXPERT | OPT_VIDEO | OPT_GRAB, {(void*)opt_video_standard}, "set television standard (NTSC, PAL (SECAM))", "standard" },
3763
    { "dv1394", OPT_EXPERT | OPT_GRAB, {(void*)opt_dv1394}, "set DV1394 grab", "" },
3764
    { "ad", HAS_ARG | OPT_EXPERT | OPT_AUDIO | OPT_GRAB, {(void*)opt_audio_device}, "set audio device", "device" },
3765
    { NULL, },
3766
};
3767

    
3768
static void show_banner(void)
3769
{
3770
    printf("ffmpeg version " FFMPEG_VERSION ", build %d, Copyright (c) 2000-2004 Fabrice Bellard\n",
3771
        LIBAVCODEC_BUILD);
3772
    printf("  built on " __DATE__ " " __TIME__);
3773
#ifdef __GNUC__
3774
    printf(", using gcc %d.%d.%d\n",
3775
        __GNUC__, __GNUC_MINOR__, __GNUC_PATCHLEVEL__);
3776
#else
3777
    printf(", using a non-gcc compiler\n");
3778
#endif
3779
}
3780

    
3781
static void show_license(void)
3782
{
3783
    show_banner();
3784
#ifdef CONFIG_GPL
3785
    printf(
3786
    "This program is free software; you can redistribute it and/or modify\n"   
3787
    "it under the terms of the GNU General Public License as published by\n"
3788
    "the Free Software Foundation; either version 2 of the License, or\n"
3789
    "(at your option) any later version.\n"
3790
    "\n"
3791
    "This program is distributed in the hope that it will be useful,\n"
3792
    "but WITHOUT ANY WARRANTY; without even the implied warranty of\n"
3793
    "MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n"
3794
    "GNU General Public License for more details.\n"
3795
    "\n"
3796
    "You should have received a copy of the GNU General Public License\n"
3797
    "along with this program; if not, write to the Free Software\n"
3798
    "Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA\n"
3799
    );
3800
#else
3801
    printf(
3802
    "This library is free software; you can redistribute it and/or\n"
3803
    "modify it under the terms of the GNU Lesser General Public\n"
3804
    "License as published by the Free Software Foundation; either\n"
3805
    "version 2 of the License, or (at your option) any later version.\n"
3806
    "\n"
3807
    "This library is distributed in the hope that it will be useful,\n"
3808
    "but WITHOUT ANY WARRANTY; without even the implied warranty of\n"
3809
    "MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n"
3810
    "Lesser General Public License for more details.\n"
3811
    "\n"
3812
    "You should have received a copy of the GNU Lesser General Public\n"
3813
    "License along with this library; if not, write to the Free Software\n"
3814
    "Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA\n"
3815
    );
3816
#endif
3817
    exit(1);
3818
}
3819

    
3820
static void show_help(void)
3821
{
3822
    show_banner();
3823
    printf("usage: ffmpeg [[options] -i input_file]... {[options] outfile}...\n"
3824
           "Hyper fast Audio and Video encoder\n");
3825
    printf("\n");
3826
    show_help_options(options, "Main options:\n",
3827
                      OPT_EXPERT | OPT_AUDIO | OPT_VIDEO, 0);
3828
    show_help_options(options, "\nVideo options:\n",
3829
                      OPT_EXPERT | OPT_AUDIO | OPT_VIDEO | OPT_GRAB, 
3830
                      OPT_VIDEO);
3831
    show_help_options(options, "\nAdvanced Video options:\n",
3832
                      OPT_EXPERT | OPT_AUDIO | OPT_VIDEO | OPT_GRAB, 
3833
                      OPT_VIDEO | OPT_EXPERT);
3834
    show_help_options(options, "\nAudio options:\n",
3835
                      OPT_EXPERT | OPT_AUDIO | OPT_VIDEO | OPT_GRAB, 
3836
                      OPT_AUDIO);
3837
    show_help_options(options, "\nAdvanced Audio options:\n",
3838
                      OPT_EXPERT | OPT_AUDIO | OPT_VIDEO | OPT_GRAB, 
3839
                      OPT_AUDIO | OPT_EXPERT);
3840
    show_help_options(options, "\nAudio/Video grab options:\n",
3841
                      OPT_GRAB, 
3842
                      OPT_GRAB);
3843
    show_help_options(options, "\nAdvanced options:\n",
3844
                      OPT_EXPERT | OPT_AUDIO | OPT_VIDEO | OPT_GRAB, 
3845
                      OPT_EXPERT);
3846
    exit(1);
3847
}
3848

    
3849
void parse_arg_file(const char *filename)
3850
{
3851
    opt_output_file(filename);
3852
}
3853

    
3854
int main(int argc, char **argv)
3855
{
3856
    int i;
3857
    int64_t ti;
3858

    
3859
    av_register_all();
3860

    
3861
    if (argc <= 1)
3862
        show_help();
3863
    else
3864
        show_banner();
3865
    
3866
    /* parse options */
3867
    parse_options(argc, argv, options);
3868

    
3869
    /* file converter / grab */
3870
    if (nb_output_files <= 0) {
3871
        fprintf(stderr, "Must supply at least one output file\n");
3872
        exit(1);
3873
    }
3874
    
3875
    if (nb_input_files == 0) {
3876
        input_sync = 1;
3877
        prepare_grab();
3878
    }
3879

    
3880
    ti = getutime();
3881
    av_encode(output_files, nb_output_files, input_files, nb_input_files, 
3882
              stream_maps, nb_stream_maps);
3883
    ti = getutime() - ti;
3884
    if (do_benchmark) {
3885
        printf("bench: utime=%0.3fs\n", ti / 1000000.0);
3886
    }
3887

    
3888
    /* close files */
3889
    for(i=0;i<nb_output_files;i++) {
3890
        /* maybe av_close_output_file ??? */
3891
        AVFormatContext *s = output_files[i];
3892
        int j;
3893
        if (!(s->oformat->flags & AVFMT_NOFILE))
3894
            url_fclose(&s->pb);
3895
        for(j=0;j<s->nb_streams;j++)
3896
            av_free(s->streams[j]);
3897
        av_free(s);
3898
    }
3899
    for(i=0;i<nb_input_files;i++)
3900
        av_close_input_file(input_files[i]);
3901

    
3902
    av_free_static();
3903

    
3904
    if(intra_matrix)
3905
        av_free(intra_matrix);
3906
    if(inter_matrix)
3907
        av_free(inter_matrix);
3908
    
3909
#ifdef POWERPC_PERFORMANCE_REPORT
3910
    extern void powerpc_display_perf_report(void);
3911
    powerpc_display_perf_report();
3912
#endif /* POWERPC_PERFORMANCE_REPORT */
3913

    
3914
#ifndef CONFIG_WIN32
3915
    if (received_sigterm) {
3916
        fprintf(stderr,
3917
            "Received signal %d: terminating.\n",
3918
            (int) received_sigterm);
3919
        exit (255);
3920
    }
3921
#endif
3922
    exit(0); /* not all OS-es handle main() return value */
3923
    return 0;
3924
}