Statistics
| Branch: | Revision:

ffmpeg / ffmpeg.c @ 0888fd22

History | View | Annotate | Download (148 KB)

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

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

    
43
#include "cmdutils.h"
44

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

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

    
52
/* select an input stream for an output stream */
53
typedef struct AVStreamMap {
54
    int file_index;
55
    int stream_index;
56
    int sync_file_index;
57
    int sync_stream_index;
58
} AVStreamMap;
59

    
60
/** select an input file for an output file */
61
typedef struct AVMetaDataMap {
62
    int out_file;
63
    int in_file;
64
} AVMetaDataMap;
65

    
66
extern const OptionDef options[];
67

    
68
static void show_help(void);
69
static void show_license(void);
70
static int opt_default(const char *opt, const char *arg);
71

    
72
#define MAX_FILES 20
73

    
74
static AVFormatContext *input_files[MAX_FILES];
75
static int64_t input_files_ts_offset[MAX_FILES];
76
static int nb_input_files = 0;
77

    
78
static AVFormatContext *output_files[MAX_FILES];
79
static int nb_output_files = 0;
80

    
81
static AVStreamMap stream_maps[MAX_FILES];
82
static int nb_stream_maps;
83

    
84
static AVMetaDataMap meta_data_maps[MAX_FILES];
85
static int nb_meta_data_maps;
86

    
87
static AVInputFormat *file_iformat;
88
static AVOutputFormat *file_oformat;
89
static AVImageFormat *image_format;
90
static int frame_width  = 0;
91
static int frame_height = 0;
92
static float frame_aspect_ratio = 0;
93
static enum PixelFormat frame_pix_fmt = PIX_FMT_NONE;
94
static int frame_padtop  = 0;
95
static int frame_padbottom = 0;
96
static int frame_padleft  = 0;
97
static int frame_padright = 0;
98
static int padcolor[3] = {16,128,128}; /* default to black */
99
static int frame_topBand  = 0;
100
static int frame_bottomBand = 0;
101
static int frame_leftBand  = 0;
102
static int frame_rightBand = 0;
103
static int max_frames[4] = {INT_MAX, INT_MAX, INT_MAX, INT_MAX};
104
static int frame_rate = 25;
105
static int frame_rate_base = 1;
106
static int video_bit_rate = 200*1000;
107
static int video_bit_rate_tolerance = 4000*1000;
108
static float video_qscale = 0;
109
static int video_qmin = 2;
110
static int video_qmax = 31;
111
static int video_lmin = 2*FF_QP2LAMBDA;
112
static int video_lmax = 31*FF_QP2LAMBDA;
113
static int video_mb_lmin = 2*FF_QP2LAMBDA;
114
static int video_mb_lmax = 31*FF_QP2LAMBDA;
115
static int video_qdiff = 3;
116
static float video_qblur = 0.5;
117
static float video_qsquish = 0.0;
118
static float video_qcomp = 0.5;
119
static uint16_t *intra_matrix = NULL;
120
static uint16_t *inter_matrix = NULL;
121
#if 0 //experimental, (can be removed)
122
static float video_rc_qsquish=1.0;
123
static float video_rc_qmod_amp=0;
124
static int video_rc_qmod_freq=0;
125
#endif
126
static char *video_rc_override_string=NULL;
127
static char *video_rc_eq="tex^qComp";
128
static int video_rc_buffer_size=0;
129
static float video_rc_buffer_aggressivity=1.0;
130
static int video_rc_max_rate=0;
131
static int video_rc_min_rate=0;
132
static float video_rc_initial_cplx=0;
133
static float video_b_qfactor = 1.25;
134
static float video_b_qoffset = 1.25;
135
static float video_i_qfactor = -0.8;
136
static float video_i_qoffset = 0.0;
137
static int video_intra_quant_bias= FF_DEFAULT_QUANT_BIAS;
138
static int video_inter_quant_bias= FF_DEFAULT_QUANT_BIAS;
139
static int me_method = ME_EPZS;
140
static int video_disable = 0;
141
static int video_discard = 0;
142
static int video_codec_id = CODEC_ID_NONE;
143
static int video_codec_tag = 0;
144
static int same_quality = 0;
145
static int b_frames = 0;
146
static int b_strategy = 0;
147
static int pre_me = 0;
148
static int do_deinterlace = 0;
149
static int workaround_bugs = FF_BUG_AUTODETECT;
150
static int packet_size = 0;
151
static int error_rate = 0;
152
static int strict = 0;
153
static int top_field_first = -1;
154
static int sc_threshold = 0;
155
static int me_threshold = 0;
156
static int mb_threshold = 0;
157
static int intra_dc_precision = 8;
158
static int me_penalty_compensation= 256;
159
static int frame_skip_threshold= 0;
160
static int frame_skip_factor= 0;
161
static int frame_skip_exp= 0;
162
extern int loop_input; /* currently a hack */
163
static int loop_output = AVFMT_NOOUTPUTLOOP;
164
static int genpts = 0;
165
static int qp_hist = 0;
166

    
167
static int gop_size = 12;
168
static int intra_only = 0;
169
static int audio_sample_rate = 44100;
170
static int audio_bit_rate = 64000;
171
#define QSCALE_NONE -99999
172
static float audio_qscale = QSCALE_NONE;
173
static int audio_disable = 0;
174
static int audio_channels = 1;
175
static int audio_codec_id = CODEC_ID_NONE;
176
static int audio_codec_tag = 0;
177
static char *audio_language = NULL;
178

    
179
static int subtitle_codec_id = CODEC_ID_NONE;
180
static char *subtitle_language = NULL;
181

    
182
static int mux_rate= 0;
183
static int mux_packet_size= 0;
184
static float mux_preload= 0.5;
185
static float mux_max_delay= 0.7;
186

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

    
212
static int rate_emu = 0;
213

    
214
#ifdef CONFIG_BKTR
215
static char *video_grab_format = "bktr";
216
#else
217
static char *video_grab_format = "video4linux";
218
#endif
219
static char *video_device = NULL;
220
static char *grab_device = NULL;
221
static int  video_channel = 0;
222
static char *video_standard = "ntsc";
223

    
224
static char *audio_grab_format = "audio_device";
225
static char *audio_device = NULL;
226
static int audio_volume = 256;
227

    
228
static int using_stdin = 0;
229
static int using_vhook = 0;
230
static int verbose = 1;
231
static int thread_count= 1;
232
static int q_pressed = 0;
233
static int me_range = 0;
234
static int64_t video_size = 0;
235
static int64_t audio_size = 0;
236
static int64_t extra_size = 0;
237
static int nb_frames_dup = 0;
238
static int nb_frames_drop = 0;
239
static int input_sync;
240
static int limit_filesize = 0; //
241

    
242
static int pgmyuv_compatibility_hack=0;
243

    
244
const char **opt_names=NULL;
245
int opt_name_count=0;
246
AVCodecContext *avctx_opts;
247

    
248

    
249
#define DEFAULT_PASS_LOGFILENAME "ffmpeg2pass"
250

    
251
struct AVInputStream;
252

    
253
typedef struct AVOutputStream {
254
    int file_index;          /* file index */
255
    int index;               /* stream index in the output file */
256
    int source_index;        /* AVInputStream index */
257
    AVStream *st;            /* stream in the output file */
258
    int encoding_needed;     /* true if encoding needed for this stream */
259
    int frame_number;
260
    /* input pts and corresponding output pts
261
       for A/V sync */
262
    //double sync_ipts;        /* dts from the AVPacket of the demuxer in second units */
263
    struct AVInputStream *sync_ist; /* input stream to sync against */
264
    int64_t sync_opts;       /* output frame counter, could be changed to some true timestamp */ //FIXME look at frame_number
265
    /* video only */
266
    int video_resample;      /* video_resample and video_crop are mutually exclusive */
267
    AVFrame pict_tmp;      /* temporary image for resampling */
268
    ImgReSampleContext *img_resample_ctx; /* for image resampling */
269

    
270
    int video_crop;          /* video_resample and video_crop are mutually exclusive */
271
    int topBand;             /* cropping area sizes */
272
    int leftBand;
273

    
274
    int video_pad;           /* video_resample and video_pad are mutually exclusive */
275
    int padtop;              /* padding area sizes */
276
    int padbottom;
277
    int padleft;
278
    int padright;
279

    
280
    /* audio only */
281
    int audio_resample;
282
    ReSampleContext *resample; /* for audio resampling */
283
    FifoBuffer fifo;     /* for compression: one audio fifo per codec */
284
    FILE *logfile;
285
} AVOutputStream;
286

    
287
typedef struct AVInputStream {
288
    int file_index;
289
    int index;
290
    AVStream *st;
291
    int discard;             /* true if stream data should be discarded */
292
    int decoding_needed;     /* true if the packets must be decoded in 'raw_fifo' */
293
    int64_t sample_index;      /* current sample */
294

    
295
    int64_t       start;     /* time when read started */
296
    unsigned long frame;     /* current frame */
297
    int64_t       next_pts;  /* synthetic pts for cases where pkt.pts
298
                                is not defined */
299
    int64_t       pts;       /* current pts */
300
    int is_start;            /* is 1 at the start and after a discontinuity */
301
} AVInputStream;
302

    
303
typedef struct AVInputFile {
304
    int eof_reached;      /* true if eof reached */
305
    int ist_index;        /* index of first stream in ist_table */
306
    int buffer_size;      /* current total buffer size */
307
    int buffer_size_max;  /* buffer size at which we consider we can stop
308
                             buffering */
309
    int nb_streams;       /* nb streams we are aware of */
310
} AVInputFile;
311

    
312
#ifndef CONFIG_WIN32
313

    
314
/* init terminal so that we can grab keys */
315
static struct termios oldtty;
316

    
317
static void term_exit(void)
318
{
319
    tcsetattr (0, TCSANOW, &oldtty);
320
}
321

    
322
static volatile sig_atomic_t received_sigterm = 0;
323

    
324
static void
325
sigterm_handler(int sig)
326
{
327
    received_sigterm = sig;
328
    term_exit();
329
}
330

    
331
static void term_init(void)
332
{
333
    struct termios tty;
334

    
335
    tcgetattr (0, &tty);
336
    oldtty = tty;
337

    
338
    tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
339
                          |INLCR|IGNCR|ICRNL|IXON);
340
    tty.c_oflag |= OPOST;
341
    tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
342
    tty.c_cflag &= ~(CSIZE|PARENB);
343
    tty.c_cflag |= CS8;
344
    tty.c_cc[VMIN] = 1;
345
    tty.c_cc[VTIME] = 0;
346

    
347
    tcsetattr (0, TCSANOW, &tty);
348

    
349
    signal(SIGINT , sigterm_handler); /* Interrupt (ANSI).  */
350
    signal(SIGQUIT, sigterm_handler); /* Quit (POSIX).  */
351
    signal(SIGTERM, sigterm_handler); /* Termination (ANSI).  */
352
    /*
353
    register a function to be called at normal program termination
354
    */
355
    atexit(term_exit);
356
#ifdef CONFIG_BEOS_NETSERVER
357
    fcntl(0, F_SETFL, fcntl(0, F_GETFL) | O_NONBLOCK);
358
#endif
359
}
360

    
361
/* read a key without blocking */
362
static int read_key(void)
363
{
364
    int n = 1;
365
    unsigned char ch;
366
#ifndef CONFIG_BEOS_NETSERVER
367
    struct timeval tv;
368
    fd_set rfds;
369

    
370
    FD_ZERO(&rfds);
371
    FD_SET(0, &rfds);
372
    tv.tv_sec = 0;
373
    tv.tv_usec = 0;
374
    n = select(1, &rfds, NULL, NULL, &tv);
375
#endif
376
    if (n > 0) {
377
        n = read(0, &ch, 1);
378
        if (n == 1)
379
            return ch;
380

    
381
        return n;
382
    }
383
    return -1;
384
}
385

    
386
static int decode_interrupt_cb(void)
387
{
388
    return q_pressed || (q_pressed = read_key() == 'q');
389
}
390

    
391
#else
392

    
393
static volatile int received_sigterm = 0;
394

    
395
/* no interactive support */
396
static void term_exit(void)
397
{
398
}
399

    
400
static void term_init(void)
401
{
402
}
403

    
404
static int read_key(void)
405
{
406
    return 0;
407
}
408

    
409
#endif
410

    
411
static int read_ffserver_streams(AVFormatContext *s, const char *filename)
412
{
413
    int i, err;
414
    AVFormatContext *ic;
415

    
416
    err = av_open_input_file(&ic, filename, NULL, FFM_PACKET_SIZE, NULL);
417
    if (err < 0)
418
        return err;
419
    /* copy stream format */
420
    s->nb_streams = ic->nb_streams;
421
    for(i=0;i<ic->nb_streams;i++) {
422
        AVStream *st;
423

    
424
        // FIXME: a more elegant solution is needed
425
        st = av_mallocz(sizeof(AVStream));
426
        memcpy(st, ic->streams[i], sizeof(AVStream));
427
        st->codec = avcodec_alloc_context();
428
        memcpy(st->codec, ic->streams[i]->codec, sizeof(AVCodecContext));
429
        s->streams[i] = st;
430
    }
431

    
432
    av_close_input_file(ic);
433
    return 0;
434
}
435

    
436
static double
437
get_sync_ipts(const AVOutputStream *ost)
438
{
439
    const AVInputStream *ist = ost->sync_ist;
440
    return (double)(ist->pts + input_files_ts_offset[ist->file_index] - start_time)/AV_TIME_BASE;
441
}
442

    
443
#define MAX_AUDIO_PACKET_SIZE (128 * 1024)
444

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

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

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

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

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

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

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

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

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

    
530
        frame_bytes = enc->frame_size * 2 * enc->channels;
531

    
532
        while (fifo_read(&ost->fifo, audio_buf, frame_bytes,
533
                     &ost->fifo.rptr) == 0) {
534
            AVPacket pkt;
535
            av_init_packet(&pkt);
536

    
537
            ret = avcodec_encode_audio(enc, audio_out, audio_out_size,
538
                                       (short *)audio_buf);
539
            audio_size += ret;
540
            pkt.stream_index= ost->index;
541
            pkt.data= audio_out;
542
            pkt.size= ret;
543
            if(enc->coded_frame && enc->coded_frame->pts != AV_NOPTS_VALUE)
544
                pkt.pts= av_rescale_q(enc->coded_frame->pts, enc->time_base, ost->st->time_base);
545
            pkt.flags |= PKT_FLAG_KEY;
546
            av_interleaved_write_frame(s, &pkt);
547

    
548
            ost->sync_opts += enc->frame_size;
549
        }
550
    } else {
551
        AVPacket pkt;
552
        av_init_packet(&pkt);
553

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

    
556
        /* output a pcm frame */
557
        /* XXX: change encoding codec API to avoid this ? */
558
        switch(enc->codec->id) {
559
        case CODEC_ID_PCM_S32LE:
560
        case CODEC_ID_PCM_S32BE:
561
        case CODEC_ID_PCM_U32LE:
562
        case CODEC_ID_PCM_U32BE:
563
            size_out = size_out << 1;
564
            break;
565
        case CODEC_ID_PCM_S24LE:
566
        case CODEC_ID_PCM_S24BE:
567
        case CODEC_ID_PCM_U24LE:
568
        case CODEC_ID_PCM_U24BE:
569
        case CODEC_ID_PCM_S24DAUD:
570
            size_out = size_out / 2 * 3;
571
            break;
572
        case CODEC_ID_PCM_S16LE:
573
        case CODEC_ID_PCM_S16BE:
574
        case CODEC_ID_PCM_U16LE:
575
        case CODEC_ID_PCM_U16BE:
576
            break;
577
        default:
578
            size_out = size_out >> 1;
579
            break;
580
        }
581
        ret = avcodec_encode_audio(enc, audio_out, size_out,
582
                                   (short *)buftmp);
583
        audio_size += ret;
584
        pkt.stream_index= ost->index;
585
        pkt.data= audio_out;
586
        pkt.size= ret;
587
        if(enc->coded_frame && enc->coded_frame->pts != AV_NOPTS_VALUE)
588
            pkt.pts= av_rescale_q(enc->coded_frame->pts, enc->time_base, ost->st->time_base);
589
        pkt.flags |= PKT_FLAG_KEY;
590
        av_interleaved_write_frame(s, &pkt);
591
    }
592
}
593

    
594
static void pre_process_video_frame(AVInputStream *ist, AVPicture *picture, void **bufp)
595
{
596
    AVCodecContext *dec;
597
    AVPicture *picture2;
598
    AVPicture picture_tmp;
599
    uint8_t *buf = 0;
600

    
601
    dec = ist->st->codec;
602

    
603
    /* deinterlace : must be done before any resize */
604
    if (do_deinterlace || using_vhook) {
605
        int size;
606

    
607
        /* create temporary picture */
608
        size = avpicture_get_size(dec->pix_fmt, dec->width, dec->height);
609
        buf = av_malloc(size);
610
        if (!buf)
611
            return;
612

    
613
        picture2 = &picture_tmp;
614
        avpicture_fill(picture2, buf, dec->pix_fmt, dec->width, dec->height);
615

    
616
        if (do_deinterlace){
617
            if(avpicture_deinterlace(picture2, picture,
618
                                     dec->pix_fmt, dec->width, dec->height) < 0) {
619
                /* if error, do not deinterlace */
620
                av_free(buf);
621
                buf = NULL;
622
                picture2 = picture;
623
            }
624
        } else {
625
            if (img_convert(picture2, dec->pix_fmt, picture,
626
                            dec->pix_fmt, dec->width, dec->height) < 0) {
627
                /* if error, do not copy */
628
                av_free(buf);
629
                buf = NULL;
630
                picture2 = picture;
631
            }
632
        }
633
    } else {
634
        picture2 = picture;
635
    }
636

    
637
    frame_hook_process(picture2, dec->pix_fmt, dec->width, dec->height);
638

    
639
    if (picture != picture2)
640
        *picture = *picture2;
641
    *bufp = buf;
642
}
643

    
644
/* we begin to correct av delay at this threshold */
645
#define AV_DELAY_MAX 0.100
646

    
647

    
648
/* Expects img to be yuv420 */
649
static void fill_pad_region(AVPicture* img, int height, int width,
650
        int padtop, int padbottom, int padleft, int padright, int *color) {
651

    
652
    int i, y, shift;
653
    uint8_t *optr;
654

    
655
    for (i = 0; i < 3; i++) {
656
        shift = (i == 0) ? 0 : 1;
657

    
658
        if (padtop || padleft) {
659
            memset(img->data[i], color[i], (((img->linesize[i] * padtop) +
660
                            padleft) >> shift));
661
        }
662

    
663
        if (padleft || padright) {
664
            optr = img->data[i] + (img->linesize[i] * (padtop >> shift)) +
665
                (img->linesize[i] - (padright >> shift));
666

    
667
            for (y = 0; y < ((height - (padtop + padbottom) - 1) >> shift); y++) {
668
                memset(optr, color[i], (padleft + padright) >> shift);
669
                optr += img->linesize[i];
670
            }
671
        }
672

    
673
        if (padbottom || padright) {
674
            optr = img->data[i] + (((img->linesize[i] * (height - padbottom)) - padright) >> shift);
675
            memset(optr, color[i], (((img->linesize[i] * padbottom) + padright) >> shift));
676
        }
677
    }
678
}
679

    
680
static void do_subtitle_out(AVFormatContext *s,
681
                            AVOutputStream *ost,
682
                            AVInputStream *ist,
683
                            AVSubtitle *sub,
684
                            int64_t pts)
685
{
686
    static uint8_t *subtitle_out = NULL;
687
    int subtitle_out_max_size = 65536;
688
    int subtitle_out_size, nb, i;
689
    AVCodecContext *enc;
690
    AVPacket pkt;
691

    
692
    if (pts == AV_NOPTS_VALUE) {
693
        fprintf(stderr, "Subtitle packets must have a pts\n");
694
        return;
695
    }
696

    
697
    enc = ost->st->codec;
698

    
699
    if (!subtitle_out) {
700
        subtitle_out = av_malloc(subtitle_out_max_size);
701
    }
702

    
703
    /* Note: DVB subtitle need one packet to draw them and one other
704
       packet to clear them */
705
    /* XXX: signal it in the codec context ? */
706
    if (enc->codec_id == CODEC_ID_DVB_SUBTITLE)
707
        nb = 2;
708
    else
709
        nb = 1;
710

    
711
    for(i = 0; i < nb; i++) {
712
        subtitle_out_size = avcodec_encode_subtitle(enc, subtitle_out,
713
                                                    subtitle_out_max_size, sub);
714

    
715
        av_init_packet(&pkt);
716
        pkt.stream_index = ost->index;
717
        pkt.data = subtitle_out;
718
        pkt.size = subtitle_out_size;
719
        pkt.pts = av_rescale_q(av_rescale_q(pts, ist->st->time_base, AV_TIME_BASE_Q) + input_files_ts_offset[ist->file_index], AV_TIME_BASE_Q,  ost->st->time_base);
720
        if (enc->codec_id == CODEC_ID_DVB_SUBTITLE) {
721
            /* XXX: the pts correction is handled here. Maybe handling
722
               it in the codec would be better */
723
            if (i == 0)
724
                pkt.pts += 90 * sub->start_display_time;
725
            else
726
                pkt.pts += 90 * sub->end_display_time;
727
        }
728
        av_interleaved_write_frame(s, &pkt);
729
    }
730
}
731

    
732
static int bit_buffer_size= 1024*256;
733
static uint8_t *bit_buffer= NULL;
734

    
735
static void do_video_out(AVFormatContext *s,
736
                         AVOutputStream *ost,
737
                         AVInputStream *ist,
738
                         AVFrame *in_picture,
739
                         int *frame_size)
