Statistics
| Branch: | Revision:

ffmpeg / ffmpeg.c @ 356e7a9d

History | View | Annotate | Download (146 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
18
 */
19
#define HAVE_AV_CONFIG_H
20
#include <limits.h>
21
#include "avformat.h"
22
#include "swscale.h"
23
#include "framehook.h"
24
#include "dsputil.h"
25
#include "opt.h"
26

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

    
44
#include "version.h"
45
#include "cmdutils.h"
46

    
47
#undef NDEBUG
48
#include <assert.h>
49

    
50
#if !defined(INFINITY) && defined(HUGE_VAL)
51
#define INFINITY HUGE_VAL
52
#endif
53

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

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

    
68
extern const OptionDef options[];
69

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

    
74
#define MAX_FILES 20
75

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

    
80
static AVFormatContext *output_files[MAX_FILES];
81
static int nb_output_files = 0;
82

    
83
static AVStreamMap stream_maps[MAX_FILES];
84
static int nb_stream_maps;
85

    
86
static AVMetaDataMap meta_data_maps[MAX_FILES];
87
static int nb_meta_data_maps;
88

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

    
162
static int intra_only = 0;
163
static int audio_sample_rate = 44100;
164
static int audio_bit_rate = 64000;
165
#define QSCALE_NONE -99999
166
static float audio_qscale = QSCALE_NONE;
167
static int audio_disable = 0;
168
static int audio_channels = 1;
169
static int audio_codec_id = CODEC_ID_NONE;
170
static int audio_codec_tag = 0;
171
static char *audio_language = NULL;
172

    
173
static int subtitle_codec_id = CODEC_ID_NONE;
174
static char *subtitle_language = NULL;
175

    
176
static int mux_rate= 0;
177
static int mux_packet_size= 0;
178
static float mux_preload= 0.5;
179
static float mux_max_delay= 0.7;
180

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

    
207
static int rate_emu = 0;
208

    
209
#ifdef CONFIG_BKTR
210
static const char *video_grab_format = "bktr";
211
#else
212
#ifdef CONFIG_VIDEO4LINUX2
213
static const char *video_grab_format = "video4linux2";
214
#else
215
static const char *video_grab_format = "video4linux";
216
#endif
217
#endif
218
static char *video_device = NULL;
219
static char *grab_device = NULL;
220
static int  video_channel = 0;
221
static char *video_standard = "ntsc";
222

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

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

    
241
static int pgmyuv_compatibility_hack=0;
242
static int dts_delta_threshold = 10;
243

    
244
static int sws_flags = SWS_BICUBIC;
245

    
246
const char **opt_names=NULL;
247
int opt_name_count=0;
248
AVCodecContext *avctx_opts;
249
AVFormatContext *avformat_opts;
250

    
251
static AVBitStreamFilterContext *video_bitstream_filters=NULL;
252
static AVBitStreamFilterContext *audio_bitstream_filters=NULL;
253
static AVBitStreamFilterContext *bitstream_filters[MAX_FILES][MAX_STREAMS];
254

    
255
#define DEFAULT_PASS_LOGFILENAME "ffmpeg2pass"
256

    
257
struct AVInputStream;
258

    
259
typedef struct AVOutputStream {
260
    int file_index;          /* file index */
261
    int index;               /* stream index in the output file */
262
    int source_index;        /* AVInputStream index */
263
    AVStream *st;            /* stream in the output file */
264
    int encoding_needed;     /* true if encoding needed for this stream */
265
    int frame_number;
266
    /* input pts and corresponding output pts
267
       for A/V sync */
268
    //double sync_ipts;        /* dts from the AVPacket of the demuxer in second units */
269
    struct AVInputStream *sync_ist; /* input stream to sync against */
270
    int64_t sync_opts;       /* output frame counter, could be changed to some true timestamp */ //FIXME look at frame_number
271
    /* video only */
272
    int video_resample;
273
    AVFrame pict_tmp;      /* temporary image for resampling */
274
    struct SwsContext *img_resample_ctx; /* for image resampling */
275
    int resample_height;
276

    
277
    int video_crop;
278
    int topBand;             /* cropping area sizes */
279
    int leftBand;
280

    
281
    int video_pad;
282
    int padtop;              /* padding area sizes */
283
    int padbottom;
284
    int padleft;
285
    int padright;
286

    
287
    /* audio only */
288
    int audio_resample;
289
    ReSampleContext *resample; /* for audio resampling */
290
    FifoBuffer fifo;     /* for compression: one audio fifo per codec */
291
    FILE *logfile;
292
} AVOutputStream;
293

    
294
typedef struct AVInputStream {
295
    int file_index;
296
    int index;
297
    AVStream *st;
298
    int discard;             /* true if stream data should be discarded */
299
    int decoding_needed;     /* true if the packets must be decoded in 'raw_fifo' */
300
    int64_t sample_index;      /* current sample */
301

    
302
    int64_t       start;     /* time when read started */
303
    unsigned long frame;     /* current frame */
304
    int64_t       next_pts;  /* synthetic pts for cases where pkt.pts
305
                                is not defined */
306
    int64_t       pts;       /* current pts */
307
    int is_start;            /* is 1 at the start and after a discontinuity */
308
} AVInputStream;
309

    
310
typedef struct AVInputFile {
311
    int eof_reached;      /* true if eof reached */
312
    int ist_index;        /* index of first stream in ist_table */
313
    int buffer_size;      /* current total buffer size */
314
    int buffer_size_max;  /* buffer size at which we consider we can stop
315
                             buffering */
316
    int nb_streams;       /* nb streams we are aware of */
317
} AVInputFile;
318

    
319
#ifndef __MINGW32__
320

    
321
/* init terminal so that we can grab keys */
322
static struct termios oldtty;
323

    
324
static void term_exit(void)
325
{
326
    tcsetattr (0, TCSANOW, &oldtty);
327
}
328

    
329
static volatile sig_atomic_t received_sigterm = 0;
330

    
331
static void
332
sigterm_handler(int sig)
333
{
334
    received_sigterm = sig;
335
    term_exit();
336
}
337

    
338
static void term_init(void)
339
{
340
    struct termios tty;
341

    
342
    tcgetattr (0, &tty);
343
    oldtty = tty;
344

    
345
    tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
346
                          |INLCR|IGNCR|ICRNL|IXON);
347
    tty.c_oflag |= OPOST;
348
    tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
349
    tty.c_cflag &= ~(CSIZE|PARENB);
350
    tty.c_cflag |= CS8;
351
    tty.c_cc[VMIN] = 1;
352
    tty.c_cc[VTIME] = 0;
353

    
354
    tcsetattr (0, TCSANOW, &tty);
355

    
356
    signal(SIGINT , sigterm_handler); /* Interrupt (ANSI).  */
357
    signal(SIGQUIT, sigterm_handler); /* Quit (POSIX).  */
358
    signal(SIGTERM, sigterm_handler); /* Termination (ANSI).  */
359
    /*
360
    register a function to be called at normal program termination
361
    */
362
    atexit(term_exit);
363
#ifdef CONFIG_BEOS_NETSERVER
364
    fcntl(0, F_SETFL, fcntl(0, F_GETFL) | O_NONBLOCK);
365
#endif
366
}
367

    
368
/* read a key without blocking */
369
static int read_key(void)
370
{
371
    int n = 1;
372
    unsigned char ch;
373
#ifndef CONFIG_BEOS_NETSERVER
374
    struct timeval tv;
375
    fd_set rfds;
376

    
377
    FD_ZERO(&rfds);
378
    FD_SET(0, &rfds);
379
    tv.tv_sec = 0;
380
    tv.tv_usec = 0;
381
    n = select(1, &rfds, NULL, NULL, &tv);
382
#endif
383
    if (n > 0) {
384
        n = read(0, &ch, 1);
385
        if (n == 1)
386
            return ch;
387

    
388
        return n;
389
    }
390
    return -1;
391
}
392

    
393
static int decode_interrupt_cb(void)
394
{
395
    return q_pressed || (q_pressed = read_key() == 'q');
396
}
397

    
398
#else
399

    
400
static volatile int received_sigterm = 0;
401

    
402
/* no interactive support */
403
static void term_exit(void)
404
{
405
}
406

    
407
static void term_init(void)
408
{
409
}
410

    
411
static int read_key(void)
412
{
413
    return 0;
414
}
415

    
416
#endif
417

    
418
static int read_ffserver_streams(AVFormatContext *s, const char *filename)
419
{
420
    int i, err;
421
    AVFormatContext *ic;
422

    
423
    err = av_open_input_file(&ic, filename, NULL, FFM_PACKET_SIZE, NULL);
424
    if (err < 0)
425
        return err;
426
    /* copy stream format */
427
    s->nb_streams = ic->nb_streams;
428
    for(i=0;i<ic->nb_streams;i++) {
429
        AVStream *st;
430

    
431
        // FIXME: a more elegant solution is needed
432
        st = av_mallocz(sizeof(AVStream));
433
        memcpy(st, ic->streams[i], sizeof(AVStream));
434
        st->codec = avcodec_alloc_context();
435
        memcpy(st->codec, ic->streams[i]->codec, sizeof(AVCodecContext));
436
        s->streams[i] = st;
437
    }
438

    
439
    av_close_input_file(ic);
440
    return 0;
441
}
442

    
443
static double
444
get_sync_ipts(const AVOutputStream *ost)
445
{
446
    const AVInputStream *ist = ost->sync_ist;
447
    return (double)(ist->pts + input_files_ts_offset[ist->file_index] - start_time)/AV_TIME_BASE;
448
}
449

    
450
static void write_frame(AVFormatContext *s, AVPacket *pkt, AVCodecContext *avctx, AVBitStreamFilterContext *bsfc){
451
    while(bsfc){
452
        AVPacket new_pkt= *pkt;
453
        int a= av_bitstream_filter_filter(bsfc, avctx, NULL,
454
                                          &new_pkt.data, &new_pkt.size,
455
                                          pkt->data, pkt->size,
456
                                          pkt->flags & PKT_FLAG_KEY);
457
        if(a){
458
            av_free_packet(pkt);
459
            new_pkt.destruct= av_destruct_packet;
460
        }
461
        *pkt= new_pkt;
462

    
463
        bsfc= bsfc->next;
464
    }
465

    
466
    av_interleaved_write_frame(s, pkt);
467
}
468

    
469
#define MAX_AUDIO_PACKET_SIZE (128 * 1024)
470

    
471
static void do_audio_out(AVFormatContext *s,
472
                         AVOutputStream *ost,
473
                         AVInputStream *ist,
474
                         unsigned char *buf, int size)
475
{
476
    uint8_t *buftmp;
477
    static uint8_t *audio_buf = NULL;
478
    static uint8_t *audio_out = NULL;
479
    const int audio_out_size= 4*MAX_AUDIO_PACKET_SIZE;
480

    
481
    int size_out, frame_bytes, ret;
482
    AVCodecContext *enc= ost->st->codec;
483

    
484
    /* SC: dynamic allocation of buffers */
485
    if (!audio_buf)
486
        audio_buf = av_malloc(2*MAX_AUDIO_PACKET_SIZE);
487
    if (!audio_out)
488
        audio_out = av_malloc(audio_out_size);
489
    if (!audio_buf || !audio_out)
490
        return;               /* Should signal an error ! */
491

    
492
    if(audio_sync_method){
493
        double delta = get_sync_ipts(ost) * enc->sample_rate - ost->sync_opts
494
                - fifo_size(&ost->fifo, ost->fifo.rptr)/(ost->st->codec->channels * 2);
495
        double idelta= delta*ist->st->codec->sample_rate / enc->sample_rate;
496
        int byte_delta= ((int)idelta)*2*ist->st->codec->channels;
497

    
498
        //FIXME resample delay
499
        if(fabs(delta) > 50){
500
            if(ist->is_start){
501
                if(byte_delta < 0){
502
                    byte_delta= FFMAX(byte_delta, -size);
503
                    size += byte_delta;
504
                    buf  -= byte_delta;
505
                    if(verbose > 2)
506
                        fprintf(stderr, "discarding %d audio samples\n", (int)-delta);
507
                    if(!size)
508
                        return;
509
                    ist->is_start=0;
510
                }else{
511
                    static uint8_t *input_tmp= NULL;
512
                    input_tmp= av_realloc(input_tmp, byte_delta + size);
513

    
514
                    if(byte_delta + size <= MAX_AUDIO_PACKET_SIZE)
515
                        ist->is_start=0;
516
                    else
517
                        byte_delta= MAX_AUDIO_PACKET_SIZE - size;
518

    
519
                    memset(input_tmp, 0, byte_delta);
520
                    memcpy(input_tmp + byte_delta, buf, size);
521
                    buf= input_tmp;
522
                    size += byte_delta;
523
                    if(verbose > 2)
524
                        fprintf(stderr, "adding %d audio samples of silence\n", (int)delta);
525
                }
526
            }else if(audio_sync_method>1){
527
                int comp= clip(delta, -audio_sync_method, audio_sync_method);
528
                assert(ost->audio_resample);
529
                if(verbose > 2)
530
                    fprintf(stderr, "compensating audio timestamp drift:%f compensation:%d in:%d\n", delta, comp, enc->sample_rate);
531
//                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));
532
                av_resample_compensate(*(struct AVResampleContext**)ost->resample, comp, enc->sample_rate);
533
            }
534
        }
535
    }else
536
        ost->sync_opts= lrintf(get_sync_ipts(ost) * enc->sample_rate)
537
                        - fifo_size(&ost->fifo, ost->fifo.rptr)/(ost->st->codec->channels * 2); //FIXME wrong
538

    
539
    if (ost->audio_resample) {
540
        buftmp = audio_buf;
541
        size_out = audio_resample(ost->resample,
542
                                  (short *)buftmp, (short *)buf,
543
                                  size / (ist->st->codec->channels * 2));
544
        size_out = size_out * enc->channels * 2;
545
    } else {
546
        buftmp = buf;
547
        size_out = size;
548
    }
549

    
550
    /* now encode as many frames as possible */
551
    if (enc->frame_size > 1) {
552
        /* output resampled raw samples */
553
        fifo_write(&ost->fifo, buftmp, size_out,
554
                   &ost->fifo.wptr);
555

    
556
        frame_bytes = enc->frame_size * 2 * enc->channels;
557

    
558
        while (fifo_read(&ost->fifo, audio_buf, frame_bytes,
559
                     &ost->fifo.rptr) == 0) {
560
            AVPacket pkt;
561
            av_init_packet(&pkt);
562

    
563
            ret = avcodec_encode_audio(enc, audio_out, audio_out_size,
564
                                       (short *)audio_buf);
565
            audio_size += ret;
566
            pkt.stream_index= ost->index;
567
            pkt.data= audio_out;
568
            pkt.size= ret;
569
            if(enc->coded_frame && enc->coded_frame->pts != AV_NOPTS_VALUE)
570
                pkt.pts= av_rescale_q(enc->coded_frame->pts, enc->time_base, ost->st->time_base);
571
            pkt.flags |= PKT_FLAG_KEY;
572
            write_frame(s, &pkt, ost->st->codec, bitstream_filters[ost->file_index][pkt.stream_index]);
573

    
574
            ost->sync_opts += enc->frame_size;
575
        }
576
    } else {
577
        AVPacket pkt;
578
        av_init_packet(&pkt);
579

    
580
        ost->sync_opts += size_out / (2 * enc->channels);
581

    
582
        /* output a pcm frame */
583
        /* XXX: change encoding codec API to avoid this ? */
584
        switch(enc->codec->id) {
585
        case CODEC_ID_PCM_S32LE:
586
        case CODEC_ID_PCM_S32BE:
587
        case CODEC_ID_PCM_U32LE:
588
        case CODEC_ID_PCM_U32BE:
589
            size_out = size_out << 1;
590
            break;
591
        case CODEC_ID_PCM_S24LE:
592
        case CODEC_ID_PCM_S24BE:
593
        case CODEC_ID_PCM_U24LE:
594
        case CODEC_ID_PCM_U24BE:
595
        case CODEC_ID_PCM_S24DAUD:
596
            size_out = size_out / 2 * 3;
597
            break;
598
        case CODEC_ID_PCM_S16LE:
599
        case CODEC_ID_PCM_S16BE:
600
        case CODEC_ID_PCM_U16LE:
601
        case CODEC_ID_PCM_U16BE:
602
            break;
603
        default:
604
            size_out = size_out >> 1;
605
            break;
606
        }
607
        ret = avcodec_encode_audio(enc, audio_out, size_out,
608
                                   (short *)buftmp);
609
        audio_size += ret;
610
        pkt.stream_index= ost->index;
611
        pkt.data= audio_out;
612
        pkt.size= ret;
613
        if(enc->coded_frame && enc->coded_frame->pts != AV_NOPTS_VALUE)
614
            pkt.pts= av_rescale_q(enc->coded_frame->pts, enc->time_base, ost->st->time_base);
615
        pkt.flags |= PKT_FLAG_KEY;
616
        write_frame(s, &pkt, ost->st->codec, bitstream_filters[ost->file_index][pkt.stream_index]);
617
    }
618
}
619

    
620
static void pre_process_video_frame(AVInputStream *ist, AVPicture *picture, void **bufp)
621
{
622
    AVCodecContext *dec;
623
    AVPicture *picture2;
624
    AVPicture picture_tmp;
625
    uint8_t *buf = 0;
626

    
627
    dec = ist->st->codec;
628

    
629
    /* deinterlace : must be done before any resize */
630
    if (do_deinterlace || using_vhook) {
631
        int size;
632

    
633
        /* create temporary picture */
634
        size = avpicture_get_size(dec->pix_fmt, dec->width, dec->height);
635
        buf = av_malloc(size);
636
        if (!buf)
637
            return;
638

    
639
        picture2 = &picture_tmp;
640
        avpicture_fill(picture2, buf, dec->pix_fmt, dec->width, dec->height);
641

    
642
        if (do_deinterlace){
643
            if(avpicture_deinterlace(picture2, picture,
644
                                     dec->pix_fmt, dec->width, dec->height) < 0) {
645
                /* if error, do not deinterlace */
646
                av_free(buf);
647
                buf = NULL;
648
                picture2 = picture;
649
            }
650
        } else {
651
            img_copy(picture2, picture, dec->pix_fmt, dec->width, dec->height);
652
        }
653
    } else {
654
        picture2 = picture;
655
    }
656

    
657
    frame_hook_process(picture2, dec->pix_fmt, dec->width, dec->height);
658

    
659
    if (picture != picture2)
660
        *picture = *picture2;
661
    *bufp = buf;
662
}
663

    
664
/* we begin to correct av delay at this threshold */
665
#define AV_DELAY_MAX 0.100
666

    
667
static void do_subtitle_out(AVFormatContext *s,
668
                            AVOutputStream *ost,
669
                            AVInputStream *ist,
670
                            AVSubtitle *sub,
671
                            int64_t pts)
672
{
673
    static uint8_t *subtitle_out = NULL;
674
    int subtitle_out_max_size = 65536;
675
    int subtitle_out_size, nb, i;
676
    AVCodecContext *enc;
677
    AVPacket pkt;
678

    
679
    if (pts == AV_NOPTS_VALUE) {
680
        fprintf(stderr, "Subtitle packets must have a pts\n");
681
        return;
682
    }
683

    
684
    enc = ost->st->codec;
685

    
686
    if (!subtitle_out) {
687
        subtitle_out = av_malloc(subtitle_out_max_size);
688
    }
689

    
690
    /* Note: DVB subtitle need one packet to draw them and one other
691
       packet to clear them */
692
    /* XXX: signal it in the codec context ? */
693
    if (enc->codec_id == CODEC_ID_DVB_SUBTITLE)
694
        nb = 2;
695
    else
696
        nb = 1;
697

    
698
    for(i = 0; i < nb; i++) {
699
        subtitle_out_size = avcodec_encode_subtitle(enc, subtitle_out,
700
                                                    subtitle_out_max_size, sub);
701

    
702
        av_init_packet(&pkt);
703
        pkt.stream_index = ost->index;
704
        pkt.data = subtitle_out;
705
        pkt.size = subtitle_out_size;
706
        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);
707
        if (enc->codec_id == CODEC_ID_DVB_SUBTITLE) {
708
            /* XXX: the pts correction is handled here. Maybe handling
709
               it in the codec would be better */
710
            if (i == 0)
711
                pkt.pts += 90 * sub->start_display_time;
712
            else
713
                pkt.pts += 90 * sub->end_display_time;
714
        }
715
        write_frame(s, &pkt, ost->st->codec, bitstream_filters[ost->file_index][pkt.stream_index]);
716
    }
717
}
718

    
719
static int bit_buffer_size= 1024*256;
720
static uint8_t *bit_buffer= NULL;
721

    
722
static void do_video_out(AVFormatContext *s,
723
                         AVOutputStream *ost,
724
                         AVInputStream *ist,
725
                         AVFrame *in_picture,
726
                         int *frame_size)