740
{
741
    int nb_frames, i, ret;
742
    AVFrame *final_picture, *formatted_picture;
743
    AVFrame picture_format_temp, picture_crop_temp;
744
    uint8_t *buf = NULL, *buf1 = NULL;
745
    AVCodecContext *enc, *dec;
746
    enum PixelFormat target_pixfmt;
747

    
748
    avcodec_get_frame_defaults(&picture_format_temp);
749
    avcodec_get_frame_defaults(&picture_crop_temp);
750

    
751
    enc = ost->st->codec;
752
    dec = ist->st->codec;
753

    
754
    /* by default, we output a single frame */
755
    nb_frames = 1;
756

    
757
    *frame_size = 0;
758

    
759
    if(video_sync_method){
760
        double vdelta;
761
        vdelta = get_sync_ipts(ost) / av_q2d(enc->time_base) - ost->sync_opts;
762
        //FIXME set to 0.5 after we fix some dts/pts bugs like in avidec.c
763
        if (vdelta < -1.1)
764
            nb_frames = 0;
765
        else if (vdelta > 1.1)
766
            nb_frames = lrintf(vdelta);
767
//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);
768
        if (nb_frames == 0){
769
            ++nb_frames_drop;
770
            if (verbose>2)
771
                fprintf(stderr, "*** drop!\n");
772
        }else if (nb_frames > 1) {
773
            nb_frames_dup += nb_frames;
774
            if (verbose>2)
775
                fprintf(stderr, "*** %d dup!\n", nb_frames-1);
776
        }
777
    }else
778
        ost->sync_opts= lrintf(get_sync_ipts(ost) / av_q2d(enc->time_base));
779

    
780
    nb_frames= FFMIN(nb_frames, max_frames[CODEC_TYPE_VIDEO] - ost->frame_number);
781
    if (nb_frames <= 0)
782
        return;
783

    
784
    /* convert pixel format if needed */
785
    target_pixfmt = ost->video_resample || ost->video_pad
786
        ? PIX_FMT_YUV420P : enc->pix_fmt;
787
    if (dec->pix_fmt != target_pixfmt) {
788
        int size;
789

    
790
        /* create temporary picture */
791
        size = avpicture_get_size(target_pixfmt, dec->width, dec->height);
792
        buf = av_malloc(size);
793
        if (!buf)
794
            return;
795
        formatted_picture = &picture_format_temp;
796
        avpicture_fill((AVPicture*)formatted_picture, buf, target_pixfmt, dec->width, dec->height);
797

    
798
        if (img_convert((AVPicture*)formatted_picture, target_pixfmt,
799
                        (AVPicture *)in_picture, dec->pix_fmt,
800
                        dec->width, dec->height) < 0) {
801

    
802
            if (verbose >= 0)
803
                fprintf(stderr, "pixel format conversion not handled\n");
804

    
805
            goto the_end;
806
        }
807
    } else {
808
        formatted_picture = in_picture;
809
    }
810

    
811
    /* XXX: resampling could be done before raw format conversion in
812
       some cases to go faster */
813
    /* XXX: only works for YUV420P */
814
    if (ost->video_resample) {
815
        final_picture = &ost->pict_tmp;
816
        img_resample(ost->img_resample_ctx, (AVPicture*)final_picture, (AVPicture*)formatted_picture);
817

    
818
        if (ost->padtop || ost->padbottom || ost->padleft || ost->padright) {
819
            fill_pad_region((AVPicture*)final_picture, enc->height, enc->width,
820
                    ost->padtop, ost->padbottom, ost->padleft, ost->padright,
821
                    padcolor);
822
        }
823

    
824
        if (enc->pix_fmt != PIX_FMT_YUV420P) {
825
            int size;
826

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

    
836
            if (img_convert((AVPicture*)final_picture, enc->pix_fmt,
837
                            (AVPicture*)&ost->pict_tmp, PIX_FMT_YUV420P,
838
                            enc->width, enc->height) < 0) {
839

    
840
                if (verbose >= 0)
841
                    fprintf(stderr, "pixel format conversion not handled\n");
842

    
843
                goto the_end;
844
            }
845
        }
846
    } else if (ost->video_crop) {
847
        picture_crop_temp.data[0] = formatted_picture->data[0] +
848
                (ost->topBand * formatted_picture->linesize[0]) + ost->leftBand;
849

    
850
        picture_crop_temp.data[1] = formatted_picture->data[1] +
851
                ((ost->topBand >> 1) * formatted_picture->linesize[1]) +
852
                (ost->leftBand >> 1);
853

    
854
        picture_crop_temp.data[2] = formatted_picture->data[2] +
855
                ((ost->topBand >> 1) * formatted_picture->linesize[2]) +
856
                (ost->leftBand >> 1);
857

    
858
        picture_crop_temp.linesize[0] = formatted_picture->linesize[0];
859
        picture_crop_temp.linesize[1] = formatted_picture->linesize[1];
860
        picture_crop_temp.linesize[2] = formatted_picture->linesize[2];
861
        final_picture = &picture_crop_temp;
862
    } else if (ost->video_pad) {
863
        final_picture = &ost->pict_tmp;
864

    
865
        for (i = 0; i < 3; i++) {
866
            uint8_t *optr, *iptr;
867
            int shift = (i == 0) ? 0 : 1;
868
            int y, yheight;
869

    
870
            /* set offset to start writing image into */
871
            optr = final_picture->data[i] + (((final_picture->linesize[i] *
872
                            ost->padtop) + ost->padleft) >> shift);
873
            iptr = formatted_picture->data[i];
874

    
875
            yheight = (enc->height - ost->padtop - ost->padbottom) >> shift;
876
            for (y = 0; y < yheight; y++) {
877
                /* copy unpadded image row into padded image row */
878
                memcpy(optr, iptr, formatted_picture->linesize[i]);
879
                optr += final_picture->linesize[i];
880
                iptr += formatted_picture->linesize[i];
881
            }
882
        }
883

    
884
        fill_pad_region((AVPicture*)final_picture, enc->height, enc->width,
885
                ost->padtop, ost->padbottom, ost->padleft, ost->padright,
886
                padcolor);
887

    
888
        if (enc->pix_fmt != PIX_FMT_YUV420P) {
889
            int size;
890

    
891
            av_free(buf);
892
            /* create temporary picture */
893
            size = avpicture_get_size(enc->pix_fmt, enc->width, enc->height);
894
            buf = av_malloc(size);
895
            if (!buf)
896
                return;
897
            final_picture = &picture_format_temp;
898
            avpicture_fill((AVPicture*)final_picture, buf, enc->pix_fmt, enc->width, enc->height);
899

    
900
            if (img_convert((AVPicture*)final_picture, enc->pix_fmt,
901
                        (AVPicture*)&ost->pict_tmp, PIX_FMT_YUV420P,
902
                        enc->width, enc->height) < 0) {
903

    
904
                if (verbose >= 0)
905
                    fprintf(stderr, "pixel format conversion not handled\n");
906

    
907
                goto the_end;
908
            }
909
        }
910
    } else {
911
        final_picture = formatted_picture;
912
    }
913
    /* duplicates frame if needed */
914
    for(i=0;i<nb_frames;i++) {
915
        AVPacket pkt;
916
        av_init_packet(&pkt);
917
        pkt.stream_index= ost->index;
918

    
919
        if (s->oformat->flags & AVFMT_RAWPICTURE) {
920
            /* raw pictures are written as AVPicture structure to
921
               avoid any copies. We support temorarily the older
922
               method. */
923
            AVFrame* old_frame = enc->coded_frame;
924
            enc->coded_frame = dec->coded_frame; //FIXME/XXX remove this hack
925
            pkt.data= (uint8_t *)final_picture;
926
            pkt.size=  sizeof(AVPicture);
927
            if(dec->coded_frame && enc->coded_frame->pts != AV_NOPTS_VALUE)
928
                pkt.pts= av_rescale_q(enc->coded_frame->pts, enc->time_base, ost->st->time_base);
929
            if(dec->coded_frame && dec->coded_frame->key_frame)
930
                pkt.flags |= PKT_FLAG_KEY;
931

    
932
            av_interleaved_write_frame(s, &pkt);
933
            enc->coded_frame = old_frame;
934
        } else {
935
            AVFrame big_picture;
936

    
937
            big_picture= *final_picture;
938
            /* better than nothing: use input picture interlaced
939
               settings */
940
            big_picture.interlaced_frame = in_picture->interlaced_frame;
941
            if(avctx_opts->flags & (CODEC_FLAG_INTERLACED_DCT|CODEC_FLAG_INTERLACED_ME)){
942
                if(top_field_first == -1)
943
                    big_picture.top_field_first = in_picture->top_field_first;
944
                else
945
                    big_picture.top_field_first = top_field_first;
946
            }
947

    
948
            /* handles sameq here. This is not correct because it may
949
               not be a global option */
950
            if (same_quality) {
951
                big_picture.quality = ist->st->quality;
952
            }else
953
                big_picture.quality = ost->st->quality;
954
            if(!me_threshold)
955
                big_picture.pict_type = 0;
956
//            big_picture.pts = AV_NOPTS_VALUE;
957
            big_picture.pts= ost->sync_opts;
958
//            big_picture.pts= av_rescale(ost->sync_opts, AV_TIME_BASE*(int64_t)enc->time_base.num, enc->time_base.den);
959
//av_log(NULL, AV_LOG_DEBUG, "%lld -> encoder\n", ost->sync_opts);
960
            ret = avcodec_encode_video(enc,
961
                                       bit_buffer, bit_buffer_size,
962
                                       &big_picture);
963
            //enc->frame_number = enc->real_pict_num;
964
            if(ret>0){
965
                pkt.data= bit_buffer;
966
                pkt.size= ret;
967
                if(enc->coded_frame && enc->coded_frame->pts != AV_NOPTS_VALUE)
968
                    pkt.pts= av_rescale_q(enc->coded_frame->pts, enc->time_base, ost->st->time_base);
969
/*av_log(NULL, AV_LOG_DEBUG, "encoder -> %lld/%lld\n",
970
   pkt.pts != AV_NOPTS_VALUE ? av_rescale(pkt.pts, enc->time_base.den, AV_TIME_BASE*(int64_t)enc->time_base.num) : -1,
971
   pkt.dts != AV_NOPTS_VALUE ? av_rescale(pkt.dts, enc->time_base.den, AV_TIME_BASE*(int64_t)enc->time_base.num) : -1);*/
972

    
973
                if(enc->coded_frame && enc->coded_frame->key_frame)
974
                    pkt.flags |= PKT_FLAG_KEY;
975
                av_interleaved_write_frame(s, &pkt);
976
                *frame_size = ret;
977
                //fprintf(stderr,"\nFrame: %3d %3d size: %5d type: %d",
978
                //        enc->frame_number-1, enc->real_pict_num, ret,
979
                //        enc->pict_type);
980
                /* if two pass, output log */
981
                if (ost->logfile && enc->stats_out) {
982
                    fprintf(ost->logfile, "%s", enc->stats_out);
983
                }
984
            }
985
        }
986
        ost->sync_opts++;
987
        ost->frame_number++;
988
    }
989
 the_end:
990
    av_free(buf);
991
    av_free(buf1);
992
}
993

    
994
static double psnr(double d){
995
    if(d==0) return INFINITY;
996
    return -10.0*log(d)/log(10.0);
997
}
998

    
999
static void do_video_stats(AVFormatContext *os, AVOutputStream *ost,
1000
                           int frame_size)
1001
{
1002
    static FILE *fvstats=NULL;
1003
    char filename[40];
1004
    time_t today2;
1005
    struct tm *today;
1006
    AVCodecContext *enc;
1007
    int frame_number;
1008
    int64_t ti;
1009
    double ti1, bitrate, avg_bitrate;
1010

    
1011
    if (!fvstats) {
1012
        today2 = time(NULL);
1013
        today = localtime(&today2);
1014
        snprintf(filename, sizeof(filename), "vstats_%02d%02d%02d.log", today->tm_hour,
1015
                                               today->tm_min,
1016
                                               today->tm_sec);
1017
        fvstats = fopen(filename,"w");
1018
        if (!fvstats) {
1019
            perror("fopen");
1020
            exit(1);
1021
        }
1022
    }
1023

    
1024
    ti = MAXINT64;
1025
    enc = ost->st->codec;
1026
    if (enc->codec_type == CODEC_TYPE_VIDEO) {
1027
        frame_number = ost->frame_number;
1028
        fprintf(fvstats, "frame= %5d q= %2.1f ", frame_number, enc->coded_frame->quality/(float)FF_QP2LAMBDA);
1029
        if (enc->flags&CODEC_FLAG_PSNR)
1030
            fprintf(fvstats, "PSNR= %6.2f ", psnr(enc->coded_frame->error[0]/(enc->width*enc->height*255.0*255.0)));
1031

    
1032
        fprintf(fvstats,"f_size= %6d ", frame_size);
1033
        /* compute pts value */
1034
        ti1 = ost->sync_opts * av_q2d(enc->time_base);
1035
        if (ti1 < 0.01)
1036
            ti1 = 0.01;
1037

    
1038
        bitrate = (frame_size * 8) / av_q2d(enc->time_base) / 1000.0;
1039
        avg_bitrate = (double)(video_size * 8) / ti1 / 1000.0;
1040
        fprintf(fvstats, "s_size= %8.0fkB time= %0.3f br= %7.1fkbits/s avg_br= %7.1fkbits/s ",
1041
            (double)video_size / 1024, ti1, bitrate, avg_bitrate);
1042
        fprintf(fvstats,"type= %c\n", av_get_pict_type_char(enc->coded_frame->pict_type));
1043
    }
1044
}
1045

    
1046
static void print_report(AVFormatContext **output_files,
1047
                         AVOutputStream **ost_table, int nb_ostreams,
1048
                         int is_last_report)
1049
{
1050
    char buf[1024];
1051
    AVOutputStream *ost;
1052
    AVFormatContext *oc, *os;
1053
    int64_t total_size;
1054
    AVCodecContext *enc;
1055
    int frame_number, vid, i;
1056
    double bitrate, ti1, pts;
1057
    static int64_t last_time = -1;
1058
    static int qp_histogram[52];
1059

    
1060
    if (!is_last_report) {
1061
        int64_t cur_time;
1062
        /* display the report every 0.5 seconds */
1063
        cur_time = av_gettime();
1064
        if (last_time == -1) {
1065
            last_time = cur_time;
1066
            return;
1067
        }
1068
        if ((cur_time - last_time) < 500000)
1069
            return;
1070
        last_time = cur_time;
1071
    }
1072

    
1073

    
1074
    oc = output_files[0];
1075

    
1076
    total_size = url_ftell(&oc->pb);
1077

    
1078
    buf[0] = '\0';
1079
    ti1 = 1e10;
1080
    vid = 0;
1081
    for(i=0;i<nb_ostreams;i++) {
1082
        ost = ost_table[i];
1083
        os = output_files[ost->file_index];
1084
        enc = ost->st->codec;
1085
        if (vid && enc->codec_type == CODEC_TYPE_VIDEO) {
1086
            snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "q=%2.1f ",
1087
                    enc->coded_frame->quality/(float)FF_QP2LAMBDA);
1088
        }
1089
        if (!vid && enc->codec_type == CODEC_TYPE_VIDEO) {
1090
            frame_number = ost->frame_number;
1091
            snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "frame=%5d q=%3.1f ",
1092
                    frame_number, enc->coded_frame ? enc->coded_frame->quality/(float)FF_QP2LAMBDA : -1);
1093
            if(is_last_report)
1094
                snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "L");
1095
            if(qp_hist && enc->coded_frame){
1096
                int j;
1097
                int qp= lrintf(enc->coded_frame->quality/(float)FF_QP2LAMBDA);
1098
                if(qp>=0 && qp<sizeof(qp_histogram)/sizeof(int))
1099
                    qp_histogram[qp]++;
1100
                for(j=0; j<32; j++)
1101
                    snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "%X", (int)lrintf(log(qp_histogram[j]+1)/log(2)));
1102
            }
1103
            if (enc->flags&CODEC_FLAG_PSNR){
1104
                int j;
1105
                double error, error_sum=0;
1106
                double scale, scale_sum=0;
1107
                char type[3]= {'Y','U','V'};
1108
                snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "PSNR=");
1109
                for(j=0; j<3; j++){
1110
                    if(is_last_report){
1111
                        error= enc->error[j];
1112
                        scale= enc->width*enc->height*255.0*255.0*frame_number;
1113
                    }else{
1114
                        error= enc->coded_frame->error[j];
1115
                        scale= enc->width*enc->height*255.0*255.0;
1116
                    }
1117
                    if(j) scale/=4;
1118
                    error_sum += error;
1119
                    scale_sum += scale;
1120
                    snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "%c:%2.2f ", type[j], psnr(error/scale));
1121
                }
1122
                snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "*:%2.2f ", psnr(error_sum/scale_sum));
1123
            }
1124
            vid = 1;
1125
        }
1126
        /* compute min output value */
1127
        pts = (double)ost->st->pts.val * ost->st->time_base.num / ost->st->time_base.den;
1128
        if ((pts < ti1) && (pts > 0))
1129
            ti1 = pts;
1130
    }
1131
    if (ti1 < 0.01)
1132
        ti1 = 0.01;
1133

    
1134
    if (verbose || is_last_report) {
1135
        bitrate = (double)(total_size * 8) / ti1 / 1000.0;
1136

    
1137
        snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
1138
            "size=%8.0fkB time=%0.1f bitrate=%6.1fkbits/s",
1139
            (double)total_size / 1024, ti1, bitrate);
1140

    
1141
        if (verbose > 1)
1142
          snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), " dup=%d drop=%d",
1143
                  nb_frames_dup, nb_frames_drop);
1144

    
1145
        if (verbose >= 0)
1146
            fprintf(stderr, "%s    \r", buf);
1147

    
1148
        fflush(stderr);
1149
    }
1150

    
1151
    if (is_last_report && verbose >= 0){
1152
        int64_t raw= audio_size + video_size + extra_size;
1153
        fprintf(stderr, "\n");
1154
        fprintf(stderr, "video:%1.0fkB audio:%1.0fkB global headers:%1.0fkB muxing overhead %f%%\n",
1155
                video_size/1024.0,
1156
                audio_size/1024.0,
1157
                extra_size/1024.0,
1158
                100.0*(total_size - raw)/raw
1159
        );
1160
    }
1161
}
1162

    
1163
/* pkt = NULL means EOF (needed to flush decoder buffers) */
1164
static int output_packet(AVInputStream *ist, int ist_index,
1165
                         AVOutputStream **ost_table, int nb_ostreams,
1166
                         const AVPacket *pkt)