727
{
728
    int nb_frames, i, ret;
729
    AVFrame *final_picture, *formatted_picture, *resampling_dst, *padding_src;
730
    AVFrame picture_crop_temp, picture_pad_temp;
731
    uint8_t *buf = NULL, *buf1 = NULL;
732
    AVCodecContext *enc, *dec;
733

    
734
    avcodec_get_frame_defaults(&picture_crop_temp);
735
    avcodec_get_frame_defaults(&picture_pad_temp);
736

    
737
    enc = ost->st->codec;
738
    dec = ist->st->codec;
739

    
740
    /* by default, we output a single frame */
741
    nb_frames = 1;
742

    
743
    *frame_size = 0;
744

    
745
    if(video_sync_method){
746
        double vdelta;
747
        vdelta = get_sync_ipts(ost) / av_q2d(enc->time_base) - ost->sync_opts;
748
        //FIXME set to 0.5 after we fix some dts/pts bugs like in avidec.c
749
        if (vdelta < -1.1)
750
            nb_frames = 0;
751
        else if (vdelta > 1.1)
752
            nb_frames = lrintf(vdelta);
753
//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);
754
        if (nb_frames == 0){
755
            ++nb_frames_drop;
756
            if (verbose>2)
757
                fprintf(stderr, "*** drop!\n");
758
        }else if (nb_frames > 1) {
759
            nb_frames_dup += nb_frames;
760
            if (verbose>2)
761
                fprintf(stderr, "*** %d dup!\n", nb_frames-1);
762
        }
763
    }else
764
        ost->sync_opts= lrintf(get_sync_ipts(ost) / av_q2d(enc->time_base));
765

    
766
    nb_frames= FFMIN(nb_frames, max_frames[CODEC_TYPE_VIDEO] - ost->frame_number);
767
    if (nb_frames <= 0)
768
        return;
769

    
770
    if (ost->video_crop) {
771
        if (img_crop((AVPicture *)&picture_crop_temp, (AVPicture *)in_picture, dec->pix_fmt, ost->topBand, ost->leftBand) < 0) {
772
            av_log(NULL, AV_LOG_ERROR, "error cropping picture\n");
773
            goto the_end;
774
        }
775
        formatted_picture = &picture_crop_temp;
776
    } else {
777
        formatted_picture = in_picture;
778
    }
779

    
780
    final_picture = formatted_picture;
781
    padding_src = formatted_picture;
782
    resampling_dst = &ost->pict_tmp;
783
    if (ost->video_pad) {
784
        final_picture = &ost->pict_tmp;
785
        if (ost->video_resample) {
786
            if (img_crop((AVPicture *)&picture_pad_temp, (AVPicture *)final_picture, enc->pix_fmt, ost->padtop, ost->padleft) < 0) {
787
                av_log(NULL, AV_LOG_ERROR, "error padding picture\n");
788
                goto the_end;
789
            }
790
            resampling_dst = &picture_pad_temp;
791
        }
792
    }
793

    
794
    if (ost->video_resample) {
795
        padding_src = NULL;
796
        final_picture = &ost->pict_tmp;
797
        sws_scale(ost->img_resample_ctx, formatted_picture->data, formatted_picture->linesize,
798
              0, ost->resample_height, resampling_dst->data, resampling_dst->linesize);
799
    }
800

    
801
    if (ost->video_pad) {
802
        img_pad((AVPicture*)final_picture, (AVPicture *)padding_src,
803
                enc->height, enc->width, enc->pix_fmt,
804
                ost->padtop, ost->padbottom, ost->padleft, ost->padright, padcolor);
805
    }
806

    
807
    /* duplicates frame if needed */
808
    for(i=0;i<nb_frames;i++) {
809
        AVPacket pkt;
810
        av_init_packet(&pkt);
811
        pkt.stream_index= ost->index;
812

    
813
        if (s->oformat->flags & AVFMT_RAWPICTURE) {
814
            /* raw pictures are written as AVPicture structure to
815
               avoid any copies. We support temorarily the older
816
               method. */
817
            AVFrame* old_frame = enc->coded_frame;
818
            enc->coded_frame = dec->coded_frame; //FIXME/XXX remove this hack
819
            pkt.data= (uint8_t *)final_picture;
820
            pkt.size=  sizeof(AVPicture);
821
            if(dec->coded_frame && enc->coded_frame->pts != AV_NOPTS_VALUE)
822
                pkt.pts= av_rescale_q(enc->coded_frame->pts, enc->time_base, ost->st->time_base);
823
            if(dec->coded_frame && dec->coded_frame->key_frame)
824
                pkt.flags |= PKT_FLAG_KEY;
825

    
826
            write_frame(s, &pkt, ost->st->codec, bitstream_filters[ost->file_index][pkt.stream_index]);
827
            enc->coded_frame = old_frame;
828
        } else {
829
            AVFrame big_picture;
830

    
831
            big_picture= *final_picture;
832
            /* better than nothing: use input picture interlaced
833
               settings */
834
            big_picture.interlaced_frame = in_picture->interlaced_frame;
835
            if(avctx_opts->flags & (CODEC_FLAG_INTERLACED_DCT|CODEC_FLAG_INTERLACED_ME)){
836
                if(top_field_first == -1)
837
                    big_picture.top_field_first = in_picture->top_field_first;
838
                else
839
                    big_picture.top_field_first = top_field_first;
840
            }
841

    
842
            /* handles sameq here. This is not correct because it may
843
               not be a global option */
844
            if (same_quality) {
845
                big_picture.quality = ist->st->quality;
846
            }else
847
                big_picture.quality = ost->st->quality;
848
            if(!me_threshold)
849
                big_picture.pict_type = 0;
850
//            big_picture.pts = AV_NOPTS_VALUE;
851
            big_picture.pts= ost->sync_opts;
852
//            big_picture.pts= av_rescale(ost->sync_opts, AV_TIME_BASE*(int64_t)enc->time_base.num, enc->time_base.den);
853
//av_log(NULL, AV_LOG_DEBUG, "%lld -> encoder\n", ost->sync_opts);
854
            ret = avcodec_encode_video(enc,
855
                                       bit_buffer, bit_buffer_size,
856
                                       &big_picture);
857
            //enc->frame_number = enc->real_pict_num;
858
            if(ret>0){
859
                pkt.data= bit_buffer;
860
                pkt.size= ret;
861
                if(enc->coded_frame && enc->coded_frame->pts != AV_NOPTS_VALUE)
862
                    pkt.pts= av_rescale_q(enc->coded_frame->pts, enc->time_base, ost->st->time_base);
863
/*av_log(NULL, AV_LOG_DEBUG, "encoder -> %lld/%lld\n",
864
   pkt.pts != AV_NOPTS_VALUE ? av_rescale(pkt.pts, enc->time_base.den, AV_TIME_BASE*(int64_t)enc->time_base.num) : -1,
865
   pkt.dts != AV_NOPTS_VALUE ? av_rescale(pkt.dts, enc->time_base.den, AV_TIME_BASE*(int64_t)enc->time_base.num) : -1);*/
866

    
867
                if(enc->coded_frame && enc->coded_frame->key_frame)
868
                    pkt.flags |= PKT_FLAG_KEY;
869
                write_frame(s, &pkt, ost->st->codec, bitstream_filters[ost->file_index][pkt.stream_index]);
870
                *frame_size = ret;
871
                //fprintf(stderr,"\nFrame: %3d %3d size: %5d type: %d",
872
                //        enc->frame_number-1, enc->real_pict_num, ret,
873
                //        enc->pict_type);
874
                /* if two pass, output log */
875
                if (ost->logfile && enc->stats_out) {
876
                    fprintf(ost->logfile, "%s", enc->stats_out);
877
                }
878
            }
879
        }
880
        ost->sync_opts++;
881
        ost->frame_number++;
882
    }
883
 the_end:
884
    av_free(buf);
885
    av_free(buf1);
886
}
887

    
888
static double psnr(double d){
889
    if(d==0) return INFINITY;
890
    return -10.0*log(d)/log(10.0);
891
}
892

    
893
static void do_video_stats(AVFormatContext *os, AVOutputStream *ost,
894
                           int frame_size)
895
{
896
    static FILE *fvstats=NULL;
897
    char filename[40];
898
    time_t today2;
899
    struct tm *today;
900
    AVCodecContext *enc;
901
    int frame_number;
902
    int64_t ti;
903
    double ti1, bitrate, avg_bitrate;
904

    
905
    if (!fvstats) {
906
        today2 = time(NULL);
907
        today = localtime(&today2);
908
        snprintf(filename, sizeof(filename), "vstats_%02d%02d%02d.log", today->tm_hour,
909
                                               today->tm_min,
910
                                               today->tm_sec);
911
        fvstats = fopen(filename,"w");
912
        if (!fvstats) {
913
            perror("fopen");
914
            exit(1);
915
        }
916
    }
917

    
918
    ti = MAXINT64;
919
    enc = ost->st->codec;
920
    if (enc->codec_type == CODEC_TYPE_VIDEO) {
921
        frame_number = ost->frame_number;
922
        fprintf(fvstats, "frame= %5d q= %2.1f ", frame_number, enc->coded_frame->quality/(float)FF_QP2LAMBDA);
923
        if (enc->flags&CODEC_FLAG_PSNR)
924
            fprintf(fvstats, "PSNR= %6.2f ", psnr(enc->coded_frame->error[0]/(enc->width*enc->height*255.0*255.0)));
925

    
926
        fprintf(fvstats,"f_size= %6d ", frame_size);
927
        /* compute pts value */
928
        ti1 = ost->sync_opts * av_q2d(enc->time_base);
929
        if (ti1 < 0.01)
930
            ti1 = 0.01;
931

    
932
        bitrate = (frame_size * 8) / av_q2d(enc->time_base) / 1000.0;
933
        avg_bitrate = (double)(video_size * 8) / ti1 / 1000.0;
934
        fprintf(fvstats, "s_size= %8.0fkB time= %0.3f br= %7.1fkbits/s avg_br= %7.1fkbits/s ",
935
            (double)video_size / 1024, ti1, bitrate, avg_bitrate);
936
        fprintf(fvstats,"type= %c\n", av_get_pict_type_char(enc->coded_frame->pict_type));
937
    }
938
}
939

    
940
static void print_report(AVFormatContext **output_files,
941
                         AVOutputStream **ost_table, int nb_ostreams,
942
                         int is_last_report)
943
{
944
    char buf[1024];
945
    AVOutputStream *ost;
946
    AVFormatContext *oc, *os;
947
    int64_t total_size;
948
    AVCodecContext *enc;
949
    int frame_number, vid, i;
950
    double bitrate, ti1, pts;
951
    static int64_t last_time = -1;
952
    static int qp_histogram[52];
953

    
954
    if (!is_last_report) {
955
        int64_t cur_time;
956
        /* display the report every 0.5 seconds */
957
        cur_time = av_gettime();
958
        if (last_time == -1) {
959
            last_time = cur_time;
960
            return;
961
        }
962
        if ((cur_time - last_time) < 500000)
963
            return;
964
        last_time = cur_time;
965
    }
966

    
967

    
968
    oc = output_files[0];
969

    
970
    total_size = url_ftell(&oc->pb);
971

    
972
    buf[0] = '\0';
973
    ti1 = 1e10;
974
    vid = 0;
975
    for(i=0;i<nb_ostreams;i++) {
976
        ost = ost_table[i];
977
        os = output_files[ost->file_index];
978
        enc = ost->st->codec;
979
        if (vid && enc->codec_type == CODEC_TYPE_VIDEO) {
980
            snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "q=%2.1f ",
981
                    enc->coded_frame->quality/(float)FF_QP2LAMBDA);
982
        }
983
        if (!vid && enc->codec_type == CODEC_TYPE_VIDEO) {
984
            frame_number = ost->frame_number;
985
            snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "frame=%5d q=%3.1f ",
986
                    frame_number, enc->coded_frame ? enc->coded_frame->quality/(float)FF_QP2LAMBDA : -1);
987
            if(is_last_report)
988
                snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "L");
989
            if(qp_hist && enc->coded_frame){
990
                int j;
991
                int qp= lrintf(enc->coded_frame->quality/(float)FF_QP2LAMBDA);
992
                if(qp>=0 && qp<sizeof(qp_histogram)/sizeof(int))
993
                    qp_histogram[qp]++;
994
                for(j=0; j<32; j++)
995
                    snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "%X", (int)lrintf(log(qp_histogram[j]+1)/log(2)));
996
            }
997
            if (enc->flags&CODEC_FLAG_PSNR){
998
                int j;
999
                double error, error_sum=0;
1000
                double scale, scale_sum=0;
1001
                char type[3]= {'Y','U','V'};
1002
                snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "PSNR=");
1003
                for(j=0; j<3; j++){
1004
                    if(is_last_report){
1005
                        error= enc->error[j];
1006
                        scale= enc->width*enc->height*255.0*255.0*frame_number;
1007
                    }else{
1008
                        error= enc->coded_frame->error[j];
1009
                        scale= enc->width*enc->height*255.0*255.0;
1010
                    }
1011
                    if(j) scale/=4;
1012
                    error_sum += error;
1013
                    scale_sum += scale;
1014
                    snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "%c:%2.2f ", type[j], psnr(error/scale));
1015
                }
1016
                snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "*:%2.2f ", psnr(error_sum/scale_sum));
1017
            }
1018
            vid = 1;
1019
        }
1020
        /* compute min output value */
1021
        pts = (double)ost->st->pts.val * ost->st->time_base.num / ost->st->time_base.den;
1022
        if ((pts < ti1) && (pts > 0))
1023
            ti1 = pts;
1024
    }
1025
    if (ti1 < 0.01)
1026
        ti1 = 0.01;
1027

    
1028
    if (verbose || is_last_report) {
1029
        bitrate = (double)(total_size * 8) / ti1 / 1000.0;
1030

    
1031
        snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
1032
            "size=%8.0fkB time=%0.1f bitrate=%6.1fkbits/s",
1033
            (double)total_size / 1024, ti1, bitrate);
1034

    
1035
        if (verbose > 1)
1036
          snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), " dup=%d drop=%d",
1037
                  nb_frames_dup, nb_frames_drop);
1038

    
1039
        if (verbose >= 0)
1040
            fprintf(stderr, "%s    \r", buf);
1041

    
1042
        fflush(stderr);
1043
    }
1044

    
1045
    if (is_last_report && verbose >= 0){
1046
        int64_t raw= audio_size + video_size + extra_size;
1047
        fprintf(stderr, "\n");
1048
        fprintf(stderr, "video:%1.0fkB audio:%1.0fkB global headers:%1.0fkB muxing overhead %f%%\n",
1049
                video_size/1024.0,
1050
                audio_size/1024.0,
1051
                extra_size/1024.0,
1052
                100.0*(total_size - raw)/raw
1053
        );
1054
    }
1055
}
1056

    
1057
/* pkt = NULL means EOF (needed to flush decoder buffers) */
1058
static int output_packet(AVInputStream *ist, int ist_index,
1059
                         AVOutputStream **ost_table, int nb_ostreams,
1060
                         const AVPacket *pkt)
1061
{
1062
    AVFormatContext *os;
1063
    AVOutputStream *ost;
1064
    uint8_t *ptr;
1065
    int len, ret, i;
1066
    uint8_t *data_buf;
1067
    int data_size, got_picture;
1068
    AVFrame picture;
1069
    void *buffer_to_free;
1070
    static unsigned int samples_size= 0;
1071
    static short *samples= NULL;
1072
    AVSubtitle subtitle, *subtitle_to_free;
1073
    int got_subtitle;
1074

    
1075
    if(!pkt){
1076
        ist->pts= ist->next_pts; // needed for last packet if vsync=0
1077
    } else if (pkt->dts != AV_NOPTS_VALUE) { //FIXME seems redundant, as libavformat does this too
1078
        ist->next_pts = ist->pts = av_rescale_q(pkt->dts, ist->st->time_base, AV_TIME_BASE_Q);
1079
    } else {
1080
//        assert(ist->pts == ist->next_pts);
1081
    }
1082

    
1083
    if (pkt == NULL) {
1084
        /* EOF handling */
1085
        ptr = NULL;
1086
        len = 0;
1087
        goto handle_eof;
1088
    }
1089

    
1090
    len = pkt->size;
1091
    ptr = pkt->data;
1092
    while (len > 0) {
1093
    handle_eof:
1094
        /* decode the packet if needed */
1095
        data_buf = NULL; /* fail safe */
1096
        data_size = 0;
1097
        subtitle_to_free = NULL;
1098
        if (ist->decoding_needed) {
1099
            switch(ist->st->codec->codec_type) {
1100
            case CODEC_TYPE_AUDIO:{
1101
                if(pkt)
1102
                    samples= av_fast_realloc(samples, &samples_size, FFMAX(pkt->size, AVCODEC_MAX_AUDIO_FRAME_SIZE));
1103
                    /* XXX: could avoid copy if PCM 16 bits with same
1104
                       endianness as CPU */
1105
                ret = avcodec_decode_audio(ist->st->codec, samples, &data_size,
1106
                                           ptr, len);
1107
                if (ret < 0)
1108
                    goto fail_decode;
1109
                ptr += ret;
1110
                len -= ret;
1111
                /* Some bug in mpeg audio decoder gives */
1112
                /* data_size < 0, it seems they are overflows */
1113
                if (data_size <= 0) {
1114
                    /* no audio frame */
1115
                    continue;
1116
                }
1117
                data_buf = (uint8_t *)samples;
1118
                ist->next_pts += ((int64_t)AV_TIME_BASE/2 * data_size) /
1119
                    (ist->st->codec->sample_rate * ist->st->codec->channels);
1120
                break;}
1121
            case CODEC_TYPE_VIDEO:
1122
                    data_size = (ist->st->codec->width * ist->st->codec->height * 3) / 2;
1123
                    /* XXX: allocate picture correctly */
1124
                    avcodec_get_frame_defaults(&picture);
1125

    
1126
                    ret = avcodec_decode_video(ist->st->codec,
1127
                                               &picture, &got_picture, ptr, len);
1128
                    ist->st->quality= picture.quality;
1129
                    if (ret < 0)
1130
                        goto fail_decode;
1131
                    if (!got_picture) {
1132
                        /* no picture yet */
1133
                        goto discard_packet;
1134
                    }
1135
                    if (ist->st->codec->time_base.num != 0) {
1136
                        ist->next_pts += ((int64_t)AV_TIME_BASE *
1137
                                          ist->st->codec->time_base.num) /
1138
                            ist->st->codec->time_base.den;
1139
                    }
1140
                    len = 0;
1141
                    break;
1142
            case CODEC_TYPE_SUBTITLE:
1143
                ret = avcodec_decode_subtitle(ist->st->codec,
1144
                                              &subtitle, &got_subtitle, ptr, len);
1145
                if (ret < 0)
1146
                    goto fail_decode;
1147
                if (!got_subtitle) {
1148
                    goto discard_packet;
1149
                }
1150
                subtitle_to_free = &subtitle;
1151
                len = 0;
1152
                break;
1153
            default:
1154
                goto fail_decode;
1155
            }
1156
        } else {
1157
                switch(ist->st->codec->codec_type) {
1158
                case CODEC_TYPE_AUDIO:
1159
                    ist->next_pts += ((int64_t)AV_TIME_BASE * ist->st->codec->frame_size) /
1160
                        (ist->st->codec->sample_rate * ist->st->codec->channels);
1161
                    break;
1162
                case CODEC_TYPE_VIDEO:
1163
                    if (ist->st->codec->time_base.num != 0) {
1164
                        ist->next_pts += ((int64_t)AV_TIME_BASE *
1165
                                          ist->st->codec->time_base.num) /
1166
                            ist->st->codec->time_base.den;
1167
                    }
1168
                    break;
1169
                }
1170
                data_buf = ptr;
1171
                data_size = len;
1172
                ret = len;
1173
                len = 0;
1174
            }
1175

    
1176
            buffer_to_free = NULL;
1177
            if (ist->st->codec->codec_type == CODEC_TYPE_VIDEO) {
1178
                pre_process_video_frame(ist, (AVPicture *)&picture,
1179
                                        &buffer_to_free);
1180
            }
1181

    
1182
            // preprocess audio (volume)
1183
            if (ist->st->codec->codec_type == CODEC_TYPE_AUDIO) {
1184
                if (audio_volume != 256) {
1185
                    short *volp;
1186
                    volp = samples;
1187
                    for(i=0;i<(data_size / sizeof(short));i++) {
1188
                        int v = ((*volp) * audio_volume + 128) >> 8;
1189
                        if (v < -32768) v = -32768;
1190
                        if (v >  32767) v = 32767;
1191
                        *volp++ = v;
1192
                    }
1193
                }
1194
            }
1195

    
1196
            /* frame rate emulation */
1197
            if (ist->st->codec->rate_emu) {
1198
                int64_t pts = av_rescale((int64_t) ist->frame * ist->st->codec->time_base.num, 1000000, ist->st->codec->time_base.den);
1199
                int64_t now = av_gettime() - ist->start;
1200
                if (pts > now)
1201
                    usleep(pts - now);
1202

    
1203
                ist->frame++;
1204
            }
1205

    
1206
#if 0
1207
            /* mpeg PTS deordering : if it is a P or I frame, the PTS
1208
               is the one of the next displayed one */
1209
            /* XXX: add mpeg4 too ? */
1210
            if (ist->st->codec->codec_id == CODEC_ID_MPEG1VIDEO) {
1211
                if (ist->st->codec->pict_type != B_TYPE) {
1212
                    int64_t tmp;
1213
                    tmp = ist->last_ip_pts;
1214
                    ist->last_ip_pts  = ist->frac_pts.val;
1215
                    ist->frac_pts.val = tmp;
1216
                }
1217
            }
1218
#endif
1219
            /* if output time reached then transcode raw format,
1220
               encode packets and output them */
1221
            if (start_time == 0 || ist->pts >= start_time)
1222
                for(i=0;i<nb_ostreams;i++) {
1223
                    int frame_size;
1224

    
1225
                    ost = ost_table[i];
1226
                    if (ost->source_index == ist_index) {
1227
                        os = output_files[ost->file_index];
1228

    
1229
#if 0
1230
                        printf("%d: got pts=%0.3f %0.3f\n", i,
1231
                               (double)pkt->pts / AV_TIME_BASE,
1232
                               ((double)ist->pts / AV_TIME_BASE) -
1233
                               ((double)ost->st->pts.val * ost->st->time_base.num / ost->st->time_base.den));
1234
#endif
1235
                        /* set the input output pts pairs */
1236
                        //ost->sync_ipts = (double)(ist->pts + input_files_ts_offset[ist->file_index] - start_time)/ AV_TIME_BASE;
1237

    
1238
                        if (ost->encoding_needed) {
1239
                            switch(ost->st->codec->codec_type) {
1240
                            case CODEC_TYPE_AUDIO:
1241
                                do_audio_out(os, ost, ist, data_buf, data_size);
1242
                                break;
1243
                            case CODEC_TYPE_VIDEO:
1244
                                    do_video_out(os, ost, ist, &picture, &frame_size);
1245
                                    video_size += frame_size;
1246
                                    if (do_vstats && frame_size)
1247
                                        do_video_stats(os, ost, frame_size);
1248
                                break;
1249
                            case CODEC_TYPE_SUBTITLE:
1250
                                do_subtitle_out(os, ost, ist, &subtitle,
1251
                                                pkt->pts);
1252
                                break;
1253
                            default:
1254
                                av_abort();
1255
                            }
1256
                        } else {
1257
                            AVFrame avframe; //FIXME/XXX remove this
1258
                            AVPacket opkt;
1259
                            av_init_packet(&opkt);
1260

    
1261
                            /* no reencoding needed : output the packet directly */
1262
                            /* force the input stream PTS */
1263

    
1264
                            avcodec_get_frame_defaults(&avframe);
1265
                            ost->st->codec->coded_frame= &avframe;
1266
                            avframe.key_frame = pkt->flags & PKT_FLAG_KEY;
1267

    
1268
                            if(ost->st->codec->codec_type == CODEC_TYPE_AUDIO)
1269
                                audio_size += data_size;
1270
                            else if (ost->st->codec->codec_type == CODEC_TYPE_VIDEO) {
1271
                                video_size += data_size;
1272
                                ost->sync_opts++;
1273
                            }
1274

    
1275
                            opkt.stream_index= ost->index;
1276
                            if(pkt->pts != AV_NOPTS_VALUE)
1277
                                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);
1278
                            else
1279
                                opkt.pts= AV_NOPTS_VALUE;
1280

    
1281
                            {
1282
                                int64_t dts;
1283
                                if (pkt->dts == AV_NOPTS_VALUE)
1284
                                    dts = ist->next_pts;
1285
                                else
1286
                                    dts= av_rescale_q(pkt->dts, ist->st->time_base, AV_TIME_BASE_Q);
1287
                                opkt.dts= av_rescale_q(dts + input_files_ts_offset[ist->file_index], AV_TIME_BASE_Q,  ost->st->time_base);
1288
                            }
1289
                            opkt.flags= pkt->flags;
1290

    
1291
                            //FIXME remove the following 2 lines they shall be replaced by the bitstream filters
1292
                            if(av_parser_change(ist->st->parser, ost->st->codec, &opkt.data, &opkt.size, data_buf, data_size, pkt->flags & PKT_FLAG_KEY))
1293
                                opkt.destruct= av_destruct_packet;
1294

    
1295
                            write_frame(os, &opkt, ost->st->codec, bitstream_filters[ost->file_index][pkt->stream_index]);
1296
                            ost->st->codec->frame_number++;
1297
                            ost->frame_number++;
1298
                            av_free_packet(&opkt);
1299
                        }
1300
                    }
1301
                }
1302
            av_free(buffer_to_free);
1303
            /* XXX: allocate the subtitles in the codec ? */
1304
            if (subtitle_to_free) {
1305
                if (subtitle_to_free->rects != NULL) {
1306
                    for (i = 0; i < subtitle_to_free->num_rects; i++) {
1307
                        av_free(subtitle_to_free->rects[i].bitmap);
1308
                        av_free(subtitle_to_free->rects[i].rgba_palette);
1309
                    }
1310
                    av_freep(&subtitle_to_free->rects);
1311
                }
1312
                subtitle_to_free->num_rects = 0;
1313
                subtitle_to_free = NULL;
1314
            }
1315
        }
1316
 discard_packet:
1317
    if (pkt == NULL) {
1318
        /* EOF handling */
1319

    
1320
        for(i=0;i<nb_ostreams;i++) {
1321
            ost = ost_table[i];
1322
            if (ost->source_index == ist_index) {
1323
                AVCodecContext *enc= ost->st->codec;
1324
                os = output_files[ost->file_index];
1325

    
1326
                if(ost->st->codec->codec_type == CODEC_TYPE_AUDIO && enc->frame_size <=1)
1327
                    continue;
1328
                if(ost->st->codec->codec_type == CODEC_TYPE_VIDEO && (os->oformat->flags & AVFMT_RAWPICTURE))
1329
                    continue;
1330

    
1331
                if (ost->encoding_needed) {
1332
                    for(;;) {
1333
                        AVPacket pkt;
1334
                        int fifo_bytes;
1335
                        av_init_packet(&pkt);
1336
                        pkt.stream_index= ost->index;
1337

    
1338
                        switch(ost->st->codec->codec_type) {
1339
                        case CODEC_TYPE_AUDIO:
1340
                            fifo_bytes = fifo_size(&ost->fifo, NULL);
1341
                            ret = 0;
1342
                            /* encode any samples remaining in fifo */
1343
                            if(fifo_bytes > 0 && enc->codec->capabilities & CODEC_CAP_SMALL_LAST_FRAME) {
1344
                                int fs_tmp = enc->frame_size;
1345
                                enc->frame_size = fifo_bytes / (2 * enc->channels);
1346
                                if(fifo_read(&ost->fifo, (uint8_t *)samples, fifo_bytes,
1347
                                        &ost->fifo.rptr) == 0) {
1348
                                    ret = avcodec_encode_audio(enc, bit_buffer, bit_buffer_size, samples);
1349
                                }
1350
                                enc->frame_size = fs_tmp;
1351
                            }
1352
                            if(ret <= 0) {
1353
                                ret = avcodec_encode_audio(enc, bit_buffer, bit_buffer_size, NULL);
1354
                            }
1355
                            audio_size += ret;
1356
                            pkt.flags |= PKT_FLAG_KEY;
1357
                            break;
1358
                        case CODEC_TYPE_VIDEO:
1359
                            ret = avcodec_encode_video(enc, bit_buffer, bit_buffer_size, NULL);
1360
                            video_size += ret;
1361
                            if(enc->coded_frame && enc->coded_frame->key_frame)
1362
                                pkt.flags |= PKT_FLAG_KEY;
1363
                            if (ost->logfile && enc->stats_out) {
1364
                                fprintf(ost->logfile, "%s", enc->stats_out);
1365
                            }
1366
                            break;
1367
                        default:
1368
                            ret=-1;
1369
                        }
1370

    
1371
                        if(ret<=0)
1372
                            break;
1373
                        pkt.data= bit_buffer;
1374
                        pkt.size= ret;
1375
                        if(enc->coded_frame && enc->coded_frame->pts != AV_NOPTS_VALUE)
1376
                            pkt.pts= av_rescale_q(enc->coded_frame->pts, enc->time_base, ost->st->time_base);
1377
                        write_frame(os, &pkt, ost->st->codec, bitstream_filters[ost->file_index][pkt.stream_index]);
1378
                    }
1379
                }
1380
            }
1381
        }
1382
    }
1383

    
1384
    return 0;
1385
 fail_decode:
1386
    return -1;
1387
}
1388

    
1389

    
1390
/*
1391
 * The following code is the main loop of the file converter
1392
 */
1393
static int av_encode(AVFormatContext **output_files,
1394
                     int nb_output_files,
1395
                     AVFormatContext **input_files,
1396
                     int nb_input_files,
1397
                     AVStreamMap *stream_maps, int nb_stream_maps)
1398
{
1399
    int ret, i, j, k, n, nb_istreams = 0, nb_ostreams = 0;
1400
    AVFormatContext *is, *os;
1401
    AVCodecContext *codec, *icodec;
1402
    AVOutputStream *ost, **ost_table = NULL;
1403
    AVInputStream *ist, **ist_table = NULL;
1404
    AVInputFile *file_table;
1405
    AVFormatContext *stream_no_data;
1406
    int key;
1407

    
1408
    file_table= (AVInputFile*) av_mallocz(nb_input_files * sizeof(AVInputFile));
1409
    if (!file_table)
1410
        goto fail;
1411

    
1412
    /* input stream init */
1413
    j = 0;
1414
    for(i=0;i<nb_input_files;i++) {
1415
        is = input_files[i];
1416
        file_table[i].ist_index = j;
1417
        file_table[i].nb_streams = is->nb_streams;
1418
        j += is->nb_streams;
1419
    }
1420
    nb_istreams = j;
1421

    
1422
    ist_table = av_mallocz(nb_istreams * sizeof(AVInputStream *));
1423
    if (!ist_table)
1424
        goto fail;
1425

    
1426
    for(i=0;i<nb_istreams;i++) {
1427
        ist = av_mallocz(sizeof(AVInputStream));
1428
        if (!ist)
1429
            goto fail;
1430
        ist_table[i] = ist;
1431
    }
1432
    j = 0;
1433
    for(i=0;i<nb_input_files;i++) {
1434
        is = input_files[i];
1435
        for(k=0;k<is->nb_streams;k++) {
1436
            ist = ist_table[j++];
1437
            ist->st = is->streams[k];
1438
            ist->file_index = i;
1439
            ist->index = k;
1440
            ist->discard = 1; /* the stream is discarded by default
1441
                                 (changed later) */
1442

    
1443
            if (ist->st->codec->rate_emu) {
1444
                ist->start = av_gettime();
1445
                ist->frame = 0;
1446
            }
1447
        }
1448
    }
1449

    
1450
    /* output stream init */
1451
    nb_ostreams = 0;
1452
    for(i=0;i<nb_output_files;i++) {
1453
        os = output_files[i];
1454
        nb_ostreams += os->nb_streams;
1455
    }
1456
    if (nb_stream_maps > 0 && nb_stream_maps != nb_ostreams) {
1457
        fprintf(stderr, "Number of stream maps must match number of output streams\n");
1458
        exit(1);
1459
    }
1460

    
1461
    /* Sanity check the mapping args -- do the input files & streams exist? */
1462
    for(i=0;i<nb_stream_maps;i++) {
1463
        int fi = stream_maps[i].file_index;
1464
        int si = stream_maps[i].stream_index;
1465

    
1466
        if (fi < 0 || fi > nb_input_files - 1 ||
1467
            si < 0 || si > file_table[fi].nb_streams - 1) {
1468
            fprintf(stderr,"Could not find input stream #%d.%d\n", fi, si);
1469
            exit(1);
1470
        }
1471
        fi = stream_maps[i].sync_file_index;
1472
        si = stream_maps[i].sync_stream_index;
1473
        if (fi < 0 || fi > nb_input_files - 1 ||
1474
            si < 0 || si > file_table[fi].nb_streams - 1) {
1475
            fprintf(stderr,"Could not find sync stream #%d.%d\n", fi, si);
1476
            exit(1);
1477
        }
1478
    }
1479

    
1480
    ost_table = av_mallocz(sizeof(AVOutputStream *) * nb_ostreams);
1481
    if (!ost_table)
1482
        goto fail;
1483
    for(i=0;i<nb_ostreams;i++) {
1484
        ost = av_mallocz(sizeof(AVOutputStream));
1485
        if (!ost)
1486
            goto fail;
1487
        ost_table[i] = ost;
1488
    }
1489

    
1490
    n = 0;
1491
    for(k=0;k<nb_output_files;k++) {
1492
        os = output_files[k];
1493
        for(i=0;i<os->nb_streams;i++) {
1494
            int found;
1495
            ost = ost_table[n++];
1496
            ost->file_index = k;
1497
            ost->index = i;
1498
            ost->st = os->streams[i];
1499
            if (nb_stream_maps > 0) {
1500
                ost->source_index = file_table[stream_maps[n-1].file_index].ist_index +
1501
                    stream_maps[n-1].stream_index;
1502

    
1503
                /* Sanity check that the stream types match */
1504
                if (ist_table[ost->source_index]->st->codec->codec_type != ost->st->codec->codec_type) {
1505
                    fprintf(stderr, "Codec type mismatch for mapping #%d.%d -> #%d.%d\n",
1506
                        stream_maps[n-1].file_index, stream_maps[n-1].stream_index,
1507
                        ost->file_index, ost->index);
1508
                    exit(1);
1509
                }
1510

    
1511
            } else {
1512
                /* get corresponding input stream index : we select the first one with the right type */
1513
                found = 0;
1514
                for(j=0;j<nb_istreams;j++) {
1515
                    ist = ist_table[j];
1516
                    if (ist->discard &&
1517
                        ist->st->codec->codec_type == ost->st->codec->codec_type) {
1518
                        ost->source_index = j;
1519
                        found = 1;
1520
                        break;
1521
                    }
1522
                }
1523

    
1524
                if (!found) {
1525
                    /* try again and reuse existing stream */
1526
                    for(j=0;j<nb_istreams;j++) {
1527
                        ist = ist_table[j];
1528
                        if (ist->st->codec->codec_type == ost->st->codec->codec_type) {
1529
                            ost->source_index = j;
1530
                            found = 1;
1531
                        }
1532
                    }
1533
                    if (!found) {
1534
                        fprintf(stderr, "Could not find input stream matching output stream #%d.%d\n",
1535
                                ost->file_index, ost->index);
1536
                        exit(1);
1537
                    }
1538
                }
1539
            }
1540
            ist = ist_table[ost->source_index];
1541
            ist->discard = 0;
1542
            ost->sync_ist = (nb_stream_maps > 0) ?
1543
                ist_table[file_table[stream_maps[n-1].sync_file_index].ist_index +
1544
                         stream_maps[n-1].sync_stream_index] : ist;
1545
        }
1546
    }
1547

    
1548
    /* for each output stream, we compute the right encoding parameters */
1549
    for(i=0;i<nb_ostreams;i++) {
1550
        ost = ost_table[i];
1551
        ist = ist_table[ost->source_index];
1552

    
1553
        codec = ost->st->codec;
1554
        icodec = ist->st->codec;
1555

    
1556
        if (ost->st->stream_copy) {
1557
            /* if stream_copy is selected, no need to decode or encode */
1558
            codec->codec_id = icodec->codec_id;
1559
            codec->codec_type = icodec->codec_type;
1560
            if(!codec->codec_tag) codec->codec_tag = icodec->codec_tag;
1561
            codec->bit_rate = icodec->bit_rate;
1562
            codec->extradata= icodec->extradata;
1563
            codec->extradata_size= icodec->extradata_size;
1564
            codec->time_base = icodec->time_base;
1565
            switch(codec->codec_type) {
1566
            case CODEC_TYPE_AUDIO:
1567
                codec->sample_rate = icodec->sample_rate;
1568
                codec->channels = icodec->channels;
1569
                codec->frame_size = icodec->frame_size;
1570
                codec->block_align= icodec->block_align;
1571
                break;
1572
            case CODEC_TYPE_VIDEO:
1573
                codec->pix_fmt = icodec->pix_fmt;
1574
                codec->width = icodec->width;
1575
                codec->height = icodec->height;
1576
                codec->has_b_frames = icodec->has_b_frames;
1577
                break;
1578
            case CODEC_TYPE_SUBTITLE:
1579
                break;
1580
            default:
1581
                av_abort();
1582
            }
1583
        } else {
1584
            switch(codec->codec_type) {
1585
            case CODEC_TYPE_AUDIO:
1586
                if (fifo_init(&ost->fifo, 2 * MAX_AUDIO_PACKET_SIZE))
1587
                    goto fail;
1588

    
1589
                if (codec->channels == icodec->channels &&
1590
                    codec->sample_rate == icodec->sample_rate) {
1591
                    ost->audio_resample = 0;
1592
                } else {
1593
                    if (codec->channels != icodec->channels &&
1594
                        (icodec->codec_id == CODEC_ID_AC3 ||
1595
                         icodec->codec_id == CODEC_ID_DTS)) {
1596
                        /* Special case for 5:1 AC3 and DTS input */
1597
                        /* and mono or stereo output      */
1598
                        /* Request specific number of channels */
1599
                        icodec->channels = codec->channels;
1600
                        if (codec->sample_rate == icodec->sample_rate)
1601
                            ost->audio_resample = 0;
1602
                        else {
1603
                            ost->audio_resample = 1;
1604
                        }
1605
                    } else {
1606
                        ost->audio_resample = 1;
1607
                    }
1608
                }
1609
                if(audio_sync_method>1)
1610
                    ost->audio_resample = 1;
1611

    
1612
                if(ost->audio_resample){
1613
                    ost->resample = audio_resample_init(codec->channels, icodec->channels,
1614
                                                    codec->sample_rate, icodec->sample_rate);
1615
                    if(!ost->resample){
1616
                        printf("Can't resample.  Aborting.\n");
1617
                        av_abort();
1618
                    }
1619
                }
1620
                ist->decoding_needed = 1;
1621
                ost->encoding_needed = 1;
1622
                break;
1623
            case CODEC_TYPE_VIDEO:
1624
                ost->video_crop = ((frame_leftBand + frame_rightBand + frame_topBand + frame_bottomBand) != 0);
1625
                ost->video_pad = ((frame_padleft + frame_padright + frame_padtop + frame_padbottom) != 0);
1626
                ost->video_resample = ((codec->width != icodec->width -
1627
                                (frame_leftBand + frame_rightBand) +
1628
                                (frame_padleft + frame_padright)) ||
1629
                        (codec->height != icodec->height -
1630
                                (frame_topBand  + frame_bottomBand) +
1631
                                (frame_padtop + frame_padbottom)) ||
1632
                        (codec->pix_fmt != icodec->pix_fmt));
1633
                if (ost->video_crop) {
1634
                    ost->topBand = frame_topBand;
1635
                    ost->leftBand = frame_leftBand;
1636
                }
1637
                if (ost->video_pad) {
1638
                    ost->padtop = frame_padtop;
1639
                    ost->padleft = frame_padleft;
1640
                    ost->padbottom = frame_padbottom;
1641
                    ost->padright = frame_padright;
1642
                    if (!ost->video_resample) {
1643
                        avcodec_get_frame_defaults(&ost->pict_tmp);
1644
                        if( avpicture_alloc( (AVPicture*)&ost->pict_tmp, codec->pix_fmt,
1645
                                         codec->width, codec->height ) )
1646
                            goto fail;
1647
                    }
1648
                }
1649
                if (ost->video_resample) {
1650
                    avcodec_get_frame_defaults(&ost->pict_tmp);
1651
                    if( avpicture_alloc( (AVPicture*)&ost->pict_tmp, codec->pix_fmt,
1652
                                         codec->width, codec->height ) )
1653
                        goto fail;
1654

    
1655
                    ost->img_resample_ctx = sws_getContext(
1656
                            icodec->width - (frame_leftBand + frame_rightBand),
1657
                            icodec->height - (frame_topBand + frame_bottomBand),
1658
                            icodec->pix_fmt,
1659
                            codec->width - (frame_padleft + frame_padright),
1660
                            codec->height - (frame_padtop + frame_padbottom),
1661
                            codec->pix_fmt,
1662
                            sws_flags, NULL, NULL, NULL);
1663
                    if (ost->img_resample_ctx == NULL) {
1664
                        fprintf(stderr, "Cannot get resampling context\n");
1665
                        exit(1);
1666
                    }
1667
                    ost->resample_height = icodec->height - (frame_topBand + frame_bottomBand);
1668
                }
1669
                ost->encoding_needed = 1;
1670
                ist->decoding_needed = 1;
1671
                break;
1672
            case CODEC_TYPE_SUBTITLE:
1673
                ost->encoding_needed = 1;
1674
                ist->decoding_needed = 1;
1675
                break;
1676
            default:
1677
                av_abort();
1678
                break;
1679
            }
1680
            /* two pass mode */
1681
            if (ost->encoding_needed &&
1682
                (codec->flags & (CODEC_FLAG_PASS1 | CODEC_FLAG_PASS2))) {
1683
                char logfilename[1024];
1684
                FILE *f;
1685
                int size;
1686
                char *logbuffer;
1687

    
1688
                snprintf(logfilename, sizeof(logfilename), "%s-%d.log",
1689
                         pass_logfilename ?
1690
                         pass_logfilename : DEFAULT_PASS_LOGFILENAME, i);
1691
                if (codec->flags & CODEC_FLAG_PASS1) {
1692
                    f = fopen(logfilename, "w");
1693
                    if (!f) {
1694
                        perror(logfilename);
1695
                        exit(1);
1696
                    }
1697
                    ost->logfile = f;
1698
                } else {
1699
                    /* read the log file */
1700
                    f = fopen(logfilename, "r");
1701
                    if (!f) {
1702
                        perror(logfilename);
1703
                        exit(1);
1704
                    }
1705
                    fseek(f, 0, SEEK_END);
1706
                    size = ftell(f);
1707
                    fseek(f, 0, SEEK_SET);
1708
                    logbuffer = av_malloc(size + 1);
1709
                    if (!logbuffer) {
1710
                        fprintf(stderr, "Could not allocate log buffer\n");
1711
                        exit(1);
1712
                    }
1713
                    size = fread(logbuffer, 1, size, f);
1714
                    fclose(f);
1715
                    logbuffer[size] = '\0';
1716
                    codec->stats_in = logbuffer;
1717
                }
1718
            }
1719
        }
1720
        if(codec->codec_type == CODEC_TYPE_VIDEO){
1721
            int size= codec->width * codec->height;
1722
            bit_buffer_size= FFMAX(bit_buffer_size, 4*size);
1723
        }
1724
    }
1725

    
1726
    if (!bit_buffer)
1727
        bit_buffer = av_malloc(bit_buffer_size);
1728
    if (!bit_buffer)
1729
        goto fail;
1730

    
1731
    /* dump the file output parameters - cannot be done before in case
1732
       of stream copy */
1733
    for(i=0;i<nb_output_files;i++) {
1734
        dump_format(output_files[i], i, output_files[i]->filename, 1);
1735
    }
1736

    
1737
    /* dump the stream mapping */
1738
    if (verbose >= 0) {
1739
        fprintf(stderr, "Stream mapping:\n");
1740
        for(i=0;i<nb_ostreams;i++) {
1741
            ost = ost_table[i];
1742
            fprintf(stderr, "  Stream #%d.%d -> #%d.%d",
1743
                    ist_table[ost->source_index]->file_index,
1744
                    ist_table[ost->source_index]->index,
1745
                    ost->file_index,
1746
                    ost->index);
1747
            if (ost->sync_ist != ist_table[ost->source_index])
1748
                fprintf(stderr, " [sync #%d.%d]",
1749
                        ost->sync_ist->file_index,
1750
                        ost->sync_ist->index);
1751
            fprintf(stderr, "\n");
1752
        }
1753
    }
1754

    
1755
    /* open each encoder */
1756
    for(i=0;i<nb_ostreams;i++) {
1757
        ost = ost_table[i];
1758
        if (ost->encoding_needed) {
1759
            AVCodec *codec;
1760
            codec = avcodec_find_encoder(ost->st->codec->codec_id);
1761
            if (!codec) {
1762
                fprintf(stderr, "Unsupported codec for output stream #%d.%d\n",
1763
                        ost->file_index, ost->index);
1764
                exit(1);
1765
            }
1766
            if (avcodec_open(ost->st->codec, codec) < 0) {
1767
                fprintf(stderr, "Error while opening codec for output stream #%d.%d - maybe incorrect parameters such as bit_rate, rate, width or height\n",
1768
                        ost->file_index, ost->index);
1769
                exit(1);
1770
            }
1771
            extra_size += ost->st->codec->extradata_size;
1772
        }
1773
    }
1774

    
1775
    /* open each decoder */
1776
    for(i=0;i<nb_istreams;i++) {
1777
        ist = ist_table[i];
1778
        if (ist->decoding_needed) {
1779
            AVCodec *codec;
1780
            codec = avcodec_find_decoder(ist->st->codec->codec_id);
1781
            if (!codec) {
1782
                fprintf(stderr, "Unsupported codec (id=%d) for input stream #%d.%d\n",
1783
                        ist->st->codec->codec_id, ist->file_index, ist->index);
1784
                exit(1);
1785
            }
1786
            if (avcodec_open(ist->st->codec, codec) < 0) {
1787
                fprintf(stderr, "Error while opening codec for input stream #%d.%d\n",
1788
                        ist->file_index, ist->index);
1789
                exit(1);
1790
            }
1791
            //if (ist->st->codec->codec_type == CODEC_TYPE_VIDEO)
1792
            //    ist->st->codec->flags |= CODEC_FLAG_REPEAT_FIELD;
1793
        }
1794
    }
1795

    
1796
    /* init pts */
1797
    for(i=0;i<nb_istreams;i++) {
1798
        ist = ist_table[i];
1799
        is = input_files[ist->file_index];
1800
        ist->pts = 0;
1801
        ist->next_pts = av_rescale_q(ist->st->start_time, ist->st->time_base, AV_TIME_BASE_Q);
1802
        if(ist->st->start_time == AV_NOPTS_VALUE)
1803
            ist->next_pts=0;
1804
        if(input_files_ts_offset[ist->file_index])
1805
            ist->next_pts= AV_NOPTS_VALUE;
1806
        ist->is_start = 1;
1807
    }
1808

    
1809
    /* compute buffer size max (should use a complete heuristic) */
1810
    for(i=0;i<nb_input_files;i++) {
1811
        file_table[i].buffer_size_max = 2048;
1812
    }
1813

    
1814
    /* set meta data information from input file if required */
1815
    for (i=0;i<nb_meta_data_maps;i++) {
1816
        AVFormatContext *out_file;
1817
        AVFormatContext *in_file;
1818

    
1819
        int out_file_index = meta_data_maps[i].out_file;
1820
        int in_file_index = meta_data_maps[i].in_file;
1821
        if ( out_file_index < 0 || out_file_index >= nb_output_files ) {
1822
            fprintf(stderr, "Invalid output file index %d map_meta_data(%d,%d)\n", out_file_index, out_file_index, in_file_index);
1823
            ret = -EINVAL;
1824
            goto fail;
1825
        }
1826
        if ( in_file_index < 0 || in_file_index >= nb_input_files ) {
1827
            fprintf(stderr, "Invalid input file index %d map_meta_data(%d,%d)\n", in_file_index, out_file_index, in_file_index);
1828
            ret = -EINVAL;
1829
            goto fail;
1830
        }
1831

    
1832
        out_file = output_files[out_file_index];
1833
        in_file = input_files[in_file_index];
1834

    
1835
        strcpy(out_file->title, in_file->title);
1836
        strcpy(out_file->author, in_file->author);
1837
        strcpy(out_file->copyright, in_file->copyright);
1838
        strcpy(out_file->comment, in_file->comment);
1839
        strcpy(out_file->album, in_file->album);
1840
        out_file->year = in_file->year;
1841
        out_file->track = in_file->track;
1842
        strcpy(out_file->genre, in_file->genre);
1843
    }
1844

    
1845
    /* open files and write file headers */
1846
    for(i=0;i<nb_output_files;i++) {
1847
        os = output_files[i];
1848
        if (av_write_header(os) < 0) {
1849
            fprintf(stderr, "Could not write header for output file #%d (incorrect codec parameters ?)\n", i);
1850
            ret = -EINVAL;
1851
            goto fail;
1852
        }
1853
    }
1854

    
1855
#ifndef __MINGW32__
1856
    if ( !using_stdin && verbose >= 0) {
1857
        fprintf(stderr, "Press [q] to stop encoding\n");
1858
        url_set_interrupt_cb(decode_interrupt_cb);
1859
    }
1860
#endif
1861
    term_init();
1862

    
1863
    stream_no_data = 0;
1864
    key = -1;
1865

    
1866
    for(; received_sigterm == 0;) {
1867
        int file_index, ist_index;
1868
        AVPacket pkt;
1869
        double ipts_min;
1870
        double opts_min;
1871

    
1872
    redo:
1873
        ipts_min= 1e100;
1874
        opts_min= 1e100;
1875
        /* if 'q' pressed, exits */
1876
        if (!using_stdin) {
1877
            if (q_pressed)
1878
                break;
1879
            /* read_key() returns 0 on EOF */
1880
            key = read_key();
1881
            if (key == 'q')
1882
                break;
1883
        }
1884

    
1885
        /* select the stream that we must read now by looking at the
1886
           smallest output pts */
1887
        file_index = -1;
1888
        for(i=0;i<nb_ostreams;i++) {
1889
            double ipts, opts;
1890
            ost = ost_table[i];
1891
            os = output_files[ost->file_index];
1892
            ist = ist_table[ost->source_index];
1893
            if(ost->st->codec->codec_type == CODEC_TYPE_VIDEO)
1894
                opts = ost->sync_opts * av_q2d(ost->st->codec->time_base);
1895
            else
1896
                opts = ost->st->pts.val * av_q2d(ost->st->time_base);
1897
            ipts = (double)ist->pts;
1898
            if (!file_table[ist->file_index].eof_reached){
1899
                if(ipts < ipts_min) {
1900
                    ipts_min = ipts;
1901
                    if(input_sync ) file_index = ist->file_index;
1902
                }
1903
                if(opts < opts_min) {
1904
                    opts_min = opts;
1905
                    if(!input_sync) file_index = ist->file_index;
1906
                }
1907
            }
1908
            if(ost->frame_number >= max_frames[ost->st->codec->codec_type]){
1909
                file_index= -1;
1910
                break;
1911
            }
1912
        }
1913
        /* if none, if is finished */
1914
        if (file_index < 0) {
1915
            break;
1916
        }
1917

    
1918
        /* finish if recording time exhausted */
1919
        if (recording_time > 0 && opts_min >= (recording_time / 1000000.0))
1920
            break;
1921

    
1922
        /* finish if limit size exhausted */
1923
        if (limit_filesize != 0 && (limit_filesize * 1024) < url_ftell(&output_files[0]->pb))
1924
            break;
1925

    
1926
        /* read a frame from it and output it in the fifo */
1927
        is = input_files[file_index];
1928
        if (av_read_frame(is, &pkt) < 0) {
1929
            file_table[file_index].eof_reached = 1;
1930
            if (opt_shortest) break; else continue; //
1931
        }
1932

    
1933
        if (!pkt.size) {
1934
            stream_no_data = is;
1935
        } else {
1936
            stream_no_data = 0;
1937
        }
1938
        if (do_pkt_dump) {
1939
            av_pkt_dump(stdout, &pkt, do_hex_dump);
1940
        }
1941
        /* the following test is needed in case new streams appear
1942
           dynamically in stream : we ignore them */
1943
        if (pkt.stream_index >= file_table[file_index].nb_streams)
1944
            goto discard_packet;
1945
        ist_index = file_table[file_index].ist_index + pkt.stream_index;
1946
        ist = ist_table[ist_index];
1947
        if (ist->discard)
1948
            goto discard_packet;
1949

    
1950
//        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);
1951
        if (pkt.dts != AV_NOPTS_VALUE && ist->next_pts != AV_NOPTS_VALUE) {
1952
            int64_t delta= av_rescale_q(pkt.dts, ist->st->time_base, AV_TIME_BASE_Q) - ist->next_pts;
1953
            if(ABS(delta) > 1LL*dts_delta_threshold*AV_TIME_BASE && !copy_ts){
1954
                input_files_ts_offset[ist->file_index]-= delta;
1955
                if (verbose > 2)
1956
                    fprintf(stderr, "timestamp discontinuity %"PRId64", new offset= %"PRId64"\n", delta, input_files_ts_offset[ist->file_index]);
1957
                for(i=0; i<file_table[file_index].nb_streams; i++){
1958
                    int index= file_table[file_index].ist_index + i;
1959
                    ist_table[index]->next_pts += delta;
1960
                    ist_table[index]->is_start=1;
1961
                }
1962
            }
1963
        }
1964

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

    
1968
            if (verbose >= 0)
1969
                fprintf(stderr, "Error while decoding stream #%d.%d\n",
1970
                        ist->file_index, ist->index);
1971

    
1972
            av_free_packet(&pkt);
1973
            goto redo;
1974
        }
1975

    
1976
    discard_packet:
1977
        av_free_packet(&pkt);
1978

    
1979
        /* dump report by using the output first video and audio streams */
1980
        print_report(output_files, ost_table, nb_ostreams, 0);
1981
    }