1167
{
1168
    AVFormatContext *os;
1169
    AVOutputStream *ost;
1170
    uint8_t *ptr;
1171
    int len, ret, i;
1172
    uint8_t *data_buf;
1173
    int data_size, got_picture;
1174
    AVFrame picture;
1175
    void *buffer_to_free;
1176
    static int samples_size= 0;
1177
    static short *samples= NULL;
1178
    AVSubtitle subtitle, *subtitle_to_free;
1179
    int got_subtitle;
1180

    
1181
    if(!pkt){
1182
        ist->pts= ist->next_pts; // needed for last packet if vsync=0
1183
    } else if (pkt->dts != AV_NOPTS_VALUE) { //FIXME seems redundant, as libavformat does this too
1184
        ist->next_pts = ist->pts = av_rescale_q(pkt->dts, ist->st->time_base, AV_TIME_BASE_Q);
1185
    } else {
1186
//        assert(ist->pts == ist->next_pts);
1187
    }
1188

    
1189
    if (pkt == NULL) {
1190
        /* EOF handling */
1191
        ptr = NULL;
1192
        len = 0;
1193
        goto handle_eof;
1194
    }
1195

    
1196
    len = pkt->size;
1197
    ptr = pkt->data;
1198
    while (len > 0) {
1199
    handle_eof:
1200
        /* decode the packet if needed */
1201
        data_buf = NULL; /* fail safe */
1202
        data_size = 0;
1203
        subtitle_to_free = NULL;
1204
        if (ist->decoding_needed) {
1205
            switch(ist->st->codec->codec_type) {
1206
            case CODEC_TYPE_AUDIO:{
1207
                if(pkt)
1208
                    samples= av_fast_realloc(samples, &samples_size, FFMAX(pkt->size, AVCODEC_MAX_AUDIO_FRAME_SIZE));
1209
                    /* XXX: could avoid copy if PCM 16 bits with same
1210
                       endianness as CPU */
1211
                ret = avcodec_decode_audio(ist->st->codec, samples, &data_size,
1212
                                           ptr, len);
1213
                if (ret < 0)
1214
                    goto fail_decode;
1215
                ptr += ret;
1216
                len -= ret;
1217
                /* Some bug in mpeg audio decoder gives */
1218
                /* data_size < 0, it seems they are overflows */
1219
                if (data_size <= 0) {
1220
                    /* no audio frame */
1221
                    continue;
1222
                }
1223
                data_buf = (uint8_t *)samples;
1224
                ist->next_pts += ((int64_t)AV_TIME_BASE/2 * data_size) /
1225
                    (ist->st->codec->sample_rate * ist->st->codec->channels);
1226
                break;}
1227
            case CODEC_TYPE_VIDEO:
1228
                    data_size = (ist->st->codec->width * ist->st->codec->height * 3) / 2;
1229
                    /* XXX: allocate picture correctly */
1230
                    avcodec_get_frame_defaults(&picture);
1231

    
1232
                    ret = avcodec_decode_video(ist->st->codec,
1233
                                               &picture, &got_picture, ptr, len);
1234
                    ist->st->quality= picture.quality;
1235
                    if (ret < 0)
1236
                        goto fail_decode;
1237
                    if (!got_picture) {
1238
                        /* no picture yet */
1239
                        goto discard_packet;
1240
                    }
1241
                    if (ist->st->codec->time_base.num != 0) {
1242
                        ist->next_pts += ((int64_t)AV_TIME_BASE *
1243
                                          ist->st->codec->time_base.num) /
1244
                            ist->st->codec->time_base.den;
1245
                    }
1246
                    len = 0;
1247
                    break;
1248
            case CODEC_TYPE_SUBTITLE:
1249
                ret = avcodec_decode_subtitle(ist->st->codec,
1250
                                              &subtitle, &got_subtitle, ptr, len);
1251
                if (ret < 0)
1252
                    goto fail_decode;
1253
                if (!got_subtitle) {
1254
                    goto discard_packet;
1255
                }
1256
                subtitle_to_free = &subtitle;
1257
                len = 0;
1258
                break;
1259
            default:
1260
                goto fail_decode;
1261
            }
1262
        } else {
1263
                switch(ist->st->codec->codec_type) {
1264
                case CODEC_TYPE_AUDIO:
1265
                    ist->next_pts += ((int64_t)AV_TIME_BASE * ist->st->codec->frame_size) /
1266
                        (ist->st->codec->sample_rate * ist->st->codec->channels);
1267
                    break;
1268
                case CODEC_TYPE_VIDEO:
1269
                    if (ist->st->codec->time_base.num != 0) {
1270
                        ist->next_pts += ((int64_t)AV_TIME_BASE *
1271
                                          ist->st->codec->time_base.num) /
1272
                            ist->st->codec->time_base.den;
1273
                    }
1274
                    break;
1275
                }
1276
                data_buf = ptr;
1277
                data_size = len;
1278
                ret = len;
1279
                len = 0;
1280
            }
1281

    
1282
            buffer_to_free = NULL;
1283
            if (ist->st->codec->codec_type == CODEC_TYPE_VIDEO) {
1284
                pre_process_video_frame(ist, (AVPicture *)&picture,
1285
                                        &buffer_to_free);
1286
            }
1287

    
1288
            // preprocess audio (volume)
1289
            if (ist->st->codec->codec_type == CODEC_TYPE_AUDIO) {
1290
                if (audio_volume != 256) {
1291
                    short *volp;
1292
                    volp = samples;
1293
                    for(i=0;i<(data_size / sizeof(short));i++) {
1294
                        int v = ((*volp) * audio_volume + 128) >> 8;
1295
                        if (v < -32768) v = -32768;
1296
                        if (v >  32767) v = 32767;
1297
                        *volp++ = v;
1298
                    }
1299
                }
1300
            }
1301

    
1302
            /* frame rate emulation */
1303
            if (ist->st->codec->rate_emu) {
1304
                int64_t pts = av_rescale((int64_t) ist->frame * ist->st->codec->time_base.num, 1000000, ist->st->codec->time_base.den);
1305
                int64_t now = av_gettime() - ist->start;
1306
                if (pts > now)
1307
                    usleep(pts - now);
1308

    
1309
                ist->frame++;
1310
            }
1311

    
1312
#if 0
1313
            /* mpeg PTS deordering : if it is a P or I frame, the PTS
1314
               is the one of the next displayed one */
1315
            /* XXX: add mpeg4 too ? */
1316
            if (ist->st->codec->codec_id == CODEC_ID_MPEG1VIDEO) {
1317
                if (ist->st->codec->pict_type != B_TYPE) {
1318
                    int64_t tmp;
1319
                    tmp = ist->last_ip_pts;
1320
                    ist->last_ip_pts  = ist->frac_pts.val;
1321
                    ist->frac_pts.val = tmp;
1322
                }
1323
            }
1324
#endif
1325
            /* if output time reached then transcode raw format,
1326
               encode packets and output them */
1327
            if (start_time == 0 || ist->pts >= start_time)
1328
                for(i=0;i<nb_ostreams;i++) {
1329
                    int frame_size;
1330

    
1331
                    ost = ost_table[i];
1332
                    if (ost->source_index == ist_index) {
1333
                        os = output_files[ost->file_index];
1334

    
1335
#if 0
1336
                        printf("%d: got pts=%0.3f %0.3f\n", i,
1337
                               (double)pkt->pts / AV_TIME_BASE,
1338
                               ((double)ist->pts / AV_TIME_BASE) -
1339
                               ((double)ost->st->pts.val * ost->st->time_base.num / ost->st->time_base.den));
1340
#endif
1341
                        /* set the input output pts pairs */
1342
                        //ost->sync_ipts = (double)(ist->pts + input_files_ts_offset[ist->file_index] - start_time)/ AV_TIME_BASE;
1343

    
1344
                        if (ost->encoding_needed) {
1345
                            switch(ost->st->codec->codec_type) {
1346
                            case CODEC_TYPE_AUDIO:
1347
                                do_audio_out(os, ost, ist, data_buf, data_size);
1348
                                break;
1349
                            case CODEC_TYPE_VIDEO:
1350
                                    do_video_out(os, ost, ist, &picture, &frame_size);
1351
                                    video_size += frame_size;
1352
                                    if (do_vstats && frame_size)
1353
                                        do_video_stats(os, ost, frame_size);
1354
                                break;
1355
                            case CODEC_TYPE_SUBTITLE:
1356
                                do_subtitle_out(os, ost, ist, &subtitle,
1357
                                                pkt->pts);
1358
                                break;
1359
                            default:
1360
                                av_abort();
1361
                            }
1362
                        } else {
1363
                            AVFrame avframe; //FIXME/XXX remove this
1364
                            AVPacket opkt;
1365
                            av_init_packet(&opkt);
1366

    
1367
                            /* no reencoding needed : output the packet directly */
1368
                            /* force the input stream PTS */
1369

    
1370
                            avcodec_get_frame_defaults(&avframe);
1371
                            ost->st->codec->coded_frame= &avframe;
1372
                            avframe.key_frame = pkt->flags & PKT_FLAG_KEY;
1373

    
1374
                            if(ost->st->codec->codec_type == CODEC_TYPE_AUDIO)
1375
                                audio_size += data_size;
1376
                            else if (ost->st->codec->codec_type == CODEC_TYPE_VIDEO) {
1377
                                video_size += data_size;
1378
                                ost->sync_opts++;
1379
                            }
1380

    
1381
                            opkt.stream_index= ost->index;
1382
                            if(pkt->pts != AV_NOPTS_VALUE)
1383
                                opkt.pts= av_rescale_q(av_rescale_q(pkt->pts, ist->st->time_base, AV_TIME_BASE_Q) + input_files_ts_offset[ist->file_index], AV_TIME_BASE_Q,  ost->st->time_base);
1384
                            else
1385
                                opkt.pts= AV_NOPTS_VALUE;
1386

    
1387
                            {
1388
                                int64_t dts;
1389
                                if (pkt->dts == AV_NOPTS_VALUE)
1390
                                    dts = ist->next_pts;
1391
                                else
1392
                                    dts= av_rescale_q(pkt->dts, ist->st->time_base, AV_TIME_BASE_Q);
1393
                                opkt.dts= av_rescale_q(dts + input_files_ts_offset[ist->file_index], AV_TIME_BASE_Q,  ost->st->time_base);
1394
                            }
1395
                            opkt.flags= pkt->flags;
1396
                            if(av_parser_change(ist->st->parser, ost->st->codec, &opkt.data, &opkt.size, data_buf, data_size, pkt->flags & PKT_FLAG_KEY))
1397
                                opkt.destruct= av_destruct_packet;
1398
                            av_interleaved_write_frame(os, &opkt);
1399
                            ost->st->codec->frame_number++;
1400
                            ost->frame_number++;
1401
                            av_free_packet(&opkt);
1402
                        }
1403
                    }
1404
                }
1405
            av_free(buffer_to_free);
1406
            /* XXX: allocate the subtitles in the codec ? */
1407
            if (subtitle_to_free) {
1408
                if (subtitle_to_free->rects != NULL) {
1409
                    for (i = 0; i < subtitle_to_free->num_rects; i++) {
1410
                        av_free(subtitle_to_free->rects[i].bitmap);
1411
                        av_free(subtitle_to_free->rects[i].rgba_palette);
1412
                    }
1413
                    av_freep(&subtitle_to_free->rects);
1414
                }
1415
                subtitle_to_free->num_rects = 0;
1416
                subtitle_to_free = NULL;
1417
            }
1418
        }
1419
 discard_packet:
1420
    if (pkt == NULL) {
1421
        /* EOF handling */
1422

    
1423
        for(i=0;i<nb_ostreams;i++) {
1424
            ost = ost_table[i];
1425
            if (ost->source_index == ist_index) {
1426
                AVCodecContext *enc= ost->st->codec;
1427
                os = output_files[ost->file_index];
1428

    
1429
                if(ost->st->codec->codec_type == CODEC_TYPE_AUDIO && enc->frame_size <=1)
1430
                    continue;
1431
                if(ost->st->codec->codec_type == CODEC_TYPE_VIDEO && (os->oformat->flags & AVFMT_RAWPICTURE))
1432
                    continue;
1433

    
1434
                if (ost->encoding_needed) {
1435
                    for(;;) {
1436
                        AVPacket pkt;
1437
                        av_init_packet(&pkt);
1438
                        pkt.stream_index= ost->index;
1439

    
1440
                        switch(ost->st->codec->codec_type) {
1441
                        case CODEC_TYPE_AUDIO:
1442
                            ret = avcodec_encode_audio(enc, bit_buffer, bit_buffer_size, NULL);
1443
                            audio_size += ret;
1444
                            pkt.flags |= PKT_FLAG_KEY;
1445
                            break;
1446
                        case CODEC_TYPE_VIDEO:
1447
                            ret = avcodec_encode_video(enc, bit_buffer, bit_buffer_size, NULL);
1448
                            video_size += ret;
1449
                            if(enc->coded_frame && enc->coded_frame->key_frame)
1450
                                pkt.flags |= PKT_FLAG_KEY;
1451
                            if (ost->logfile && enc->stats_out) {
1452
                                fprintf(ost->logfile, "%s", enc->stats_out);
1453
                            }
1454
                            break;
1455
                        default:
1456
                            ret=-1;
1457
                        }
1458

    
1459
                        if(ret<=0)
1460
                            break;
1461
                        pkt.data= bit_buffer;
1462
                        pkt.size= ret;
1463
                        if(enc->coded_frame && enc->coded_frame->pts != AV_NOPTS_VALUE)
1464
                            pkt.pts= av_rescale_q(enc->coded_frame->pts, enc->time_base, ost->st->time_base);
1465
                        av_interleaved_write_frame(os, &pkt);
1466
                    }
1467
                }
1468
            }
1469
        }
1470
    }
1471

    
1472
    return 0;
1473
 fail_decode:
1474
    return -1;
1475
}
1476

    
1477

    
1478
/*
1479
 * The following code is the main loop of the file converter
1480
 */
1481
static int av_encode(AVFormatContext **output_files,
1482
                     int nb_output_files,
1483
                     AVFormatContext **input_files,
1484
                     int nb_input_files,
1485
                     AVStreamMap *stream_maps, int nb_stream_maps)