1982

    
1983
    /* at the end of stream, we must flush the decoder buffers */
1984
    for(i=0;i<nb_istreams;i++) {
1985
        ist = ist_table[i];
1986
        if (ist->decoding_needed) {
1987
            output_packet(ist, i, ost_table, nb_ostreams, NULL);
1988
        }
1989
    }
1990

    
1991
    term_exit();
1992

    
1993
    /* write the trailer if needed and close file */
1994
    for(i=0;i<nb_output_files;i++) {
1995
        os = output_files[i];
1996
        av_write_trailer(os);
1997
    }
1998

    
1999
    /* dump report by using the first video and audio streams */
2000
    print_report(output_files, ost_table, nb_ostreams, 1);
2001

    
2002
    /* close each encoder */
2003
    for(i=0;i<nb_ostreams;i++) {
2004
        ost = ost_table[i];
2005
        if (ost->encoding_needed) {
2006
            av_freep(&ost->st->codec->stats_in);
2007
            avcodec_close(ost->st->codec);
2008
        }
2009
    }
2010

    
2011
    /* close each decoder */
2012
    for(i=0;i<nb_istreams;i++) {
2013
        ist = ist_table[i];
2014
        if (ist->decoding_needed) {
2015
            avcodec_close(ist->st->codec);
2016
        }
2017
    }
2018

    
2019
    /* finished ! */
2020

    
2021
    ret = 0;
2022
 fail1:
2023
    av_freep(&bit_buffer);
2024
    av_free(file_table);
2025

    
2026
    if (ist_table) {
2027
        for(i=0;i<nb_istreams;i++) {
2028
            ist = ist_table[i];
2029
            av_free(ist);
2030
        }
2031
        av_free(ist_table);
2032
    }
2033
    if (ost_table) {
2034
        for(i=0;i<nb_ostreams;i++) {
2035
            ost = ost_table[i];
2036
            if (ost) {
2037
                if (ost->logfile) {
2038
                    fclose(ost->logfile);
2039
                    ost->logfile = NULL;
2040
                }
2041
                fifo_free(&ost->fifo); /* works even if fifo is not
2042
                                          initialized but set to zero */
2043
                av_free(ost->pict_tmp.data[0]);
2044
                if (ost->video_resample)
2045
                    sws_freeContext(ost->img_resample_ctx);
2046
                if (ost->audio_resample)
2047
                    audio_resample_close(ost->resample);
2048
                av_free(ost);
2049
            }
2050
        }
2051
        av_free(ost_table);
2052
    }
2053
    return ret;
2054
 fail:
2055
    ret = -ENOMEM;
2056
    goto fail1;
2057
}
2058

    
2059
#if 0
2060
int file_read(const char *filename)
2061
{
2062
    URLContext *h;
2063
    unsigned char buffer[1024];
2064
    int len, i;
2065

2066
    if (url_open(&h, filename, O_RDONLY) < 0) {
2067
        printf("could not open '%s'\n", filename);
2068
        return -1;
2069
    }
2070
    for(;;) {
2071
        len = url_read(h, buffer, sizeof(buffer));
2072
        if (len <= 0)
2073
            break;
2074
        for(i=0;i<len;i++) putchar(buffer[i]);
2075
    }
2076
    url_close(h);
2077
    return 0;
2078
}
2079
#endif
2080

    
2081
static void opt_image_format(const char *arg)
2082
{
2083
    AVImageFormat *f;
2084

    
2085
    for(f = first_image_format; f != NULL; f = f->next) {
2086
        if (!strcmp(arg, f->name))
2087
            break;
2088
    }
2089
    if (!f) {
2090
        fprintf(stderr, "Unknown image format: '%s'\n", arg);
2091
        exit(1);
2092
    }
2093
    image_format = f;
2094
}
2095

    
2096
static void opt_format(const char *arg)
2097
{
2098
    /* compatibility stuff for pgmyuv */
2099
    if (!strcmp(arg, "pgmyuv")) {
2100
        pgmyuv_compatibility_hack=1;
2101
//        opt_image_format(arg);
2102
        arg = "image2";
2103
    }
2104

    
2105
    file_iformat = av_find_input_format(arg);
2106
    file_oformat = guess_format(arg, NULL, NULL);
2107
    if (!file_iformat && !file_oformat) {
2108
        fprintf(stderr, "Unknown input or output format: %s\n", arg);
2109
        exit(1);
2110
    }
2111
}
2112

    
2113
static void opt_video_bitrate_tolerance(const char *arg)
2114
{
2115
    video_bit_rate_tolerance = atoi(arg) * 1000;
2116
}
2117

    
2118
static void opt_video_buffer_size(const char *arg)
2119
{
2120
    video_rc_buffer_size = atoi(arg) * 8*1024;
2121
}
2122

    
2123
static void opt_video_rc_eq(char *arg)
2124
{
2125
    video_rc_eq = arg;
2126
}
2127

    
2128
static void opt_video_rc_override_string(char *arg)
2129
{
2130
    video_rc_override_string = arg;
2131
}
2132

    
2133

    
2134
static void opt_workaround_bugs(const char *arg)
2135
{
2136
    workaround_bugs = atoi(arg);
2137
}
2138

    
2139
static void opt_me_threshold(const char *arg)
2140
{
2141
    me_threshold = atoi(arg);
2142
}
2143

    
2144
static void opt_mb_threshold(const char *arg)
2145
{
2146
    mb_threshold = atoi(arg);
2147
}
2148

    
2149
static void opt_verbose(const char *arg)
2150
{
2151
    verbose = atoi(arg);
2152
    av_log_set_level(atoi(arg));
2153
}
2154

    
2155
static void opt_frame_rate(const char *arg)
2156
{
2157
    if (parse_frame_rate(&frame_rate, &frame_rate_base, arg) < 0) {
2158
        fprintf(stderr, "Incorrect frame rate\n");
2159
        exit(1);
2160
    }
2161
}
2162

    
2163
static void opt_frame_crop_top(const char *arg)
2164
{
2165
    frame_topBand = atoi(arg);
2166
    if (frame_topBand < 0) {
2167
        fprintf(stderr, "Incorrect top crop size\n");
2168
        exit(1);
2169
    }
2170
    if ((frame_topBand % 2) != 0) {
2171
        fprintf(stderr, "Top crop size must be a multiple of 2\n");
2172
        exit(1);
2173
    }
2174
    if ((frame_topBand) >= frame_height){
2175
        fprintf(stderr, "Vertical crop dimensions are outside the range of the original image.\nRemember to crop first and scale second.\n");
2176
        exit(1);
2177
    }
2178
    frame_height -= frame_topBand;
2179
}
2180

    
2181
static void opt_frame_crop_bottom(const char *arg)
2182
{
2183
    frame_bottomBand = atoi(arg);
2184
    if (frame_bottomBand < 0) {
2185
        fprintf(stderr, "Incorrect bottom crop size\n");
2186
        exit(1);
2187
    }
2188
    if ((frame_bottomBand % 2) != 0) {
2189
        fprintf(stderr, "Bottom crop size must be a multiple of 2\n");
2190
        exit(1);
2191
    }
2192
    if ((frame_bottomBand) >= frame_height){
2193
        fprintf(stderr, "Vertical crop dimensions are outside the range of the original image.\nRemember to crop first and scale second.\n");
2194
        exit(1);
2195
    }
2196
    frame_height -= frame_bottomBand;
2197
}
2198

    
2199
static void opt_frame_crop_left(const char *arg)
2200
{
2201
    frame_leftBand = atoi(arg);
2202
    if (frame_leftBand < 0) {
2203
        fprintf(stderr, "Incorrect left crop size\n");
2204
        exit(1);
2205
    }
2206
    if ((frame_leftBand % 2) != 0) {
2207
        fprintf(stderr, "Left crop size must be a multiple of 2\n");
2208
        exit(1);
2209
    }
2210
    if ((frame_leftBand) >= frame_width){
2211
        fprintf(stderr, "Horizontal crop dimensions are outside the range of the original image.\nRemember to crop first and scale second.\n");
2212
        exit(1);
2213
    }
2214
    frame_width -= frame_leftBand;
2215
}
2216

    
2217
static void opt_frame_crop_right(const char *arg)
2218
{
2219
    frame_rightBand = atoi(arg);
2220
    if (frame_rightBand < 0) {
2221
        fprintf(stderr, "Incorrect right crop size\n");
2222
        exit(1);
2223
    }
2224
    if ((frame_rightBand % 2) != 0) {
2225
        fprintf(stderr, "Right crop size must be a multiple of 2\n");
2226
        exit(1);
2227
    }
2228
    if ((frame_rightBand) >= frame_width){
2229
        fprintf(stderr, "Horizontal crop dimensions are outside the range of the original image.\nRemember to crop first and scale second.\n");
2230
        exit(1);
2231
    }
2232
    frame_width -= frame_rightBand;
2233
}
2234

    
2235
static void opt_frame_size(const char *arg)
2236
{
2237
    if (parse_image_size(&frame_width, &frame_height, arg) < 0) {
2238
        fprintf(stderr, "Incorrect frame size\n");
2239
        exit(1);
2240
    }
2241
    if ((frame_width % 2) != 0 || (frame_height % 2) != 0) {
2242
        fprintf(stderr, "Frame size must be a multiple of 2\n");
2243
        exit(1);
2244
    }
2245
}
2246

    
2247

    
2248
#define SCALEBITS 10
2249
#define ONE_HALF  (1 << (SCALEBITS - 1))
2250
#define FIX(x)    ((int) ((x) * (1<<SCALEBITS) + 0.5))
2251

    
2252
#define RGB_TO_Y(r, g, b) \
2253
((FIX(0.29900) * (r) + FIX(0.58700) * (g) + \
2254
  FIX(0.11400) * (b) + ONE_HALF) >> SCALEBITS)
2255

    
2256
#define RGB_TO_U(r1, g1, b1, shift)\
2257
(((- FIX(0.16874) * r1 - FIX(0.33126) * g1 +         \
2258
     FIX(0.50000) * b1 + (ONE_HALF << shift) - 1) >> (SCALEBITS + shift)) + 128)
2259

    
2260
#define RGB_TO_V(r1, g1, b1, shift)\
2261
(((FIX(0.50000) * r1 - FIX(0.41869) * g1 -           \
2262
   FIX(0.08131) * b1 + (ONE_HALF << shift) - 1) >> (SCALEBITS + shift)) + 128)