1486
{
1487
    int ret, i, j, k, n, nb_istreams = 0, nb_ostreams = 0;
1488
    AVFormatContext *is, *os;
1489
    AVCodecContext *codec, *icodec;
1490
    AVOutputStream *ost, **ost_table = NULL;
1491
    AVInputStream *ist, **ist_table = NULL;
1492
    AVInputFile *file_table;
1493
    AVFormatContext *stream_no_data;
1494
    int key;
1495

    
1496
    file_table= (AVInputFile*) av_mallocz(nb_input_files * sizeof(AVInputFile));
1497
    if (!file_table)
1498
        goto fail;
1499

    
1500
    /* input stream init */
1501
    j = 0;
1502
    for(i=0;i<nb_input_files;i++) {
1503
        is = input_files[i];
1504
        file_table[i].ist_index = j;
1505
        file_table[i].nb_streams = is->nb_streams;
1506
        j += is->nb_streams;
1507
    }
1508
    nb_istreams = j;
1509

    
1510
    ist_table = av_mallocz(nb_istreams * sizeof(AVInputStream *));
1511
    if (!ist_table)
1512
        goto fail;
1513

    
1514
    for(i=0;i<nb_istreams;i++) {
1515
        ist = av_mallocz(sizeof(AVInputStream));
1516
        if (!ist)
1517
            goto fail;
1518
        ist_table[i] = ist;
1519
    }
1520
    j = 0;
1521
    for(i=0;i<nb_input_files;i++) {
1522
        is = input_files[i];
1523
        for(k=0;k<is->nb_streams;k++) {
1524
            ist = ist_table[j++];
1525
            ist->st = is->streams[k];
1526
            ist->file_index = i;
1527
            ist->index = k;
1528
            ist->discard = 1; /* the stream is discarded by default
1529
                                 (changed later) */
1530

    
1531
            if (ist->st->codec->rate_emu) {
1532
                ist->start = av_gettime();
1533
                ist->frame = 0;
1534
            }
1535
        }
1536
    }
1537

    
1538
    /* output stream init */
1539
    nb_ostreams = 0;
1540
    for(i=0;i<nb_output_files;i++) {
1541
        os = output_files[i];
1542
        nb_ostreams += os->nb_streams;
1543
    }
1544
    if (nb_stream_maps > 0 && nb_stream_maps != nb_ostreams) {
1545
        fprintf(stderr, "Number of stream maps must match number of output streams\n");
1546
        exit(1);
1547
    }
1548

    
1549
    /* Sanity check the mapping args -- do the input files & streams exist? */
1550
    for(i=0;i<nb_stream_maps;i++) {
1551
        int fi = stream_maps[i].file_index;
1552
        int si = stream_maps[i].stream_index;
1553

    
1554
        if (fi < 0 || fi > nb_input_files - 1 ||
1555
            si < 0 || si > file_table[fi].nb_streams - 1) {
1556
            fprintf(stderr,"Could not find input stream #%d.%d\n", fi, si);
1557
            exit(1);
1558
        }
1559
        fi = stream_maps[i].sync_file_index;
1560
        si = stream_maps[i].sync_stream_index;
1561
        if (fi < 0 || fi > nb_input_files - 1 ||
1562
            si < 0 || si > file_table[fi].nb_streams - 1) {
1563
            fprintf(stderr,"Could not find sync stream #%d.%d\n", fi, si);
1564
            exit(1);
1565
        }
1566
    }
1567

    
1568
    ost_table = av_mallocz(sizeof(AVOutputStream *) * nb_ostreams);
1569
    if (!ost_table)
1570
        goto fail;
1571
    for(i=0;i<nb_ostreams;i++) {
1572
        ost = av_mallocz(sizeof(AVOutputStream));
1573
        if (!ost)
1574
            goto fail;
1575
        ost_table[i] = ost;
1576
    }
1577

    
1578
    n = 0;
1579
    for(k=0;k<nb_output_files;k++) {
1580
        os = output_files[k];
1581
        for(i=0;i<os->nb_streams;i++) {
1582
            int found;
1583
            ost = ost_table[n++];
1584
            ost->file_index = k;
1585
            ost->index = i;
1586
            ost->st = os->streams[i];
1587
            if (nb_stream_maps > 0) {
1588
                ost->source_index = file_table[stream_maps[n-1].file_index].ist_index +
1589
                    stream_maps[n-1].stream_index;
1590

    
1591
                /* Sanity check that the stream types match */
1592
                if (ist_table[ost->source_index]->st->codec->codec_type != ost->st->codec->codec_type) {
1593
                    fprintf(stderr, "Codec type mismatch for mapping #%d.%d -> #%d.%d\n",
1594
                        stream_maps[n-1].file_index, stream_maps[n-1].stream_index,
1595
                        ost->file_index, ost->index);
1596
                    exit(1);
1597
                }
1598

    
1599
            } else {
1600
                /* get corresponding input stream index : we select the first one with the right type */
1601
                found = 0;
1602
                for(j=0;j<nb_istreams;j++) {
1603
                    ist = ist_table[j];
1604
                    if (ist->discard &&
1605
                        ist->st->codec->codec_type == ost->st->codec->codec_type) {
1606
                        ost->source_index = j;
1607
                        found = 1;
1608
                        break;
1609
                    }
1610
                }
1611

    
1612
                if (!found) {
1613
                    /* try again and reuse existing stream */
1614
                    for(j=0;j<nb_istreams;j++) {
1615
                        ist = ist_table[j];
1616
                        if (ist->st->codec->codec_type == ost->st->codec->codec_type) {
1617
                            ost->source_index = j;
1618
                            found = 1;
1619
                        }
1620
                    }
1621
                    if (!found) {
1622
                        fprintf(stderr, "Could not find input stream matching output stream #%d.%d\n",
1623
                                ost->file_index, ost->index);
1624
                        exit(1);
1625
                    }
1626
                }
1627
            }
1628
            ist = ist_table[ost->source_index];
1629
            ist->discard = 0;
1630
            ost->sync_ist = (nb_stream_maps > 0) ?
1631
                ist_table[file_table[stream_maps[n-1].sync_file_index].ist_index +
1632
                         stream_maps[n-1].sync_stream_index] : ist;
1633
        }
1634
    }
1635

    
1636
    /* for each output stream, we compute the right encoding parameters */
1637
    for(i=0;i<nb_ostreams;i++) {
1638
        ost = ost_table[i];
1639
        ist = ist_table[ost->source_index];
1640

    
1641
        codec = ost->st->codec;
1642
        icodec = ist->st->codec;
1643

    
1644
        if (ost->st->stream_copy) {
1645
            /* if stream_copy is selected, no need to decode or encode */
1646
            codec->codec_id = icodec->codec_id;
1647
            codec->codec_type = icodec->codec_type;
1648
            if(!codec->codec_tag) codec->codec_tag = icodec->codec_tag;
1649
            codec->bit_rate = icodec->bit_rate;
1650
            codec->extradata= icodec->extradata;
1651
            codec->extradata_size= icodec->extradata_size;
1652
            codec->time_base = icodec->time_base;
1653
            switch(codec->codec_type) {
1654
            case CODEC_TYPE_AUDIO:
1655
                codec->sample_rate = icodec->sample_rate;
1656
                codec->channels = icodec->channels;
1657
                codec->frame_size = icodec->frame_size;
1658
                codec->block_align= icodec->block_align;
1659
                break;
1660
            case CODEC_TYPE_VIDEO:
1661
                codec->width = icodec->width;
1662
                codec->height = icodec->height;
1663
                codec->has_b_frames = icodec->has_b_frames;
1664
                break;
1665
            case CODEC_TYPE_SUBTITLE:
1666
                break;
1667
            default:
1668
                av_abort();
1669
            }
1670
        } else {
1671
            switch(codec->codec_type) {
1672
            case CODEC_TYPE_AUDIO:
1673
                if (fifo_init(&ost->fifo, 2 * MAX_AUDIO_PACKET_SIZE))
1674
                    goto fail;
1675

    
1676
                if (codec->channels == icodec->channels &&
1677
                    codec->sample_rate == icodec->sample_rate) {
1678
                    ost->audio_resample = 0;
1679
                } else {
1680
                    if (codec->channels != icodec->channels &&
1681
                        (icodec->codec_id == CODEC_ID_AC3 ||
1682
                         icodec->codec_id == CODEC_ID_DTS)) {
1683
                        /* Special case for 5:1 AC3 and DTS input */
1684
                        /* and mono or stereo output      */
1685
                        /* Request specific number of channels */
1686
                        icodec->channels = codec->channels;
1687
                        if (codec->sample_rate == icodec->sample_rate)
1688
                            ost->audio_resample = 0;
1689
                        else {
1690
                            ost->audio_resample = 1;
1691
                        }
1692
                    } else {
1693
                        ost->audio_resample = 1;
1694
                    }
1695
                }
1696
                if(audio_sync_method>1)
1697
                    ost->audio_resample = 1;
1698

    
1699
                if(ost->audio_resample){
1700
                    ost->resample = audio_resample_init(codec->channels, icodec->channels,
1701
                                                    codec->sample_rate, icodec->sample_rate);
1702
                    if(!ost->resample){
1703
                        printf("Can't resample.  Aborting.\n");
1704
                        av_abort();
1705
                    }
1706
                }
1707
                ist->decoding_needed = 1;
1708
                ost->encoding_needed = 1;
1709
                break;
1710
            case CODEC_TYPE_VIDEO:
1711
                if (codec->width == icodec->width &&
1712
                    codec->height == icodec->height &&
1713
                    frame_topBand == 0 &&
1714
                    frame_bottomBand == 0 &&
1715
                    frame_leftBand == 0 &&
1716
                    frame_rightBand == 0 &&
1717
                    frame_padtop == 0 &&
1718
                    frame_padbottom == 0 &&
1719
                    frame_padleft == 0 &&
1720
                    frame_padright == 0)
1721
                {
1722
                    ost->video_resample = 0;
1723
                    ost->video_crop = 0;
1724
                    ost->video_pad = 0;
1725
                } else if ((codec->width == icodec->width -
1726
                                (frame_leftBand + frame_rightBand)) &&
1727
                        (codec->height == icodec->height -
1728
                                (frame_topBand  + frame_bottomBand)))
1729
                {
1730
                    ost->video_resample = 0;
1731
                    ost->video_crop = 1;
1732
                    ost->topBand = frame_topBand;
1733
                    ost->leftBand = frame_leftBand;
1734
                } else if ((codec->width == icodec->width +
1735
                                (frame_padleft + frame_padright)) &&
1736
                        (codec->height == icodec->height +
1737
                                (frame_padtop + frame_padbottom))) {
1738
                    ost->video_resample = 0;
1739
                    ost->video_crop = 0;
1740
                    ost->video_pad = 1;
1741
                    ost->padtop = frame_padtop;
1742
                    ost->padleft = frame_padleft;
1743
                    ost->padbottom = frame_padbottom;
1744
                    ost->padright = frame_padright;
1745
                    avcodec_get_frame_defaults(&ost->pict_tmp);
1746
                    if( avpicture_alloc( (AVPicture*)&ost->pict_tmp, PIX_FMT_YUV420P,
1747
                                codec->width, codec->height ) )
1748
                        goto fail;
1749
                } else {
1750
                    ost->video_resample = 1;
1751
                    ost->video_crop = 0; // cropping is handled as part of resample
1752
                    avcodec_get_frame_defaults(&ost->pict_tmp);
1753
                    if( avpicture_alloc( (AVPicture*)&ost->pict_tmp, PIX_FMT_YUV420P,
1754
                                         codec->width, codec->height ) )
1755
                        goto fail;
1756

    
1757
                    ost->img_resample_ctx = img_resample_full_init(
1758
                                      codec->width, codec->height,
1759
                                      icodec->width, icodec->height,
1760
                                      frame_topBand, frame_bottomBand,
1761
                            frame_leftBand, frame_rightBand,
1762
                            frame_padtop, frame_padbottom,
1763
                            frame_padleft, frame_padright);
1764

    
1765
                    ost->padtop = frame_padtop;
1766
                    ost->padleft = frame_padleft;
1767
                    ost->padbottom = frame_padbottom;
1768
                    ost->padright = frame_padright;
1769

    
1770
                }
1771
                ost->encoding_needed = 1;
1772
                ist->decoding_needed = 1;
1773
                break;
1774
            case CODEC_TYPE_SUBTITLE:
1775
                ost->encoding_needed = 1;
1776
                ist->decoding_needed = 1;
1777
                break;
1778
            default:
1779
                av_abort();
1780
                break;
1781
            }
1782
            /* two pass mode */
1783
            if (ost->encoding_needed &&
1784
                (codec->flags & (CODEC_FLAG_PASS1 | CODEC_FLAG_PASS2))) {
1785
                char logfilename[1024];
1786
                FILE *f;
1787
                int size;
1788
                char *logbuffer;
1789

    
1790
                snprintf(logfilename, sizeof(logfilename), "%s-%d.log",
1791
                         pass_logfilename ?
1792
                         pass_logfilename : DEFAULT_PASS_LOGFILENAME, i);
1793
                if (codec->flags & CODEC_FLAG_PASS1) {
1794
                    f = fopen(logfilename, "w");
1795
                    if (!f) {
1796
                        perror(logfilename);
1797
                        exit(1);
1798
                    }
1799
                    ost->logfile = f;
1800
                } else {
1801
                    /* read the log file */
1802
                    f = fopen(logfilename, "r");
1803
                    if (!f) {
1804
                        perror(logfilename);
1805
                        exit(1);
1806
                    }
1807
                    fseek(f, 0, SEEK_END);
1808
                    size = ftell(f);
1809
                    fseek(f, 0, SEEK_SET);
1810
                    logbuffer = av_malloc(size + 1);
1811
                    if (!logbuffer) {
1812
                        fprintf(stderr, "Could not allocate log buffer\n");
1813
                        exit(1);
1814
                    }
1815
                    size = fread(logbuffer, 1, size, f);
1816
                    fclose(f);
1817
                    logbuffer[size] = '\0';
1818
                    codec->stats_in = logbuffer;
1819
                }
1820
            }
1821
        }
1822
        if(codec->codec_type == CODEC_TYPE_VIDEO){
1823
            int size= codec->width * codec->height;
1824
            bit_buffer_size= FFMAX(bit_buffer_size, 4*size);
1825
        }
1826
    }
1827

    
1828
    if (!bit_buffer)
1829
        bit_buffer = av_malloc(bit_buffer_size);
1830
    if (!bit_buffer)
1831
        goto fail;
1832

    
1833
    /* dump the file output parameters - cannot be done before in case
1834
       of stream copy */
1835
    for(i=0;i<nb_output_files;i++) {
1836
        dump_format(output_files[i], i, output_files[i]->filename, 1);
1837
    }
1838

    
1839
    /* dump the stream mapping */
1840
    if (verbose >= 0) {
1841
        fprintf(stderr, "Stream mapping:\n");
1842
        for(i=0;i<nb_ostreams;i++) {
1843
            ost = ost_table[i];
1844
            fprintf(stderr, "  Stream #%d.%d -> #%d.%d",
1845
                    ist_table[ost->source_index]->file_index,
1846
                    ist_table[ost->source_index]->index,
1847
                    ost->file_index,
1848
                    ost->index);
1849
            if (ost->sync_ist != ist_table[ost->source_index])
1850
                fprintf(stderr, " [sync #%d.%d]",
1851
                        ost->sync_ist->file_index,
1852
                        ost->sync_ist->index);
1853
            fprintf(stderr, "\n");
1854
        }
1855
    }
1856

    
1857
    /* open each encoder */
1858
    for(i=0;i<nb_ostreams;i++) {
1859
        ost = ost_table[i];
1860
        if (ost->encoding_needed) {
1861
            AVCodec *codec;
1862
            codec = avcodec_find_encoder(ost->st->codec->codec_id);
1863
            if (!codec) {
1864
                fprintf(stderr, "Unsupported codec for output stream #%d.%d\n",
1865
                        ost->file_index, ost->index);
1866
                exit(1);
1867
            }
1868
            if (avcodec_open(ost->st->codec, codec) < 0) {
1869
                fprintf(stderr, "Error while opening codec for output stream #%d.%d - maybe incorrect parameters such as bit_rate, rate, width or height\n",
1870
                        ost->file_index, ost->index);
1871
                exit(1);
1872
            }
1873
            extra_size += ost->st->codec->extradata_size;
1874
        }
1875
    }
1876

    
1877
    /* open each decoder */
1878
    for(i=0;i<nb_istreams;i++) {
1879
        ist = ist_table[i];
1880
        if (ist->decoding_needed) {
1881
            AVCodec *codec;
1882
            codec = avcodec_find_decoder(ist->st->codec->codec_id);
1883
            if (!codec) {
1884
                fprintf(stderr, "Unsupported codec (id=%d) for input stream #%d.%d\n",
1885
                        ist->st->codec->codec_id, ist->file_index, ist->index);
1886
                exit(1);
1887
            }
1888
            if (avcodec_open(ist->st->codec, codec) < 0) {
1889
                fprintf(stderr, "Error while opening codec for input stream #%d.%d\n",
1890
                        ist->file_index, ist->index);
1891
                exit(1);
1892
            }
1893
            //if (ist->st->codec->codec_type == CODEC_TYPE_VIDEO)
1894
            //    ist->st->codec->flags |= CODEC_FLAG_REPEAT_FIELD;
1895
        }
1896
    }
1897

    
1898
    /* init pts */
1899
    for(i=0;i<nb_istreams;i++) {
1900
        ist = ist_table[i];
1901
        is = input_files[ist->file_index];
1902
        ist->pts = 0;
1903
        ist->next_pts = av_rescale_q(ist->st->start_time, ist->st->time_base, AV_TIME_BASE_Q);
1904
        if(ist->st->start_time == AV_NOPTS_VALUE)
1905
            ist->next_pts=0;
1906
        if(input_files_ts_offset[ist->file_index])
1907
            ist->next_pts= AV_NOPTS_VALUE;
1908
        ist->is_start = 1;
1909
    }
1910

    
1911
    /* compute buffer size max (should use a complete heuristic) */
1912
    for(i=0;i<nb_input_files;i++) {
1913
        file_table[i].buffer_size_max = 2048;
1914
    }
1915

    
1916
    /* set meta data information from input file if required */
1917
    for (i=0;i<nb_meta_data_maps;i++) {
1918
        AVFormatContext *out_file;
1919
        AVFormatContext *in_file;
1920

    
1921
        int out_file_index = meta_data_maps[i].out_file;
1922
        int in_file_index = meta_data_maps[i].in_file;
1923
        if ( out_file_index < 0 || out_file_index >= nb_output_files ) {
1924
            fprintf(stderr, "Invalid output file index %d map_meta_data(%d,%d)\n", out_file_index, out_file_index, in_file_index);
1925
            ret = -EINVAL;
1926
            goto fail;
1927
        }
1928
        if ( in_file_index < 0 || in_file_index >= nb_input_files ) {
1929
            fprintf(stderr, "Invalid input file index %d map_meta_data(%d,%d)\n", in_file_index, out_file_index, in_file_index);
1930
            ret = -EINVAL;
1931
            goto fail;
1932
        }
1933

    
1934
        out_file = output_files[out_file_index];
1935
        in_file = input_files[in_file_index];
1936

    
1937
        strcpy(out_file->title, in_file->title);
1938
        strcpy(out_file->author, in_file->author);
1939
        strcpy(out_file->copyright, in_file->copyright);
1940
        strcpy(out_file->comment, in_file->comment);
1941
        strcpy(out_file->album, in_file->album);
1942
        out_file->year = in_file->year;
1943
        out_file->track = in_file->track;
1944
        strcpy(out_file->genre, in_file->genre);
1945
    }
1946

    
1947
    /* open files and write file headers */
1948
    for(i=0;i<nb_output_files;i++) {
1949
        os = output_files[i];
1950
        if (av_write_header(os) < 0) {
1951
            fprintf(stderr, "Could not write header for output file #%d (incorrect codec parameters ?)\n", i);
1952
            ret = -EINVAL;
1953
            goto fail;
1954
        }
1955
    }
1956

    
1957
#ifndef CONFIG_WIN32
1958
    if ( !using_stdin && verbose >= 0) {
1959
        fprintf(stderr, "Press [q] to stop encoding\n");
1960
        url_set_interrupt_cb(decode_interrupt_cb);
1961
    }
1962
#endif
1963
    term_init();
1964

    
1965
    stream_no_data = 0;
1966
    key = -1;
1967

    
1968
    for(; received_sigterm == 0;) {
1969
        int file_index, ist_index;
1970
        AVPacket pkt;
1971
        double ipts_min;
1972
        double opts_min;
1973

    
1974
    redo:
1975
        ipts_min= 1e100;
1976
        opts_min= 1e100;
1977
        /* if 'q' pressed, exits */
1978
        if (!using_stdin) {
1979
            if (q_pressed)
1980
                break;
1981
            /* read_key() returns 0 on EOF */
1982
            key = read_key();
1983
            if (key == 'q')
1984
                break;
1985
        }
1986

    
1987
        /* select the stream that we must read now by looking at the
1988
           smallest output pts */
1989
        file_index = -1;
1990
        for(i=0;i<nb_ostreams;i++) {
1991
            double ipts, opts;
1992
            ost = ost_table[i];
1993
            os = output_files[ost->file_index];
1994
            ist = ist_table[ost->source_index];
1995
            if(ost->st->codec->codec_type == CODEC_TYPE_VIDEO)
1996
                opts = ost->sync_opts * av_q2d(ost->st->codec->time_base);
1997
            else
1998
                opts = ost->st->pts.val * av_q2d(ost->st->time_base);
1999
            ipts = (double)ist->pts;
2000
            if (!file_table[ist->file_index].eof_reached){
2001
                if(ipts < ipts_min) {
2002
                    ipts_min = ipts;
2003
                    if(input_sync ) file_index = ist->file_index;
2004
                }
2005
                if(opts < opts_min) {
2006
                    opts_min = opts;
2007
                    if(!input_sync) file_index = ist->file_index;
2008
                }
2009
            }
2010
            if(ost->frame_number >= max_frames[ost->st->codec->codec_type]){
2011
                file_index= -1;
2012
                break;
2013
            }
2014
        }
2015
        /* if none, if is finished */
2016
        if (file_index < 0) {
2017
            break;
2018
        }
2019

    
2020
        /* finish if recording time exhausted */
2021
        if (recording_time > 0 && opts_min >= (recording_time / 1000000.0))
2022
            break;
2023

    
2024
        /* finish if limit size exhausted */
2025
        if (limit_filesize != 0 && (limit_filesize * 1024) < url_ftell(&output_files[0]->pb))
2026
            break;
2027

    
2028
        /* read a frame from it and output it in the fifo */
2029
        is = input_files[file_index];
2030
        if (av_read_frame(is, &pkt) < 0) {
2031
            file_table[file_index].eof_reached = 1;
2032
            if (opt_shortest) break; else continue; //
2033
        }
2034

    
2035
        if (!pkt.size) {
2036
            stream_no_data = is;
2037
        } else {
2038
            stream_no_data = 0;
2039
        }
2040
        if (do_pkt_dump) {
2041
            av_pkt_dump(stdout, &pkt, do_hex_dump);
2042
        }
2043
        /* the following test is needed in case new streams appear
2044
           dynamically in stream : we ignore them */
2045
        if (pkt.stream_index >= file_table[file_index].nb_streams)
2046
            goto discard_packet;
2047
        ist_index = file_table[file_index].ist_index + pkt.stream_index;
2048
        ist = ist_table[ist_index];
2049
        if (ist->discard)
2050
            goto discard_packet;
2051

    
2052
//        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);
2053
        if (pkt.dts != AV_NOPTS_VALUE && ist->next_pts != AV_NOPTS_VALUE) {
2054
            int64_t delta= av_rescale_q(pkt.dts, ist->st->time_base, AV_TIME_BASE_Q) - ist->next_pts;
2055
            if(ABS(delta) > 10LL*AV_TIME_BASE && !copy_ts){
2056
                input_files_ts_offset[ist->file_index]-= delta;
2057
                if (verbose > 2)
2058
                    fprintf(stderr, "timestamp discontinuity %"PRId64", new offset= %"PRId64"\n", delta, input_files_ts_offset[ist->file_index]);
2059
                for(i=0; i<file_table[file_index].nb_streams; i++){
2060
                    int index= file_table[file_index].ist_index + i;
2061
                    ist_table[index]->next_pts += delta;
2062
                    ist_table[index]->is_start=1;
2063
                }
2064
            }
2065
        }
2066

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

    
2070
            if (verbose >= 0)
2071
                fprintf(stderr, "Error while decoding stream #%d.%d\n",
2072
                        ist->file_index, ist->index);
2073

    
2074
            av_free_packet(&pkt);
2075
            goto redo;
2076
        }
2077

    
2078
    discard_packet:
2079
        av_free_packet(&pkt);
2080

    
2081
        /* dump report by using the output first video and audio streams */
2082
        print_report(output_files, ost_table, nb_ostreams, 0);
2083
    }
2084

    
2085
    /* at the end of stream, we must flush the decoder buffers */
2086
    for(i=0;i<nb_istreams;i++) {
2087
        ist = ist_table[i];
2088
        if (ist->decoding_needed) {
2089
            output_packet(ist, i, ost_table, nb_ostreams, NULL);
2090
        }
2091
    }
2092

    
2093
    term_exit();
2094

    
2095
    /* write the trailer if needed and close file */
2096
    for(i=0;i<nb_output_files;i++) {
2097
        os = output_files[i];
2098
        av_write_trailer(os);
2099
    }
2100

    
2101
    /* dump report by using the first video and audio streams */
2102
    print_report(output_files, ost_table, nb_ostreams, 1);
2103

    
2104
    /* close each encoder */
2105
    for(i=0;i<nb_ostreams;i++) {
2106
        ost = ost_table[i];
2107
        if (ost->encoding_needed) {
2108
            av_freep(&ost->st->codec->stats_in);
2109
            avcodec_close(ost->st->codec);
2110
        }
2111
    }
2112

    
2113
    /* close each decoder */
2114
    for(i=0;i<nb_istreams;i++) {
2115
        ist = ist_table[i];
2116
        if (ist->decoding_needed) {
2117
            avcodec_close(ist->st->codec);
2118
        }
2119
    }
2120

    
2121
    /* finished ! */
2122

    
2123
    ret = 0;
2124
 fail1:
2125
    av_freep(&bit_buffer);
2126
    av_free(file_table);
2127

    
2128
    if (ist_table) {
2129
        for(i=0;i<nb_istreams;i++) {
2130
            ist = ist_table[i];
2131
            av_free(ist);
2132
        }
2133
        av_free(ist_table);
2134
    }
2135
    if (ost_table) {
2136
        for(i=0;i<nb_ostreams;i++) {
2137
            ost = ost_table[i];
2138
            if (ost) {
2139
                if (ost->logfile) {
2140
                    fclose(ost->logfile);
2141
                    ost->logfile = NULL;
2142
                }
2143
                fifo_free(&ost->fifo); /* works even if fifo is not
2144
                                          initialized but set to zero */
2145
                av_free(ost->pict_tmp.data[0]);
2146
                if (ost->video_resample)
2147
                    img_resample_close(ost->img_resample_ctx);
2148
                if (ost->audio_resample)
2149
                    audio_resample_close(ost->resample);
2150
                av_free(ost);
2151
            }
2152
        }
2153
        av_free(ost_table);
2154
    }
2155
    return ret;
2156
 fail:
2157
    ret = -ENOMEM;
2158
    goto fail1;
2159
}
2160

    
2161
#if 0
2162
int file_read(const char *filename)
2163
{
2164
    URLContext *h;
2165
    unsigned char buffer[1024];
2166
    int len, i;
2167

2168
    if (url_open(&h, filename, O_RDONLY) < 0) {
2169
        printf("could not open '%s'\n", filename);
2170
        return -1;
2171
    }
2172
    for(;;) {
2173
        len = url_read(h, buffer, sizeof(buffer));
2174
        if (len <= 0)
2175
            break;
2176
        for(i=0;i<len;i++) putchar(buffer[i]);
2177
    }
2178
    url_close(h);
2179
    return 0;
2180
}
2181
#endif
2182

    
2183
static void opt_image_format(const char *arg)
2184
{
2185
    AVImageFormat *f;
2186

    
2187
    for(f = first_image_format; f != NULL; f = f->next) {
2188
        if (!strcmp(arg, f->name))
2189
            break;
2190
    }
2191
    if (!f) {
2192
        fprintf(stderr, "Unknown image format: '%s'\n", arg);
2193
        exit(1);
2194
    }
2195
    image_format = f;
2196
}
2197

    
2198
static void opt_format(const char *arg)
2199
{
2200
    /* compatibility stuff for pgmyuv */
2201
    if (!strcmp(arg, "pgmyuv")) {
2202
        pgmyuv_compatibility_hack=1;
2203
//        opt_image_format(arg);
2204
        arg = "image2";
2205
    }
2206

    
2207
    file_iformat = av_find_input_format(arg);
2208
    file_oformat = guess_format(arg, NULL, NULL);
2209
    if (!file_iformat && !file_oformat) {
2210
        fprintf(stderr, "Unknown input or output format: %s\n", arg);
2211
        exit(1);
2212
    }
2213
}
2214

    
2215
static void opt_video_bitrate(const char *arg)
2216
{
2217
    video_bit_rate = atoi(arg) * 1000;
2218
}
2219

    
2220
static void opt_video_bitrate_tolerance(const char *arg)
2221
{
2222
    video_bit_rate_tolerance = atoi(arg) * 1000;
2223
}
2224

    
2225
static void opt_video_bitrate_max(const char *arg)
2226
{
2227
    video_rc_max_rate = atoi(arg) * 1000;
2228
}
2229

    
2230
static void opt_video_bitrate_min(const char *arg)
2231
{
2232
    video_rc_min_rate = atoi(arg) * 1000;
2233
}
2234

    
2235
static void opt_video_buffer_size(const char *arg)
2236
{
2237
    video_rc_buffer_size = atoi(arg) * 8*1024;
2238
}
2239

    
2240
static void opt_video_rc_eq(char *arg)
2241
{
2242
    video_rc_eq = arg;
2243
}
2244

    
2245
static void opt_video_rc_override_string(char *arg)
2246
{
2247
    video_rc_override_string = arg;
2248
}
2249

    
2250

    
2251
static void opt_workaround_bugs(const char *arg)
2252
{
2253
    workaround_bugs = atoi(arg);
2254
}
2255

    
2256
static void opt_me_threshold(const char *arg)
2257
{
2258
    me_threshold = atoi(arg);
2259
}
2260

    
2261
static void opt_mb_threshold(const char *arg)
2262
{
2263
    mb_threshold = atoi(arg);
2264
}
2265

    
2266
static void opt_verbose(const char *arg)
2267
{
2268
    verbose = atoi(arg);
2269
    av_log_set_level(atoi(arg));
2270
}
2271

    
2272
static void opt_frame_rate(const char *arg)
2273
{
2274
    if (parse_frame_rate(&frame_rate, &frame_rate_base, arg) < 0) {
2275
        fprintf(stderr, "Incorrect frame rate\n");
2276
        exit(1);
2277
    }
2278
}
2279

    
2280
static void opt_frame_crop_top(const char *arg)
2281
{
2282
    frame_topBand = atoi(arg);
2283
    if (frame_topBand < 0) {
2284
        fprintf(stderr, "Incorrect top crop size\n");
2285
        exit(1);
2286
    }
2287
    if ((frame_topBand % 2) != 0) {
2288
        fprintf(stderr, "Top crop size must be a multiple of 2\n");
2289
        exit(1);
2290
    }
2291
    if ((frame_topBand) >= frame_height){
2292
            fprintf(stderr, "Vertical crop dimensions are outside the range of the original image.\nRemember to crop first and scale second.\n");
2293
        exit(1);
2294
    }
2295
    frame_height -= frame_topBand;
2296
}
2297

    
2298
static void opt_frame_crop_bottom(const char *arg)
2299
{
2300
    frame_bottomBand = atoi(arg);
2301
    if (frame_bottomBand < 0) {
2302
        fprintf(stderr, "Incorrect bottom crop size\n");
2303
        exit(1);
2304
    }
2305
    if ((frame_bottomBand % 2) != 0) {
2306
        fprintf(stderr, "Bottom crop size must be a multiple of 2\n");
2307
        exit(1);
2308
    }
2309
    if ((frame_bottomBand) >= frame_height){
2310
            fprintf(stderr, "Vertical crop dimensions are outside the range of the original image.\nRemember to crop first and scale second.\n");
2311
        exit(1);
2312
    }
2313
    frame_height -= frame_bottomBand;
2314
}
2315

    
2316
static void opt_frame_crop_left(const char *arg)
2317
{
2318
    frame_leftBand = atoi(arg);
2319
    if (frame_leftBand < 0) {
2320
        fprintf(stderr, "Incorrect left crop size\n");
2321
        exit(1);
2322
    }
2323
    if ((frame_leftBand % 2) != 0) {
2324
        fprintf(stderr, "Left crop size must be a multiple of 2\n");
2325
        exit(1);
2326
    }
2327
    if ((frame_leftBand) >= frame_width){
2328
            fprintf(stderr, "Horizontal crop dimensions are outside the range of the original image.\nRemember to crop first and scale second.\n");
2329
        exit(1);
2330
    }
2331
    frame_width -= frame_leftBand;
2332
}
2333

    
2334
static void opt_frame_crop_right(const char *arg)
2335
{
2336
    frame_rightBand = atoi(arg);
2337
    if (frame_rightBand < 0) {
2338
        fprintf(stderr, "Incorrect right crop size\n");
2339
        exit(1);
2340
    }
2341
    if ((frame_rightBand % 2) != 0) {
2342
        fprintf(stderr, "Right crop size must be a multiple of 2\n");
2343
        exit(1);
2344
    }
2345
    if ((frame_rightBand) >= frame_width){
2346
            fprintf(stderr, "Horizontal crop dimensions are outside the range of the original image.\nRemember to crop first and scale second.\n");
2347
        exit(1);
2348
    }
2349
    frame_width -= frame_rightBand;
2350
}
2351

    
2352
static void opt_frame_size(const char *arg)
2353
{
2354
    if (parse_image_size(&frame_width, &frame_height, arg) < 0) {
2355
        fprintf(stderr, "Incorrect frame size\n");
2356
        exit(1);
2357
    }
2358
    if ((frame_width % 2) != 0 || (frame_height % 2) != 0) {
2359
        fprintf(stderr, "Frame size must be a multiple of 2\n");
2360
        exit(1);
2361
    }
2362
}
2363

    
2364

    
2365
#define SCALEBITS 10
2366
#define ONE_HALF  (1 << (SCALEBITS - 1))
2367
#define FIX(x)          ((int) ((x) * (1<<SCALEBITS) + 0.5))
2368

    
2369
#define RGB_TO_Y(r, g, b) \
2370
((FIX(0.29900) * (r) + FIX(0.58700) * (g) + \
2371
  FIX(0.11400) * (b) + ONE_HALF) >> SCALEBITS)
2372

    
2373
#define RGB_TO_U(r1, g1, b1, shift)\
2374
(((- FIX(0.16874) * r1 - FIX(0.33126) * g1 +         \
2375
     FIX(0.50000) * b1 + (ONE_HALF << shift) - 1) >> (SCALEBITS + shift)) + 128)
2376

    
2377
#define RGB_TO_V(r1, g1, b1, shift)\
2378
(((FIX(0.50000) * r1 - FIX(0.41869) * g1 -           \
2379
   FIX(0.08131) * b1 + (ONE_HALF << shift) - 1) >> (SCALEBITS + shift)) + 128)
2380

    
2381
static void opt_pad_color(const char *arg) {
2382
    /* Input is expected to be six hex digits similar to
2383
       how colors are expressed in html tags (but without the #) */
2384
    int rgb = strtol(arg, NULL, 16);
2385
    int r,g,b;
2386

    
2387
    r = (rgb >> 16);
2388
    g = ((rgb >> 8) & 255);
2389
    b = (rgb & 255);
2390

    
2391
    padcolor[0] = RGB_TO_Y(r,g,b);
2392
    padcolor[1] = RGB_TO_U(r,g,b,0);
2393
    padcolor[2] = RGB_TO_V(r,g,b,0);
2394
}
2395

    
2396
static void opt_frame_pad_top(const char *arg)
2397
{
2398
    frame_padtop = atoi(arg);
2399
    if (frame_padtop < 0) {
2400
        fprintf(stderr, "Incorrect top pad size\n");
2401
        exit(1);
2402
    }
2403
    if ((frame_padtop % 2) != 0) {
2404
        fprintf(stderr, "Top pad size must be a multiple of 2\n");
2405
        exit(1);
2406
    }
2407
}
2408

    
2409
static void opt_frame_pad_bottom(const char *arg)
2410
{
2411
    frame_padbottom = atoi(arg);
2412
    if (frame_padbottom < 0) {
2413
        fprintf(stderr, "Incorrect bottom pad size\n");
2414
        exit(1);
2415
    }
2416
    if ((frame_padbottom % 2) != 0) {
2417
        fprintf(stderr, "Bottom pad size must be a multiple of 2\n");
2418
        exit(1);
2419
    }
2420
}
2421

    
2422

    
2423
static void opt_frame_pad_left(const char *arg)
2424
{
2425
    frame_padleft = atoi(arg);
2426
    if (frame_padleft < 0) {
2427
        fprintf(stderr, "Incorrect left pad size\n");
2428
        exit(1);
2429
    }
2430
    if ((frame_padleft % 2) != 0) {
2431
        fprintf(stderr, "Left pad size must be a multiple of 2\n");
2432
        exit(1);
2433
    }
2434
}
2435

    
2436

    
2437
static void opt_frame_pad_right(const char *arg)
2438
{
2439
    frame_padright = atoi(arg);
2440
    if (frame_padright < 0) {
2441
        fprintf(stderr, "Incorrect right pad size\n");
2442
        exit(1);
2443
    }
2444
    if ((frame_padright % 2) != 0) {
2445
        fprintf(stderr, "Right pad size must be a multiple of 2\n");
2446
        exit(1);
2447
    }
2448
}
2449

    
2450

    
2451
static void opt_frame_pix_fmt(const char *arg)
2452
{
2453
    frame_pix_fmt = avcodec_get_pix_fmt(arg);
2454
}
2455

    
2456
static void opt_frame_aspect_ratio(const char *arg)
2457
{
2458
    int x = 0, y = 0;
2459
    double ar = 0;
2460
    const char *p;
2461

    
2462
    p = strchr(arg, ':');
2463
    if (p) {
2464
        x = strtol(arg, (char **)&arg, 10);
2465
        if (arg == p)
2466
            y = strtol(arg+1, (char **)&arg, 10);
2467
        if (x > 0 && y > 0)
2468
            ar = (double)x / (double)y;
2469
    } else
2470
        ar = strtod(arg, (char **)&arg);
2471

    
2472
    if (!ar) {
2473
        fprintf(stderr, "Incorrect aspect ratio specification.\n");
2474
        exit(1);
2475
    }
2476
    frame_aspect_ratio = ar;
2477
}
2478

    
2479
static void opt_gop_size(const char *arg)
2480
{
2481
    gop_size = atoi(arg);
2482
}
2483

    
2484
static void opt_b_frames(const char *arg)
2485
{
2486
    b_frames = atoi(arg);
2487
    if (b_frames > FF_MAX_B_FRAMES) {
2488
        fprintf(stderr, "\nCannot have more than %d B frames, increase FF_MAX_B_FRAMES.\n", FF_MAX_B_FRAMES);
2489
        exit(1);
2490
    } else if (b_frames < 1) {
2491
        fprintf(stderr, "\nNumber of B frames must be higher than 0\n");
2492
        exit(1);
2493
    }
2494
}
2495

    
2496
static void opt_pre_me(const char *arg)
2497
{
2498
    pre_me = atoi(arg);
2499
}
2500

    
2501
static void opt_qscale(const char *arg)
2502
{
2503
    video_qscale = atof(arg);
2504
    if (video_qscale < 0.01 ||
2505
        video_qscale > 255) {
2506
        fprintf(stderr, "qscale must be >= 0.01 and <= 255\n");
2507
        exit(1);
2508
    }
2509
}
2510

    
2511
static void opt_qsquish(const char *arg)
2512
{
2513
    video_qsquish = atof(arg);
2514
    if (video_qsquish < 0.0 ||
2515
        video_qsquish > 99.0) {
2516
        fprintf(stderr, "qsquish must be >= 0.0 and <= 99.0\n");
2517
        exit(1);
2518
    }
2519
}
2520

    
2521
static void opt_lmax(const char *arg)
2522
{
2523
    video_lmax = atof(arg)*FF_QP2LAMBDA;
2524
}
2525

    
2526
static void opt_lmin(const char *arg)
2527
{
2528
    video_lmin = atof(arg)*FF_QP2LAMBDA;
2529
}
2530

    
2531
static void opt_qmin(const char *arg)
2532
{
2533
    video_qmin = atoi(arg);
2534
    if (video_qmin < 1 ||
2535
        video_qmin > 31) {
2536
        fprintf(stderr, "qmin must be >= 1 and <= 31\n");
2537
        exit(1);
2538
    }
2539
}
2540

    
2541
static void opt_qmax(const char *arg)
2542
{
2543
    video_qmax = atoi(arg);
2544
    if (video_qmax < 1 ||
2545
        video_qmax > 31) {
2546
        fprintf(stderr, "qmax must be >= 1 and <= 31\n");
2547
        exit(1);
2548
    }
2549
}
2550

    
2551
static void opt_mb_lmin(const char *arg)
2552
{
2553
    video_mb_lmin = atof(arg)*FF_QP2LAMBDA;
2554
    if (video_mb_lmin < 1 ||
2555
        video_mb_lmin > FF_LAMBDA_MAX) {
2556
        fprintf(stderr, "mblmin must be >= 1 and <= %d\n", FF_LAMBDA_MAX / FF_QP2LAMBDA);
2557
        exit(1);
2558
    }
2559
}
2560

    
2561
static void opt_mb_lmax(const char *arg)
2562
{
2563
    video_mb_lmax = atof(arg)*FF_QP2LAMBDA;
2564
    if (video_mb_lmax < 1 ||
2565
        video_mb_lmax > FF_LAMBDA_MAX) {
2566
        fprintf(stderr, "mblmax must be >= 1 and <= %d\n", FF_LAMBDA_MAX / FF_QP2LAMBDA);
2567
        exit(1);
2568
    }
2569
}
2570

    
2571
static void opt_qdiff(const char *arg)
2572
{
2573
    video_qdiff = atoi(arg);
2574
    if (video_qdiff < 0 ||
2575
        video_qdiff > 31) {
2576
        fprintf(stderr, "qdiff must be >= 1 and <= 31\n");
2577
        exit(1);
2578
    }
2579
}
2580

    
2581
static void opt_qblur(const char *arg)
2582
{
2583
    video_qblur = atof(arg);
2584
}
2585

    
2586
static void opt_qcomp(const char *arg)
2587
{
2588
    video_qcomp = atof(arg);
2589
}
2590

    
2591
static void opt_rc_initial_cplx(const char *arg)
2592
{
2593
    video_rc_initial_cplx = atof(arg);
2594
}
2595
static void opt_b_qfactor(const char *arg)
2596
{
2597
    video_b_qfactor = atof(arg);
2598
}
2599
static void opt_i_qfactor(const char *arg)
2600
{
2601
    video_i_qfactor = atof(arg);
2602
}
2603
static void opt_b_qoffset(const char *arg)
2604
{
2605
    video_b_qoffset = atof(arg);
2606
}
2607
static void opt_i_qoffset(const char *arg)
2608
{
2609
    video_i_qoffset = atof(arg);
2610
}
2611

    
2612
static void opt_ibias(const char *arg)
2613
{
2614
    video_intra_quant_bias = atoi(arg);
2615
}
2616
static void opt_pbias(const char *arg)
2617
{
2618
    video_inter_quant_bias = atoi(arg);
2619
}
2620

    
2621
static void opt_packet_size(const char *arg)
2622
{
2623
    packet_size= atoi(arg);
2624
}
2625

    
2626
static void opt_error_rate(const char *arg)
2627
{
2628
    error_rate= atoi(arg);
2629
}
2630

    
2631
static void opt_strict(const char *arg)
2632
{
2633
    strict= atoi(arg);
2634
}
2635

    
2636
static void opt_top_field_first(const char *arg)
2637
{
2638
    top_field_first= atoi(arg);
2639
}
2640

    
2641
static void opt_sc_threshold(const char *arg)
2642
{
2643
    sc_threshold= atoi(arg);
2644
}
2645

    
2646
static void opt_me_range(const char *arg)
2647
{
2648
    me_range = atoi(arg);
2649
}
2650

    
2651
static void opt_thread_count(const char *arg)
2652
{
2653
    thread_count= atoi(arg);
2654
#if !defined(HAVE_THREADS)
2655
    if (verbose >= 0)
2656
        fprintf(stderr, "Warning: not compiled with thread support, using thread emulation\n");
2657
#endif
2658
}
2659

    
2660
static void opt_audio_bitrate(const char *arg)
2661
{
2662
    audio_bit_rate = atoi(arg) * 1000;
2663
}
2664

    
2665
static void opt_audio_rate(const char *arg)
2666
{
2667
    audio_sample_rate = atoi(arg);
2668
}
2669

    
2670
static void opt_audio_channels(const char *arg)
2671
{
2672
    audio_channels = atoi(arg);
2673
}
2674

    
2675
static void opt_video_device(const char *arg)
2676
{
2677
    video_device = av_strdup(arg);
2678
}
2679

    
2680
static void opt_grab_device(const char *arg)
2681
{
2682
    grab_device = av_strdup(arg);
2683
}
2684

    
2685
static void opt_video_channel(const char *arg)
2686
{
2687
    video_channel = strtol(arg, NULL, 0);
2688
}
2689

    
2690
static void opt_video_standard(const char *arg)
2691
{
2692
    video_standard = av_strdup(arg);
2693
}
2694

    
2695
static void opt_audio_device(const char *arg)
2696
{
2697
    audio_device = av_strdup(arg);
2698
}
2699

    
2700
static void opt_codec(int *pstream_copy, int *pcodec_id,
2701
                      int codec_type, const char *arg)