2263

    
2264
static void opt_pad_color(const char *arg) {
2265
    /* Input is expected to be six hex digits similar to
2266
       how colors are expressed in html tags (but without the #) */
2267
    int rgb = strtol(arg, NULL, 16);
2268
    int r,g,b;
2269

    
2270
    r = (rgb >> 16);
2271
    g = ((rgb >> 8) & 255);
2272
    b = (rgb & 255);
2273

    
2274
    padcolor[0] = RGB_TO_Y(r,g,b);
2275
    padcolor[1] = RGB_TO_U(r,g,b,0);
2276
    padcolor[2] = RGB_TO_V(r,g,b,0);
2277
}
2278

    
2279
static void opt_frame_pad_top(const char *arg)
2280
{
2281
    frame_padtop = atoi(arg);
2282
    if (frame_padtop < 0) {
2283
        fprintf(stderr, "Incorrect top pad size\n");
2284
        exit(1);
2285
    }
2286
    if ((frame_padtop % 2) != 0) {
2287
        fprintf(stderr, "Top pad size must be a multiple of 2\n");
2288
        exit(1);
2289
    }
2290
}
2291

    
2292
static void opt_frame_pad_bottom(const char *arg)
2293
{
2294
    frame_padbottom = atoi(arg);
2295
    if (frame_padbottom < 0) {
2296
        fprintf(stderr, "Incorrect bottom pad size\n");
2297
        exit(1);
2298
    }
2299
    if ((frame_padbottom % 2) != 0) {
2300
        fprintf(stderr, "Bottom pad size must be a multiple of 2\n");
2301
        exit(1);
2302
    }
2303
}
2304

    
2305

    
2306
static void opt_frame_pad_left(const char *arg)
2307
{
2308
    frame_padleft = atoi(arg);
2309
    if (frame_padleft < 0) {
2310
        fprintf(stderr, "Incorrect left pad size\n");
2311
        exit(1);
2312
    }
2313
    if ((frame_padleft % 2) != 0) {
2314
        fprintf(stderr, "Left pad size must be a multiple of 2\n");
2315
        exit(1);
2316
    }
2317
}
2318

    
2319

    
2320
static void opt_frame_pad_right(const char *arg)
2321
{
2322
    frame_padright = atoi(arg);
2323
    if (frame_padright < 0) {
2324
        fprintf(stderr, "Incorrect right pad size\n");
2325
        exit(1);
2326
    }
2327
    if ((frame_padright % 2) != 0) {
2328
        fprintf(stderr, "Right pad size must be a multiple of 2\n");
2329
        exit(1);
2330
    }
2331
}
2332

    
2333

    
2334
static void opt_frame_pix_fmt(const char *arg)
2335
{
2336
    frame_pix_fmt = avcodec_get_pix_fmt(arg);
2337
}
2338

    
2339
static void opt_frame_aspect_ratio(const char *arg)
2340
{
2341
    int x = 0, y = 0;
2342
    double ar = 0;
2343
    const char *p;
2344

    
2345
    p = strchr(arg, ':');
2346
    if (p) {
2347
        x = strtol(arg, (char **)&arg, 10);
2348
        if (arg == p)
2349
            y = strtol(arg+1, (char **)&arg, 10);
2350
        if (x > 0 && y > 0)
2351
            ar = (double)x / (double)y;
2352
    } else
2353
        ar = strtod(arg, (char **)&arg);
2354

    
2355
    if (!ar) {
2356
        fprintf(stderr, "Incorrect aspect ratio specification.\n");
2357
        exit(1);
2358
    }
2359
    frame_aspect_ratio = ar;
2360
}
2361

    
2362
static void opt_b_frames(const char *arg)
2363
{
2364
    b_frames = atoi(arg);
2365
    if (b_frames > FF_MAX_B_FRAMES) {
2366
        fprintf(stderr, "\nCannot have more than %d B frames, increase FF_MAX_B_FRAMES.\n", FF_MAX_B_FRAMES);
2367
        exit(1);
2368
    } else if (b_frames < 1) {
2369
        fprintf(stderr, "\nNumber of B frames must be higher than 0\n");
2370
        exit(1);
2371
    }
2372
}
2373

    
2374
static void opt_qscale(const char *arg)
2375
{
2376
    video_qscale = atof(arg);
2377
    if (video_qscale <= 0 ||
2378
        video_qscale > 255) {
2379
        fprintf(stderr, "qscale must be > 0.0 and <= 255\n");
2380
        exit(1);
2381
    }
2382
}
2383

    
2384
static void opt_qsquish(const char *arg)
2385
{
2386
    video_qsquish = atof(arg);
2387
    if (video_qsquish < 0.0 ||
2388
        video_qsquish > 99.0) {
2389
        fprintf(stderr, "qsquish must be >= 0.0 and <= 99.0\n");
2390
        exit(1);
2391
    }
2392
}
2393

    
2394
static void opt_lmax(const char *arg)
2395
{
2396
    video_lmax = atof(arg)*FF_QP2LAMBDA;
2397
}
2398

    
2399
static void opt_lmin(const char *arg)
2400
{
2401
    video_lmin = atof(arg)*FF_QP2LAMBDA;
2402
}
2403

    
2404
static void opt_qmin(const char *arg)
2405
{
2406
    video_qmin = atoi(arg);
2407
    if (video_qmin < 1 ||
2408
        video_qmin > 51) {
2409
        fprintf(stderr, "qmin must be >= 1 and <= 51\n");
2410
        exit(1);
2411
    }
2412
}
2413

    
2414
static void opt_qmax(const char *arg)
2415
{
2416
    video_qmax = atoi(arg);
2417
    if (video_qmax < 1 ||
2418
        video_qmax > 51) {
2419
        fprintf(stderr, "qmax must be >= 1 and <= 51\n");
2420
        exit(1);
2421
    }
2422
}
2423

    
2424
static void opt_mb_lmin(const char *arg)
2425
{
2426
    video_mb_lmin = atof(arg)*FF_QP2LAMBDA;
2427
    if (video_mb_lmin < 1 ||
2428
        video_mb_lmin > FF_LAMBDA_MAX) {
2429
        fprintf(stderr, "mblmin must be >= 1 and <= %d\n", FF_LAMBDA_MAX / FF_QP2LAMBDA);
2430
        exit(1);
2431
    }
2432
}
2433

    
2434
static void opt_mb_lmax(const char *arg)
2435
{
2436
    video_mb_lmax = atof(arg)*FF_QP2LAMBDA;
2437
    if (video_mb_lmax < 1 ||
2438
        video_mb_lmax > FF_LAMBDA_MAX) {
2439
        fprintf(stderr, "mblmax must be >= 1 and <= %d\n", FF_LAMBDA_MAX / FF_QP2LAMBDA);
2440
        exit(1);
2441
    }
2442
}
2443

    
2444
static void opt_qdiff(const char *arg)
2445
{
2446
    video_qdiff = atoi(arg);
2447
    if (video_qdiff < 0 ||
2448
        video_qdiff > 31) {
2449
        fprintf(stderr, "qdiff must be >= 1 and <= 31\n");
2450
        exit(1);
2451
    }
2452
}
2453

    
2454
static void opt_qblur(const char *arg)
2455
{
2456
    video_qblur = atof(arg);
2457
}
2458

    
2459
static void opt_qcomp(const char *arg)
2460
{
2461
    video_qcomp = atof(arg);
2462
}
2463

    
2464
static void opt_rc_initial_cplx(const char *arg)
2465
{
2466
    video_rc_initial_cplx = atof(arg);
2467
}
2468
static void opt_b_qfactor(const char *arg)
2469
{
2470
    video_b_qfactor = atof(arg);
2471
}
2472
static void opt_i_qfactor(const char *arg)
2473
{
2474
    video_i_qfactor = atof(arg);
2475
}
2476
static void opt_b_qoffset(const char *arg)
2477
{
2478
    video_b_qoffset = atof(arg);
2479
}
2480
static void opt_i_qoffset(const char *arg)
2481
{
2482
    video_i_qoffset = atof(arg);
2483
}
2484

    
2485
static void opt_pbias(const char *arg)
2486
{
2487
    video_inter_quant_bias = atoi(arg);
2488
}
2489

    
2490
static void opt_packet_size(const char *arg)
2491
{
2492
    packet_size= atoi(arg);
2493
}
2494

    
2495
static void opt_error_rate(const char *arg)
2496
{
2497
    error_rate= atoi(arg);
2498
}
2499

    
2500
static void opt_strict(const char *arg)
2501
{
2502
    strict= atoi(arg);
2503
}
2504

    
2505
static void opt_top_field_first(const char *arg)
2506
{
2507
    top_field_first= atoi(arg);
2508
}
2509

    
2510
static void opt_sc_threshold(const char *arg)
2511
{
2512
    sc_threshold= atoi(arg);
2513
}
2514

    
2515
static void opt_me_range(const char *arg)
2516
{
2517
    me_range = atoi(arg);
2518
}
2519

    
2520
static void opt_thread_count(const char *arg)
2521
{
2522
    thread_count= atoi(arg);
2523
#if !defined(HAVE_THREADS)
2524
    if (verbose >= 0)
2525
        fprintf(stderr, "Warning: not compiled with thread support, using thread emulation\n");
2526
#endif
2527
}
2528

    
2529
static void opt_audio_bitrate(const char *arg)
2530
{
2531
    audio_bit_rate = atoi(arg) * 1000;
2532
}
2533

    
2534
static void opt_audio_rate(const char *arg)
2535
{
2536
    audio_sample_rate = atoi(arg);
2537
}
2538

    
2539
static void opt_audio_channels(const char *arg)
2540
{
2541
    audio_channels = atoi(arg);
2542
}
2543

    
2544
static void opt_video_device(const char *arg)
2545
{
2546
    video_device = av_strdup(arg);
2547
}
2548

    
2549
static void opt_grab_device(const char *arg)
2550
{
2551
    grab_device = av_strdup(arg);
2552
}
2553

    
2554
static void opt_video_channel(const char *arg)
2555
{
2556
    video_channel = strtol(arg, NULL, 0);
2557
}
2558

    
2559
static void opt_video_standard(const char *arg)
2560
{
2561
    video_standard = av_strdup(arg);
2562
}
2563

    
2564
static void opt_audio_device(const char *arg)
2565
{
2566
    audio_device = av_strdup(arg);
2567
}
2568

    
2569
static void opt_codec(int *pstream_copy, int *pcodec_id,
2570
                      int codec_type, const char *arg)
2571
{
2572
    AVCodec *p;
2573

    
2574
    if (!strcmp(arg, "copy")) {
2575
        *pstream_copy = 1;
2576
    } else {
2577
        p = first_avcodec;
2578
        while (p) {
2579
            if (!strcmp(p->name, arg) && p->type == codec_type)
2580
                break;
2581
            p = p->next;
2582
        }
2583
        if (p == NULL) {
2584
            fprintf(stderr, "Unknown codec '%s'\n", arg);
2585
            exit(1);
2586
        } else {
2587
            *pcodec_id = p->id;
2588
        }
2589
    }
2590
}
2591

    
2592
static void opt_audio_codec(const char *arg)
2593
{
2594
    opt_codec(&audio_stream_copy, &audio_codec_id, CODEC_TYPE_AUDIO, arg);
2595
}
2596

    
2597
static void opt_audio_tag(const char *arg)
2598
{
2599
    char *tail;
2600
    audio_codec_tag= strtol(arg, &tail, 0);
2601

    
2602
    if(!tail || *tail)
2603
        audio_codec_tag= arg[0] + (arg[1]<<8) + (arg[2]<<16) + (arg[3]<<24);
2604
}
2605

    
2606
static void opt_video_tag(const char *arg)
2607
{
2608
    char *tail;
2609
    video_codec_tag= strtol(arg, &tail, 0);
2610

    
2611
    if(!tail || *tail)
2612
        video_codec_tag= arg[0] + (arg[1]<<8) + (arg[2]<<16) + (arg[3]<<24);
2613
}
2614

    
2615
static void add_frame_hooker(const char *arg)
2616
{
2617
    int argc = 0;
2618
    char *argv[64];
2619
    int i;
2620
    char *args = av_strdup(arg);
2621

    
2622
    using_vhook = 1;
2623

    
2624
    argv[0] = strtok(args, " ");
2625
    while (argc < 62 && (argv[++argc] = strtok(NULL, " "))) {
2626
    }
2627

    
2628
    i = frame_hook_add(argc, argv);
2629

    
2630
    if (i != 0) {
2631
        fprintf(stderr, "Failed to add video hook function: %s\n", arg);
2632
        exit(1);
2633
    }
2634
}
2635

    
2636
const char *motion_str[] = {
2637
    "zero",
2638
    "full",
2639
    "log",
2640
    "phods",
2641
    "epzs",
2642
    "x1",
2643
    "hex",
2644
    "umh",
2645
    "iter",
2646
    NULL,
2647
};
2648

    
2649
static void opt_motion_estimation(const char *arg)
2650
{
2651
    const char **p;
2652
    p = motion_str;
2653
    for(;;) {
2654
        if (!*p) {
2655
            fprintf(stderr, "Unknown motion estimation method '%s'\n", arg);
2656
            exit(1);
2657
        }
2658
        if (!strcmp(*p, arg))
2659
            break;
2660
        p++;
2661
    }
2662
    me_method = (p - motion_str) + 1;
2663
}
2664

    
2665
static void opt_video_codec(const char *arg)
2666
{
2667
    opt_codec(&video_stream_copy, &video_codec_id, CODEC_TYPE_VIDEO, arg);
2668
}
2669

    
2670
static void opt_subtitle_codec(const char *arg)
2671
{
2672
    opt_codec(&subtitle_stream_copy, &subtitle_codec_id, CODEC_TYPE_SUBTITLE, arg);
2673
}
2674

    
2675
static void opt_map(const char *arg)
2676
{
2677
    AVStreamMap *m;
2678
    const char *p;
2679

    
2680
    p = arg;
2681
    m = &stream_maps[nb_stream_maps++];
2682

    
2683
    m->file_index = strtol(arg, (char **)&p, 0);
2684
    if (*p)
2685
        p++;
2686

    
2687
    m->stream_index = strtol(p, (char **)&p, 0);
2688
    if (*p) {
2689
        p++;
2690
        m->sync_file_index = strtol(p, (char **)&p, 0);
2691
        if (*p)
2692
            p++;
2693
        m->sync_stream_index = strtol(p, (char **)&p, 0);
2694
    } else {
2695
        m->sync_file_index = m->file_index;
2696
        m->sync_stream_index = m->stream_index;
2697
    }
2698
}
2699

    
2700
static void opt_map_meta_data(const char *arg)
2701
{
2702
    AVMetaDataMap *m;
2703
    const char *p;
2704

    
2705
    p = arg;
2706
    m = &meta_data_maps[nb_meta_data_maps++];
2707

    
2708
    m->out_file = strtol(arg, (char **)&p, 0);
2709
    if (*p)
2710
        p++;
2711

    
2712
    m->in_file = strtol(p, (char **)&p, 0);
2713
}
2714

    
2715
static void opt_recording_time(const char *arg)
2716
{
2717
    recording_time = parse_date(arg, 1);
2718
}
2719

    
2720
static void opt_start_time(const char *arg)
2721
{
2722
    start_time = parse_date(arg, 1);
2723
}
2724

    
2725
static void opt_rec_timestamp(const char *arg)
2726
{
2727
    rec_timestamp = parse_date(arg, 0) / 1000000;
2728
}
2729

    
2730
static void opt_input_ts_offset(const char *arg)
2731
{
2732
    input_ts_offset = parse_date(arg, 1);
2733
}
2734

    
2735
static void opt_input_file(const char *filename)
2736
{
2737
    AVFormatContext *ic;
2738
    AVFormatParameters params, *ap = &params;
2739
    int err, i, ret, rfps, rfps_base;
2740
    int64_t timestamp;
2741

    
2742
    if (!strcmp(filename, "-"))
2743
        filename = "pipe:";
2744

    
2745
    using_stdin |= !strncmp(filename, "pipe:", 5) ||
2746
                   !strcmp( filename, "/dev/stdin" );
2747

    
2748
    /* get default parameters from command line */
2749
    ic = av_alloc_format_context();
2750

    
2751
    memset(ap, 0, sizeof(*ap));
2752
    ap->prealloced_context = 1;
2753
    ap->sample_rate = audio_sample_rate;
2754
    ap->channels = audio_channels;
2755
    ap->time_base.den = frame_rate;
2756
    ap->time_base.num = frame_rate_base;
2757
    ap->width = frame_width + frame_padleft + frame_padright;
2758
    ap->height = frame_height + frame_padtop + frame_padbottom;
2759
    ap->image_format = image_format;
2760
    ap->pix_fmt = frame_pix_fmt;
2761
    ap->device  = grab_device;
2762
    ap->channel = video_channel;
2763
    ap->standard = video_standard;
2764
    ap->video_codec_id = video_codec_id;
2765
    ap->audio_codec_id = audio_codec_id;
2766
    if(pgmyuv_compatibility_hack)
2767
        ap->video_codec_id= CODEC_ID_PGMYUV;
2768

    
2769
    for(i=0; i<opt_name_count; i++){
2770
        AVOption *opt;
2771
        double d= av_get_double(avformat_opts, opt_names[i], &opt);
2772
        if(d==d && (opt->flags&AV_OPT_FLAG_DECODING_PARAM))
2773
            av_set_double(ic, opt_names[i], d);
2774
    }
2775
    /* open the input file with generic libav function */
2776
    err = av_open_input_file(&ic, filename, file_iformat, 0, ap);
2777
    if (err < 0) {
2778
        print_error(filename, err);
2779
        exit(1);
2780
    }
2781

    
2782
    ic->loop_input = loop_input;
2783

    
2784
    /* If not enough info to get the stream parameters, we decode the
2785
       first frames to get it. (used in mpeg case for example) */
2786
    ret = av_find_stream_info(ic);
2787
    if (ret < 0 && verbose >= 0) {
2788
        fprintf(stderr, "%s: could not find codec parameters\n", filename);
2789
        exit(1);
2790
    }
2791

    
2792
    timestamp = start_time;
2793
    /* add the stream start time */
2794
    if (ic->start_time != AV_NOPTS_VALUE)
2795
        timestamp += ic->start_time;
2796

    
2797
    /* if seeking requested, we execute it */
2798
    if (start_time != 0) {
2799
        ret = av_seek_frame(ic, -1, timestamp, AVSEEK_FLAG_BACKWARD);
2800
        if (ret < 0) {
2801
            fprintf(stderr, "%s: could not seek to position %0.3f\n",
2802
                    filename, (double)timestamp / AV_TIME_BASE);
2803
        }
2804
        /* reset seek info */
2805
        start_time = 0;
2806
    }
2807

    
2808
    /* update the current parameters so that they match the one of the input stream */
2809
    for(i=0;i<ic->nb_streams;i++) {
2810
        int j;
2811
        AVCodecContext *enc = ic->streams[i]->codec;
2812
#if defined(HAVE_THREADS)
2813
        if(thread_count>1)
2814
            avcodec_thread_init(enc, thread_count);
2815
#endif
2816
        enc->thread_count= thread_count;
2817
        switch(enc->codec_type) {
2818
        case CODEC_TYPE_AUDIO:
2819
            for(j=0; j<opt_name_count; j++){
2820
                AVOption *opt;
2821
                double d= av_get_double(avctx_opts, opt_names[j], &opt);
2822
                if(d==d && (opt->flags&AV_OPT_FLAG_AUDIO_PARAM) && (opt->flags&AV_OPT_FLAG_DECODING_PARAM))
2823
                    av_set_double(enc, opt_names[j], d);
2824
            }
2825
            //fprintf(stderr, "\nInput Audio channels: %d", enc->channels);
2826
            audio_channels = enc->channels;
2827
            audio_sample_rate = enc->sample_rate;
2828
            if(audio_disable)
2829
                ic->streams[i]->discard= AVDISCARD_ALL;
2830
            break;
2831
        case CODEC_TYPE_VIDEO:
2832
            for(j=0; j<opt_name_count; j++){
2833
                AVOption *opt;
2834
                double d= av_get_double(avctx_opts, opt_names[j], &opt);
2835
                if(d==d && (opt->flags&AV_OPT_FLAG_VIDEO_PARAM) && (opt->flags&AV_OPT_FLAG_DECODING_PARAM))
2836
                    av_set_double(enc, opt_names[j], d);
2837
            }
2838
            frame_height = enc->height;
2839
            frame_width = enc->width;
2840
            frame_aspect_ratio = av_q2d(enc->sample_aspect_ratio) * enc->width / enc->height;
2841
            frame_pix_fmt = enc->pix_fmt;
2842
            rfps      = ic->streams[i]->r_frame_rate.num;
2843
            rfps_base = ic->streams[i]->r_frame_rate.den;
2844
            enc->workaround_bugs = workaround_bugs;
2845
            if(enc->lowres) enc->flags |= CODEC_FLAG_EMU_EDGE;
2846
            if(me_threshold)
2847
                enc->debug |= FF_DEBUG_MV;
2848

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

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

    
2855
                    (float)rfps / rfps_base, rfps, rfps_base);
2856
            }
2857
            /* update the current frame rate to match the stream frame rate */
2858
            frame_rate      = rfps;
2859
            frame_rate_base = rfps_base;
2860

    
2861
            enc->rate_emu = rate_emu;
2862
            if(video_disable)
2863
                ic->streams[i]->discard= AVDISCARD_ALL;
2864
            else if(video_discard)
2865
                ic->streams[i]->discard= video_discard;
2866
            break;
2867
        case CODEC_TYPE_DATA:
2868
            break;
2869
        case CODEC_TYPE_SUBTITLE:
2870
            break;
2871
        case CODEC_TYPE_UNKNOWN:
2872
            break;
2873
        default:
2874
            av_abort();
2875
        }
2876
    }
2877

    
2878
    input_files[nb_input_files] = ic;
2879
    input_files_ts_offset[nb_input_files] = input_ts_offset - (copy_ts ? 0 : timestamp);
2880
    /* dump the file content */
2881
    if (verbose >= 0)
2882
        dump_format(ic, nb_input_files, filename, 0);
2883

    
2884
    nb_input_files++;
2885
    file_iformat = NULL;
2886
    file_oformat = NULL;
2887
    image_format = NULL;
2888

    
2889
    grab_device = NULL;
2890
    video_channel = 0;
2891

    
2892
    rate_emu = 0;