2702
{
2703
    AVCodec *p;
2704

    
2705
    if (!strcmp(arg, "copy")) {
2706
        *pstream_copy = 1;
2707
    } else {
2708
        p = first_avcodec;
2709
        while (p) {
2710
            if (!strcmp(p->name, arg) && p->type == codec_type)
2711
                break;
2712
            p = p->next;
2713
        }
2714
        if (p == NULL) {
2715
            fprintf(stderr, "Unknown codec '%s'\n", arg);
2716
            exit(1);
2717
        } else {
2718
            *pcodec_id = p->id;
2719
        }
2720
    }
2721
}
2722

    
2723
static void opt_audio_codec(const char *arg)
2724
{
2725
    opt_codec(&audio_stream_copy, &audio_codec_id, CODEC_TYPE_AUDIO, arg);
2726
}
2727

    
2728
static void opt_audio_tag(const char *arg)
2729
{
2730
    char *tail;
2731
    audio_codec_tag= strtol(arg, &tail, 0);
2732

    
2733
    if(!tail || *tail)
2734
        audio_codec_tag= arg[0] + (arg[1]<<8) + (arg[2]<<16) + (arg[3]<<24);
2735
}
2736

    
2737
static void opt_video_tag(const char *arg)
2738
{
2739
    char *tail;
2740
    video_codec_tag= strtol(arg, &tail, 0);
2741

    
2742
    if(!tail || *tail)
2743
        video_codec_tag= arg[0] + (arg[1]<<8) + (arg[2]<<16) + (arg[3]<<24);
2744
}
2745

    
2746
static void add_frame_hooker(const char *arg)
2747
{
2748
    int argc = 0;
2749
    char *argv[64];
2750
    int i;
2751
    char *args = av_strdup(arg);
2752

    
2753
    using_vhook = 1;
2754

    
2755
    argv[0] = strtok(args, " ");
2756
    while (argc < 62 && (argv[++argc] = strtok(NULL, " "))) {
2757
    }
2758

    
2759
    i = frame_hook_add(argc, argv);
2760

    
2761
    if (i != 0) {
2762
        fprintf(stderr, "Failed to add video hook function: %s\n", arg);
2763
        exit(1);
2764
    }
2765
}
2766

    
2767
const char *motion_str[] = {
2768
    "zero",
2769
    "full",
2770
    "log",
2771
    "phods",
2772
    "epzs",
2773
    "x1",
2774
    NULL,
2775
};
2776

    
2777
static void opt_motion_estimation(const char *arg)
2778
{
2779
    const char **p;
2780
    p = motion_str;
2781
    for(;;) {
2782
        if (!*p) {
2783
            fprintf(stderr, "Unknown motion estimation method '%s'\n", arg);
2784
            exit(1);
2785
        }
2786
        if (!strcmp(*p, arg))
2787
            break;
2788
        p++;
2789
    }
2790
    me_method = (p - motion_str) + 1;
2791
}
2792

    
2793
static void opt_video_codec(const char *arg)
2794
{
2795
    opt_codec(&video_stream_copy, &video_codec_id, CODEC_TYPE_VIDEO, arg);
2796
}
2797

    
2798
static void opt_subtitle_codec(const char *arg)
2799
{
2800
    opt_codec(&subtitle_stream_copy, &subtitle_codec_id, CODEC_TYPE_SUBTITLE, arg);
2801
}
2802

    
2803
static void opt_map(const char *arg)
2804
{
2805
    AVStreamMap *m;
2806
    const char *p;
2807

    
2808
    p = arg;
2809
    m = &stream_maps[nb_stream_maps++];
2810

    
2811
    m->file_index = strtol(arg, (char **)&p, 0);
2812
    if (*p)
2813
        p++;
2814

    
2815
    m->stream_index = strtol(p, (char **)&p, 0);
2816
    if (*p) {
2817
        p++;
2818
        m->sync_file_index = strtol(p, (char **)&p, 0);
2819
        if (*p)
2820
            p++;
2821
        m->sync_stream_index = strtol(p, (char **)&p, 0);
2822
    } else {
2823
        m->sync_file_index = m->file_index;
2824
        m->sync_stream_index = m->stream_index;
2825
    }
2826
}
2827

    
2828
static void opt_map_meta_data(const char *arg)
2829
{
2830
    AVMetaDataMap *m;
2831
    const char *p;
2832

    
2833
    p = arg;
2834
    m = &meta_data_maps[nb_meta_data_maps++];
2835

    
2836
    m->out_file = strtol(arg, (char **)&p, 0);
2837
    if (*p)
2838
        p++;
2839

    
2840
    m->in_file = strtol(p, (char **)&p, 0);
2841
}
2842

    
2843
static void opt_recording_time(const char *arg)
2844
{
2845
    recording_time = parse_date(arg, 1);
2846
}
2847

    
2848
static void opt_start_time(const char *arg)
2849
{
2850
    start_time = parse_date(arg, 1);
2851
}
2852

    
2853
static void opt_rec_timestamp(const char *arg)
2854
{
2855
    rec_timestamp = parse_date(arg, 0) / 1000000;
2856
}
2857

    
2858
static void opt_input_ts_offset(const char *arg)
2859
{
2860
    input_ts_offset = parse_date(arg, 1);
2861
}
2862

    
2863
static void opt_input_file(const char *filename)
2864
{
2865
    AVFormatContext *ic;
2866
    AVFormatParameters params, *ap = &params;
2867
    int err, i, ret, rfps, rfps_base;
2868
    int64_t timestamp;
2869

    
2870
    if (!strcmp(filename, "-"))
2871
        filename = "pipe:";
2872

    
2873
    using_stdin |= !strncmp(filename, "pipe:", 5) ||
2874
                   !strcmp( filename, "/dev/stdin" );
2875

    
2876
    /* get default parameters from command line */
2877
    memset(ap, 0, sizeof(*ap));
2878
    ap->sample_rate = audio_sample_rate;
2879
    ap->channels = audio_channels;
2880
    ap->time_base.den = frame_rate;
2881
    ap->time_base.num = frame_rate_base;
2882
    ap->width = frame_width + frame_padleft + frame_padright;
2883
    ap->height = frame_height + frame_padtop + frame_padbottom;
2884
    ap->image_format = image_format;
2885
    ap->pix_fmt = frame_pix_fmt;
2886
    ap->device  = grab_device;
2887
    ap->channel = video_channel;
2888
    ap->standard = video_standard;
2889
    ap->video_codec_id = video_codec_id;
2890
    ap->audio_codec_id = audio_codec_id;
2891
    if(pgmyuv_compatibility_hack)
2892
        ap->video_codec_id= CODEC_ID_PGMYUV;
2893

    
2894
    /* open the input file with generic libav function */
2895
    err = av_open_input_file(&ic, filename, file_iformat, 0, ap);
2896
    if (err < 0) {
2897
        print_error(filename, err);
2898
        exit(1);
2899
    }
2900

    
2901
    if(genpts)
2902
        ic->flags|= AVFMT_FLAG_GENPTS;
2903

    
2904
    /* If not enough info to get the stream parameters, we decode the
2905
       first frames to get it. (used in mpeg case for example) */
2906
    ret = av_find_stream_info(ic);
2907
    if (ret < 0 && verbose >= 0) {
2908
        fprintf(stderr, "%s: could not find codec parameters\n", filename);
2909
        exit(1);
2910
    }
2911

    
2912
    timestamp = start_time;
2913
    /* add the stream start time */
2914
    if (ic->start_time != AV_NOPTS_VALUE)
2915
        timestamp += ic->start_time;
2916

    
2917
    /* if seeking requested, we execute it */
2918
    if (start_time != 0) {
2919
        ret = av_seek_frame(ic, -1, timestamp, AVSEEK_FLAG_BACKWARD);
2920
        if (ret < 0) {
2921
            fprintf(stderr, "%s: could not seek to position %0.3f\n",
2922
                    filename, (double)timestamp / AV_TIME_BASE);
2923
        }
2924
        /* reset seek info */
2925
        start_time = 0;
2926
    }
2927

    
2928
    /* update the current parameters so that they match the one of the input stream */
2929
    for(i=0;i<ic->nb_streams;i++) {
2930
        int j;
2931
        AVCodecContext *enc = ic->streams[i]->codec;
2932
#if defined(HAVE_THREADS)
2933
        if(thread_count>1)
2934
            avcodec_thread_init(enc, thread_count);
2935
#endif
2936
        enc->thread_count= thread_count;
2937
        switch(enc->codec_type) {
2938
        case CODEC_TYPE_AUDIO:
2939
            for(j=0; j<opt_name_count; j++){
2940
                AVOption *opt;
2941
                double d= av_get_double(avctx_opts, opt_names[j], &opt);
2942
                if(d==d && (opt->flags&AV_OPT_FLAG_AUDIO_PARAM) && (opt->flags&AV_OPT_FLAG_DECODING_PARAM))
2943
                    av_set_double(enc, opt_names[j], d);
2944
            }
2945
            //fprintf(stderr, "\nInput Audio channels: %d", enc->channels);
2946
            audio_channels = enc->channels;
2947
            audio_sample_rate = enc->sample_rate;
2948
            if(audio_disable)
2949
                ic->streams[i]->discard= AVDISCARD_ALL;
2950
            break;
2951
        case CODEC_TYPE_VIDEO:
2952
            for(j=0; j<opt_name_count; j++){
2953
                AVOption *opt;
2954
                double d= av_get_double(avctx_opts, opt_names[j], &opt);
2955
                if(d==d && (opt->flags&AV_OPT_FLAG_VIDEO_PARAM) && (opt->flags&AV_OPT_FLAG_DECODING_PARAM))
2956
                    av_set_double(enc, opt_names[j], d);
2957
            }
2958
            frame_height = enc->height;
2959
            frame_width = enc->width;
2960
            frame_aspect_ratio = av_q2d(enc->sample_aspect_ratio) * enc->width / enc->height;
2961
            frame_pix_fmt = enc->pix_fmt;
2962
            rfps      = ic->streams[i]->r_frame_rate.num;
2963
            rfps_base = ic->streams[i]->r_frame_rate.den;
2964
            enc->workaround_bugs = workaround_bugs;
2965
            if(enc->lowres) enc->flags |= CODEC_FLAG_EMU_EDGE;
2966
            if(me_threshold)
2967
                enc->debug |= FF_DEBUG_MV;
2968

    
2969
            if (enc->time_base.den != rfps || enc->time_base.num != rfps_base) {
2970

    
2971
                if (verbose >= 0)
2972
                    fprintf(stderr,"\nSeems that stream %d comes from film source: %2.2f (%d/%d) -> %2.2f (%d/%d)\n",
2973
                            i, (float)enc->time_base.den / enc->time_base.num, enc->time_base.den, enc->time_base.num,
2974

    
2975
                    (float)rfps / rfps_base, rfps, rfps_base);
2976
            }
2977
            /* update the current frame rate to match the stream frame rate */
2978
            frame_rate      = rfps;
2979
            frame_rate_base = rfps_base;
2980

    
2981
            enc->rate_emu = rate_emu;
2982
            if(video_disable)
2983
                ic->streams[i]->discard= AVDISCARD_ALL;
2984
            else if(video_discard)
2985
                ic->streams[i]->discard= video_discard;
2986
            break;
2987
        case CODEC_TYPE_DATA:
2988
            break;
2989
        case CODEC_TYPE_SUBTITLE:
2990
            break;
2991
        case CODEC_TYPE_UNKNOWN:
2992
            break;
2993
        default:
2994
            av_abort();
2995
        }
2996
    }
2997

    
2998
    input_files[nb_input_files] = ic;
2999
    input_files_ts_offset[nb_input_files] = input_ts_offset - (copy_ts ? 0 : timestamp);
3000
    /* dump the file content */
3001
    if (verbose >= 0)
3002
        dump_format(ic, nb_input_files, filename, 0);
3003

    
3004
    nb_input_files++;
3005
    file_iformat = NULL;
3006
    file_oformat = NULL;
3007
    image_format = NULL;
3008

    
3009
    grab_device = NULL;
3010
    video_channel = 0;
3011

    
3012
    rate_emu = 0;
3013
}
3014

    
3015
static void opt_grab(const char *arg)
3016
{
3017
    file_iformat = av_find_input_format(arg);
3018
    opt_input_file("");
3019
}
3020

    
3021
static void check_audio_video_inputs(int *has_video_ptr, int *has_audio_ptr)
3022
{
3023
    int has_video, has_audio, i, j;
3024
    AVFormatContext *ic;
3025

    
3026
    has_video = 0;
3027
    has_audio = 0;
3028
    for(j=0;j<nb_input_files;j++) {
3029
        ic = input_files[j];
3030
        for(i=0;i<ic->nb_streams;i++) {
3031
            AVCodecContext *enc = ic->streams[i]->codec;
3032
            switch(enc->codec_type) {
3033
            case CODEC_TYPE_AUDIO:
3034
                has_audio = 1;
3035
                break;
3036
            case CODEC_TYPE_VIDEO:
3037
                has_video = 1;
3038
                break;
3039
            case CODEC_TYPE_DATA:
3040
            case CODEC_TYPE_UNKNOWN:
3041
            case CODEC_TYPE_SUBTITLE:
3042
                break;
3043
            default:
3044
                av_abort();
3045
            }
3046
        }
3047
    }
3048
    *has_video_ptr = has_video;
3049
    *has_audio_ptr = has_audio;
3050
}
3051

    
3052
static void new_video_stream(AVFormatContext *oc)
3053
{
3054
    AVStream *st;
3055
    AVCodecContext *video_enc;
3056
    int codec_id;
3057

    
3058
    st = av_new_stream(oc, oc->nb_streams);
3059
    if (!st) {
3060
        fprintf(stderr, "Could not alloc stream\n");
3061
        exit(1);
3062
    }
3063
#if defined(HAVE_THREADS)
3064
    if(thread_count>1)
3065
        avcodec_thread_init(st->codec, thread_count);
3066
#endif
3067

    
3068
    video_enc = st->codec;
3069

    
3070
    if(video_codec_tag)
3071
        video_enc->codec_tag= video_codec_tag;
3072

    
3073
    if(   (video_global_header&1)
3074
       || (video_global_header==0 && (oc->oformat->flags & AVFMT_GLOBALHEADER))){
3075
        video_enc->flags |= CODEC_FLAG_GLOBAL_HEADER;
3076
        avctx_opts->flags|= CODEC_FLAG_GLOBAL_HEADER;
3077
    }
3078
    if(video_global_header&2){
3079
        video_enc->flags2 |= CODEC_FLAG2_LOCAL_HEADER;
3080
        avctx_opts->flags2|= CODEC_FLAG2_LOCAL_HEADER;
3081
    }
3082

    
3083
    if (video_stream_copy) {
3084
        st->stream_copy = 1;
3085
        video_enc->codec_type = CODEC_TYPE_VIDEO;
3086
    } else {
3087
        char *p;
3088
        int i;
3089
        AVCodec *codec;
3090

    
3091
        codec_id = av_guess_codec(oc->oformat, NULL, oc->filename, NULL, CODEC_TYPE_VIDEO);
3092
        if (video_codec_id != CODEC_ID_NONE)
3093
            codec_id = video_codec_id;
3094

    
3095
        video_enc->codec_id = codec_id;
3096
        codec = avcodec_find_encoder(codec_id);
3097

    
3098
        for(i=0; i<opt_name_count; i++){
3099
             AVOption *opt;
3100
             double d= av_get_double(avctx_opts, opt_names[i], &opt);
3101
             if(d==d && (opt->flags&AV_OPT_FLAG_VIDEO_PARAM) && (opt->flags&AV_OPT_FLAG_ENCODING_PARAM))
3102
                 av_set_double(video_enc, opt_names[i], d);
3103
        }
3104

    
3105
        video_enc->bit_rate = video_bit_rate;
3106
        video_enc->bit_rate_tolerance = video_bit_rate_tolerance;
3107
        video_enc->time_base.den = frame_rate;
3108
        video_enc->time_base.num = frame_rate_base;
3109
        if(codec && codec->supported_framerates){
3110
            const AVRational *p= codec->supported_framerates;
3111
            AVRational req= (AVRational){frame_rate, frame_rate_base};
3112
            const AVRational *best=NULL;
3113
            AVRational best_error= (AVRational){INT_MAX, 1};
3114
            for(; p->den!=0; p++){
3115
                AVRational error= av_sub_q(req, *p);
3116
                if(error.num <0) error.num *= -1;
3117
                if(av_cmp_q(error, best_error) < 0){
3118
                    best_error= error;
3119
                    best= p;
3120
                }
3121
            }
3122
            video_enc->time_base.den= best->num;
3123
            video_enc->time_base.num= best->den;
3124
        }
3125

    
3126
        video_enc->width = frame_width + frame_padright + frame_padleft;
3127
        video_enc->height = frame_height + frame_padtop + frame_padbottom;
3128
        video_enc->sample_aspect_ratio = av_d2q(frame_aspect_ratio*frame_height/frame_width, 255);
3129
        video_enc->pix_fmt = frame_pix_fmt;
3130

    
3131
        if(codec && codec->pix_fmts){
3132
            const enum PixelFormat *p= codec->pix_fmts;
3133
            for(; *p!=-1; p++){
3134
                if(*p == video_enc->pix_fmt)
3135
                    break;
3136
            }
3137
            if(*p == -1)
3138
                video_enc->pix_fmt = codec->pix_fmts[0];
3139
        }
3140

    
3141
        if (!intra_only)
3142
            video_enc->gop_size = gop_size;
3143
        else
3144
            video_enc->gop_size = 0;
3145
        if (video_qscale || same_quality) {
3146
            video_enc->flags |= CODEC_FLAG_QSCALE;
3147
            video_enc->global_quality=
3148
                st->quality = FF_QP2LAMBDA * video_qscale;
3149
        }
3150

    
3151
        if(intra_matrix)
3152
            video_enc->intra_matrix = intra_matrix;
3153
        if(inter_matrix)
3154
            video_enc->inter_matrix = inter_matrix;
3155

    
3156
        video_enc->pre_me = pre_me;
3157

    
3158
        if (b_frames) {
3159
            video_enc->max_b_frames = b_frames;
3160
            video_enc->b_frame_strategy = b_strategy;
3161
            video_enc->b_quant_factor = 2.0;
3162
        }
3163
        video_enc->qmin = video_qmin;
3164
        video_enc->qmax = video_qmax;
3165
        video_enc->lmin = video_lmin;
3166
        video_enc->lmax = video_lmax;
3167
        video_enc->rc_qsquish = video_qsquish;
3168
        video_enc->mb_lmin = video_mb_lmin;
3169
        video_enc->mb_lmax = video_mb_lmax;
3170
        video_enc->max_qdiff = video_qdiff;
3171
        video_enc->qblur = video_qblur;
3172
        video_enc->qcompress = video_qcomp;
3173
        video_enc->rc_eq = video_rc_eq;
3174
        video_enc->workaround_bugs = workaround_bugs;
3175
        video_enc->thread_count = thread_count;
3176
        p= video_rc_override_string;
3177
        for(i=0; p; i++){
3178
            int start, end, q;
3179
            int e=sscanf(p, "%d,%d,%d", &start, &end, &q);
3180
            if(e!=3){
3181
                fprintf(stderr, "error parsing rc_override\n");
3182
                exit(1);
3183
            }
3184
            video_enc->rc_override=
3185
                av_realloc(video_enc->rc_override,
3186
                           sizeof(RcOverride)*(i+1));
3187
            video_enc->rc_override[i].start_frame= start;
3188
            video_enc->rc_override[i].end_frame  = end;
3189
            if(q>0){
3190
                video_enc->rc_override[i].qscale= q;
3191
                video_enc->rc_override[i].quality_factor= 1.0;
3192
            }
3193
            else{
3194
                video_enc->rc_override[i].qscale= 0;
3195
                video_enc->rc_override[i].quality_factor= -q/100.0;
3196
            }
3197
            p= strchr(p, '/');
3198
            if(p) p++;
3199
        }
3200
        video_enc->rc_override_count=i;
3201

    
3202
        video_enc->rc_max_rate = video_rc_max_rate;
3203
        video_enc->rc_min_rate = video_rc_min_rate;
3204
        video_enc->rc_buffer_size = video_rc_buffer_size;
3205
        video_enc->rc_initial_buffer_occupancy = video_rc_buffer_size*3/4;
3206
        video_enc->rc_buffer_aggressivity= video_rc_buffer_aggressivity;
3207
        video_enc->rc_initial_cplx= video_rc_initial_cplx;
3208
        video_enc->i_quant_factor = video_i_qfactor;
3209
        video_enc->b_quant_factor = video_b_qfactor;
3210
        video_enc->i_quant_offset = video_i_qoffset;
3211
        video_enc->b_quant_offset = video_b_qoffset;
3212
        video_enc->intra_quant_bias = video_intra_quant_bias;
3213
        video_enc->inter_quant_bias = video_inter_quant_bias;
3214
        video_enc->me_threshold= me_threshold;
3215
        video_enc->mb_threshold= mb_threshold;
3216
        video_enc->intra_dc_precision= intra_dc_precision - 8;
3217
        video_enc->strict_std_compliance = strict;
3218
        video_enc->error_rate = error_rate;
3219
        video_enc->scenechange_threshold= sc_threshold;
3220
        video_enc->me_range = me_range;
3221
        video_enc->me_penalty_compensation= me_penalty_compensation;
3222
        video_enc->frame_skip_threshold= frame_skip_threshold;
3223
        video_enc->frame_skip_factor= frame_skip_factor;
3224
        video_enc->frame_skip_exp= frame_skip_exp;
3225

    
3226
        if(packet_size){
3227
            video_enc->rtp_mode= 1;
3228
            video_enc->rtp_payload_size= packet_size;
3229
        }
3230

    
3231
        if (do_psnr)
3232
            video_enc->flags|= CODEC_FLAG_PSNR;
3233

    
3234
        video_enc->me_method = me_method;
3235

    
3236
        /* two pass mode */
3237
        if (do_pass) {
3238
            if (do_pass == 1) {
3239
                video_enc->flags |= CODEC_FLAG_PASS1;
3240
            } else {
3241
                video_enc->flags |= CODEC_FLAG_PASS2;
3242
            }
3243
        }
3244
    }
3245

    
3246
    /* reset some key parameters */
3247
    video_disable = 0;
3248
    video_codec_id = CODEC_ID_NONE;
3249
    video_stream_copy = 0;
3250
}
3251

    
3252
static void new_audio_stream(AVFormatContext *oc)
3253
{
3254
    AVStream *st;
3255
    AVCodecContext *audio_enc;
3256
    int codec_id, i;
3257

    
3258
    st = av_new_stream(oc, oc->nb_streams);
3259
    if (!st) {
3260
        fprintf(stderr, "Could not alloc stream\n");
3261
        exit(1);
3262
    }
3263
#if defined(HAVE_THREADS)
3264
    if(thread_count>1)
3265
        avcodec_thread_init(st->codec, thread_count);
3266
#endif
3267

    
3268
    audio_enc = st->codec;
3269
    audio_enc->codec_type = CODEC_TYPE_AUDIO;
3270

    
3271
    if(audio_codec_tag)
3272
        audio_enc->codec_tag= audio_codec_tag;
3273

    
3274
    if (oc->oformat->flags & AVFMT_GLOBALHEADER) {
3275
        audio_enc->flags |= CODEC_FLAG_GLOBAL_HEADER;
3276
        avctx_opts->flags|= CODEC_FLAG_GLOBAL_HEADER;
3277
    }
3278
    if (audio_stream_copy) {
3279
        st->stream_copy = 1;
3280
        audio_enc->channels = audio_channels;
3281
    } else {
3282
        codec_id = av_guess_codec(oc->oformat, NULL, oc->filename, NULL, CODEC_TYPE_AUDIO);
3283

    
3284
        for(i=0; i<opt_name_count; i++){
3285
            AVOption *opt;
3286
            double d= av_get_double(avctx_opts, opt_names[i], &opt);
3287
            if(d==d && (opt->flags&AV_OPT_FLAG_AUDIO_PARAM) && (opt->flags&AV_OPT_FLAG_ENCODING_PARAM))
3288
                av_set_double(audio_enc, opt_names[i], d);
3289
        }
3290

    
3291
        if (audio_codec_id != CODEC_ID_NONE)
3292
            codec_id = audio_codec_id;
3293
        audio_enc->codec_id = codec_id;
3294

    
3295
        audio_enc->bit_rate = audio_bit_rate;
3296
        if (audio_qscale > QSCALE_NONE) {
3297
            audio_enc->flags |= CODEC_FLAG_QSCALE;
3298
            audio_enc->global_quality = st->quality = FF_QP2LAMBDA * audio_qscale;
3299
        }
3300
        audio_enc->strict_std_compliance = strict;
3301
        audio_enc->thread_count = thread_count;
3302
        /* For audio codecs other than AC3 or DTS we limit */
3303
        /* the number of coded channels to stereo   */
3304
        if (audio_channels > 2 && codec_id != CODEC_ID_AC3
3305
            && codec_id != CODEC_ID_DTS) {
3306
            audio_enc->channels = 2;
3307
        } else
3308
            audio_enc->channels = audio_channels;
3309
    }
3310
    audio_enc->sample_rate = audio_sample_rate;
3311
    audio_enc->time_base= (AVRational){1, audio_sample_rate};
3312
    if (audio_language) {
3313
        pstrcpy(st->language, sizeof(st->language), audio_language);
3314
        av_free(audio_language);
3315
        audio_language = NULL;
3316
    }
3317

    
3318
    /* reset some key parameters */
3319
    audio_disable = 0;
3320
    audio_codec_id = CODEC_ID_NONE;
3321
    audio_stream_copy = 0;
3322
}
3323

    
3324
static void opt_new_subtitle_stream(void)
3325
{
3326
    AVFormatContext *oc;
3327
    AVStream *st;
3328
    AVCodecContext *subtitle_enc;
3329
    int i;
3330

    
3331
    if (nb_output_files <= 0) {
3332
        fprintf(stderr, "At least one output file must be specified\n");
3333
        exit(1);
3334
    }
3335
    oc = output_files[nb_output_files - 1];
3336

    
3337
    st = av_new_stream(oc, oc->nb_streams);
3338
    if (!st) {
3339
        fprintf(stderr, "Could not alloc stream\n");
3340
        exit(1);
3341
    }
3342

    
3343
    subtitle_enc = st->codec;
3344
    subtitle_enc->codec_type = CODEC_TYPE_SUBTITLE;
3345
    if (subtitle_stream_copy) {
3346
        st->stream_copy = 1;
3347
    } else {
3348
        for(i=0; i<opt_name_count; i++){
3349
             AVOption *opt;
3350
             double d= av_get_double(avctx_opts, opt_names[i], &opt);
3351
             if(d==d && (opt->flags&AV_OPT_FLAG_SUBTITLE_PARAM) && (opt->flags&AV_OPT_FLAG_ENCODING_PARAM))
3352
                 av_set_double(subtitle_enc, opt_names[i], d);
3353
        }
3354
        subtitle_enc->codec_id = subtitle_codec_id;
3355
    }
3356

    
3357
    if (subtitle_language) {
3358
        pstrcpy(st->language, sizeof(st->language), subtitle_language);
3359
        av_free(subtitle_language);
3360
        subtitle_language = NULL;
3361
    }
3362

    
3363
    subtitle_codec_id = CODEC_ID_NONE;
3364
    subtitle_stream_copy = 0;
3365
}
3366

    
3367
static void opt_new_audio_stream(void)
3368
{
3369
    AVFormatContext *oc;
3370
    if (nb_output_files <= 0) {
3371
        fprintf(stderr, "At least one output file must be specified\n");
3372
        exit(1);
3373
    }
3374
    oc = output_files[nb_output_files - 1];
3375
    new_audio_stream(oc);
3376
}
3377

    
3378
static void opt_new_video_stream(void)
3379
{
3380
    AVFormatContext *oc;
3381
    if (nb_output_files <= 0) {
3382
        fprintf(stderr, "At least one output file must be specified\n");
3383
        exit(1);
3384
    }
3385
    oc = output_files[nb_output_files - 1];
3386
    new_video_stream(oc);
3387
}
3388

    
3389
static void opt_output_file(const char *filename)
3390
{
3391
    AVFormatContext *oc;
3392
    int use_video, use_audio, input_has_video, input_has_audio;
3393
    AVFormatParameters params, *ap = &params;
3394

    
3395
    if (!strcmp(filename, "-"))
3396
        filename = "pipe:";
3397

    
3398
    oc = av_alloc_format_context();
3399

    
3400
    if (!file_oformat) {
3401
        file_oformat = guess_format(NULL, filename, NULL);
3402
        if (!file_oformat) {
3403
            fprintf(stderr, "Unable for find a suitable output format for '%s'\n",
3404
                    filename);
3405
            exit(1);
3406
        }
3407
    }
3408

    
3409
    oc->oformat = file_oformat;
3410
    pstrcpy(oc->filename, sizeof(oc->filename), filename);
3411

    
3412
    if (!strcmp(file_oformat->name, "ffm") &&
3413
        strstart(filename, "http:", NULL)) {
3414
        /* special case for files sent to ffserver: we get the stream
3415
           parameters from ffserver */
3416
        if (read_ffserver_streams(oc, filename) < 0) {
3417
            fprintf(stderr, "Could not read stream parameters from '%s'\n", filename);
3418
            exit(1);
3419
        }
3420
    } else {
3421
        use_video = file_oformat->video_codec != CODEC_ID_NONE || video_stream_copy || video_codec_id != CODEC_ID_NONE;
3422
        use_audio = file_oformat->audio_codec != CODEC_ID_NONE || audio_stream_copy || audio_codec_id != CODEC_ID_NONE;
3423

    
3424
        /* disable if no corresponding type found and at least one
3425
           input file */
3426
        if (nb_input_files > 0) {
3427
            check_audio_video_inputs(&input_has_video, &input_has_audio);
3428
            if (!input_has_video)
3429
                use_video = 0;
3430
            if (!input_has_audio)
3431
                use_audio = 0;
3432
        }
3433

    
3434
        /* manual disable */
3435
        if (audio_disable) {
3436
            use_audio = 0;
3437
        }
3438
        if (video_disable) {
3439
            use_video = 0;
3440
        }
3441

    
3442
        if (use_video) {
3443
            new_video_stream(oc);
3444
        }
3445

    
3446
        if (use_audio) {
3447
            new_audio_stream(oc);
3448
        }
3449

    
3450
        if (!oc->nb_streams) {
3451
            fprintf(stderr, "No audio or video streams available\n");
3452
            exit(1);
3453
        }
3454

    
3455
        oc->timestamp = rec_timestamp;
3456

    
3457
        if (str_title)
3458
            pstrcpy(oc->title, sizeof(oc->title), str_title);
3459
        if (str_author)
3460
            pstrcpy(oc->author, sizeof(oc->author), str_author);
3461
        if (str_copyright)
3462
            pstrcpy(oc->copyright, sizeof(oc->copyright), str_copyright);
3463
        if (str_comment)
3464
            pstrcpy(oc->comment, sizeof(oc->comment), str_comment);
3465
    }
3466

    
3467
    output_files[nb_output_files++] = oc;
3468

    
3469
    /* check filename in case of an image number is expected */
3470
    if (oc->oformat->flags & AVFMT_NEEDNUMBER) {
3471
        if (filename_number_test(oc->filename) < 0) {
3472
            print_error(oc->filename, AVERROR_NUMEXPECTED);
3473
            exit(1);
3474
        }
3475
    }
3476

    
3477
    if (!(oc->oformat->flags & AVFMT_NOFILE)) {
3478
        /* test if it already exists to avoid loosing precious files */
3479
        if (!file_overwrite &&
3480
            (strchr(filename, ':') == NULL ||
3481
             strstart(filename, "file:", NULL))) {
3482
            if (url_exist(filename)) {
3483
                int c;
3484

    
3485
                if ( !using_stdin ) {
3486
                    fprintf(stderr,"File '%s' already exists. Overwrite ? [y/N] ", filename);
3487
                    fflush(stderr);
3488
                    c = getchar();
3489
                    if (toupper(c) != 'Y') {
3490
                        fprintf(stderr, "Not overwriting - exiting\n");
3491
                        exit(1);
3492
                    }
3493
                                }
3494
                                else {
3495
                    fprintf(stderr,"File '%s' already exists. Exiting.\n", filename);
3496
                    exit(1);
3497
                                }
3498
            }
3499
        }
3500

    
3501
        /* open the file */
3502
        if (url_fopen(&oc->pb, filename, URL_WRONLY) < 0) {
3503
            fprintf(stderr, "Could not open '%s'\n", filename);
3504
            exit(1);
3505
        }
3506
    }
3507

    
3508
    memset(ap, 0, sizeof(*ap));
3509
    ap->image_format = image_format;
3510
    if (av_set_parameters(oc, ap) < 0) {
3511
        fprintf(stderr, "%s: Invalid encoding parameters\n",
3512
                oc->filename);
3513
        exit(1);
3514
    }
3515

    
3516
    oc->packet_size= mux_packet_size;
3517
    oc->mux_rate= mux_rate;
3518
    oc->preload= (int)(mux_preload*AV_TIME_BASE);
3519
    oc->max_delay= (int)(mux_max_delay*AV_TIME_BASE);
3520
    oc->loop_output = loop_output;
3521

    
3522
    /* reset some options */
3523
    file_oformat = NULL;
3524
    file_iformat = NULL;
3525
    image_format = NULL;
3526
}
3527

    
3528
/* prepare dummy protocols for grab */
3529
static void prepare_grab(void)
3530
{
3531
    int has_video, has_audio, i, j;
3532
    AVFormatContext *oc;
3533
    AVFormatContext *ic;
3534
    AVFormatParameters vp1, *vp = &vp1;
3535
    AVFormatParameters ap1, *ap = &ap1;
3536

    
3537
    /* see if audio/video inputs are needed */
3538
    has_video = 0;
3539
    has_audio = 0;
3540
    memset(ap, 0, sizeof(*ap));
3541
    memset(vp, 0, sizeof(*vp));
3542
    vp->time_base.num= 1;
3543
    for(j=0;j<nb_output_files;j++) {
3544
        oc = output_files[j];
3545
        for(i=0;i<oc->nb_streams;i++) {
3546
            AVCodecContext *enc = oc->streams[i]->codec;
3547
            switch(enc->codec_type) {
3548
            case CODEC_TYPE_AUDIO:
3549
                if (enc->sample_rate > ap->sample_rate)
3550
                    ap->sample_rate = enc->sample_rate;
3551
                if (enc->channels > ap->channels)
3552
                    ap->channels = enc->channels;
3553
                has_audio = 1;
3554
                break;
3555
            case CODEC_TYPE_VIDEO:
3556
                if (enc->width > vp->width)
3557
                    vp->width = enc->width;
3558
                if (enc->height > vp->height)
3559
                    vp->height = enc->height;
3560

    
3561
                if (vp->time_base.num*(int64_t)enc->time_base.den > enc->time_base.num*(int64_t)vp->time_base.den){
3562
                    vp->time_base = enc->time_base;
3563
                }
3564
                has_video = 1;
3565
                break;
3566
            default:
3567
                av_abort();
3568
            }
3569
        }
3570
    }
3571

    
3572
    if (has_video == 0 && has_audio == 0) {
3573
        fprintf(stderr, "Output file must have at least one audio or video stream\n");
3574
        exit(1);
3575
    }
3576

    
3577
    if (has_video) {
3578
        AVInputFormat *fmt1;
3579
        fmt1 = av_find_input_format(video_grab_format);
3580
        vp->device  = video_device;
3581
        vp->channel = video_channel;
3582
        vp->standard = video_standard;
3583
        if (av_open_input_file(&ic, "", fmt1, 0, vp) < 0) {
3584
            fprintf(stderr, "Could not find video grab device\n");
3585
            exit(1);
3586
        }
3587
        /* If not enough info to get the stream parameters, we decode the
3588
           first frames to get it. */
3589
        if ((ic->ctx_flags & AVFMTCTX_NOHEADER) && av_find_stream_info(ic) < 0) {
3590
            fprintf(stderr, "Could not find video grab parameters\n");
3591
            exit(1);
3592
        }
3593
        /* by now video grab has one stream */
3594
        ic->streams[0]->r_frame_rate.num = vp->time_base.den;
3595
        ic->streams[0]->r_frame_rate.den = vp->time_base.num;
3596
        input_files[nb_input_files] = ic;
3597

    
3598
        if (verbose >= 0)
3599
            dump_format(ic, nb_input_files, "", 0);
3600

    
3601
        nb_input_files++;
3602
    }
3603
    if (has_audio && audio_grab_format) {
3604
        AVInputFormat *fmt1;
3605
        fmt1 = av_find_input_format(audio_grab_format);
3606
        ap->device = audio_device;
3607
        if (av_open_input_file(&ic, "", fmt1, 0, ap) < 0) {
3608
            fprintf(stderr, "Could not find audio grab device\n");
3609
            exit(1);
3610
        }
3611
        input_files[nb_input_files] = ic;
3612

    
3613
        if (verbose >= 0)
3614
            dump_format(ic, nb_input_files, "", 0);
3615

    
3616
        nb_input_files++;
3617
    }
3618
}
3619

    
3620
/* same option as mencoder */
3621
static void opt_pass(const char *pass_str)
3622
{
3623
    int pass;
3624
    pass = atoi(pass_str);
3625
    if (pass != 1 && pass != 2) {
3626
        fprintf(stderr, "pass number can be only 1 or 2\n");
3627
        exit(1);
3628
    }
3629
    do_pass = pass;
3630
}
3631

    
3632
#if defined(CONFIG_WIN32) || defined(CONFIG_OS2)
3633
static int64_t getutime(void)
3634
{
3635
  return av_gettime();
3636
}
3637
#else
3638
static int64_t getutime(void)
3639
{
3640
    struct rusage rusage;
3641

    
3642
    getrusage(RUSAGE_SELF, &rusage);
3643
    return (rusage.ru_utime.tv_sec * 1000000LL) + rusage.ru_utime.tv_usec;
3644
}
3645
#endif
3646

    
3647
extern int ffm_nopts;
3648

    
3649
static void show_formats(void)
3650
{
3651
    AVInputFormat *ifmt;
3652
    AVOutputFormat *ofmt;
3653
    AVImageFormat *image_fmt;
3654
    URLProtocol *up;
3655
    AVCodec *p, *p2;
3656
    const char **pp, *last_name;
3657

    
3658
    printf("File formats:\n");
3659
    last_name= "000";
3660
    for(;;){
3661
        int decode=0;
3662
        int encode=0;
3663
        const char *name=NULL;
3664
        const char *long_name=NULL;
3665

    
3666
        for(ofmt = first_oformat; ofmt != NULL; ofmt = ofmt->next) {
3667
            if((name == NULL || strcmp(ofmt->name, name)<0) &&
3668
                strcmp(ofmt->name, last_name)>0){
3669
                name= ofmt->name;
3670
                long_name= ofmt->long_name;
3671
                encode=1;
3672
            }
3673
        }
3674
        for(ifmt = first_iformat; ifmt != NULL; ifmt = ifmt->next) {
3675
            if((name == NULL || strcmp(ifmt->name, name)<0) &&
3676
                strcmp(ifmt->name, last_name)>0){
3677
                name= ifmt->name;
3678
                long_name= ifmt->long_name;
3679
                encode=0;
3680
            }
3681
            if(name && strcmp(ifmt->name, name)==0)
3682
                decode=1;
3683
        }
3684
        if(name==NULL)
3685
            break;
3686
        last_name= name;
3687

    
3688
        printf(
3689
            " %s%s %-15s %s\n",
3690
            decode ? "D":" ",
3691
            encode ? "E":" ",
3692
            name,
3693
            long_name ? long_name:" ");
3694
    }
3695
    printf("\n");
3696

    
3697
    printf("Image formats (filename extensions, if any, follow):\n");
3698
    for(image_fmt = first_image_format; image_fmt != NULL;
3699
        image_fmt = image_fmt->next) {
3700
        printf(
3701
            " %s%s %-6s %s\n",
3702
            image_fmt->img_read  ? "D":" ",
3703
            image_fmt->img_write ? "E":" ",
3704
            image_fmt->name,
3705
            image_fmt->extensions ? image_fmt->extensions:" ");
3706
    }
3707
    printf("\n");
3708

    
3709
    printf("Codecs:\n");
3710
    last_name= "000";
3711
    for(;;){
3712
        int decode=0;
3713
        int encode=0;
3714
        int cap=0;
3715
        const char *type_str;
3716

    
3717
        p2=NULL;
3718
        for(p = first_avcodec; p != NULL; p = p->next) {
3719
            if((p2==NULL || strcmp(p->name, p2->name)<0) &&
3720
                strcmp(p->name, last_name)>0){
3721
                p2= p;
3722
                decode= encode= cap=0;
3723
            }
3724
            if(p2 && strcmp(p->name, p2->name)==0){
3725
                if(p->decode) decode=1;
3726
                if(p->encode) encode=1;
3727
                cap |= p->capabilities;
3728
            }
3729
        }
3730
        if(p2==NULL)
3731
            break;
3732
        last_name= p2->name;
3733

    
3734
        switch(p2->type) {
3735
        case CODEC_TYPE_VIDEO:
3736
            type_str = "V";
3737
            break;
3738
        case CODEC_TYPE_AUDIO:
3739
            type_str = "A";
3740
            break;
3741
        case CODEC_TYPE_SUBTITLE:
3742
            type_str = "S";
3743
            break;
3744
        default:
3745
            type_str = "?";
3746
            break;
3747
        }
3748
        printf(
3749
            " %s%s%s%s%s%s %s",
3750
            decode ? "D": (/*p2->decoder ? "d":*/" "),
3751
            encode ? "E":" ",
3752
            type_str,
3753
            cap & CODEC_CAP_DRAW_HORIZ_BAND ? "S":" ",
3754
            cap & CODEC_CAP_DR1 ? "D":" ",
3755
            cap & CODEC_CAP_TRUNCATED ? "T":" ",
3756
            p2->name);
3757
       /* if(p2->decoder && decode==0)
3758
            printf(" use %s for decoding", p2->decoder->name);*/
3759
        printf("\n");
3760
    }
3761
    printf("\n");
3762

    
3763
    printf("Supported file protocols:\n");
3764
    for(up = first_protocol; up != NULL; up = up->next)
3765
        printf(" %s:", up->name);
3766
    printf("\n");
3767

    
3768
    printf("Frame size, frame rate abbreviations:\n ntsc pal qntsc qpal sntsc spal film ntsc-film sqcif qcif cif 4cif\n");
3769
    printf("Motion estimation methods:\n");
3770
    pp = motion_str;
3771
    while (*pp) {
3772
        printf(" %s", *pp);
3773
        if ((pp - motion_str + 1) == ME_ZERO)
3774
            printf("(fastest)");
3775
        else if ((pp - motion_str + 1) == ME_FULL)
3776
            printf("(slowest)");
3777
        else if ((pp - motion_str + 1) == ME_EPZS)
3778
            printf("(default)");
3779
        pp++;
3780
    }
3781
    printf("\n\n");
3782
    printf(
3783
"Note, the names of encoders and decoders dont always match, so there are\n"
3784
"several cases where the above table shows encoder only or decoder only entries\n"
3785
"even though both encoding and decoding are supported for example, the h263\n"
3786
"decoder corresponds to the h263 and h263p encoders, for file formats its even\n"
3787
"worse\n");
3788
    exit(1);
3789
}
3790

    
3791
void parse_matrix_coeffs(uint16_t *dest, const char *str)
3792
{
3793
    int i;
3794
    const char *p = str;
3795
    for(i = 0;; i++) {
3796
        dest[i] = atoi(p);
3797
        if(i == 63)
3798
            break;
3799
        p = strchr(p, ',');
3800
        if(!p) {
3801
            fprintf(stderr, "Syntax error in matrix \"%s\" at coeff %d\n", str, i);
3802
            exit(1);
3803
        }
3804
        p++;
3805
    }
3806
}
3807

    
3808
void opt_inter_matrix(const char *arg)
3809
{
3810
    inter_matrix = av_mallocz(sizeof(uint16_t) * 64);
3811
    parse_matrix_coeffs(inter_matrix, arg);
3812
}
3813

    
3814
void opt_intra_matrix(const char *arg)
3815
{
3816
    intra_matrix = av_mallocz(sizeof(uint16_t) * 64);
3817
    parse_matrix_coeffs(intra_matrix, arg);
3818
}
3819

    
3820
static void opt_target(const char *arg)
3821
{
3822
    int norm = -1;
3823
    static const char *const frame_rates[] = {"25", "30000/1001", "24000/1001"};
3824

    
3825
    if(!strncmp(arg, "pal-", 4)) {
3826
        norm = 0;
3827
        arg += 4;
3828
    } else if(!strncmp(arg, "ntsc-", 5)) {
3829
        norm = 1;
3830
        arg += 5;
3831
    } else if(!strncmp(arg, "film-", 5)) {
3832
        norm = 2;
3833
        arg += 5;
3834
    } else {
3835
        int fr;
3836
        /* Calculate FR via float to avoid int overflow */
3837
        fr = (int)(frame_rate * 1000.0 / frame_rate_base);
3838
        if(fr == 25000) {
3839
            norm = 0;
3840
        } else if((fr == 29970) || (fr == 23976)) {
3841
            norm = 1;
3842
        } else {
3843
            /* Try to determine PAL/NTSC by peeking in the input files */
3844
            if(nb_input_files) {
3845
                int i, j;
3846
                for(j = 0; j < nb_input_files; j++) {
3847
                    for(i = 0; i < input_files[j]->nb_streams; i++) {
3848
                        AVCodecContext *c = input_files[j]->streams[i]->codec;
3849
                        if(c->codec_type != CODEC_TYPE_VIDEO)
3850
                            continue;
3851
                        fr = c->time_base.den * 1000 / c->time_base.num;
3852
                        if(fr == 25000) {
3853
                            norm = 0;
3854
                            break;
3855
                        } else if((fr == 29970) || (fr == 23976)) {
3856
                            norm = 1;
3857
                            break;
3858
                        }
3859
                    }
3860
                    if(norm >= 0)
3861
                        break;
3862
                }
3863
            }
3864
        }
3865
        if(verbose && norm >= 0)
3866
            fprintf(stderr, "Assuming %s for target.\n", norm ? "NTSC" : "PAL");
3867
    }
3868

    
3869
    if(norm < 0) {
3870
        fprintf(stderr, "Could not determine norm (PAL/NTSC/NTSC-Film) for target.\n");
3871
        fprintf(stderr, "Please prefix target with \"pal-\", \"ntsc-\" or \"film-\",\n");
3872
        fprintf(stderr, "or set a framerate with \"-r xxx\".\n");
3873
        exit(1);
3874
    }
3875

    
3876
    if(!strcmp(arg, "vcd")) {
3877

    
3878
        opt_video_codec("mpeg1video");
3879
        opt_audio_codec("mp2");
3880
        opt_format("vcd");
3881

    
3882
        opt_frame_size(norm ? "352x240" : "352x288");
3883
        opt_frame_rate(frame_rates[norm]);
3884
        opt_gop_size(norm ? "18" : "15");
3885

    
3886
        video_bit_rate = 1150000;
3887
        video_rc_max_rate = 1150000;
3888
        video_rc_min_rate = 1150000;
3889
        video_rc_buffer_size = 40*1024*8;
3890

    
3891
        audio_bit_rate = 224000;
3892
        audio_sample_rate = 44100;
3893

    
3894
        mux_packet_size= 2324;
3895
        mux_rate= 2352 * 75 * 8;
3896

    
3897
        /* We have to offset the PTS, so that it is consistent with the SCR.
3898
           SCR starts at 36000, but the first two packs contain only padding
3899
           and the first pack from the other stream, respectively, may also have
3900
           been written before.
3901
           So the real data starts at SCR 36000+3*1200. */
3902
        mux_preload= (36000+3*1200) / 90000.0; //0.44
3903
    } else if(!strcmp(arg, "svcd")) {
3904

    
3905
        opt_video_codec("mpeg2video");
3906
        opt_audio_codec("mp2");
3907
        opt_format("svcd");
3908

    
3909
        opt_frame_size(norm ? "480x480" : "480x576");
3910
        opt_frame_rate(frame_rates[norm]);
3911
        opt_gop_size(norm ? "18" : "15");
3912

    
3913
        video_bit_rate = 2040000;
3914
        video_rc_max_rate = 2516000;
3915
        video_rc_min_rate = 0; //1145000;
3916
        video_rc_buffer_size = 224*1024*8;
3917
        opt_default("flags", "+SCAN_OFFSET");
3918

    
3919

    
3920
        audio_bit_rate = 224000;
3921
        audio_sample_rate = 44100;
3922

    
3923
        mux_packet_size= 2324;
3924

    
3925
    } else if(!strcmp(arg, "dvd")) {
3926

    
3927
        opt_video_codec("mpeg2video");
3928
        opt_audio_codec("ac3");
3929
        opt_format("dvd");
3930

    
3931
        opt_frame_size(norm ? "720x480" : "720x576");
3932
        opt_frame_rate(frame_rates[norm]);
3933
        opt_gop_size(norm ? "18" : "15");
3934

    
3935
        video_bit_rate = 6000000;
3936
        video_rc_max_rate = 9000000;
3937
        video_rc_min_rate = 0; //1500000;
3938
        video_rc_buffer_size = 224*1024*8;
3939

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

    
3943
        audio_bit_rate = 448000;
3944
        audio_sample_rate = 48000;
3945

    
3946
    } else if(!strcmp(arg, "dv")) {
3947

    
3948
        opt_format("dv");
3949

    
3950
        opt_frame_size(norm ? "720x480" : "720x576");
3951
        opt_frame_rate(frame_rates[norm]);
3952

    
3953
        audio_sample_rate = 48000;
3954
        audio_channels = 2;
3955

    
3956
    } else {
3957
        fprintf(stderr, "Unknown target: %s\n", arg);
3958
        exit(1);
3959
    }
3960
}
3961

    
3962
static void show_version(void)
3963
{
3964
    fprintf(stderr, "ffmpeg      " FFMPEG_VERSION "\n"
3965
           "libavcodec  %d\n"
3966
           "libavformat %d\n",
3967
           avcodec_build(), LIBAVFORMAT_BUILD);
3968
    exit(1);
3969
}
3970

    
3971
static int opt_default(const char *opt, const char *arg){
3972
    AVOption *o= av_set_string(avctx_opts, opt, arg);
3973
    if(!o)
3974
        return -1;
3975

    
3976
//    av_log(NULL, AV_LOG_ERROR, "%s:%s: %f 0x%0X\n", opt, arg, av_get_double(avctx_opts, opt, NULL), (int)av_get_int(avctx_opts, opt, NULL));
3977

    
3978
    //FIXME we should always use avctx_opts, ... for storing options so there wont be any need to keep track of whats set over this
3979
    opt_names= av_realloc(opt_names, sizeof(void*)*(opt_name_count+1));
3980
    opt_names[opt_name_count++]= o->name;
3981

    
3982
    /* disable generate of real time pts in ffm (need to be supressed anyway) */
3983
    if(avctx_opts->flags & CODEC_FLAG_BITEXACT)
3984
        ffm_nopts = 1;
3985

    
3986
    if(avctx_opts->debug)
3987
        av_log_set_level(AV_LOG_DEBUG);
3988
    return 0;
3989
}
3990

    
3991
const OptionDef options[] = {
3992
    /* main options */
3993
    { "L", 0, {(void*)show_license}, "show license" },
3994
    { "h", 0, {(void*)show_help}, "show help" },
3995
    { "version", 0, {(void*)show_version}, "show version" },
3996
    { "formats", 0, {(void*)show_formats}, "show available formats, codecs, protocols, ..." },
3997
    { "f", HAS_ARG, {(void*)opt_format}, "force format", "fmt" },
3998
    { "img", HAS_ARG, {(void*)opt_image_format}, "force image format", "img_fmt" },
3999
    { "i", HAS_ARG, {(void*)opt_input_file}, "input file name", "filename" },
4000
    { "y", OPT_BOOL, {(void*)&file_overwrite}, "overwrite output files" },
4001
    { "map", HAS_ARG | OPT_EXPERT, {(void*)opt_map}, "set input stream mapping", "file:stream[:syncfile:syncstream]" },
4002
    { "map_meta_data", HAS_ARG | OPT_EXPERT, {(void*)opt_map_meta_data}, "set meta data information of outfile from infile", "outfile:infile" },
4003
    { "t", HAS_ARG, {(void*)opt_recording_time}, "set the recording time", "duration" },
4004
    { "fs", HAS_ARG | OPT_INT, {(void*)&limit_filesize}, "set the limit file size", "limit_size" }, //
4005
    { "ss", HAS_ARG, {(void*)opt_start_time}, "set the start time offset", "time_off" },
4006
    { "itsoffset", HAS_ARG, {(void*)opt_input_ts_offset}, "set the input ts offset", "time_off" },
4007
    { "title", HAS_ARG | OPT_STRING, {(void*)&str_title}, "set the title", "string" },
4008
    { "timestamp", HAS_ARG, {(void*)&opt_rec_timestamp}, "set the timestamp", "time" },
4009
    { "author", HAS_ARG | OPT_STRING, {(void*)&str_author}, "set the author", "string" },
4010
    { "copyright", HAS_ARG | OPT_STRING, {(void*)&str_copyright}, "set the copyright", "string" },
4011
    { "comment", HAS_ARG | OPT_STRING, {(void*)&str_comment}, "set the comment", "string" },
4012
    { "benchmark", OPT_BOOL | OPT_EXPERT, {(void*)&do_benchmark},
4013
      "add timings for benchmarking" },
4014
    { "dump", OPT_BOOL | OPT_EXPERT, {(void*)&do_pkt_dump},
4015
      "dump each input packet" },
4016
    { "hex", OPT_BOOL | OPT_EXPERT, {(void*)&do_hex_dump},
4017
      "when dumping packets, also dump the payload" },
4018
    { "re", OPT_BOOL | OPT_EXPERT, {(void*)&rate_emu}, "read input at native frame rate", "" },
4019
    { "loop", OPT_BOOL | OPT_EXPERT, {(void*)&loop_input}, "loop (current only works with images)" },
4020
    { "loop_output", HAS_ARG | OPT_INT | OPT_EXPERT, {(void*)&loop_output}, "number of times to loop output in formats that support looping (0 loops forever)", "" },
4021
    { "v", HAS_ARG, {(void*)opt_verbose}, "control amount of logging", "verbose" },
4022
    { "target", HAS_ARG, {(void*)opt_target}, "specify target file type (\"vcd\", \"svcd\", \"dvd\", \"dv\", \"pal-vcd\", \"ntsc-svcd\", ...)", "type" },
4023
    { "threads", HAS_ARG | OPT_EXPERT, {(void*)opt_thread_count}, "thread count", "count" },
4024
    { "vsync", HAS_ARG | OPT_INT | OPT_EXPERT, {(void*)&video_sync_method}, "video sync method", "" },
4025
    { "async", HAS_ARG | OPT_INT | OPT_EXPERT, {(void*)&audio_sync_method}, "audio sync method", "" },
4026
    { "vglobal", HAS_ARG | OPT_INT | OPT_EXPERT, {(void*)&video_global_header}, "video global header storage type", "" },
4027
    { "copyts", OPT_BOOL | OPT_EXPERT, {(void*)&copy_ts}, "copy timestamps" },
4028
    { "shortest", OPT_BOOL | OPT_EXPERT, {(void*)&opt_shortest}, "finish encoding within shortest input" }, //
4029

    
4030
    /* video options */
4031
    { "b", HAS_ARG | OPT_VIDEO, {(void*)opt_video_bitrate}, "set video bitrate (in kbit/s)", "bitrate" },
4032
    { "vframes", OPT_INT | HAS_ARG | OPT_VIDEO, {(void*)&max_frames[CODEC_TYPE_VIDEO]}, "set the number of video frames to record", "number" },
4033
    { "aframes", OPT_INT | HAS_ARG | OPT_AUDIO, {(void*)&max_frames[CODEC_TYPE_AUDIO]}, "set the number of audio frames to record", "number" },
4034
    { "dframes", OPT_INT | HAS_ARG, {(void*)&max_frames[CODEC_TYPE_DATA]}, "set the number of data frames to record", "number" },
4035
    { "r", HAS_ARG | OPT_VIDEO, {(void*)opt_frame_rate}, "set frame rate (Hz value, fraction or abbreviation)", "rate" },
4036
    { "s", HAS_ARG | OPT_VIDEO, {(void*)opt_frame_size}, "set frame size (WxH or abbreviation)", "size" },
4037
    { "aspect", HAS_ARG | OPT_VIDEO, {(void*)opt_frame_aspect_ratio}, "set aspect ratio (4:3, 16:9 or 1.3333, 1.7777)", "aspect" },
4038
    { "pix_fmt", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_frame_pix_fmt}, "set pixel format", "format" },