2893
}
2894

    
2895
static void opt_grab(const char *arg)
2896
{
2897
    file_iformat = av_find_input_format(arg);
2898
    opt_input_file("");
2899
}
2900

    
2901
static void check_audio_video_inputs(int *has_video_ptr, int *has_audio_ptr)
2902
{
2903
    int has_video, has_audio, i, j;
2904
    AVFormatContext *ic;
2905

    
2906
    has_video = 0;
2907
    has_audio = 0;
2908
    for(j=0;j<nb_input_files;j++) {
2909
        ic = input_files[j];
2910
        for(i=0;i<ic->nb_streams;i++) {
2911
            AVCodecContext *enc = ic->streams[i]->codec;
2912
            switch(enc->codec_type) {
2913
            case CODEC_TYPE_AUDIO:
2914
                has_audio = 1;
2915
                break;
2916
            case CODEC_TYPE_VIDEO:
2917
                has_video = 1;
2918
                break;
2919
            case CODEC_TYPE_DATA:
2920
            case CODEC_TYPE_UNKNOWN:
2921
            case CODEC_TYPE_SUBTITLE:
2922
                break;
2923
            default:
2924
                av_abort();
2925
            }
2926
        }
2927
    }
2928
    *has_video_ptr = has_video;
2929
    *has_audio_ptr = has_audio;
2930
}
2931

    
2932
static void new_video_stream(AVFormatContext *oc)
2933
{
2934
    AVStream *st;
2935
    AVCodecContext *video_enc;
2936
    int codec_id;
2937

    
2938
    st = av_new_stream(oc, oc->nb_streams);
2939
    if (!st) {
2940
        fprintf(stderr, "Could not alloc stream\n");
2941
        exit(1);
2942
    }
2943
    bitstream_filters[nb_output_files][oc->nb_streams - 1]= video_bitstream_filters;
2944
    video_bitstream_filters= NULL;
2945

    
2946
#if defined(HAVE_THREADS)
2947
    if(thread_count>1)
2948
        avcodec_thread_init(st->codec, thread_count);
2949
#endif
2950

    
2951
    video_enc = st->codec;
2952

    
2953
    if(video_codec_tag)
2954
        video_enc->codec_tag= video_codec_tag;
2955

    
2956
    if(   (video_global_header&1)
2957
       || (video_global_header==0 && (oc->oformat->flags & AVFMT_GLOBALHEADER))){
2958
        video_enc->flags |= CODEC_FLAG_GLOBAL_HEADER;
2959
        avctx_opts->flags|= CODEC_FLAG_GLOBAL_HEADER;
2960
    }
2961
    if(video_global_header&2){
2962
        video_enc->flags2 |= CODEC_FLAG2_LOCAL_HEADER;
2963
        avctx_opts->flags2|= CODEC_FLAG2_LOCAL_HEADER;
2964
    }
2965

    
2966
    if (video_stream_copy) {
2967
        st->stream_copy = 1;
2968
        video_enc->codec_type = CODEC_TYPE_VIDEO;
2969
    } else {
2970
        char *p;
2971
        int i;
2972
        AVCodec *codec;
2973

    
2974
        codec_id = av_guess_codec(oc->oformat, NULL, oc->filename, NULL, CODEC_TYPE_VIDEO);
2975
        if (video_codec_id != CODEC_ID_NONE)
2976
            codec_id = video_codec_id;
2977

    
2978
        video_enc->codec_id = codec_id;
2979
        codec = avcodec_find_encoder(codec_id);
2980

    
2981
        for(i=0; i<opt_name_count; i++){
2982
             AVOption *opt;
2983
             double d= av_get_double(avctx_opts, opt_names[i], &opt);
2984
             if(d==d && (opt->flags&AV_OPT_FLAG_VIDEO_PARAM) && (opt->flags&AV_OPT_FLAG_ENCODING_PARAM))
2985
                 av_set_double(video_enc, opt_names[i], d);
2986
        }
2987

    
2988
        video_enc->bit_rate_tolerance = video_bit_rate_tolerance;
2989
        video_enc->time_base.den = frame_rate;
2990
        video_enc->time_base.num = frame_rate_base;
2991
        if(codec && codec->supported_framerates){
2992
            const AVRational *p= codec->supported_framerates;
2993
            AVRational req= (AVRational){frame_rate, frame_rate_base};
2994
            const AVRational *best=NULL;
2995
            AVRational best_error= (AVRational){INT_MAX, 1};
2996
            for(; p->den!=0; p++){
2997
                AVRational error= av_sub_q(req, *p);
2998
                if(error.num <0) error.num *= -1;
2999
                if(av_cmp_q(error, best_error) < 0){
3000
                    best_error= error;
3001
                    best= p;
3002
                }
3003
            }
3004
            video_enc->time_base.den= best->num;
3005
            video_enc->time_base.num= best->den;
3006
        }
3007

    
3008
        video_enc->width = frame_width + frame_padright + frame_padleft;
3009
        video_enc->height = frame_height + frame_padtop + frame_padbottom;
3010
        video_enc->sample_aspect_ratio = av_d2q(frame_aspect_ratio*video_enc->height/video_enc->width, 255);
3011
        video_enc->pix_fmt = frame_pix_fmt;
3012

    
3013
        if(codec && codec->pix_fmts){
3014
            const enum PixelFormat *p= codec->pix_fmts;
3015
            for(; *p!=-1; p++){
3016
                if(*p == video_enc->pix_fmt)
3017
                    break;
3018
            }
3019
            if(*p == -1)
3020
                video_enc->pix_fmt = codec->pix_fmts[0];
3021
        }
3022

    
3023
        if (intra_only)
3024
            video_enc->gop_size = 0;
3025
        if (video_qscale || same_quality) {
3026
            video_enc->flags |= CODEC_FLAG_QSCALE;
3027
            video_enc->global_quality=
3028
                st->quality = FF_QP2LAMBDA * video_qscale;
3029
        }
3030

    
3031
        if(intra_matrix)
3032
            video_enc->intra_matrix = intra_matrix;
3033
        if(inter_matrix)
3034
            video_enc->inter_matrix = inter_matrix;
3035

    
3036
        if (b_frames) {
3037
            video_enc->max_b_frames = b_frames;
3038
            video_enc->b_quant_factor = 2.0;
3039
        }
3040
        video_enc->qmin = video_qmin;
3041
        video_enc->qmax = video_qmax;
3042
        video_enc->lmin = video_lmin;
3043
        video_enc->lmax = video_lmax;
3044
        video_enc->rc_qsquish = video_qsquish;
3045
        video_enc->mb_lmin = video_mb_lmin;
3046
        video_enc->mb_lmax = video_mb_lmax;
3047
        video_enc->max_qdiff = video_qdiff;
3048
        video_enc->qblur = video_qblur;
3049
        video_enc->qcompress = video_qcomp;
3050
        video_enc->rc_eq = video_rc_eq;
3051
        video_enc->workaround_bugs = workaround_bugs;
3052
        video_enc->thread_count = thread_count;
3053
        p= video_rc_override_string;
3054
        for(i=0; p; i++){
3055
            int start, end, q;
3056
            int e=sscanf(p, "%d,%d,%d", &start, &end, &q);
3057
            if(e!=3){
3058
                fprintf(stderr, "error parsing rc_override\n");
3059
                exit(1);
3060
            }
3061
            video_enc->rc_override=
3062
                av_realloc(video_enc->rc_override,
3063
                           sizeof(RcOverride)*(i+1));
3064
            video_enc->rc_override[i].start_frame= start;
3065
            video_enc->rc_override[i].end_frame  = end;
3066
            if(q>0){
3067
                video_enc->rc_override[i].qscale= q;
3068
                video_enc->rc_override[i].quality_factor= 1.0;
3069
            }
3070
            else{
3071
                video_enc->rc_override[i].qscale= 0;
3072
                video_enc->rc_override[i].quality_factor= -q/100.0;
3073
            }
3074
            p= strchr(p, '/');
3075
            if(p) p++;
3076
        }
3077
        video_enc->rc_override_count=i;
3078

    
3079
        video_enc->rc_buffer_size = video_rc_buffer_size;
3080
        video_enc->rc_initial_buffer_occupancy = video_rc_buffer_size*3/4;
3081
        video_enc->rc_buffer_aggressivity= video_rc_buffer_aggressivity;
3082
        video_enc->rc_initial_cplx= video_rc_initial_cplx;
3083
        video_enc->i_quant_factor = video_i_qfactor;
3084
        video_enc->b_quant_factor = video_b_qfactor;
3085
        video_enc->i_quant_offset = video_i_qoffset;
3086
        video_enc->b_quant_offset = video_b_qoffset;
3087
        video_enc->inter_quant_bias = video_inter_quant_bias;
3088
        video_enc->me_threshold= me_threshold;
3089
        video_enc->mb_threshold= mb_threshold;
3090
        video_enc->intra_dc_precision= intra_dc_precision - 8;
3091
        video_enc->strict_std_compliance = strict;
3092
        video_enc->error_rate = error_rate;
3093
        video_enc->scenechange_threshold= sc_threshold;
3094
        video_enc->me_range = me_range;
3095
        video_enc->me_penalty_compensation= me_penalty_compensation;
3096
        video_enc->frame_skip_threshold= frame_skip_threshold;
3097
        video_enc->frame_skip_factor= frame_skip_factor;
3098
        video_enc->frame_skip_exp= frame_skip_exp;
3099

    
3100
        if(packet_size){
3101
            video_enc->rtp_mode= 1;
3102
            video_enc->rtp_payload_size= packet_size;
3103
        }
3104

    
3105
        if (do_psnr)
3106
            video_enc->flags|= CODEC_FLAG_PSNR;
3107

    
3108
        video_enc->me_method = me_method;
3109

    
3110
        /* two pass mode */
3111
        if (do_pass) {
3112
            if (do_pass == 1) {
3113
                video_enc->flags |= CODEC_FLAG_PASS1;
3114
            } else {
3115
                video_enc->flags |= CODEC_FLAG_PASS2;
3116
            }
3117
        }
3118
    }
3119

    
3120
    /* reset some key parameters */
3121
    video_disable = 0;
3122
    video_codec_id = CODEC_ID_NONE;
3123
    video_stream_copy = 0;
3124
}
3125

    
3126
static void new_audio_stream(AVFormatContext *oc)
3127
{
3128
    AVStream *st;
3129
    AVCodecContext *audio_enc;
3130
    int codec_id, i;
3131

    
3132
    st = av_new_stream(oc, oc->nb_streams);
3133
    if (!st) {
3134
        fprintf(stderr, "Could not alloc stream\n");
3135
        exit(1);
3136
    }
3137

    
3138
    bitstream_filters[nb_output_files][oc->nb_streams - 1]= audio_bitstream_filters;
3139
    audio_bitstream_filters= NULL;
3140

    
3141
#if defined(HAVE_THREADS)
3142
    if(thread_count>1)
3143
        avcodec_thread_init(st->codec, thread_count);
3144
#endif
3145

    
3146
    audio_enc = st->codec;
3147
    audio_enc->codec_type = CODEC_TYPE_AUDIO;
3148

    
3149
    if(audio_codec_tag)
3150
        audio_enc->codec_tag= audio_codec_tag;
3151

    
3152
    if (oc->oformat->flags & AVFMT_GLOBALHEADER) {
3153
        audio_enc->flags |= CODEC_FLAG_GLOBAL_HEADER;
3154
        avctx_opts->flags|= CODEC_FLAG_GLOBAL_HEADER;
3155
    }
3156
    if (audio_stream_copy) {
3157
        st->stream_copy = 1;
3158
        audio_enc->channels = audio_channels;
3159
    } else {
3160
        codec_id = av_guess_codec(oc->oformat, NULL, oc->filename, NULL, CODEC_TYPE_AUDIO);
3161

    
3162
        for(i=0; i<opt_name_count; i++){
3163
            AVOption *opt;
3164
            double d= av_get_double(avctx_opts, opt_names[i], &opt);
3165
            if(d==d && (opt->flags&AV_OPT_FLAG_AUDIO_PARAM) && (opt->flags&AV_OPT_FLAG_ENCODING_PARAM))
3166
                av_set_double(audio_enc, opt_names[i], d);
3167
        }
3168

    
3169
        if (audio_codec_id != CODEC_ID_NONE)
3170
            codec_id = audio_codec_id;
3171
        audio_enc->codec_id = codec_id;
3172

    
3173
        audio_enc->bit_rate = audio_bit_rate;
3174
        if (audio_qscale > QSCALE_NONE) {
3175
            audio_enc->flags |= CODEC_FLAG_QSCALE;
3176
            audio_enc->global_quality = st->quality = FF_QP2LAMBDA * audio_qscale;
3177
        }
3178
        audio_enc->strict_std_compliance = strict;
3179
        audio_enc->thread_count = thread_count;
3180
        /* For audio codecs other than AC3 or DTS we limit */
3181
        /* the number of coded channels to stereo   */
3182
        if (audio_channels > 2 && codec_id != CODEC_ID_AC3
3183
            && codec_id != CODEC_ID_DTS) {
3184
            audio_enc->channels = 2;
3185
        } else
3186
            audio_enc->channels = audio_channels;
3187
    }
3188
    audio_enc->sample_rate = audio_sample_rate;
3189
    audio_enc->time_base= (AVRational){1, audio_sample_rate};
3190
    if (audio_language) {
3191
        pstrcpy(st->language, sizeof(st->language), audio_language);
3192
        av_free(audio_language);
3193
        audio_language = NULL;
3194
    }
3195

    
3196
    /* reset some key parameters */
3197
    audio_disable = 0;
3198
    audio_codec_id = CODEC_ID_NONE;
3199
    audio_stream_copy = 0;
3200
}
3201

    
3202
static void opt_new_subtitle_stream(void)
3203
{
3204
    AVFormatContext *oc;
3205
    AVStream *st;
3206
    AVCodecContext *subtitle_enc;
3207
    int i;
3208

    
3209
    if (nb_output_files <= 0) {
3210
        fprintf(stderr, "At least one output file must be specified\n");
3211
        exit(1);
3212
    }
3213
    oc = output_files[nb_output_files - 1];
3214

    
3215
    st = av_new_stream(oc, oc->nb_streams);
3216
    if (!st) {
3217
        fprintf(stderr, "Could not alloc stream\n");
3218
        exit(1);
3219
    }
3220

    
3221
    subtitle_enc = st->codec;
3222
    subtitle_enc->codec_type = CODEC_TYPE_SUBTITLE;
3223
    if (subtitle_stream_copy) {
3224
        st->stream_copy = 1;
3225
    } else {
3226
        for(i=0; i<opt_name_count; i++){
3227
             AVOption *opt;
3228
             double d= av_get_double(avctx_opts, opt_names[i], &opt);
3229
             if(d==d && (opt->flags&AV_OPT_FLAG_SUBTITLE_PARAM) && (opt->flags&AV_OPT_FLAG_ENCODING_PARAM))
3230
                 av_set_double(subtitle_enc, opt_names[i], d);
3231
        }
3232
        subtitle_enc->codec_id = subtitle_codec_id;
3233
    }
3234

    
3235
    if (subtitle_language) {
3236
        pstrcpy(st->language, sizeof(st->language), subtitle_language);
3237
        av_free(subtitle_language);
3238
        subtitle_language = NULL;
3239
    }
3240

    
3241
    subtitle_codec_id = CODEC_ID_NONE;
3242
    subtitle_stream_copy = 0;
3243
}
3244

    
3245
static void opt_new_audio_stream(void)
3246
{
3247
    AVFormatContext *oc;
3248
    if (nb_output_files <= 0) {
3249
        fprintf(stderr, "At least one output file must be specified\n");
3250
        exit(1);
3251
    }
3252
    oc = output_files[nb_output_files - 1];
3253
    new_audio_stream(oc);
3254
}
3255

    
3256
static void opt_new_video_stream(void)
3257
{
3258
    AVFormatContext *oc;
3259
    if (nb_output_files <= 0) {
3260
        fprintf(stderr, "At least one output file must be specified\n");
3261
        exit(1);
3262
    }
3263
    oc = output_files[nb_output_files - 1];
3264
    new_video_stream(oc);
3265
}
3266

    
3267
static void opt_output_file(const char *filename)
3268
{
3269
    AVFormatContext *oc;
3270
    int use_video, use_audio, input_has_video, input_has_audio, i;
3271
    AVFormatParameters params, *ap = &params;
3272

    
3273
    if (!strcmp(filename, "-"))
3274
        filename = "pipe:";
3275

    
3276
    oc = av_alloc_format_context();
3277

    
3278
    if (!file_oformat) {
3279
        file_oformat = guess_format(NULL, filename, NULL);
3280
        if (!file_oformat) {
3281
            fprintf(stderr, "Unable for find a suitable output format for '%s'\n",
3282
                    filename);
3283
            exit(1);
3284
        }
3285
    }
3286

    
3287
    oc->oformat = file_oformat;
3288
    pstrcpy(oc->filename, sizeof(oc->filename), filename);
3289

    
3290
    if (!strcmp(file_oformat->name, "ffm") &&
3291
        strstart(filename, "http:", NULL)) {
3292
        /* special case for files sent to ffserver: we get the stream
3293
           parameters from ffserver */
3294
        if (read_ffserver_streams(oc, filename) < 0) {
3295
            fprintf(stderr, "Could not read stream parameters from '%s'\n", filename);
3296
            exit(1);
3297
        }
3298
    } else {
3299
        use_video = file_oformat->video_codec != CODEC_ID_NONE || video_stream_copy || video_codec_id != CODEC_ID_NONE;
3300
        use_audio = file_oformat->audio_codec != CODEC_ID_NONE || audio_stream_copy || audio_codec_id != CODEC_ID_NONE;
3301

    
3302
        /* disable if no corresponding type found and at least one
3303
           input file */
3304
        if (nb_input_files > 0) {
3305
            check_audio_video_inputs(&input_has_video, &input_has_audio);
3306
            if (!input_has_video)
3307
                use_video = 0;
3308
            if (!input_has_audio)
3309
                use_audio = 0;
3310
        }
3311

    
3312
        /* manual disable */
3313
        if (audio_disable) {
3314
            use_audio = 0;
3315
        }
3316
        if (video_disable) {
3317
            use_video = 0;
3318
        }
3319

    
3320
        if (use_video) {
3321
            new_video_stream(oc);
3322
        }
3323

    
3324
        if (use_audio) {
3325
            new_audio_stream(oc);
3326
        }
3327

    
3328
        if (!oc->nb_streams) {
3329
            fprintf(stderr, "No audio or video streams available\n");
3330
            exit(1);
3331
        }
3332

    
3333
        oc->timestamp = rec_timestamp;
3334

    
3335
        if (str_title)
3336
            pstrcpy(oc->title, sizeof(oc->title), str_title);
3337
        if (str_author)
3338
            pstrcpy(oc->author, sizeof(oc->author), str_author);
3339
        if (str_copyright)
3340
            pstrcpy(oc->copyright, sizeof(oc->copyright), str_copyright);
3341
        if (str_comment)
3342
            pstrcpy(oc->comment, sizeof(oc->comment), str_comment);
3343
        if (str_album)
3344
            pstrcpy(oc->album, sizeof(oc->album), str_album);
3345
    }
3346

    
3347
    output_files[nb_output_files++] = oc;
3348

    
3349
    /* check filename in case of an image number is expected */
3350
    if (oc->oformat->flags & AVFMT_NEEDNUMBER) {
3351
        if (!av_filename_number_test(oc->filename)) {
3352
            print_error(oc->filename, AVERROR_NUMEXPECTED);
3353
            exit(1);
3354
        }
3355
    }
3356

    
3357
    if (!(oc->oformat->flags & AVFMT_NOFILE)) {
3358
        /* test if it already exists to avoid loosing precious files */
3359
        if (!file_overwrite &&
3360
            (strchr(filename, ':') == NULL ||
3361
             strstart(filename, "file:", NULL))) {
3362
            if (url_exist(filename)) {
3363
                int c;
3364

    
3365
                if ( !using_stdin ) {
3366
                    fprintf(stderr,"File '%s' already exists. Overwrite ? [y/N] ", filename);
3367
                    fflush(stderr);
3368
                    c = getchar();
3369
                    if (toupper(c) != 'Y') {
3370
                        fprintf(stderr, "Not overwriting - exiting\n");
3371
                        exit(1);
3372
                    }
3373
                                }
3374
                                else {
3375
                    fprintf(stderr,"File '%s' already exists. Exiting.\n", filename);
3376
                    exit(1);
3377
                                }
3378
            }
3379
        }
3380

    
3381
        /* open the file */
3382
        if (url_fopen(&oc->pb, filename, URL_WRONLY) < 0) {
3383
            fprintf(stderr, "Could not open '%s'\n", filename);
3384
            exit(1);
3385
        }
3386
    }
3387

    
3388
    memset(ap, 0, sizeof(*ap));
3389
    ap->image_format = image_format;
3390
    if (av_set_parameters(oc, ap) < 0) {
3391
        fprintf(stderr, "%s: Invalid encoding parameters\n",
3392
                oc->filename);
3393
        exit(1);
3394
    }
3395

    
3396
    oc->packet_size= mux_packet_size;
3397
    oc->mux_rate= mux_rate;
3398
    oc->preload= (int)(mux_preload*AV_TIME_BASE);
3399
    oc->max_delay= (int)(mux_max_delay*AV_TIME_BASE);
3400
    oc->loop_output = loop_output;
3401

    
3402
    for(i=0; i<opt_name_count; i++){
3403
        AVOption *opt;
3404
        double d = av_get_double(avformat_opts, opt_names[i], &opt);
3405
        if(d==d && (opt->flags&AV_OPT_FLAG_ENCODING_PARAM))
3406
            av_set_double(oc, opt_names[i], d);
3407
    }
3408

    
3409
    /* reset some options */
3410
    file_oformat = NULL;
3411
    file_iformat = NULL;
3412
    image_format = NULL;
3413
}
3414

    
3415
/* prepare dummy protocols for grab */
3416
static void prepare_grab(void)
3417
{
3418
    int has_video, has_audio, i, j;
3419
    AVFormatContext *oc;
3420
    AVFormatContext *ic;
3421
    AVFormatParameters vp1, *vp = &vp1;
3422
    AVFormatParameters ap1, *ap = &ap1;
3423

    
3424
    /* see if audio/video inputs are needed */
3425
    has_video = 0;
3426
    has_audio = 0;
3427
    memset(ap, 0, sizeof(*ap));
3428
    memset(vp, 0, sizeof(*vp));
3429
    vp->time_base.num= 1;
3430
    for(j=0;j<nb_output_files;j++) {
3431
        oc = output_files[j];
3432
        for(i=0;i<oc->nb_streams;i++) {
3433
            AVCodecContext *enc = oc->streams[i]->codec;
3434
            switch(enc->codec_type) {
3435
            case CODEC_TYPE_AUDIO:
3436
                if (enc->sample_rate > ap->sample_rate)
3437
                    ap->sample_rate = enc->sample_rate;
3438
                if (enc->channels > ap->channels)
3439
                    ap->channels = enc->channels;
3440
                has_audio = 1;
3441
                break;
3442
            case CODEC_TYPE_VIDEO:
3443
                if (enc->width > vp->width)
3444
                    vp->width = enc->width;
3445
                if (enc->height > vp->height)
3446
                    vp->height = enc->height;
3447

    
3448
                if (vp->time_base.num*(int64_t)enc->time_base.den > enc->time_base.num*(int64_t)vp->time_base.den){
3449
                    vp->time_base = enc->time_base;
3450
                    vp->width += frame_leftBand + frame_rightBand;
3451
                    vp->width -= (frame_padleft + frame_padright);
3452
                    vp->height += frame_topBand + frame_bottomBand;
3453
                    vp->height -= (frame_padtop + frame_padbottom);
3454
                }
3455
                has_video = 1;
3456
                break;
3457
            default:
3458
                av_abort();
3459
            }
3460
        }
3461
    }
3462

    
3463
    if (has_video == 0 && has_audio == 0) {
3464
        fprintf(stderr, "Output file must have at least one audio or video stream\n");
3465
        exit(1);
3466
    }
3467

    
3468
    if (has_video) {
3469
        AVInputFormat *fmt1;
3470
        fmt1 = av_find_input_format(video_grab_format);
3471
        vp->device  = video_device;
3472
        vp->channel = video_channel;
3473
        vp->standard = video_standard;
3474
        vp->pix_fmt = frame_pix_fmt;
3475
        if (av_open_input_file(&ic, "", fmt1, 0, vp) < 0) {
3476
            fprintf(stderr, "Could not find video grab device\n");
3477
            exit(1);
3478
        }
3479
        /* If not enough info to get the stream parameters, we decode the
3480
           first frames to get it. */
3481
        if ((ic->ctx_flags & AVFMTCTX_NOHEADER) && av_find_stream_info(ic) < 0) {
3482
            fprintf(stderr, "Could not find video grab parameters\n");
3483
            exit(1);
3484
        }
3485
        /* by now video grab has one stream */
3486
        ic->streams[0]->r_frame_rate.num = vp->time_base.den;
3487
        ic->streams[0]->r_frame_rate.den = vp->time_base.num;
3488
        input_files[nb_input_files] = ic;
3489

    
3490
        if (verbose >= 0)
3491
            dump_format(ic, nb_input_files, "", 0);
3492

    
3493
        nb_input_files++;
3494
    }
3495
    if (has_audio && audio_grab_format) {
3496
        AVInputFormat *fmt1;
3497
        fmt1 = av_find_input_format(audio_grab_format);
3498
        ap->device = audio_device;
3499
        if (av_open_input_file(&ic, "", fmt1, 0, ap) < 0) {
3500
            fprintf(stderr, "Could not find audio grab device\n");
3501
            exit(1);
3502
        }
3503
        input_files[nb_input_files] = ic;
3504

    
3505
        if (verbose >= 0)
3506
            dump_format(ic, nb_input_files, "", 0);
3507

    
3508
        nb_input_files++;
3509
    }
3510
}
3511

    
3512
/* same option as mencoder */
3513
static void opt_pass(const char *pass_str)
3514
{
3515
    int pass;
3516
    pass = atoi(pass_str);
3517
    if (pass != 1 && pass != 2) {
3518
        fprintf(stderr, "pass number can be only 1 or 2\n");
3519
        exit(1);
3520
    }
3521
    do_pass = pass;
3522
}
3523

    
3524
#if defined(__MINGW32__) || defined(CONFIG_OS2)
3525
static int64_t getutime(void)
3526
{
3527
  return av_gettime();
3528
}
3529
#else
3530
static int64_t getutime(void)
3531
{
3532
    struct rusage rusage;
3533

    
3534
    getrusage(RUSAGE_SELF, &rusage);
3535
    return (rusage.ru_utime.tv_sec * 1000000LL) + rusage.ru_utime.tv_usec;
3536
}
3537
#endif
3538

    
3539
#if defined(CONFIG_FFM_DEMUXER) || defined(CONFIG_FFM_MUXER)
3540
extern int ffm_nopts;
3541
#endif
3542

    
3543
static void show_formats(void)
3544
{
3545
    AVInputFormat *ifmt;
3546
    AVOutputFormat *ofmt;
3547
    AVImageFormat *image_fmt;
3548
    URLProtocol *up;
3549
    AVCodec *p, *p2;
3550
    const char **pp, *last_name;
3551

    
3552
    printf("File formats:\n");
3553
    last_name= "000";
3554
    for(;;){
3555
        int decode=0;
3556
        int encode=0;
3557
        const char *name=NULL;
3558
        const char *long_name=NULL;
3559

    
3560
        for(ofmt = first_oformat; ofmt != NULL; ofmt = ofmt->next) {
3561
            if((name == NULL || strcmp(ofmt->name, name)<0) &&
3562
                strcmp(ofmt->name, last_name)>0){
3563
                name= ofmt->name;
3564
                long_name= ofmt->long_name;
3565
                encode=1;
3566
            }
3567
        }
3568
        for(ifmt = first_iformat; ifmt != NULL; ifmt = ifmt->next) {
3569
            if((name == NULL || strcmp(ifmt->name, name)<0) &&
3570
                strcmp(ifmt->name, last_name)>0){
3571
                name= ifmt->name;
3572
                long_name= ifmt->long_name;
3573
                encode=0;
3574
            }
3575
            if(name && strcmp(ifmt->name, name)==0)
3576
                decode=1;
3577
        }
3578
        if(name==NULL)
3579
            break;
3580
        last_name= name;
3581

    
3582
        printf(
3583
            " %s%s %-15s %s\n",
3584
            decode ? "D":" ",
3585
            encode ? "E":" ",
3586
            name,
3587
            long_name ? long_name:" ");
3588
    }
3589
    printf("\n");
3590

    
3591
    printf("Image formats (filename extensions, if any, follow):\n");
3592
    for(image_fmt = first_image_format; image_fmt != NULL;
3593
        image_fmt = image_fmt->next) {
3594
        printf(
3595
            " %s%s %-6s %s\n",
3596
            image_fmt->img_read  ? "D":" ",
3597
            image_fmt->img_write ? "E":" ",
3598
            image_fmt->name,
3599
            image_fmt->extensions ? image_fmt->extensions:" ");
3600
    }
3601
    printf("\n");
3602

    
3603
    printf("Codecs:\n");
3604
    last_name= "000";
3605
    for(;;){
3606
        int decode=0;
3607
        int encode=0;
3608
        int cap=0;
3609
        const char *type_str;
3610

    
3611
        p2=NULL;
3612
        for(p = first_avcodec; p != NULL; p = p->next) {
3613
            if((p2==NULL || strcmp(p->name, p2->name)<0) &&
3614
                strcmp(p->name, last_name)>0){
3615
                p2= p;
3616
                decode= encode= cap=0;
3617
            }
3618
            if(p2 && strcmp(p->name, p2->name)==0){
3619
                if(p->decode) decode=1;
3620
                if(p->encode) encode=1;
3621
                cap |= p->capabilities;
3622
            }
3623
        }
3624
        if(p2==NULL)
3625
            break;
3626
        last_name= p2->name;
3627

    
3628
        switch(p2->type) {
3629
        case CODEC_TYPE_VIDEO:
3630
            type_str = "V";
3631
            break;
3632
        case CODEC_TYPE_AUDIO:
3633
            type_str = "A";
3634
            break;
3635
        case CODEC_TYPE_SUBTITLE:
3636
            type_str = "S";
3637
            break;
3638
        default:
3639
            type_str = "?";
3640
            break;
3641
        }
3642
        printf(
3643
            " %s%s%s%s%s%s %s",
3644
            decode ? "D": (/*p2->decoder ? "d":*/" "),
3645
            encode ? "E":" ",
3646
            type_str,
3647
            cap & CODEC_CAP_DRAW_HORIZ_BAND ? "S":" ",
3648
            cap & CODEC_CAP_DR1 ? "D":" ",
3649
            cap & CODEC_CAP_TRUNCATED ? "T":" ",
3650
            p2->name);
3651
       /* if(p2->decoder && decode==0)
3652
            printf(" use %s for decoding", p2->decoder->name);*/
3653
        printf("\n");
3654
    }
3655
    printf("\n");
3656

    
3657
    printf("Supported file protocols:\n");
3658
    for(up = first_protocol; up != NULL; up = up->next)
3659
        printf(" %s:", up->name);
3660
    printf("\n");
3661

    
3662
    printf("Frame size, frame rate abbreviations:\n ntsc pal qntsc qpal sntsc spal film ntsc-film sqcif qcif cif 4cif\n");
3663
    printf("Motion estimation methods:\n");
3664
    pp = motion_str;
3665
    while (*pp) {
3666
        printf(" %s", *pp);
3667
        if ((pp - motion_str + 1) == ME_ZERO)
3668
            printf("(fastest)");
3669
        else if ((pp - motion_str + 1) == ME_FULL)
3670
            printf("(slowest)");
3671
        else if ((pp - motion_str + 1) == ME_EPZS)
3672
            printf("(default)");
3673
        pp++;
3674
    }
3675
    printf("\n\n");
3676
    printf(
3677
"Note, the names of encoders and decoders dont always match, so there are\n"
3678
"several cases where the above table shows encoder only or decoder only entries\n"
3679
"even though both encoding and decoding are supported for example, the h263\n"
3680
"decoder corresponds to the h263 and h263p encoders, for file formats its even\n"
3681
"worse\n");
3682
    exit(1);
3683
}
3684

    
3685
static void parse_matrix_coeffs(uint16_t *dest, const char *str)
3686
{
3687
    int i;
3688
    const char *p = str;
3689
    for(i = 0;; i++) {
3690
        dest[i] = atoi(p);
3691
        if(i == 63)
3692
            break;
3693
        p = strchr(p, ',');
3694
        if(!p) {
3695
            fprintf(stderr, "Syntax error in matrix \"%s\" at coeff %d\n", str, i);
3696
            exit(1);
3697
        }
3698
        p++;
3699
    }
3700
}
3701

    
3702
static void opt_inter_matrix(const char *arg)
3703
{
3704
    inter_matrix = av_mallocz(sizeof(uint16_t) * 64);
3705
    parse_matrix_coeffs(inter_matrix, arg);
3706
}
3707

    
3708
static void opt_intra_matrix(const char *arg)
3709
{
3710
    intra_matrix = av_mallocz(sizeof(uint16_t) * 64);
3711
    parse_matrix_coeffs(intra_matrix, arg);
3712
}
3713

    
3714
static void opt_target(const char *arg)
3715
{
3716
    int norm = -1;
3717
    static const char *const frame_rates[] = {"25", "30000/1001", "24000/1001"};
3718

    
3719
    if(!strncmp(arg, "pal-", 4)) {
3720
        norm = 0;
3721
        arg += 4;
3722
    } else if(!strncmp(arg, "ntsc-", 5)) {
3723
        norm = 1;
3724
        arg += 5;
3725
    } else if(!strncmp(arg, "film-", 5)) {
3726
        norm = 2;
3727
        arg += 5;
3728
    } else {
3729
        int fr;
3730
        /* Calculate FR via float to avoid int overflow */
3731
        fr = (int)(frame_rate * 1000.0 / frame_rate_base);
3732
        if(fr == 25000) {
3733
            norm = 0;
3734
        } else if((fr == 29970) || (fr == 23976)) {
3735
            norm = 1;
3736
        } else {
3737
            /* Try to determine PAL/NTSC by peeking in the input files */
3738
            if(nb_input_files) {
3739
                int i, j;
3740
                for(j = 0; j < nb_input_files; j++) {
3741
                    for(i = 0; i < input_files[j]->nb_streams; i++) {
3742
                        AVCodecContext *c = input_files[j]->streams[i]->codec;
3743
                        if(c->codec_type != CODEC_TYPE_VIDEO)
3744
                            continue;
3745
                        fr = c->time_base.den * 1000 / c->time_base.num;
3746
                        if(fr == 25000) {
3747
                            norm = 0;
3748
                            break;
3749
                        } else if((fr == 29970) || (fr == 23976)) {
3750
                            norm = 1;
3751
                            break;
3752
                        }
3753
                    }
3754
                    if(norm >= 0)
3755
                        break;
3756
                }
3757
            }
3758
        }
3759
        if(verbose && norm >= 0)
3760
            fprintf(stderr, "Assuming %s for target.\n", norm ? "NTSC" : "PAL");
3761
    }
3762

    
3763
    if(norm < 0) {
3764
        fprintf(stderr, "Could not determine norm (PAL/NTSC/NTSC-Film) for target.\n");
3765
        fprintf(stderr, "Please prefix target with \"pal-\", \"ntsc-\" or \"film-\",\n");
3766
        fprintf(stderr, "or set a framerate with \"-r xxx\".\n");
3767
        exit(1);
3768
    }
3769

    
3770
    if(!strcmp(arg, "vcd")) {
3771

    
3772
        opt_video_codec("mpeg1video");
3773
        opt_audio_codec("mp2");
3774
        opt_format("vcd");
3775

    
3776
        opt_frame_size(norm ? "352x240" : "352x288");
3777
        opt_frame_rate(frame_rates[norm]);
3778
        opt_default("gop", norm ? "18" : "15");
3779

    
3780
        opt_default("b", "1150000");
3781
        opt_default("maxrate", "1150000");
3782
        opt_default("minrate", "1150000");
3783
        video_rc_buffer_size = 40*1024*8;
3784

    
3785
        audio_bit_rate = 224000;
3786
        audio_sample_rate = 44100;
3787

    
3788
        mux_packet_size= 2324;
3789
        mux_rate= 2352 * 75 * 8;
3790

    
3791
        /* We have to offset the PTS, so that it is consistent with the SCR.
3792
           SCR starts at 36000, but the first two packs contain only padding
3793
           and the first pack from the other stream, respectively, may also have
3794
           been written before.
3795
           So the real data starts at SCR 36000+3*1200. */
3796
        mux_preload= (36000+3*1200) / 90000.0; //0.44
3797
    } else if(!strcmp(arg, "svcd")) {
3798

    
3799
        opt_video_codec("mpeg2video");
3800
        opt_audio_codec("mp2");
3801
        opt_format("svcd");
3802

    
3803
        opt_frame_size(norm ? "480x480" : "480x576");
3804
        opt_frame_rate(frame_rates[norm]);
3805
        opt_default("gop", norm ? "18" : "15");
3806

    
3807
        opt_default("b", "2040000");
3808
        opt_default("maxrate", "2516000");
3809
        opt_default("minrate", "0"); //1145000;
3810
        video_rc_buffer_size = 224*1024*8;
3811
        opt_default("flags", "+SCAN_OFFSET");
3812

    
3813

    
3814
        audio_bit_rate = 224000;
3815
        audio_sample_rate = 44100;
3816

    
3817
        mux_packet_size= 2324;
3818

    
3819
    } else if(!strcmp(arg, "dvd")) {
3820

    
3821
        opt_video_codec("mpeg2video");
3822
        opt_audio_codec("ac3");
3823
        opt_format("dvd");
3824

    
3825
        opt_frame_size(norm ? "720x480" : "720x576");
3826
        opt_frame_rate(frame_rates[norm]);
3827
        opt_default("gop", norm ? "18" : "15");
3828

    
3829
        opt_default("b", "6000000");
3830
        opt_default("maxrate", "9000000");
3831
        opt_default("minrate", "0"); //1500000;
3832
        video_rc_buffer_size = 224*1024*8;
3833

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

    
3837
        audio_bit_rate = 448000;
3838
        audio_sample_rate = 48000;
3839

    
3840
    } else if(!strncmp(arg, "dv", 2)) {
3841

    
3842
        opt_format("dv");
3843

    
3844
        opt_frame_size(norm ? "720x480" : "720x576");
3845
        opt_frame_pix_fmt(!strncmp(arg, "dv50", 4) ? "yuv422p" :
3846
                                             (norm ? "yuv411p" : "yuv420p"));
3847
        opt_frame_rate(frame_rates[norm]);
3848

    
3849
        audio_sample_rate = 48000;
3850
        audio_channels = 2;
3851

    
3852
    } else {
3853
        fprintf(stderr, "Unknown target: %s\n", arg);
3854
        exit(1);
3855
    }
3856
}
3857

    
3858
static void opt_video_bsf(const char *arg)
3859
{
3860
    AVBitStreamFilterContext *bsfc= av_bitstream_filter_init(arg); //FIXME split name and args for filter at '='
3861
    AVBitStreamFilterContext **bsfp;
3862

    
3863
    if(!bsfc){
3864
        fprintf(stderr, "Unkown bitstream filter %s\n", arg);
3865
        exit(1);
3866
    }
3867

    
3868
    bsfp= &video_bitstream_filters;
3869
    while(*bsfp)
3870
        bsfp= &(*bsfp)->next;
3871

    
3872
    *bsfp= bsfc;
3873
}
3874

    
3875
//FIXME avoid audio - video code duplication
3876
static void opt_audio_bsf(const char *arg)
3877
{
3878
    AVBitStreamFilterContext *bsfc= av_bitstream_filter_init(arg); //FIXME split name and args for filter at '='
3879
    AVBitStreamFilterContext **bsfp;
3880

    
3881
    if(!bsfc){
3882
        fprintf(stderr, "Unkown bitstream filter %s\n", arg);
3883
        exit(1);
3884
    }
3885

    
3886
    bsfp= &audio_bitstream_filters;
3887
    while(*bsfp)
3888
        bsfp= &(*bsfp)->next;
3889

    
3890
    *bsfp= bsfc;
3891
}
3892

    
3893
static void show_version(void)
3894
{
3895
    /* TODO: add function interface to avutil and avformat */
3896
    fprintf(stderr, "ffmpeg      " FFMPEG_VERSION "\n"
3897
           "libavutil   %d\n"
3898
           "libavcodec  %d\n"
3899
           "libavformat %d\n",
3900
           LIBAVUTIL_BUILD, avcodec_build(), LIBAVFORMAT_BUILD);
3901
    exit(1);
3902
}
3903

    
3904
static int opt_default(const char *opt, const char *arg){
3905
    AVOption *o= av_set_string(avctx_opts, opt, arg);
3906
    if(!o)
3907
        o = av_set_string(avformat_opts, opt, arg);
3908
    if(!o)
3909
        return -1;
3910

    
3911
//    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));
3912

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

    
3917
#if defined(CONFIG_FFM_DEMUXER) || defined(CONFIG_FFM_MUXER)
3918
    /* disable generate of real time pts in ffm (need to be supressed anyway) */
3919
    if(avctx_opts->flags & CODEC_FLAG_BITEXACT)
3920
        ffm_nopts = 1;
3921
#endif
3922

    
3923
    if(avctx_opts->debug)
3924
        av_log_set_level(AV_LOG_DEBUG);
3925
    return 0;
3926
}
3927

    
3928
const OptionDef options[] = {
3929
    /* main options */
3930
    { "L", 0, {(void*)show_license}, "show license" },
3931
    { "h", 0, {(void*)show_help}, "show help" },
3932
    { "version", 0, {(void*)show_version}, "show version" },
3933
    { "formats", 0, {(void*)show_formats}, "show available formats, codecs, protocols, ..." },
3934
    { "f", HAS_ARG, {(void*)opt_format}, "force format", "fmt" },
3935
    { "img", HAS_ARG, {(void*)opt_image_format}, "force image format", "img_fmt" },
3936
    { "i", HAS_ARG, {(void*)opt_input_file}, "input file name", "filename" },
3937
    { "y", OPT_BOOL, {(void*)&file_overwrite}, "overwrite output files" },
3938
    { "map", HAS_ARG | OPT_EXPERT, {(void*)opt_map}, "set input stream mapping", "file:stream[:syncfile:syncstream]" },
3939
    { "map_meta_data", HAS_ARG | OPT_EXPERT, {(void*)opt_map_meta_data}, "set meta data information of outfile from infile", "outfile:infile" },
3940
    { "t", HAS_ARG, {(void*)opt_recording_time}, "set the recording time", "duration" },
3941
    { "fs", HAS_ARG | OPT_INT, {(void*)&limit_filesize}, "set the limit file size", "limit_size" }, //
3942
    { "ss", HAS_ARG, {(void*)opt_start_time}, "set the start time offset", "time_off" },
3943
    { "itsoffset", HAS_ARG, {(void*)opt_input_ts_offset}, "set the input ts offset", "time_off" },
3944
    { "title", HAS_ARG | OPT_STRING, {(void*)&str_title}, "set the title", "string" },
3945
    { "timestamp", HAS_ARG, {(void*)&opt_rec_timestamp}, "set the timestamp", "time" },
3946
    { "author", HAS_ARG | OPT_STRING, {(void*)&str_author}, "set the author", "string" },
3947
    { "copyright", HAS_ARG | OPT_STRING, {(void*)&str_copyright}, "set the copyright", "string" },
3948
    { "comment", HAS_ARG | OPT_STRING, {(void*)&str_comment}, "set the comment", "string" },
3949
    { "album", HAS_ARG | OPT_STRING, {(void*)&str_album}, "set the album", "string" },
3950
    { "benchmark", OPT_BOOL | OPT_EXPERT, {(void*)&do_benchmark},
3951
      "add timings for benchmarking" },
3952
    { "dump", OPT_BOOL | OPT_EXPERT, {(void*)&do_pkt_dump},
3953
      "dump each input packet" },
3954
    { "hex", OPT_BOOL | OPT_EXPERT, {(void*)&do_hex_dump},
3955
      "when dumping packets, also dump the payload" },
3956
    { "re", OPT_BOOL | OPT_EXPERT, {(void*)&rate_emu}, "read input at native frame rate", "" },
3957
    { "loop_input", OPT_BOOL | OPT_EXPERT, {(void*)&loop_input}, "loop (current only works with images)" },
3958
    { "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)", "" },
3959
    { "v", HAS_ARG, {(void*)opt_verbose}, "control amount of logging", "verbose" },
3960
    { "target", HAS_ARG, {(void*)opt_target}, "specify target file type (\"vcd\", \"svcd\", \"dvd\", \"dv\", \"dv50\", \"pal-vcd\", \"ntsc-svcd\", ...)", "type" },
3961
    { "threads", HAS_ARG | OPT_EXPERT, {(void*)opt_thread_count}, "thread count", "count" },
3962
    { "vsync", HAS_ARG | OPT_INT | OPT_EXPERT, {(void*)&video_sync_method}, "video sync method", "" },
3963
    { "async", HAS_ARG | OPT_INT | OPT_EXPERT, {(void*)&audio_sync_method}, "audio sync method", "" },
3964
    { "vglobal", HAS_ARG | OPT_INT | OPT_EXPERT, {(void*)&video_global_header}, "video global header storage type", "" },
3965
    { "copyts", OPT_BOOL | OPT_EXPERT, {(void*)&copy_ts}, "copy timestamps" },
3966
    { "shortest", OPT_BOOL | OPT_EXPERT, {(void*)&opt_shortest}, "finish encoding within shortest input" }, //
3967
    { "dts_delta_threshold", HAS_ARG | OPT_INT | OPT_EXPERT, {(void*)&dts_delta_threshold}, "timestamp discontinuity delta threshold", "" },
3968

    
3969
    /* video options */
3970
    { "vframes", OPT_INT | HAS_ARG | OPT_VIDEO, {(void*)&max_frames[CODEC_TYPE_VIDEO]}, "set the number of video frames to record", "number" },
3971
    { "aframes", OPT_INT | HAS_ARG | OPT_AUDIO, {(void*)&max_frames[CODEC_TYPE_AUDIO]}, "set the number of audio frames to record", "number" },
3972
    { "dframes", OPT_INT | HAS_ARG, {(void*)&max_frames[CODEC_TYPE_DATA]}, "set the number of data frames to record", "number" },
3973
    { "r", HAS_ARG | OPT_VIDEO, {(void*)opt_frame_rate}, "set frame rate (Hz value, fraction or abbreviation)", "rate" },
3974
    { "s", HAS_ARG | OPT_VIDEO, {(void*)opt_frame_size}, "set frame size (WxH or abbreviation)", "size" },
3975
    { "aspect", HAS_ARG | OPT_VIDEO, {(void*)opt_frame_aspect_ratio}, "set aspect ratio (4:3, 16:9 or 1.3333, 1.7777)", "aspect" },
3976
    { "pix_fmt", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_frame_pix_fmt}, "set pixel format", "format" },