4039
    { "croptop", HAS_ARG | OPT_VIDEO, {(void*)opt_frame_crop_top}, "set top crop band size (in pixels)", "size" },
4040
    { "cropbottom", HAS_ARG | OPT_VIDEO, {(void*)opt_frame_crop_bottom}, "set bottom crop band size (in pixels)", "size" },
4041
    { "cropleft", HAS_ARG | OPT_VIDEO, {(void*)opt_frame_crop_left}, "set left crop band size (in pixels)", "size" },
4042
    { "cropright", HAS_ARG | OPT_VIDEO, {(void*)opt_frame_crop_right}, "set right crop band size (in pixels)", "size" },
4043
    { "padtop", HAS_ARG | OPT_VIDEO, {(void*)opt_frame_pad_top}, "set top pad band size (in pixels)", "size" },
4044
    { "padbottom", HAS_ARG | OPT_VIDEO, {(void*)opt_frame_pad_bottom}, "set bottom pad band size (in pixels)", "size" },
4045
    { "padleft", HAS_ARG | OPT_VIDEO, {(void*)opt_frame_pad_left}, "set left pad band size (in pixels)", "size" },
4046
    { "padright", HAS_ARG | OPT_VIDEO, {(void*)opt_frame_pad_right}, "set right pad band size (in pixels)", "size" },
4047
    { "padcolor", HAS_ARG | OPT_VIDEO, {(void*)opt_pad_color}, "set color of pad bands (Hex 000000 thru FFFFFF)", "color" },
4048
    { "g", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_gop_size}, "set the group of picture size", "gop_size" },
4049
    { "intra", OPT_BOOL | OPT_EXPERT | OPT_VIDEO, {(void*)&intra_only}, "use only intra frames"},
4050
    { "vn", OPT_BOOL | OPT_VIDEO, {(void*)&video_disable}, "disable video" },
4051
    { "vdt", OPT_INT | HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)&video_discard}, "discard threshold", "n" },
4052
    { "qscale", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_qscale}, "use fixed video quantiser scale (VBR)", "q" },
4053
    { "qmin", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_qmin}, "min video quantiser scale (VBR)", "q" },
4054
    { "qmax", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_qmax}, "max video quantiser scale (VBR)", "q" },
4055
    { "lmin", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_lmin}, "min video lagrange factor (VBR)", "lambda" },
4056
    { "lmax", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_lmax}, "max video lagrange factor (VBR)", "lambda" },
4057
    { "mblmin", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_mb_lmin}, "min macroblock quantiser scale (VBR)", "q" },
4058
    { "mblmax", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_mb_lmax}, "max macroblock quantiser scale (VBR)", "q" },
4059
    { "qdiff", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_qdiff}, "max difference between the quantiser scale (VBR)", "q" },
4060
    { "qblur", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_qblur}, "video quantiser scale blur (VBR)", "blur" },
4061
    { "qsquish", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_qsquish}, "how to keep quantiser between qmin and qmax (0 = clip, 1 = use differentiable function)", "squish" },
4062
    { "qcomp", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_qcomp}, "video quantiser scale compression (VBR)", "compression" },
4063
    { "rc_init_cplx", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_rc_initial_cplx}, "initial complexity for 1-pass encoding", "complexity" },
4064
    { "b_qfactor", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_b_qfactor}, "qp factor between p and b frames", "factor" },
4065
    { "i_qfactor", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_i_qfactor}, "qp factor between p and i frames", "factor" },
4066
    { "b_qoffset", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_b_qoffset}, "qp offset between p and b frames", "offset" },
4067
    { "i_qoffset", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_i_qoffset}, "qp offset between p and i frames", "offset" },
4068
    { "ibias", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_ibias}, "intra quant bias", "bias" },
4069
    { "pbias", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_pbias}, "inter quant bias", "bias" },
4070
    { "b_strategy", HAS_ARG | OPT_INT | OPT_EXPERT, {(void*)&b_strategy}, "dynamic b frame selection strategy", "strategy" },
4071
    { "rc_eq", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_video_rc_eq}, "set rate control equation", "equation" },
4072
    { "rc_override", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_video_rc_override_string}, "rate control override for specific intervals", "override" },
4073
    { "bt", HAS_ARG | OPT_VIDEO, {(void*)opt_video_bitrate_tolerance}, "set video bitrate tolerance (in kbit/s)", "tolerance" },
4074
    { "maxrate", HAS_ARG | OPT_VIDEO, {(void*)opt_video_bitrate_max}, "set max video bitrate tolerance (in kbit/s)", "bitrate" },
4075
    { "minrate", HAS_ARG | OPT_VIDEO, {(void*)opt_video_bitrate_min}, "set min video bitrate tolerance (in kbit/s)", "bitrate" },
4076
    { "bufsize", HAS_ARG | OPT_VIDEO, {(void*)opt_video_buffer_size}, "set ratecontrol buffer size (in kByte)", "size" },
4077
    { "vcodec", HAS_ARG | OPT_VIDEO, {(void*)opt_video_codec}, "force video codec ('copy' to copy stream)", "codec" },
4078
    { "me", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_motion_estimation}, "set motion estimation method",
4079
      "method" },
4080
    { "me_threshold", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_me_threshold}, "motion estimaton threshold",  "" },
4081
    { "mb_threshold", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_mb_threshold}, "macroblock threshold",  "" },
4082
    { "bf", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_b_frames}, "use 'frames' B frames", "frames" },
4083
    { "preme", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_pre_me}, "pre motion estimation", "" },
4084
    { "bug", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_workaround_bugs}, "workaround not auto detected encoder bugs", "param" },
4085
    { "ps", HAS_ARG | OPT_EXPERT, {(void*)opt_packet_size}, "set packet size in bits", "size" },
4086
    { "error", HAS_ARG | OPT_EXPERT, {(void*)opt_error_rate}, "error rate", "rate" },
4087
    { "strict", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_strict}, "how strictly to follow the standards", "strictness" },
4088
    { "sameq", OPT_BOOL | OPT_VIDEO, {(void*)&same_quality},
4089
      "use same video quality as source (implies VBR)" },
4090
    { "pass", HAS_ARG | OPT_VIDEO, {(void*)&opt_pass}, "select the pass number (1 or 2)", "n" },
4091
    { "passlogfile", HAS_ARG | OPT_STRING | OPT_VIDEO, {(void*)&pass_logfilename}, "select two pass log file name", "file" },
4092
    { "deinterlace", OPT_BOOL | OPT_EXPERT | OPT_VIDEO, {(void*)&do_deinterlace},
4093
      "deinterlace pictures" },
4094
    { "psnr", OPT_BOOL | OPT_EXPERT | OPT_VIDEO, {(void*)&do_psnr}, "calculate PSNR of compressed frames" },
4095
    { "vstats", OPT_BOOL | OPT_EXPERT | OPT_VIDEO, {(void*)&do_vstats}, "dump video coding statistics to file" },
4096
    { "vhook", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)add_frame_hooker}, "insert video processing module", "module" },
4097
    { "intra_matrix", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_intra_matrix}, "specify intra matrix coeffs", "matrix" },
4098
    { "inter_matrix", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_inter_matrix}, "specify inter matrix coeffs", "matrix" },
4099
    { "top", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_top_field_first}, "top=1/bottom=0/auto=-1 field first", "" },
4100
    { "sc_threshold", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_sc_threshold}, "scene change threshold", "threshold" },
4101
    { "me_range", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_me_range}, "limit motion vectors range (1023 for DivX player)", "range" },
4102
    { "dc", OPT_INT | HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)&intra_dc_precision}, "intra_dc_precision", "precision" },
4103
    { "mepc", OPT_INT | HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)&me_penalty_compensation}, "motion estimation bitrate penalty compensation", "factor (1.0 = 256)" },
4104
    { "vtag", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_video_tag}, "force video tag/fourcc", "fourcc/tag" },
4105
    { "skip_threshold", OPT_INT | HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)&frame_skip_threshold}, "frame skip threshold", "threshold" },
4106
    { "skip_factor", OPT_INT | HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)&frame_skip_factor}, "frame skip factor", "factor" },
4107
    { "skip_exp", OPT_INT | HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)&frame_skip_exp}, "frame skip exponent", "exponent" },
4108
    { "newvideo", OPT_VIDEO, {(void*)opt_new_video_stream}, "add a new video stream to the current output stream" },
4109
    { "genpts", OPT_BOOL | OPT_EXPERT | OPT_VIDEO, { (void *)&genpts }, "generate pts" },
4110
    { "qphist", OPT_BOOL | OPT_EXPERT | OPT_VIDEO, { (void *)&qp_hist }, "show QP histogram" },
4111

    
4112
    /* audio options */
4113
    { "ab", HAS_ARG | OPT_AUDIO, {(void*)opt_audio_bitrate}, "set audio bitrate (in kbit/s)", "bitrate", },
4114
    { "aq", OPT_FLOAT | HAS_ARG | OPT_AUDIO, {(void*)&audio_qscale}, "set audio quality (codec-specific)", "quality", },
4115
    { "ar", HAS_ARG | OPT_AUDIO, {(void*)opt_audio_rate}, "set audio sampling rate (in Hz)", "rate" },
4116
    { "ac", HAS_ARG | OPT_AUDIO, {(void*)opt_audio_channels}, "set number of audio channels", "channels" },
4117
    { "an", OPT_BOOL | OPT_AUDIO, {(void*)&audio_disable}, "disable audio" },
4118
    { "acodec", HAS_ARG | OPT_AUDIO, {(void*)opt_audio_codec}, "force audio codec ('copy' to copy stream)", "codec" },
4119
    { "atag", HAS_ARG | OPT_EXPERT | OPT_AUDIO, {(void*)opt_audio_tag}, "force audio tag/fourcc", "fourcc/tag" },
4120
    { "vol", OPT_INT | HAS_ARG | OPT_AUDIO, {(void*)&audio_volume}, "change audio volume (256=normal)" , "volume" }, //
4121
    { "newaudio", OPT_AUDIO, {(void*)opt_new_audio_stream}, "add a new audio stream to the current output stream" },
4122
    { "alang", HAS_ARG | OPT_STRING | OPT_AUDIO, {(void *)&audio_language}, "set the ISO 639 language code (3 letters) of the current audio stream" , "code" },
4123

    
4124
    /* subtitle options */
4125
    { "scodec", HAS_ARG | OPT_SUBTITLE, {(void*)opt_subtitle_codec}, "force subtitle codec ('copy' to copy stream)", "codec" },
4126
    { "newsubtitle", OPT_SUBTITLE, {(void*)opt_new_subtitle_stream}, "add a new subtitle stream to the current output stream" },
4127
    { "slang", HAS_ARG | OPT_STRING | OPT_SUBTITLE, {(void *)&subtitle_language}, "set the ISO 639 language code (3 letters) of the current subtitle stream" , "code" },
4128

    
4129
    /* grab options */
4130
    { "vd", HAS_ARG | OPT_EXPERT | OPT_VIDEO | OPT_GRAB, {(void*)opt_video_device}, "set video grab device", "device" },
4131
    { "vc", HAS_ARG | OPT_EXPERT | OPT_VIDEO | OPT_GRAB, {(void*)opt_video_channel}, "set video grab channel (DV1394 only)", "channel" },
4132
    { "tvstd", HAS_ARG | OPT_EXPERT | OPT_VIDEO | OPT_GRAB, {(void*)opt_video_standard}, "set television standard (NTSC, PAL (SECAM))", "standard" },
4133
    { "ad", HAS_ARG | OPT_EXPERT | OPT_AUDIO | OPT_GRAB, {(void*)opt_audio_device}, "set audio device", "device" },
4134

    
4135
    /* G.2 grab options */
4136
    { "grab", HAS_ARG | OPT_EXPERT | OPT_GRAB, {(void*)opt_grab}, "request grabbing using", "format" },
4137
    { "gd", HAS_ARG | OPT_EXPERT | OPT_VIDEO | OPT_GRAB, {(void*)opt_grab_device}, "set grab device", "device" },
4138

    
4139
    /* muxer options */
4140
    { "muxrate", OPT_INT | HAS_ARG | OPT_EXPERT, {(void*)&mux_rate}, "set mux rate", "rate" },
4141
    { "packetsize", OPT_INT | HAS_ARG | OPT_EXPERT, {(void*)&mux_packet_size}, "set packet size", "size" },
4142
    { "muxdelay", OPT_FLOAT | HAS_ARG | OPT_EXPERT, {(void*)&mux_max_delay}, "set the maximum demux-decode delay", "seconds" },
4143
    { "muxpreload", OPT_FLOAT | HAS_ARG | OPT_EXPERT, {(void*)&mux_preload}, "set the initial demux-decode delay", "seconds" },
4144
    { "default", OPT_FUNC2 | HAS_ARG | OPT_AUDIO | OPT_VIDEO | OPT_EXPERT, {(void*)opt_default}, "generic catch all option", "" },
4145
    { NULL, },
4146
};
4147

    
4148
static void show_banner(void)
4149
{
4150
    fprintf(stderr, "ffmpeg version " FFMPEG_VERSION ", build %d, Copyright (c) 2000-2004 Fabrice Bellard\n",
4151
        LIBAVCODEC_BUILD);
4152
    fprintf(stderr, "  configuration: %s\n", FFMPEG_CONFIGURATION);
4153
    fprintf(stderr, "  built on " __DATE__ " " __TIME__);
4154
#ifdef __GNUC__
4155
    fprintf(stderr, ", gcc: %s\n", __VERSION__);
4156
#else
4157
    fprintf(stderr, ", using a non-gcc compiler\n");
4158
#endif
4159
}
4160

    
4161
static void show_license(void)
4162
{
4163
    show_banner();
4164
#ifdef CONFIG_GPL
4165
    printf(
4166
    "This program is free software; you can redistribute it and/or modify\n"
4167
    "it under the terms of the GNU General Public License as published by\n"
4168
    "the Free Software Foundation; either version 2 of the License, or\n"
4169
    "(at your option) any later version.\n"
4170
    "\n"
4171
    "This program is distributed in the hope that it will be useful,\n"
4172
    "but WITHOUT ANY WARRANTY; without even the implied warranty of\n"
4173
    "MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n"
4174
    "GNU General Public License for more details.\n"
4175
    "\n"
4176
    "You should have received a copy of the GNU General Public License\n"
4177
    "along with this program; if not, write to the Free Software\n"
4178
    "Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA\n"
4179
    );
4180
#else
4181
    printf(
4182
    "This library is free software; you can redistribute it and/or\n"
4183
    "modify it under the terms of the GNU Lesser General Public\n"
4184
    "License as published by the Free Software Foundation; either\n"
4185
    "version 2 of the License, or (at your option) any later version.\n"
4186
    "\n"
4187
    "This library is distributed in the hope that it will be useful,\n"
4188
    "but WITHOUT ANY WARRANTY; without even the implied warranty of\n"
4189
    "MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n"
4190
    "Lesser General Public License for more details.\n"
4191
    "\n"
4192
    "You should have received a copy of the GNU Lesser General Public\n"
4193
    "License along with this library; if not, write to the Free Software\n"
4194
    "Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA\n"
4195
    );
4196
#endif
4197
    exit(1);
4198
}
4199

    
4200
static void show_help(void)
4201
{
4202
    show_banner();
4203
    printf("usage: ffmpeg [[infile options] -i infile]... {[outfile options] outfile}...\n"
4204
           "Hyper fast Audio and Video encoder\n");
4205
    printf("\n");
4206
    show_help_options(options, "Main options:\n",
4207
                      OPT_EXPERT | OPT_AUDIO | OPT_VIDEO, 0);
4208
    show_help_options(options, "\nVideo options:\n",
4209
                      OPT_EXPERT | OPT_AUDIO | OPT_VIDEO | OPT_GRAB,
4210
                      OPT_VIDEO);
4211
    show_help_options(options, "\nAdvanced Video options:\n",
4212
                      OPT_EXPERT | OPT_AUDIO | OPT_VIDEO | OPT_GRAB,
4213
                      OPT_VIDEO | OPT_EXPERT);
4214
    show_help_options(options, "\nAudio options:\n",
4215
                      OPT_EXPERT | OPT_AUDIO | OPT_VIDEO | OPT_GRAB,
4216
                      OPT_AUDIO);
4217
    show_help_options(options, "\nAdvanced Audio options:\n",
4218
                      OPT_EXPERT | OPT_AUDIO | OPT_VIDEO | OPT_GRAB,
4219
                      OPT_AUDIO | OPT_EXPERT);
4220
    show_help_options(options, "\nSubtitle options:\n",
4221
                      OPT_SUBTITLE | OPT_GRAB,
4222
                      OPT_SUBTITLE);
4223
    show_help_options(options, "\nAudio/Video grab options:\n",
4224
                      OPT_GRAB,
4225
                      OPT_GRAB);
4226
    show_help_options(options, "\nAdvanced options:\n",
4227
                      OPT_EXPERT | OPT_AUDIO | OPT_VIDEO | OPT_GRAB,
4228
                      OPT_EXPERT);
4229
    av_opt_show(avctx_opts, NULL);
4230

    
4231
    exit(1);
4232
}
4233

    
4234
void parse_arg_file(const char *filename)
4235
{
4236
    opt_output_file(filename);
4237
}
4238

    
4239
int main(int argc, char **argv)
4240
{
4241
    int i;
4242
    int64_t ti;
4243

    
4244
    av_register_all();
4245

    
4246
    avctx_opts= avcodec_alloc_context();
4247

    
4248
    if (argc <= 1)
4249
        show_help();
4250
    else
4251
        show_banner();
4252

    
4253
    /* parse options */
4254
    parse_options(argc, argv, options);
4255

    
4256
    /* file converter / grab */
4257
    if (nb_output_files <= 0) {
4258
        fprintf(stderr, "Must supply at least one output file\n");
4259
        exit(1);
4260
    }
4261

    
4262
    if (nb_input_files == 0) {
4263
        input_sync = 1;
4264
        prepare_grab();
4265
    }
4266

    
4267
    ti = getutime();
4268
    av_encode(output_files, nb_output_files, input_files, nb_input_files,
4269
              stream_maps, nb_stream_maps);
4270
    ti = getutime() - ti;
4271
    if (do_benchmark) {
4272
        printf("bench: utime=%0.3fs\n", ti / 1000000.0);
4273
    }
4274

    
4275
    /* close files */
4276
    for(i=0;i<nb_output_files;i++) {
4277
        /* maybe av_close_output_file ??? */
4278
        AVFormatContext *s = output_files[i];
4279
        int j;
4280
        if (!(s->oformat->flags & AVFMT_NOFILE))
4281
            url_fclose(&s->pb);
4282
        for(j=0;j<s->nb_streams;j++)
4283
            av_free(s->streams[j]);
4284
        av_free(s);
4285
    }
4286
    for(i=0;i<nb_input_files;i++)
4287
        av_close_input_file(input_files[i]);
4288

    
4289
    av_free_static();
4290

    
4291
    if(intra_matrix)
4292
        av_free(intra_matrix);
4293
    if(inter_matrix)
4294
        av_free(inter_matrix);
4295

    
4296
#ifdef POWERPC_PERFORMANCE_REPORT
4297
    extern void powerpc_display_perf_report(void);
4298
    powerpc_display_perf_report();
4299
#endif /* POWERPC_PERFORMANCE_REPORT */
4300

    
4301
#ifndef CONFIG_WIN32
4302
    if (received_sigterm) {
4303
        fprintf(stderr,
4304
            "Received signal %d: terminating.\n",
4305
            (int) received_sigterm);
4306
        exit (255);
4307
    }
4308
#endif
4309
    exit(0); /* not all OS-es handle main() return value */
4310
    return 0;
4311
}