3977
    { "croptop", HAS_ARG | OPT_VIDEO, {(void*)opt_frame_crop_top}, "set top crop band size (in pixels)", "size" },
3978
    { "cropbottom", HAS_ARG | OPT_VIDEO, {(void*)opt_frame_crop_bottom}, "set bottom crop band size (in pixels)", "size" },
3979
    { "cropleft", HAS_ARG | OPT_VIDEO, {(void*)opt_frame_crop_left}, "set left crop band size (in pixels)", "size" },
3980
    { "cropright", HAS_ARG | OPT_VIDEO, {(void*)opt_frame_crop_right}, "set right crop band size (in pixels)", "size" },
3981
    { "padtop", HAS_ARG | OPT_VIDEO, {(void*)opt_frame_pad_top}, "set top pad band size (in pixels)", "size" },
3982
    { "padbottom", HAS_ARG | OPT_VIDEO, {(void*)opt_frame_pad_bottom}, "set bottom pad band size (in pixels)", "size" },
3983
    { "padleft", HAS_ARG | OPT_VIDEO, {(void*)opt_frame_pad_left}, "set left pad band size (in pixels)", "size" },
3984
    { "padright", HAS_ARG | OPT_VIDEO, {(void*)opt_frame_pad_right}, "set right pad band size (in pixels)", "size" },
3985
    { "padcolor", HAS_ARG | OPT_VIDEO, {(void*)opt_pad_color}, "set color of pad bands (Hex 000000 thru FFFFFF)", "color" },
3986
    { "intra", OPT_BOOL | OPT_EXPERT | OPT_VIDEO, {(void*)&intra_only}, "use only intra frames"},
3987
    { "vn", OPT_BOOL | OPT_VIDEO, {(void*)&video_disable}, "disable video" },
3988
    { "vdt", OPT_INT | HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)&video_discard}, "discard threshold", "n" },
3989
    { "qscale", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_qscale}, "use fixed video quantiser scale (VBR)", "q" },
3990
    { "qmin", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_qmin}, "min video quantiser scale (VBR)", "q" },
3991
    { "qmax", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_qmax}, "max video quantiser scale (VBR)", "q" },
3992
    { "lmin", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_lmin}, "min video lagrange factor (VBR)", "lambda" },
3993
    { "lmax", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_lmax}, "max video lagrange factor (VBR)", "lambda" },
3994
    { "mblmin", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_mb_lmin}, "min macroblock quantiser scale (VBR)", "q" },
3995
    { "mblmax", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_mb_lmax}, "max macroblock quantiser scale (VBR)", "q" },
3996
    { "qdiff", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_qdiff}, "max difference between the quantiser scale (VBR)", "q" },
3997
    { "qblur", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_qblur}, "video quantiser scale blur (VBR)", "blur" },
3998
    { "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" },
3999
    { "qcomp", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_qcomp}, "video quantiser scale compression (VBR)", "compression" },
4000
    { "rc_init_cplx", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_rc_initial_cplx}, "initial complexity for 1-pass encoding", "complexity" },
4001
    { "b_qfactor", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_b_qfactor}, "qp factor between p and b frames", "factor" },
4002
    { "i_qfactor", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_i_qfactor}, "qp factor between p and i frames", "factor" },
4003
    { "b_qoffset", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_b_qoffset}, "qp offset between p and b frames", "offset" },
4004
    { "i_qoffset", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_i_qoffset}, "qp offset between p and i frames", "offset" },
4005
    { "pbias", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_pbias}, "inter quant bias", "bias" },
4006
    { "rc_eq", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_video_rc_eq}, "set rate control equation", "equation" },
4007
    { "rc_override", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_video_rc_override_string}, "rate control override for specific intervals", "override" },
4008
    { "bt", HAS_ARG | OPT_VIDEO, {(void*)opt_video_bitrate_tolerance}, "set video bitrate tolerance (in kbit/s)", "tolerance" },
4009
    { "bufsize", HAS_ARG | OPT_VIDEO, {(void*)opt_video_buffer_size}, "set ratecontrol buffer size (in kByte)", "size" },
4010
    { "vcodec", HAS_ARG | OPT_VIDEO, {(void*)opt_video_codec}, "force video codec ('copy' to copy stream)", "codec" },
4011
    { "me", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_motion_estimation}, "set motion estimation method",
4012
      "method" },
4013
    { "me_threshold", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_me_threshold}, "motion estimaton threshold",  "" },
4014
    { "mb_threshold", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_mb_threshold}, "macroblock threshold",  "" },
4015
    { "bf", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_b_frames}, "use 'frames' B frames", "frames" },
4016
    { "bug", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_workaround_bugs}, "workaround not auto detected encoder bugs", "param" },
4017
    { "ps", HAS_ARG | OPT_EXPERT, {(void*)opt_packet_size}, "set packet size in bits", "size" },
4018
    { "error", HAS_ARG | OPT_EXPERT, {(void*)opt_error_rate}, "error rate", "rate" },
4019
    { "strict", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_strict}, "how strictly to follow the standards", "strictness" },
4020
    { "sameq", OPT_BOOL | OPT_VIDEO, {(void*)&same_quality},
4021
      "use same video quality as source (implies VBR)" },
4022
    { "pass", HAS_ARG | OPT_VIDEO, {(void*)&opt_pass}, "select the pass number (1 or 2)", "n" },
4023
    { "passlogfile", HAS_ARG | OPT_STRING | OPT_VIDEO, {(void*)&pass_logfilename}, "select two pass log file name", "file" },
4024
    { "deinterlace", OPT_BOOL | OPT_EXPERT | OPT_VIDEO, {(void*)&do_deinterlace},
4025
      "deinterlace pictures" },
4026
    { "psnr", OPT_BOOL | OPT_EXPERT | OPT_VIDEO, {(void*)&do_psnr}, "calculate PSNR of compressed frames" },
4027
    { "vstats", OPT_BOOL | OPT_EXPERT | OPT_VIDEO, {(void*)&do_vstats}, "dump video coding statistics to file" },
4028
    { "vhook", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)add_frame_hooker}, "insert video processing module", "module" },
4029
    { "intra_matrix", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_intra_matrix}, "specify intra matrix coeffs", "matrix" },
4030
    { "inter_matrix", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_inter_matrix}, "specify inter matrix coeffs", "matrix" },
4031
    { "top", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_top_field_first}, "top=1/bottom=0/auto=-1 field first", "" },
4032
    { "sc_threshold", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_sc_threshold}, "scene change threshold", "threshold" },
4033
    { "me_range", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_me_range}, "limit motion vectors range (1023 for DivX player)", "range" },
4034
    { "dc", OPT_INT | HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)&intra_dc_precision}, "intra_dc_precision", "precision" },
4035
    { "mepc", OPT_INT | HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)&me_penalty_compensation}, "motion estimation bitrate penalty compensation", "factor (1.0 = 256)" },
4036
    { "vtag", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_video_tag}, "force video tag/fourcc", "fourcc/tag" },
4037
    { "skip_threshold", OPT_INT | HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)&frame_skip_threshold}, "frame skip threshold", "threshold" },
4038
    { "skip_factor", OPT_INT | HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)&frame_skip_factor}, "frame skip factor", "factor" },
4039
    { "skip_exp", OPT_INT | HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)&frame_skip_exp}, "frame skip exponent", "exponent" },
4040
    { "newvideo", OPT_VIDEO, {(void*)opt_new_video_stream}, "add a new video stream to the current output stream" },
4041
    { "qphist", OPT_BOOL | OPT_EXPERT | OPT_VIDEO, { (void *)&qp_hist }, "show QP histogram" },
4042

    
4043
    /* audio options */
4044
    { "ab", HAS_ARG | OPT_AUDIO, {(void*)opt_audio_bitrate}, "set audio bitrate (in kbit/s)", "bitrate", },
4045
    { "aq", OPT_FLOAT | HAS_ARG | OPT_AUDIO, {(void*)&audio_qscale}, "set audio quality (codec-specific)", "quality", },
4046
    { "ar", HAS_ARG | OPT_AUDIO, {(void*)opt_audio_rate}, "set audio sampling rate (in Hz)", "rate" },
4047
    { "ac", HAS_ARG | OPT_AUDIO, {(void*)opt_audio_channels}, "set number of audio channels", "channels" },
4048
    { "an", OPT_BOOL | OPT_AUDIO, {(void*)&audio_disable}, "disable audio" },
4049
    { "acodec", HAS_ARG | OPT_AUDIO, {(void*)opt_audio_codec}, "force audio codec ('copy' to copy stream)", "codec" },
4050
    { "atag", HAS_ARG | OPT_EXPERT | OPT_AUDIO, {(void*)opt_audio_tag}, "force audio tag/fourcc", "fourcc/tag" },
4051
    { "vol", OPT_INT | HAS_ARG | OPT_AUDIO, {(void*)&audio_volume}, "change audio volume (256=normal)" , "volume" }, //
4052
    { "newaudio", OPT_AUDIO, {(void*)opt_new_audio_stream}, "add a new audio stream to the current output stream" },
4053
    { "alang", HAS_ARG | OPT_STRING | OPT_AUDIO, {(void *)&audio_language}, "set the ISO 639 language code (3 letters) of the current audio stream" , "code" },
4054

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

    
4060
    /* grab options */
4061
    { "vd", HAS_ARG | OPT_EXPERT | OPT_VIDEO | OPT_GRAB, {(void*)opt_video_device}, "set video grab device", "device" },
4062
    { "vc", HAS_ARG | OPT_EXPERT | OPT_VIDEO | OPT_GRAB, {(void*)opt_video_channel}, "set video grab channel (DV1394 only)", "channel" },
4063
    { "tvstd", HAS_ARG | OPT_EXPERT | OPT_VIDEO | OPT_GRAB, {(void*)opt_video_standard}, "set television standard (NTSC, PAL (SECAM))", "standard" },
4064
    { "ad", HAS_ARG | OPT_EXPERT | OPT_AUDIO | OPT_GRAB, {(void*)opt_audio_device}, "set audio device", "device" },
4065

    
4066
    /* G.2 grab options */
4067
    { "grab", HAS_ARG | OPT_EXPERT | OPT_GRAB, {(void*)opt_grab}, "request grabbing using", "format" },
4068
    { "gd", HAS_ARG | OPT_EXPERT | OPT_VIDEO | OPT_GRAB, {(void*)opt_grab_device}, "set grab device", "device" },
4069

    
4070
    /* muxer options */
4071
    { "muxrate", OPT_INT | HAS_ARG | OPT_EXPERT, {(void*)&mux_rate}, "set mux rate", "rate" },
4072
    { "packetsize", OPT_INT | HAS_ARG | OPT_EXPERT, {(void*)&mux_packet_size}, "set packet size", "size" },
4073
    { "muxdelay", OPT_FLOAT | HAS_ARG | OPT_EXPERT, {(void*)&mux_max_delay}, "set the maximum demux-decode delay", "seconds" },
4074
    { "muxpreload", OPT_FLOAT | HAS_ARG | OPT_EXPERT, {(void*)&mux_preload}, "set the initial demux-decode delay", "seconds" },
4075

    
4076
    { "absf", HAS_ARG | OPT_AUDIO | OPT_EXPERT, {(void*)opt_audio_bsf}, "", "bitstream filter" },
4077
    { "vbsf", HAS_ARG | OPT_VIDEO | OPT_EXPERT, {(void*)opt_video_bsf}, "", "bitstream filter" },
4078

    
4079
    { "default", OPT_FUNC2 | HAS_ARG | OPT_AUDIO | OPT_VIDEO | OPT_EXPERT, {(void*)opt_default}, "generic catch all option", "" },
4080
    { NULL, },
4081
};
4082

    
4083
static void show_banner(void)
4084
{
4085
    fprintf(stderr, "FFmpeg version " FFMPEG_VERSION ", Copyright (c) 2000-2004 Fabrice Bellard\n");
4086
    fprintf(stderr, "  configuration: " FFMPEG_CONFIGURATION "\n");
4087
    fprintf(stderr, "  libavutil version: " AV_STRINGIFY(LIBAVUTIL_VERSION) "\n");
4088
    fprintf(stderr, "  libavcodec version: " AV_STRINGIFY(LIBAVCODEC_VERSION) "\n");
4089
    fprintf(stderr, "  libavformat version: " AV_STRINGIFY(LIBAVFORMAT_VERSION) "\n");
4090
    fprintf(stderr, "  built on " __DATE__ " " __TIME__);
4091
#ifdef __GNUC__
4092
    fprintf(stderr, ", gcc: " __VERSION__ "\n");
4093
#else
4094
    fprintf(stderr, ", using a non-gcc compiler\n");
4095
#endif
4096
}
4097

    
4098
static void show_license(void)
4099
{
4100
    show_banner();
4101
#ifdef CONFIG_GPL
4102
    printf(
4103
    "This program is free software; you can redistribute it and/or modify\n"
4104
    "it under the terms of the GNU General Public License as published by\n"
4105
    "the Free Software Foundation; either version 2 of the License, or\n"
4106
    "(at your option) any later version.\n"
4107
    "\n"
4108
    "This program is distributed in the hope that it will be useful,\n"
4109
    "but WITHOUT ANY WARRANTY; without even the implied warranty of\n"
4110
    "MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n"
4111
    "GNU General Public License for more details.\n"
4112
    "\n"
4113
    "You should have received a copy of the GNU General Public License\n"
4114
    "along with this program; if not, write to the Free Software\n"
4115
    "Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA\n"
4116
    );
4117
#else
4118
    printf(
4119
    "This library is free software; you can redistribute it and/or\n"
4120
    "modify it under the terms of the GNU Lesser General Public\n"
4121
    "License as published by the Free Software Foundation; either\n"
4122
    "version 2 of the License, or (at your option) any later version.\n"
4123
    "\n"
4124
    "This library is distributed in the hope that it will be useful,\n"
4125
    "but WITHOUT ANY WARRANTY; without even the implied warranty of\n"
4126
    "MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n"
4127
    "Lesser General Public License for more details.\n"
4128
    "\n"
4129
    "You should have received a copy of the GNU Lesser General Public\n"
4130
    "License along with this library; if not, write to the Free Software\n"
4131
    "Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n"
4132
    );
4133
#endif
4134
    exit(1);
4135
}
4136

    
4137
static void show_help(void)
4138
{
4139
    show_banner();
4140
    printf("usage: ffmpeg [[infile options] -i infile]... {[outfile options] outfile}...\n"
4141
           "Hyper fast Audio and Video encoder\n");
4142
    printf("\n");
4143
    show_help_options(options, "Main options:\n",
4144
                      OPT_EXPERT | OPT_AUDIO | OPT_VIDEO, 0);
4145
    show_help_options(options, "\nVideo options:\n",
4146
                      OPT_EXPERT | OPT_AUDIO | OPT_VIDEO | OPT_GRAB,
4147
                      OPT_VIDEO);
4148
    show_help_options(options, "\nAdvanced Video options:\n",
4149
                      OPT_EXPERT | OPT_AUDIO | OPT_VIDEO | OPT_GRAB,
4150
                      OPT_VIDEO | OPT_EXPERT);
4151
    show_help_options(options, "\nAudio options:\n",
4152
                      OPT_EXPERT | OPT_AUDIO | OPT_VIDEO | OPT_GRAB,
4153
                      OPT_AUDIO);
4154
    show_help_options(options, "\nAdvanced Audio options:\n",
4155
                      OPT_EXPERT | OPT_AUDIO | OPT_VIDEO | OPT_GRAB,
4156
                      OPT_AUDIO | OPT_EXPERT);
4157
    show_help_options(options, "\nSubtitle options:\n",
4158
                      OPT_SUBTITLE | OPT_GRAB,
4159
                      OPT_SUBTITLE);
4160
    show_help_options(options, "\nAudio/Video grab options:\n",
4161
                      OPT_GRAB,
4162
                      OPT_GRAB);
4163
    show_help_options(options, "\nAdvanced options:\n",
4164
                      OPT_EXPERT | OPT_AUDIO | OPT_VIDEO | OPT_GRAB,
4165
                      OPT_EXPERT);
4166
    av_opt_show(avctx_opts, NULL);
4167
    av_opt_show(avformat_opts, NULL);
4168

    
4169
    exit(1);
4170
}
4171

    
4172
void parse_arg_file(const char *filename)
4173
{
4174
    opt_output_file(filename);
4175
}
4176

    
4177
int main(int argc, char **argv)
4178
{
4179
    int i;
4180
    int64_t ti;
4181

    
4182
    av_register_all();
4183

    
4184
    avctx_opts= avcodec_alloc_context();
4185
    avformat_opts = av_alloc_format_context();
4186

    
4187
    if (argc <= 1)
4188
        show_help();
4189
    else
4190
        show_banner();
4191

    
4192
    /* parse options */
4193
    parse_options(argc, argv, options);
4194

    
4195
    /* file converter / grab */
4196
    if (nb_output_files <= 0) {
4197
        fprintf(stderr, "Must supply at least one output file\n");
4198
        exit(1);
4199
    }
4200

    
4201
    if (nb_input_files == 0) {
4202
        input_sync = 1;
4203
        prepare_grab();
4204
    }
4205

    
4206
    ti = getutime();
4207
    av_encode(output_files, nb_output_files, input_files, nb_input_files,
4208
              stream_maps, nb_stream_maps);
4209
    ti = getutime() - ti;
4210
    if (do_benchmark) {
4211
        printf("bench: utime=%0.3fs\n", ti / 1000000.0);
4212
    }
4213

    
4214
    /* close files */
4215
    for(i=0;i<nb_output_files;i++) {
4216
        /* maybe av_close_output_file ??? */
4217
        AVFormatContext *s = output_files[i];
4218
        int j;
4219
        if (!(s->oformat->flags & AVFMT_NOFILE))
4220
            url_fclose(&s->pb);
4221
        for(j=0;j<s->nb_streams;j++)
4222
            av_free(s->streams[j]);
4223
        av_free(s);
4224
    }
4225
    for(i=0;i<nb_input_files;i++)
4226
        av_close_input_file(input_files[i]);
4227

    
4228
    av_free_static();
4229

    
4230
    if(intra_matrix)
4231
        av_free(intra_matrix);
4232
    if(inter_matrix)
4233
        av_free(inter_matrix);
4234

    
4235
#ifdef POWERPC_PERFORMANCE_REPORT
4236
    extern void powerpc_display_perf_report(void);
4237
    powerpc_display_perf_report();
4238
#endif /* POWERPC_PERFORMANCE_REPORT */
4239

    
4240
#ifndef __MINGW32__
4241
    if (received_sigterm) {
4242
        fprintf(stderr,
4243
            "Received signal %d: terminating.\n",
4244
            (int) received_sigterm);
4245
        exit (255);
4246
    }
4247
#endif
4248
    exit(0); /* not all OS-es handle main() return value */
4249
    return 0;
4250
}