Statistics
| Branch: | Revision:

ffmpeg / ffmpeg.c @ 315b0f97

History | View | Annotate | Download (142 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 float video_qscale = 0;
109
static int video_qmin = 2;
110
static int video_qmax = 31;
111
static int video_lmin = 2*FF_QP2LAMBDA;
112
static int video_lmax = 31*FF_QP2LAMBDA;
113
static int video_mb_lmin = 2*FF_QP2LAMBDA;
114
static int video_mb_lmax = 31*FF_QP2LAMBDA;
115
static int video_qdiff = 3;
116
static float video_qsquish = 0.0;
117
static uint16_t *intra_matrix = NULL;
118
static uint16_t *inter_matrix = NULL;
119
#if 0 //experimental, (can be removed)
120
static float video_rc_qsquish=1.0;
121
static float video_rc_qmod_amp=0;
122
static int video_rc_qmod_freq=0;
123
#endif
124
static char *video_rc_override_string=NULL;
125
static char *video_rc_eq="tex^qComp";
126
static float video_rc_buffer_aggressivity=1.0;
127
static int me_method = ME_EPZS;
128
static int video_disable = 0;
129
static int video_discard = 0;
130
static int video_codec_id = CODEC_ID_NONE;
131
static int video_codec_tag = 0;
132
static int same_quality = 0;
133
static int do_deinterlace = 0;
134
static int workaround_bugs = FF_BUG_AUTODETECT;
135
static int packet_size = 0;
136
static int error_rate = 0;
137
static int strict = 0;
138
static int top_field_first = -1;
139
static int sc_threshold = 0;
140
static int me_threshold = 0;
141
static int mb_threshold = 0;
142
static int intra_dc_precision = 8;
143
static int me_penalty_compensation= 256;
144
static int frame_skip_threshold= 0;
145
static int frame_skip_factor= 0;
146
static int frame_skip_exp= 0;
147
static int loop_input = 0;
148
static int loop_output = AVFMT_NOOUTPUTLOOP;
149
static int qp_hist = 0;
150

    
151
static int intra_only = 0;
152
static int audio_sample_rate = 44100;
153
static int audio_bit_rate = 64000;
154
#define QSCALE_NONE -99999
155
static float audio_qscale = QSCALE_NONE;
156
static int audio_disable = 0;
157
static int audio_channels = 1;
158
static int audio_codec_id = CODEC_ID_NONE;
159
static int audio_codec_tag = 0;
160
static char *audio_language = NULL;
161

    
162
static int subtitle_codec_id = CODEC_ID_NONE;
163
static char *subtitle_language = NULL;
164

    
165
static float mux_preload= 0.5;
166
static float mux_max_delay= 0.7;
167

    
168
static int64_t recording_time = 0;
169
static int64_t start_time = 0;
170
static int64_t rec_timestamp = 0;
171
static int64_t input_ts_offset = 0;
172
static int file_overwrite = 0;
173
static char *str_title = NULL;
174
static char *str_author = NULL;
175
static char *str_copyright = NULL;
176
static char *str_comment = NULL;
177
static char *str_album = NULL;
178
static int do_benchmark = 0;
179
static int do_hex_dump = 0;
180
static int do_pkt_dump = 0;
181
static int do_psnr = 0;
182
static int do_vstats = 0;
183
static int do_pass = 0;
184
static char *pass_logfilename = NULL;
185
static int audio_stream_copy = 0;
186
static int video_stream_copy = 0;
187
static int subtitle_stream_copy = 0;
188
static int video_sync_method= 1;
189
static int audio_sync_method= 0;
190
static int copy_ts= 0;
191
static int opt_shortest = 0; //
192
static int video_global_header = 0;
193

    
194
static int rate_emu = 0;
195

    
196
#ifdef CONFIG_BKTR
197
static const char *video_grab_format = "bktr";
198
#else
199
#ifdef CONFIG_VIDEO4LINUX2
200
static const char *video_grab_format = "video4linux2";
201
#else
202
static const char *video_grab_format = "video4linux";
203
#endif
204
#endif
205
static char *video_device = NULL;
206
static char *grab_device = NULL;
207
static int  video_channel = 0;
208
static char *video_standard = "ntsc";
209

    
210
static const char *audio_grab_format = "audio_device";
211
static char *audio_device = NULL;
212
static int audio_volume = 256;
213

    
214
static int using_stdin = 0;
215
static int using_vhook = 0;
216
static int verbose = 1;
217
static int thread_count= 1;
218
static int q_pressed = 0;
219
static int64_t video_size = 0;
220
static int64_t audio_size = 0;
221
static int64_t extra_size = 0;
222
static int nb_frames_dup = 0;
223
static int nb_frames_drop = 0;
224
static int input_sync;
225
static int limit_filesize = 0; //
226

    
227
static int pgmyuv_compatibility_hack=0;
228
static int dts_delta_threshold = 10;
229

    
230
static int sws_flags = SWS_BICUBIC;
231

    
232
const char **opt_names=NULL;
233
int opt_name_count=0;
234
AVCodecContext *avctx_opts;
235
AVFormatContext *avformat_opts;
236

    
237
static AVBitStreamFilterContext *video_bitstream_filters=NULL;
238
static AVBitStreamFilterContext *audio_bitstream_filters=NULL;
239
static AVBitStreamFilterContext *bitstream_filters[MAX_FILES][MAX_STREAMS];
240

    
241
#define DEFAULT_PASS_LOGFILENAME "ffmpeg2pass"
242

    
243
struct AVInputStream;
244

    
245
typedef struct AVOutputStream {
246
    int file_index;          /* file index */
247
    int index;               /* stream index in the output file */
248
    int source_index;        /* AVInputStream index */
249
    AVStream *st;            /* stream in the output file */
250
    int encoding_needed;     /* true if encoding needed for this stream */
251
    int frame_number;
252
    /* input pts and corresponding output pts
253
       for A/V sync */
254
    //double sync_ipts;        /* dts from the AVPacket of the demuxer in second units */
255
    struct AVInputStream *sync_ist; /* input stream to sync against */
256
    int64_t sync_opts;       /* output frame counter, could be changed to some true timestamp */ //FIXME look at frame_number
257
    /* video only */
258
    int video_resample;
259
    AVFrame pict_tmp;      /* temporary image for resampling */
260
    struct SwsContext *img_resample_ctx; /* for image resampling */
261
    int resample_height;
262

    
263
    int video_crop;
264
    int topBand;             /* cropping area sizes */
265
    int leftBand;
266

    
267
    int video_pad;
268
    int padtop;              /* padding area sizes */
269
    int padbottom;
270
    int padleft;
271
    int padright;
272

    
273
    /* audio only */
274
    int audio_resample;
275
    ReSampleContext *resample; /* for audio resampling */
276
    FifoBuffer fifo;     /* for compression: one audio fifo per codec */
277
    FILE *logfile;
278
} AVOutputStream;
279

    
280
typedef struct AVInputStream {
281
    int file_index;
282
    int index;
283
    AVStream *st;
284
    int discard;             /* true if stream data should be discarded */
285
    int decoding_needed;     /* true if the packets must be decoded in 'raw_fifo' */
286
    int64_t sample_index;      /* current sample */
287

    
288
    int64_t       start;     /* time when read started */
289
    unsigned long frame;     /* current frame */
290
    int64_t       next_pts;  /* synthetic pts for cases where pkt.pts
291
                                is not defined */
292
    int64_t       pts;       /* current pts */
293
    int is_start;            /* is 1 at the start and after a discontinuity */
294
} AVInputStream;
295

    
296
typedef struct AVInputFile {
297
    int eof_reached;      /* true if eof reached */
298
    int ist_index;        /* index of first stream in ist_table */
299
    int buffer_size;      /* current total buffer size */
300
    int buffer_size_max;  /* buffer size at which we consider we can stop
301
                             buffering */
302
    int nb_streams;       /* nb streams we are aware of */
303
} AVInputFile;
304

    
305
#ifndef __MINGW32__
306

    
307
/* init terminal so that we can grab keys */
308
static struct termios oldtty;
309

    
310
static void term_exit(void)
311
{
312
    tcsetattr (0, TCSANOW, &oldtty);
313
}
314

    
315
static volatile sig_atomic_t received_sigterm = 0;
316

    
317
static void
318
sigterm_handler(int sig)
319
{
320
    received_sigterm = sig;
321
    term_exit();
322
}
323

    
324
static void term_init(void)
325
{
326
    struct termios tty;
327

    
328
    tcgetattr (0, &tty);
329
    oldtty = tty;
330

    
331
    tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
332
                          |INLCR|IGNCR|ICRNL|IXON);
333
    tty.c_oflag |= OPOST;
334
    tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
335
    tty.c_cflag &= ~(CSIZE|PARENB);
336
    tty.c_cflag |= CS8;
337
    tty.c_cc[VMIN] = 1;
338
    tty.c_cc[VTIME] = 0;
339

    
340
    tcsetattr (0, TCSANOW, &tty);
341

    
342
    signal(SIGINT , sigterm_handler); /* Interrupt (ANSI).  */
343
    signal(SIGQUIT, sigterm_handler); /* Quit (POSIX).  */
344
    signal(SIGTERM, sigterm_handler); /* Termination (ANSI).  */
345
    /*
346
    register a function to be called at normal program termination
347
    */
348
    atexit(term_exit);
349
#ifdef CONFIG_BEOS_NETSERVER
350
    fcntl(0, F_SETFL, fcntl(0, F_GETFL) | O_NONBLOCK);
351
#endif
352
}
353

    
354
/* read a key without blocking */
355
static int read_key(void)
356
{
357
    int n = 1;
358
    unsigned char ch;
359
#ifndef CONFIG_BEOS_NETSERVER
360
    struct timeval tv;
361
    fd_set rfds;
362

    
363
    FD_ZERO(&rfds);
364
    FD_SET(0, &rfds);
365
    tv.tv_sec = 0;
366
    tv.tv_usec = 0;
367
    n = select(1, &rfds, NULL, NULL, &tv);
368
#endif
369
    if (n > 0) {
370
        n = read(0, &ch, 1);
371
        if (n == 1)
372
            return ch;
373

    
374
        return n;
375
    }
376
    return -1;
377
}
378

    
379
static int decode_interrupt_cb(void)
380
{
381
    return q_pressed || (q_pressed = read_key() == 'q');
382
}
383

    
384
#else
385

    
386
static volatile int received_sigterm = 0;
387

    
388
/* no interactive support */
389
static void term_exit(void)
390
{
391
}
392

    
393
static void term_init(void)
394
{
395
}
396

    
397
static int read_key(void)
398
{
399
    return 0;
400
}
401

    
402
#endif
403

    
404
static int read_ffserver_streams(AVFormatContext *s, const char *filename)
405
{
406
    int i, err;
407
    AVFormatContext *ic;
408

    
409
    err = av_open_input_file(&ic, filename, NULL, FFM_PACKET_SIZE, NULL);
410
    if (err < 0)
411
        return err;
412
    /* copy stream format */
413
    s->nb_streams = ic->nb_streams;
414
    for(i=0;i<ic->nb_streams;i++) {
415
        AVStream *st;
416

    
417
        // FIXME: a more elegant solution is needed
418
        st = av_mallocz(sizeof(AVStream));
419
        memcpy(st, ic->streams[i], sizeof(AVStream));
420
        st->codec = avcodec_alloc_context();
421
        memcpy(st->codec, ic->streams[i]->codec, sizeof(AVCodecContext));
422
        s->streams[i] = st;
423
    }
424

    
425
    av_close_input_file(ic);
426
    return 0;
427
}
428

    
429
static double
430
get_sync_ipts(const AVOutputStream *ost)
431
{
432
    const AVInputStream *ist = ost->sync_ist;
433
    return (double)(ist->pts + input_files_ts_offset[ist->file_index] - start_time)/AV_TIME_BASE;
434
}
435

    
436
static void write_frame(AVFormatContext *s, AVPacket *pkt, AVCodecContext *avctx, AVBitStreamFilterContext *bsfc){
437
    while(bsfc){
438
        AVPacket new_pkt= *pkt;
439
        int a= av_bitstream_filter_filter(bsfc, avctx, NULL,
440
                                          &new_pkt.data, &new_pkt.size,
441
                                          pkt->data, pkt->size,
442
                                          pkt->flags & PKT_FLAG_KEY);
443
        if(a){
444
            av_free_packet(pkt);
445
            new_pkt.destruct= av_destruct_packet;
446
        }
447
        *pkt= new_pkt;
448

    
449
        bsfc= bsfc->next;
450
    }
451

    
452
    av_interleaved_write_frame(s, pkt);
453
}
454

    
455
#define MAX_AUDIO_PACKET_SIZE (128 * 1024)
456

    
457
static void do_audio_out(AVFormatContext *s,
458
                         AVOutputStream *ost,
459
                         AVInputStream *ist,
460
                         unsigned char *buf, int size)
461
{
462
    uint8_t *buftmp;
463
    static uint8_t *audio_buf = NULL;
464
    static uint8_t *audio_out = NULL;
465
    const int audio_out_size= 4*MAX_AUDIO_PACKET_SIZE;
466

    
467
    int size_out, frame_bytes, ret;
468
    AVCodecContext *enc= ost->st->codec;
469

    
470
    /* SC: dynamic allocation of buffers */
471
    if (!audio_buf)
472
        audio_buf = av_malloc(2*MAX_AUDIO_PACKET_SIZE);
473
    if (!audio_out)
474
        audio_out = av_malloc(audio_out_size);
475
    if (!audio_buf || !audio_out)
476
        return;               /* Should signal an error ! */
477

    
478
    if(audio_sync_method){
479
        double delta = get_sync_ipts(ost) * enc->sample_rate - ost->sync_opts
480
                - fifo_size(&ost->fifo, ost->fifo.rptr)/(ost->st->codec->channels * 2);
481
        double idelta= delta*ist->st->codec->sample_rate / enc->sample_rate;
482
        int byte_delta= ((int)idelta)*2*ist->st->codec->channels;
483

    
484
        //FIXME resample delay
485
        if(fabs(delta) > 50){
486
            if(ist->is_start){
487
                if(byte_delta < 0){
488
                    byte_delta= FFMAX(byte_delta, -size);
489
                    size += byte_delta;
490
                    buf  -= byte_delta;
491
                    if(verbose > 2)
492
                        fprintf(stderr, "discarding %d audio samples\n", (int)-delta);
493
                    if(!size)
494
                        return;
495
                    ist->is_start=0;
496
                }else{
497
                    static uint8_t *input_tmp= NULL;
498
                    input_tmp= av_realloc(input_tmp, byte_delta + size);
499

    
500
                    if(byte_delta + size <= MAX_AUDIO_PACKET_SIZE)
501
                        ist->is_start=0;
502
                    else
503
                        byte_delta= MAX_AUDIO_PACKET_SIZE - size;
504

    
505
                    memset(input_tmp, 0, byte_delta);
506
                    memcpy(input_tmp + byte_delta, buf, size);
507
                    buf= input_tmp;
508
                    size += byte_delta;
509
                    if(verbose > 2)
510
                        fprintf(stderr, "adding %d audio samples of silence\n", (int)delta);
511
                }
512
            }else if(audio_sync_method>1){
513
                int comp= clip(delta, -audio_sync_method, audio_sync_method);
514
                assert(ost->audio_resample);
515
                if(verbose > 2)
516
                    fprintf(stderr, "compensating audio timestamp drift:%f compensation:%d in:%d\n", delta, comp, enc->sample_rate);
517
//                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));
518
                av_resample_compensate(*(struct AVResampleContext**)ost->resample, comp, enc->sample_rate);
519
            }
520
        }
521
    }else
522
        ost->sync_opts= lrintf(get_sync_ipts(ost) * enc->sample_rate)
523
                        - fifo_size(&ost->fifo, ost->fifo.rptr)/(ost->st->codec->channels * 2); //FIXME wrong
524

    
525
    if (ost->audio_resample) {
526
        buftmp = audio_buf;
527
        size_out = audio_resample(ost->resample,
528
                                  (short *)buftmp, (short *)buf,
529
                                  size / (ist->st->codec->channels * 2));
530
        size_out = size_out * enc->channels * 2;
531
    } else {
532
        buftmp = buf;
533
        size_out = size;
534
    }
535

    
536
    /* now encode as many frames as possible */
537
    if (enc->frame_size > 1) {
538
        /* output resampled raw samples */
539
        fifo_write(&ost->fifo, buftmp, size_out,
540
                   &ost->fifo.wptr);
541

    
542
        frame_bytes = enc->frame_size * 2 * enc->channels;
543

    
544
        while (fifo_read(&ost->fifo, audio_buf, frame_bytes,
545
                     &ost->fifo.rptr) == 0) {
546
            AVPacket pkt;
547
            av_init_packet(&pkt);
548

    
549
            ret = avcodec_encode_audio(enc, audio_out, audio_out_size,
550
                                       (short *)audio_buf);
551
            audio_size += ret;
552
            pkt.stream_index= ost->index;
553
            pkt.data= audio_out;
554
            pkt.size= ret;
555
            if(enc->coded_frame && enc->coded_frame->pts != AV_NOPTS_VALUE)
556
                pkt.pts= av_rescale_q(enc->coded_frame->pts, enc->time_base, ost->st->time_base);
557
            pkt.flags |= PKT_FLAG_KEY;
558
            write_frame(s, &pkt, ost->st->codec, bitstream_filters[ost->file_index][pkt.stream_index]);
559

    
560
            ost->sync_opts += enc->frame_size;
561
        }
562
    } else {
563
        AVPacket pkt;
564
        av_init_packet(&pkt);
565

    
566
        ost->sync_opts += size_out / (2 * enc->channels);
567

    
568
        /* output a pcm frame */
569
        /* XXX: change encoding codec API to avoid this ? */
570
        switch(enc->codec->id) {
571
        case CODEC_ID_PCM_S32LE:
572
        case CODEC_ID_PCM_S32BE:
573
        case CODEC_ID_PCM_U32LE:
574
        case CODEC_ID_PCM_U32BE:
575
            size_out = size_out << 1;
576
            break;
577
        case CODEC_ID_PCM_S24LE:
578
        case CODEC_ID_PCM_S24BE:
579
        case CODEC_ID_PCM_U24LE:
580
        case CODEC_ID_PCM_U24BE:
581
        case CODEC_ID_PCM_S24DAUD:
582
            size_out = size_out / 2 * 3;
583
            break;
584
        case CODEC_ID_PCM_S16LE:
585
        case CODEC_ID_PCM_S16BE:
586
        case CODEC_ID_PCM_U16LE:
587
        case CODEC_ID_PCM_U16BE:
588
            break;
589
        default:
590
            size_out = size_out >> 1;
591
            break;
592
        }
593
        ret = avcodec_encode_audio(enc, audio_out, size_out,
594
                                   (short *)buftmp);
595
        audio_size += ret;
596
        pkt.stream_index= ost->index;
597
        pkt.data= audio_out;
598
        pkt.size= ret;
599
        if(enc->coded_frame && enc->coded_frame->pts != AV_NOPTS_VALUE)
600
            pkt.pts= av_rescale_q(enc->coded_frame->pts, enc->time_base, ost->st->time_base);
601
        pkt.flags |= PKT_FLAG_KEY;
602
        write_frame(s, &pkt, ost->st->codec, bitstream_filters[ost->file_index][pkt.stream_index]);
603
    }
604
}
605

    
606
static void pre_process_video_frame(AVInputStream *ist, AVPicture *picture, void **bufp)
607
{
608
    AVCodecContext *dec;
609
    AVPicture *picture2;
610
    AVPicture picture_tmp;
611
    uint8_t *buf = 0;
612

    
613
    dec = ist->st->codec;
614

    
615
    /* deinterlace : must be done before any resize */
616
    if (do_deinterlace || using_vhook) {
617
        int size;
618

    
619
        /* create temporary picture */
620
        size = avpicture_get_size(dec->pix_fmt, dec->width, dec->height);
621
        buf = av_malloc(size);
622
        if (!buf)
623
            return;
624

    
625
        picture2 = &picture_tmp;
626
        avpicture_fill(picture2, buf, dec->pix_fmt, dec->width, dec->height);
627

    
628
        if (do_deinterlace){
629
            if(avpicture_deinterlace(picture2, picture,
630
                                     dec->pix_fmt, dec->width, dec->height) < 0) {
631
                /* if error, do not deinterlace */
632
                av_free(buf);
633
                buf = NULL;
634
                picture2 = picture;
635
            }
636
        } else {
637
            img_copy(picture2, picture, dec->pix_fmt, dec->width, dec->height);
638
        }
639
    } else {
640
        picture2 = picture;
641
    }
642

    
643
    frame_hook_process(picture2, dec->pix_fmt, dec->width, dec->height);
644

    
645
    if (picture != picture2)
646
        *picture = *picture2;
647
    *bufp = buf;
648
}
649

    
650
/* we begin to correct av delay at this threshold */
651
#define AV_DELAY_MAX 0.100
652

    
653
static void do_subtitle_out(AVFormatContext *s,
654
                            AVOutputStream *ost,
655
                            AVInputStream *ist,
656
                            AVSubtitle *sub,
657
                            int64_t pts)
658
{
659
    static uint8_t *subtitle_out = NULL;
660
    int subtitle_out_max_size = 65536;
661
    int subtitle_out_size, nb, i;
662
    AVCodecContext *enc;
663
    AVPacket pkt;
664

    
665
    if (pts == AV_NOPTS_VALUE) {
666
        fprintf(stderr, "Subtitle packets must have a pts\n");
667
        return;
668
    }
669

    
670
    enc = ost->st->codec;
671

    
672
    if (!subtitle_out) {
673
        subtitle_out = av_malloc(subtitle_out_max_size);
674
    }
675

    
676
    /* Note: DVB subtitle need one packet to draw them and one other
677
       packet to clear them */
678
    /* XXX: signal it in the codec context ? */
679
    if (enc->codec_id == CODEC_ID_DVB_SUBTITLE)
680
        nb = 2;
681
    else
682
        nb = 1;
683

    
684
    for(i = 0; i < nb; i++) {
685
        subtitle_out_size = avcodec_encode_subtitle(enc, subtitle_out,
686
                                                    subtitle_out_max_size, sub);
687

    
688
        av_init_packet(&pkt);
689
        pkt.stream_index = ost->index;
690
        pkt.data = subtitle_out;
691
        pkt.size = subtitle_out_size;
692
        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);
693
        if (enc->codec_id == CODEC_ID_DVB_SUBTITLE) {
694
            /* XXX: the pts correction is handled here. Maybe handling
695
               it in the codec would be better */
696
            if (i == 0)
697
                pkt.pts += 90 * sub->start_display_time;
698
            else
699
                pkt.pts += 90 * sub->end_display_time;
700
        }
701
        write_frame(s, &pkt, ost->st->codec, bitstream_filters[ost->file_index][pkt.stream_index]);
702
    }
703
}
704

    
705
static int bit_buffer_size= 1024*256;
706
static uint8_t *bit_buffer= NULL;
707

    
708
static void do_video_out(AVFormatContext *s,
709
                         AVOutputStream *ost,
710
                         AVInputStream *ist,
711
                         AVFrame *in_picture,
712
                         int *frame_size)
713
{
714
    int nb_frames, i, ret;
715
    AVFrame *final_picture, *formatted_picture, *resampling_dst, *padding_src;
716
    AVFrame picture_crop_temp, picture_pad_temp;
717
    uint8_t *buf = NULL, *buf1 = NULL;
718
    AVCodecContext *enc, *dec;
719

    
720
    avcodec_get_frame_defaults(&picture_crop_temp);
721
    avcodec_get_frame_defaults(&picture_pad_temp);
722

    
723
    enc = ost->st->codec;
724
    dec = ist->st->codec;
725

    
726
    /* by default, we output a single frame */
727
    nb_frames = 1;
728

    
729
    *frame_size = 0;
730

    
731
    if(video_sync_method){
732
        double vdelta;
733
        vdelta = get_sync_ipts(ost) / av_q2d(enc->time_base) - ost->sync_opts;
734
        //FIXME set to 0.5 after we fix some dts/pts bugs like in avidec.c
735
        if (vdelta < -1.1)
736
            nb_frames = 0;
737
        else if (vdelta > 1.1)
738
            nb_frames = lrintf(vdelta);
739
//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);
740
        if (nb_frames == 0){
741
            ++nb_frames_drop;
742
            if (verbose>2)
743
                fprintf(stderr, "*** drop!\n");
744
        }else if (nb_frames > 1) {
745
            nb_frames_dup += nb_frames;
746
            if (verbose>2)
747
                fprintf(stderr, "*** %d dup!\n", nb_frames-1);
748
        }
749
    }else
750
        ost->sync_opts= lrintf(get_sync_ipts(ost) / av_q2d(enc->time_base));
751

    
752
    nb_frames= FFMIN(nb_frames, max_frames[CODEC_TYPE_VIDEO] - ost->frame_number);
753
    if (nb_frames <= 0)
754
        return;
755

    
756
    if (ost->video_crop) {
757
        if (img_crop((AVPicture *)&picture_crop_temp, (AVPicture *)in_picture, dec->pix_fmt, ost->topBand, ost->leftBand) < 0) {
758
            av_log(NULL, AV_LOG_ERROR, "error cropping picture\n");
759
            goto the_end;
760
        }
761
        formatted_picture = &picture_crop_temp;
762
    } else {
763
        formatted_picture = in_picture;
764
    }
765

    
766
    final_picture = formatted_picture;
767
    padding_src = formatted_picture;
768
    resampling_dst = &ost->pict_tmp;
769
    if (ost->video_pad) {
770
        final_picture = &ost->pict_tmp;
771
        if (ost->video_resample) {
772
            if (img_crop((AVPicture *)&picture_pad_temp, (AVPicture *)final_picture, enc->pix_fmt, ost->padtop, ost->padleft) < 0) {
773
                av_log(NULL, AV_LOG_ERROR, "error padding picture\n");
774
                goto the_end;
775
            }
776
            resampling_dst = &picture_pad_temp;
777
        }
778
    }
779

    
780
    if (ost->video_resample) {
781
        padding_src = NULL;
782
        final_picture = &ost->pict_tmp;
783
        sws_scale(ost->img_resample_ctx, formatted_picture->data, formatted_picture->linesize,
784
              0, ost->resample_height, resampling_dst->data, resampling_dst->linesize);
785
    }
786

    
787
    if (ost->video_pad) {
788
        img_pad((AVPicture*)final_picture, (AVPicture *)padding_src,
789
                enc->height, enc->width, enc->pix_fmt,
790
                ost->padtop, ost->padbottom, ost->padleft, ost->padright, padcolor);
791
    }
792

    
793
    /* duplicates frame if needed */
794
    for(i=0;i<nb_frames;i++) {
795
        AVPacket pkt;
796
        av_init_packet(&pkt);
797
        pkt.stream_index= ost->index;
798

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

    
812
            write_frame(s, &pkt, ost->st->codec, bitstream_filters[ost->file_index][pkt.stream_index]);
813
            enc->coded_frame = old_frame;
814
        } else {
815
            AVFrame big_picture;
816

    
817
            big_picture= *final_picture;
818
            /* better than nothing: use input picture interlaced
819
               settings */
820
            big_picture.interlaced_frame = in_picture->interlaced_frame;
821
            if(avctx_opts->flags & (CODEC_FLAG_INTERLACED_DCT|CODEC_FLAG_INTERLACED_ME)){
822
                if(top_field_first == -1)
823
                    big_picture.top_field_first = in_picture->top_field_first;
824
                else
825
                    big_picture.top_field_first = top_field_first;
826
            }
827

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

    
853
                if(enc->coded_frame && enc->coded_frame->key_frame)
854
                    pkt.flags |= PKT_FLAG_KEY;
855
                write_frame(s, &pkt, ost->st->codec, bitstream_filters[ost->file_index][pkt.stream_index]);
856
                *frame_size = ret;
857
                //fprintf(stderr,"\nFrame: %3d %3d size: %5d type: %d",
858
                //        enc->frame_number-1, enc->real_pict_num, ret,
859
                //        enc->pict_type);
860
                /* if two pass, output log */
861
                if (ost->logfile && enc->stats_out) {
862
                    fprintf(ost->logfile, "%s", enc->stats_out);
863
                }
864
            }
865
        }
866
        ost->sync_opts++;
867
        ost->frame_number++;
868
    }
869
 the_end:
870
    av_free(buf);
871
    av_free(buf1);
872
}
873

    
874
static double psnr(double d){
875
    if(d==0) return INFINITY;
876
    return -10.0*log(d)/log(10.0);
877
}
878

    
879
static void do_video_stats(AVFormatContext *os, AVOutputStream *ost,
880
                           int frame_size)
881
{
882
    static FILE *fvstats=NULL;
883
    char filename[40];
884
    time_t today2;
885
    struct tm *today;
886
    AVCodecContext *enc;
887
    int frame_number;
888
    int64_t ti;
889
    double ti1, bitrate, avg_bitrate;
890

    
891
    if (!fvstats) {
892
        today2 = time(NULL);
893
        today = localtime(&today2);
894
        snprintf(filename, sizeof(filename), "vstats_%02d%02d%02d.log", today->tm_hour,
895
                                               today->tm_min,
896
                                               today->tm_sec);
897
        fvstats = fopen(filename,"w");
898
        if (!fvstats) {
899
            perror("fopen");
900
            exit(1);
901
        }
902
    }
903

    
904
    ti = MAXINT64;
905
    enc = ost->st->codec;
906
    if (enc->codec_type == CODEC_TYPE_VIDEO) {
907
        frame_number = ost->frame_number;
908
        fprintf(fvstats, "frame= %5d q= %2.1f ", frame_number, enc->coded_frame->quality/(float)FF_QP2LAMBDA);
909
        if (enc->flags&CODEC_FLAG_PSNR)
910
            fprintf(fvstats, "PSNR= %6.2f ", psnr(enc->coded_frame->error[0]/(enc->width*enc->height*255.0*255.0)));
911

    
912
        fprintf(fvstats,"f_size= %6d ", frame_size);
913
        /* compute pts value */
914
        ti1 = ost->sync_opts * av_q2d(enc->time_base);
915
        if (ti1 < 0.01)
916
            ti1 = 0.01;
917

    
918
        bitrate = (frame_size * 8) / av_q2d(enc->time_base) / 1000.0;
919
        avg_bitrate = (double)(video_size * 8) / ti1 / 1000.0;
920
        fprintf(fvstats, "s_size= %8.0fkB time= %0.3f br= %7.1fkbits/s avg_br= %7.1fkbits/s ",
921
            (double)video_size / 1024, ti1, bitrate, avg_bitrate);
922
        fprintf(fvstats,"type= %c\n", av_get_pict_type_char(enc->coded_frame->pict_type));
923
    }
924
}
925

    
926
static void print_report(AVFormatContext **output_files,
927
                         AVOutputStream **ost_table, int nb_ostreams,
928
                         int is_last_report)
929
{
930
    char buf[1024];
931
    AVOutputStream *ost;
932
    AVFormatContext *oc, *os;
933
    int64_t total_size;
934
    AVCodecContext *enc;
935
    int frame_number, vid, i;
936
    double bitrate, ti1, pts;
937
    static int64_t last_time = -1;
938
    static int qp_histogram[52];
939

    
940
    if (!is_last_report) {
941
        int64_t cur_time;
942
        /* display the report every 0.5 seconds */
943
        cur_time = av_gettime();
944
        if (last_time == -1) {
945
            last_time = cur_time;
946
            return;
947
        }
948
        if ((cur_time - last_time) < 500000)
949
            return;
950
        last_time = cur_time;
951
    }
952

    
953

    
954
    oc = output_files[0];
955

    
956
    total_size = url_ftell(&oc->pb);
957

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

    
1014
    if (verbose || is_last_report) {
1015
        bitrate = (double)(total_size * 8) / ti1 / 1000.0;
1016

    
1017
        snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
1018
            "size=%8.0fkB time=%0.1f bitrate=%6.1fkbits/s",
1019
            (double)total_size / 1024, ti1, bitrate);
1020

    
1021
        if (verbose > 1)
1022
          snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), " dup=%d drop=%d",
1023
                  nb_frames_dup, nb_frames_drop);
1024

    
1025
        if (verbose >= 0)
1026
            fprintf(stderr, "%s    \r", buf);
1027

    
1028
        fflush(stderr);
1029
    }
1030

    
1031
    if (is_last_report && verbose >= 0){
1032
        int64_t raw= audio_size + video_size + extra_size;
1033
        fprintf(stderr, "\n");
1034
        fprintf(stderr, "video:%1.0fkB audio:%1.0fkB global headers:%1.0fkB muxing overhead %f%%\n",
1035
                video_size/1024.0,
1036
                audio_size/1024.0,
1037
                extra_size/1024.0,
1038
                100.0*(total_size - raw)/raw
1039
        );
1040
    }
1041
}
1042

    
1043
/* pkt = NULL means EOF (needed to flush decoder buffers) */
1044
static int output_packet(AVInputStream *ist, int ist_index,
1045
                         AVOutputStream **ost_table, int nb_ostreams,
1046
                         const AVPacket *pkt)
1047
{
1048
    AVFormatContext *os;
1049
    AVOutputStream *ost;
1050
    uint8_t *ptr;
1051
    int len, ret, i;
1052
    uint8_t *data_buf;
1053
    int data_size, got_picture;
1054
    AVFrame picture;
1055
    void *buffer_to_free;
1056
    static unsigned int samples_size= 0;
1057
    static short *samples= NULL;
1058
    AVSubtitle subtitle, *subtitle_to_free;
1059
    int got_subtitle;
1060

    
1061
    if(!pkt){
1062
        ist->pts= ist->next_pts; // needed for last packet if vsync=0
1063
    } else if (pkt->dts != AV_NOPTS_VALUE) { //FIXME seems redundant, as libavformat does this too
1064
        ist->next_pts = ist->pts = av_rescale_q(pkt->dts, ist->st->time_base, AV_TIME_BASE_Q);
1065
    } else {
1066
//        assert(ist->pts == ist->next_pts);
1067
    }
1068

    
1069
    if (pkt == NULL) {
1070
        /* EOF handling */
1071
        ptr = NULL;
1072
        len = 0;
1073
        goto handle_eof;
1074
    }
1075

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

    
1112
                    ret = avcodec_decode_video(ist->st->codec,
1113
                                               &picture, &got_picture, ptr, len);
1114
                    ist->st->quality= picture.quality;
1115
                    if (ret < 0)
1116
                        goto fail_decode;
1117
                    if (!got_picture) {
1118
                        /* no picture yet */
1119
                        goto discard_packet;
1120
                    }
1121
                    if (ist->st->codec->time_base.num != 0) {
1122
                        ist->next_pts += ((int64_t)AV_TIME_BASE *
1123
                                          ist->st->codec->time_base.num) /
1124
                            ist->st->codec->time_base.den;
1125
                    }
1126
                    len = 0;
1127
                    break;
1128
            case CODEC_TYPE_SUBTITLE:
1129
                ret = avcodec_decode_subtitle(ist->st->codec,
1130
                                              &subtitle, &got_subtitle, ptr, len);
1131
                if (ret < 0)
1132
                    goto fail_decode;
1133
                if (!got_subtitle) {
1134
                    goto discard_packet;
1135
                }
1136
                subtitle_to_free = &subtitle;
1137
                len = 0;
1138
                break;
1139
            default:
1140
                goto fail_decode;
1141
            }
1142
        } else {
1143
                switch(ist->st->codec->codec_type) {
1144
                case CODEC_TYPE_AUDIO:
1145
                    ist->next_pts += ((int64_t)AV_TIME_BASE * ist->st->codec->frame_size) /
1146
                        (ist->st->codec->sample_rate * ist->st->codec->channels);
1147
                    break;
1148
                case CODEC_TYPE_VIDEO:
1149
                    if (ist->st->codec->time_base.num != 0) {
1150
                        ist->next_pts += ((int64_t)AV_TIME_BASE *
1151
                                          ist->st->codec->time_base.num) /
1152
                            ist->st->codec->time_base.den;
1153
                    }
1154
                    break;
1155
                }
1156
                data_buf = ptr;
1157
                data_size = len;
1158
                ret = len;
1159
                len = 0;
1160
            }
1161

    
1162
            buffer_to_free = NULL;
1163
            if (ist->st->codec->codec_type == CODEC_TYPE_VIDEO) {
1164
                pre_process_video_frame(ist, (AVPicture *)&picture,
1165
                                        &buffer_to_free);
1166
            }
1167

    
1168
            // preprocess audio (volume)
1169
            if (ist->st->codec->codec_type == CODEC_TYPE_AUDIO) {
1170
                if (audio_volume != 256) {
1171
                    short *volp;
1172
                    volp = samples;
1173
                    for(i=0;i<(data_size / sizeof(short));i++) {
1174
                        int v = ((*volp) * audio_volume + 128) >> 8;
1175
                        if (v < -32768) v = -32768;
1176
                        if (v >  32767) v = 32767;
1177
                        *volp++ = v;
1178
                    }
1179
                }
1180
            }
1181

    
1182
            /* frame rate emulation */
1183
            if (ist->st->codec->rate_emu) {
1184
                int64_t pts = av_rescale((int64_t) ist->frame * ist->st->codec->time_base.num, 1000000, ist->st->codec->time_base.den);
1185
                int64_t now = av_gettime() - ist->start;
1186
                if (pts > now)
1187
                    usleep(pts - now);
1188

    
1189
                ist->frame++;
1190
            }
1191

    
1192
#if 0
1193
            /* mpeg PTS deordering : if it is a P or I frame, the PTS
1194
               is the one of the next displayed one */
1195
            /* XXX: add mpeg4 too ? */
1196
            if (ist->st->codec->codec_id == CODEC_ID_MPEG1VIDEO) {
1197
                if (ist->st->codec->pict_type != B_TYPE) {
1198
                    int64_t tmp;
1199
                    tmp = ist->last_ip_pts;
1200
                    ist->last_ip_pts  = ist->frac_pts.val;
1201
                    ist->frac_pts.val = tmp;
1202
                }
1203
            }
1204
#endif
1205
            /* if output time reached then transcode raw format,
1206
               encode packets and output them */
1207
            if (start_time == 0 || ist->pts >= start_time)
1208
                for(i=0;i<nb_ostreams;i++) {
1209
                    int frame_size;
1210

    
1211
                    ost = ost_table[i];
1212
                    if (ost->source_index == ist_index) {
1213
                        os = output_files[ost->file_index];
1214

    
1215
#if 0
1216
                        printf("%d: got pts=%0.3f %0.3f\n", i,
1217
                               (double)pkt->pts / AV_TIME_BASE,
1218
                               ((double)ist->pts / AV_TIME_BASE) -
1219
                               ((double)ost->st->pts.val * ost->st->time_base.num / ost->st->time_base.den));
1220
#endif
1221
                        /* set the input output pts pairs */
1222
                        //ost->sync_ipts = (double)(ist->pts + input_files_ts_offset[ist->file_index] - start_time)/ AV_TIME_BASE;
1223

    
1224
                        if (ost->encoding_needed) {
1225
                            switch(ost->st->codec->codec_type) {
1226
                            case CODEC_TYPE_AUDIO:
1227
                                do_audio_out(os, ost, ist, data_buf, data_size);
1228
                                break;
1229
                            case CODEC_TYPE_VIDEO:
1230
                                    do_video_out(os, ost, ist, &picture, &frame_size);
1231
                                    video_size += frame_size;
1232
                                    if (do_vstats && frame_size)
1233
                                        do_video_stats(os, ost, frame_size);
1234
                                break;
1235
                            case CODEC_TYPE_SUBTITLE:
1236
                                do_subtitle_out(os, ost, ist, &subtitle,
1237
                                                pkt->pts);
1238
                                break;
1239
                            default:
1240
                                av_abort();
1241
                            }
1242
                        } else {
1243
                            AVFrame avframe; //FIXME/XXX remove this
1244
                            AVPacket opkt;
1245
                            av_init_packet(&opkt);
1246

    
1247
                            /* no reencoding needed : output the packet directly */
1248
                            /* force the input stream PTS */
1249

    
1250
                            avcodec_get_frame_defaults(&avframe);
1251
                            ost->st->codec->coded_frame= &avframe;
1252
                            avframe.key_frame = pkt->flags & PKT_FLAG_KEY;
1253

    
1254
                            if(ost->st->codec->codec_type == CODEC_TYPE_AUDIO)
1255
                                audio_size += data_size;
1256
                            else if (ost->st->codec->codec_type == CODEC_TYPE_VIDEO) {
1257
                                video_size += data_size;
1258
                                ost->sync_opts++;
1259
                            }
1260

    
1261
                            opkt.stream_index= ost->index;
1262
                            if(pkt->pts != AV_NOPTS_VALUE)
1263
                                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);
1264
                            else
1265
                                opkt.pts= AV_NOPTS_VALUE;
1266

    
1267
                            {
1268
                                int64_t dts;
1269
                                if (pkt->dts == AV_NOPTS_VALUE)
1270
                                    dts = ist->next_pts;
1271
                                else
1272
                                    dts= av_rescale_q(pkt->dts, ist->st->time_base, AV_TIME_BASE_Q);
1273
                                opkt.dts= av_rescale_q(dts + input_files_ts_offset[ist->file_index], AV_TIME_BASE_Q,  ost->st->time_base);
1274
                            }
1275
                            opkt.flags= pkt->flags;
1276

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

    
1281
                            write_frame(os, &opkt, ost->st->codec, bitstream_filters[ost->file_index][pkt->stream_index]);
1282
                            ost->st->codec->frame_number++;
1283
                            ost->frame_number++;
1284
                            av_free_packet(&opkt);
1285
                        }
1286
                    }
1287
                }
1288
            av_free(buffer_to_free);
1289
            /* XXX: allocate the subtitles in the codec ? */
1290
            if (subtitle_to_free) {
1291
                if (subtitle_to_free->rects != NULL) {
1292
                    for (i = 0; i < subtitle_to_free->num_rects; i++) {
1293
                        av_free(subtitle_to_free->rects[i].bitmap);
1294
                        av_free(subtitle_to_free->rects[i].rgba_palette);
1295
                    }
1296
                    av_freep(&subtitle_to_free->rects);
1297
                }
1298
                subtitle_to_free->num_rects = 0;
1299
                subtitle_to_free = NULL;
1300
            }
1301
        }
1302
 discard_packet:
1303
    if (pkt == NULL) {
1304
        /* EOF handling */
1305

    
1306
        for(i=0;i<nb_ostreams;i++) {
1307
            ost = ost_table[i];
1308
            if (ost->source_index == ist_index) {
1309
                AVCodecContext *enc= ost->st->codec;
1310
                os = output_files[ost->file_index];
1311

    
1312
                if(ost->st->codec->codec_type == CODEC_TYPE_AUDIO && enc->frame_size <=1)
1313
                    continue;
1314
                if(ost->st->codec->codec_type == CODEC_TYPE_VIDEO && (os->oformat->flags & AVFMT_RAWPICTURE))
1315
                    continue;
1316

    
1317
                if (ost->encoding_needed) {
1318
                    for(;;) {
1319
                        AVPacket pkt;
1320
                        int fifo_bytes;
1321
                        av_init_packet(&pkt);
1322
                        pkt.stream_index= ost->index;
1323

    
1324
                        switch(ost->st->codec->codec_type) {
1325
                        case CODEC_TYPE_AUDIO:
1326
                            fifo_bytes = fifo_size(&ost->fifo, NULL);
1327
                            ret = 0;
1328
                            /* encode any samples remaining in fifo */
1329
                            if(fifo_bytes > 0 && enc->codec->capabilities & CODEC_CAP_SMALL_LAST_FRAME) {
1330
                                int fs_tmp = enc->frame_size;
1331
                                enc->frame_size = fifo_bytes / (2 * enc->channels);
1332
                                if(fifo_read(&ost->fifo, (uint8_t *)samples, fifo_bytes,
1333
                                        &ost->fifo.rptr) == 0) {
1334
                                    ret = avcodec_encode_audio(enc, bit_buffer, bit_buffer_size, samples);
1335
                                }
1336
                                enc->frame_size = fs_tmp;
1337
                            }
1338
                            if(ret <= 0) {
1339
                                ret = avcodec_encode_audio(enc, bit_buffer, bit_buffer_size, NULL);
1340
                            }
1341
                            audio_size += ret;
1342
                            pkt.flags |= PKT_FLAG_KEY;
1343
                            break;
1344
                        case CODEC_TYPE_VIDEO:
1345
                            ret = avcodec_encode_video(enc, bit_buffer, bit_buffer_size, NULL);
1346
                            video_size += ret;
1347
                            if(enc->coded_frame && enc->coded_frame->key_frame)
1348
                                pkt.flags |= PKT_FLAG_KEY;
1349
                            if (ost->logfile && enc->stats_out) {
1350
                                fprintf(ost->logfile, "%s", enc->stats_out);
1351
                            }
1352
                            break;
1353
                        default:
1354
                            ret=-1;
1355
                        }
1356

    
1357
                        if(ret<=0)
1358
                            break;
1359
                        pkt.data= bit_buffer;
1360
                        pkt.size= ret;
1361
                        if(enc->coded_frame && enc->coded_frame->pts != AV_NOPTS_VALUE)
1362
                            pkt.pts= av_rescale_q(enc->coded_frame->pts, enc->time_base, ost->st->time_base);
1363
                        write_frame(os, &pkt, ost->st->codec, bitstream_filters[ost->file_index][pkt.stream_index]);
1364
                    }
1365
                }
1366
            }
1367
        }
1368
    }
1369

    
1370
    return 0;
1371
 fail_decode:
1372
    return -1;
1373
}
1374

    
1375

    
1376
/*
1377
 * The following code is the main loop of the file converter
1378
 */
1379
static int av_encode(AVFormatContext **output_files,
1380
                     int nb_output_files,
1381
                     AVFormatContext **input_files,
1382
                     int nb_input_files,
1383
                     AVStreamMap *stream_maps, int nb_stream_maps)
1384
{
1385
    int ret, i, j, k, n, nb_istreams = 0, nb_ostreams = 0;
1386
    AVFormatContext *is, *os;
1387
    AVCodecContext *codec, *icodec;
1388
    AVOutputStream *ost, **ost_table = NULL;
1389
    AVInputStream *ist, **ist_table = NULL;
1390
    AVInputFile *file_table;
1391
    AVFormatContext *stream_no_data;
1392
    int key;
1393

    
1394
    file_table= (AVInputFile*) av_mallocz(nb_input_files * sizeof(AVInputFile));
1395
    if (!file_table)
1396
        goto fail;
1397

    
1398
    /* input stream init */
1399
    j = 0;
1400
    for(i=0;i<nb_input_files;i++) {
1401
        is = input_files[i];
1402
        file_table[i].ist_index = j;
1403
        file_table[i].nb_streams = is->nb_streams;
1404
        j += is->nb_streams;
1405
    }
1406
    nb_istreams = j;
1407

    
1408
    ist_table = av_mallocz(nb_istreams * sizeof(AVInputStream *));
1409
    if (!ist_table)
1410
        goto fail;
1411

    
1412
    for(i=0;i<nb_istreams;i++) {
1413
        ist = av_mallocz(sizeof(AVInputStream));
1414
        if (!ist)
1415
            goto fail;
1416
        ist_table[i] = ist;
1417
    }
1418
    j = 0;
1419
    for(i=0;i<nb_input_files;i++) {
1420
        is = input_files[i];
1421
        for(k=0;k<is->nb_streams;k++) {
1422
            ist = ist_table[j++];
1423
            ist->st = is->streams[k];
1424
            ist->file_index = i;
1425
            ist->index = k;
1426
            ist->discard = 1; /* the stream is discarded by default
1427
                                 (changed later) */
1428

    
1429
            if (ist->st->codec->rate_emu) {
1430
                ist->start = av_gettime();
1431
                ist->frame = 0;
1432
            }
1433
        }
1434
    }
1435

    
1436
    /* output stream init */
1437
    nb_ostreams = 0;
1438
    for(i=0;i<nb_output_files;i++) {
1439
        os = output_files[i];
1440
        nb_ostreams += os->nb_streams;
1441
    }
1442
    if (nb_stream_maps > 0 && nb_stream_maps != nb_ostreams) {
1443
        fprintf(stderr, "Number of stream maps must match number of output streams\n");
1444
        exit(1);
1445
    }
1446

    
1447
    /* Sanity check the mapping args -- do the input files & streams exist? */
1448
    for(i=0;i<nb_stream_maps;i++) {
1449
        int fi = stream_maps[i].file_index;
1450
        int si = stream_maps[i].stream_index;
1451

    
1452
        if (fi < 0 || fi > nb_input_files - 1 ||
1453
            si < 0 || si > file_table[fi].nb_streams - 1) {
1454
            fprintf(stderr,"Could not find input stream #%d.%d\n", fi, si);
1455
            exit(1);
1456
        }
1457
        fi = stream_maps[i].sync_file_index;
1458
        si = stream_maps[i].sync_stream_index;
1459
        if (fi < 0 || fi > nb_input_files - 1 ||
1460
            si < 0 || si > file_table[fi].nb_streams - 1) {
1461
            fprintf(stderr,"Could not find sync stream #%d.%d\n", fi, si);
1462
            exit(1);
1463
        }
1464
    }
1465

    
1466
    ost_table = av_mallocz(sizeof(AVOutputStream *) * nb_ostreams);
1467
    if (!ost_table)
1468
        goto fail;
1469
    for(i=0;i<nb_ostreams;i++) {
1470
        ost = av_mallocz(sizeof(AVOutputStream));
1471
        if (!ost)
1472
            goto fail;
1473
        ost_table[i] = ost;
1474
    }
1475

    
1476
    n = 0;
1477
    for(k=0;k<nb_output_files;k++) {
1478
        os = output_files[k];
1479
        for(i=0;i<os->nb_streams;i++) {
1480
            int found;
1481
            ost = ost_table[n++];
1482
            ost->file_index = k;
1483
            ost->index = i;
1484
            ost->st = os->streams[i];
1485
            if (nb_stream_maps > 0) {
1486
                ost->source_index = file_table[stream_maps[n-1].file_index].ist_index +
1487
                    stream_maps[n-1].stream_index;
1488

    
1489
                /* Sanity check that the stream types match */
1490
                if (ist_table[ost->source_index]->st->codec->codec_type != ost->st->codec->codec_type) {
1491
                    fprintf(stderr, "Codec type mismatch for mapping #%d.%d -> #%d.%d\n",
1492
                        stream_maps[n-1].file_index, stream_maps[n-1].stream_index,
1493
                        ost->file_index, ost->index);
1494
                    exit(1);
1495
                }
1496

    
1497
            } else {
1498
                /* get corresponding input stream index : we select the first one with the right type */
1499
                found = 0;
1500
                for(j=0;j<nb_istreams;j++) {
1501
                    ist = ist_table[j];
1502
                    if (ist->discard &&
1503
                        ist->st->codec->codec_type == ost->st->codec->codec_type) {
1504
                        ost->source_index = j;
1505
                        found = 1;
1506
                        break;
1507
                    }
1508
                }
1509

    
1510
                if (!found) {
1511
                    /* try again and reuse existing stream */
1512
                    for(j=0;j<nb_istreams;j++) {
1513
                        ist = ist_table[j];
1514
                        if (ist->st->codec->codec_type == ost->st->codec->codec_type) {
1515
                            ost->source_index = j;
1516
                            found = 1;
1517
                        }
1518
                    }
1519
                    if (!found) {
1520
                        fprintf(stderr, "Could not find input stream matching output stream #%d.%d\n",
1521
                                ost->file_index, ost->index);
1522
                        exit(1);
1523
                    }
1524
                }
1525
            }
1526
            ist = ist_table[ost->source_index];
1527
            ist->discard = 0;
1528
            ost->sync_ist = (nb_stream_maps > 0) ?
1529
                ist_table[file_table[stream_maps[n-1].sync_file_index].ist_index +
1530
                         stream_maps[n-1].sync_stream_index] : ist;
1531
        }
1532
    }
1533

    
1534
    /* for each output stream, we compute the right encoding parameters */
1535
    for(i=0;i<nb_ostreams;i++) {
1536
        ost = ost_table[i];
1537
        ist = ist_table[ost->source_index];
1538

    
1539
        codec = ost->st->codec;
1540
        icodec = ist->st->codec;
1541

    
1542
        if (ost->st->stream_copy) {
1543
            /* if stream_copy is selected, no need to decode or encode */
1544
            codec->codec_id = icodec->codec_id;
1545
            codec->codec_type = icodec->codec_type;
1546
            if(!codec->codec_tag) codec->codec_tag = icodec->codec_tag;
1547
            codec->bit_rate = icodec->bit_rate;
1548
            codec->extradata= icodec->extradata;
1549
            codec->extradata_size= icodec->extradata_size;
1550
            codec->time_base = icodec->time_base;
1551
            switch(codec->codec_type) {
1552
            case CODEC_TYPE_AUDIO:
1553
                codec->sample_rate = icodec->sample_rate;
1554
                codec->channels = icodec->channels;
1555
                codec->frame_size = icodec->frame_size;
1556
                codec->block_align= icodec->block_align;
1557
                break;
1558
            case CODEC_TYPE_VIDEO:
1559
                codec->pix_fmt = icodec->pix_fmt;
1560
                codec->width = icodec->width;
1561
                codec->height = icodec->height;
1562
                codec->has_b_frames = icodec->has_b_frames;
1563
                break;
1564
            case CODEC_TYPE_SUBTITLE:
1565
                break;
1566
            default:
1567
                av_abort();
1568
            }
1569
        } else {
1570
            switch(codec->codec_type) {
1571
            case CODEC_TYPE_AUDIO:
1572
                if (fifo_init(&ost->fifo, 2 * MAX_AUDIO_PACKET_SIZE))
1573
                    goto fail;
1574

    
1575
                if (codec->channels == icodec->channels &&
1576
                    codec->sample_rate == icodec->sample_rate) {
1577
                    ost->audio_resample = 0;
1578
                } else {
1579
                    if (codec->channels != icodec->channels &&
1580
                        (icodec->codec_id == CODEC_ID_AC3 ||
1581
                         icodec->codec_id == CODEC_ID_DTS)) {
1582
                        /* Special case for 5:1 AC3 and DTS input */
1583
                        /* and mono or stereo output      */
1584
                        /* Request specific number of channels */
1585
                        icodec->channels = codec->channels;
1586
                        if (codec->sample_rate == icodec->sample_rate)
1587
                            ost->audio_resample = 0;
1588
                        else {
1589
                            ost->audio_resample = 1;
1590
                        }
1591
                    } else {
1592
                        ost->audio_resample = 1;
1593
                    }
1594
                }
1595
                if(audio_sync_method>1)
1596
                    ost->audio_resample = 1;
1597

    
1598
                if(ost->audio_resample){
1599
                    ost->resample = audio_resample_init(codec->channels, icodec->channels,
1600
                                                    codec->sample_rate, icodec->sample_rate);
1601
                    if(!ost->resample){
1602
                        printf("Can't resample.  Aborting.\n");
1603
                        av_abort();
1604
                    }
1605
                }
1606
                ist->decoding_needed = 1;
1607
                ost->encoding_needed = 1;
1608
                break;
1609
            case CODEC_TYPE_VIDEO:
1610
                ost->video_crop = ((frame_leftBand + frame_rightBand + frame_topBand + frame_bottomBand) != 0);
1611
                ost->video_pad = ((frame_padleft + frame_padright + frame_padtop + frame_padbottom) != 0);
1612
                ost->video_resample = ((codec->width != icodec->width -
1613
                                (frame_leftBand + frame_rightBand) +
1614
                                (frame_padleft + frame_padright)) ||
1615
                        (codec->height != icodec->height -
1616
                                (frame_topBand  + frame_bottomBand) +
1617
                                (frame_padtop + frame_padbottom)) ||
1618
                        (codec->pix_fmt != icodec->pix_fmt));
1619
                if (ost->video_crop) {
1620
                    ost->topBand = frame_topBand;
1621
                    ost->leftBand = frame_leftBand;
1622
                }
1623
                if (ost->video_pad) {
1624
                    ost->padtop = frame_padtop;
1625
                    ost->padleft = frame_padleft;
1626
                    ost->padbottom = frame_padbottom;
1627
                    ost->padright = frame_padright;
1628
                    if (!ost->video_resample) {
1629
                        avcodec_get_frame_defaults(&ost->pict_tmp);
1630
                        if( avpicture_alloc( (AVPicture*)&ost->pict_tmp, codec->pix_fmt,
1631
                                         codec->width, codec->height ) )
1632
                            goto fail;
1633
                    }
1634
                }
1635
                if (ost->video_resample) {
1636
                    avcodec_get_frame_defaults(&ost->pict_tmp);
1637
                    if( avpicture_alloc( (AVPicture*)&ost->pict_tmp, codec->pix_fmt,
1638
                                         codec->width, codec->height ) )
1639
                        goto fail;
1640

    
1641
                    ost->img_resample_ctx = sws_getContext(
1642
                            icodec->width - (frame_leftBand + frame_rightBand),
1643
                            icodec->height - (frame_topBand + frame_bottomBand),
1644
                            icodec->pix_fmt,
1645
                            codec->width - (frame_padleft + frame_padright),
1646
                            codec->height - (frame_padtop + frame_padbottom),
1647
                            codec->pix_fmt,
1648
                            sws_flags, NULL, NULL, NULL);
1649
                    if (ost->img_resample_ctx == NULL) {
1650
                        fprintf(stderr, "Cannot get resampling context\n");
1651
                        exit(1);
1652
                    }
1653
                    ost->resample_height = icodec->height - (frame_topBand + frame_bottomBand);
1654
                }
1655
                ost->encoding_needed = 1;
1656
                ist->decoding_needed = 1;
1657
                break;
1658
            case CODEC_TYPE_SUBTITLE:
1659
                ost->encoding_needed = 1;
1660
                ist->decoding_needed = 1;
1661
                break;
1662
            default:
1663
                av_abort();
1664
                break;
1665
            }
1666
            /* two pass mode */
1667
            if (ost->encoding_needed &&
1668
                (codec->flags & (CODEC_FLAG_PASS1 | CODEC_FLAG_PASS2))) {
1669
                char logfilename[1024];
1670
                FILE *f;
1671
                int size;
1672
                char *logbuffer;
1673

    
1674
                snprintf(logfilename, sizeof(logfilename), "%s-%d.log",
1675
                         pass_logfilename ?
1676
                         pass_logfilename : DEFAULT_PASS_LOGFILENAME, i);
1677
                if (codec->flags & CODEC_FLAG_PASS1) {
1678
                    f = fopen(logfilename, "w");
1679
                    if (!f) {
1680
                        perror(logfilename);
1681
                        exit(1);
1682
                    }
1683
                    ost->logfile = f;
1684
                } else {
1685
                    /* read the log file */
1686
                    f = fopen(logfilename, "r");
1687
                    if (!f) {
1688
                        perror(logfilename);
1689
                        exit(1);
1690
                    }
1691
                    fseek(f, 0, SEEK_END);
1692
                    size = ftell(f);
1693
                    fseek(f, 0, SEEK_SET);
1694
                    logbuffer = av_malloc(size + 1);
1695
                    if (!logbuffer) {
1696
                        fprintf(stderr, "Could not allocate log buffer\n");
1697
                        exit(1);
1698
                    }
1699
                    size = fread(logbuffer, 1, size, f);
1700
                    fclose(f);
1701
                    logbuffer[size] = '\0';
1702
                    codec->stats_in = logbuffer;
1703
                }
1704
            }
1705
        }
1706
        if(codec->codec_type == CODEC_TYPE_VIDEO){
1707
            int size= codec->width * codec->height;
1708
            bit_buffer_size= FFMAX(bit_buffer_size, 4*size);
1709
        }
1710
    }
1711

    
1712
    if (!bit_buffer)
1713
        bit_buffer = av_malloc(bit_buffer_size);
1714
    if (!bit_buffer)
1715
        goto fail;
1716

    
1717
    /* dump the file output parameters - cannot be done before in case
1718
       of stream copy */
1719
    for(i=0;i<nb_output_files;i++) {
1720
        dump_format(output_files[i], i, output_files[i]->filename, 1);
1721
    }
1722

    
1723
    /* dump the stream mapping */
1724
    if (verbose >= 0) {
1725
        fprintf(stderr, "Stream mapping:\n");
1726
        for(i=0;i<nb_ostreams;i++) {
1727
            ost = ost_table[i];
1728
            fprintf(stderr, "  Stream #%d.%d -> #%d.%d",
1729
                    ist_table[ost->source_index]->file_index,
1730
                    ist_table[ost->source_index]->index,
1731
                    ost->file_index,
1732
                    ost->index);
1733
            if (ost->sync_ist != ist_table[ost->source_index])
1734
                fprintf(stderr, " [sync #%d.%d]",
1735
                        ost->sync_ist->file_index,
1736
                        ost->sync_ist->index);
1737
            fprintf(stderr, "\n");
1738
        }
1739
    }
1740

    
1741
    /* open each encoder */
1742
    for(i=0;i<nb_ostreams;i++) {
1743
        ost = ost_table[i];
1744
        if (ost->encoding_needed) {
1745
            AVCodec *codec;
1746
            codec = avcodec_find_encoder(ost->st->codec->codec_id);
1747
            if (!codec) {
1748
                fprintf(stderr, "Unsupported codec for output stream #%d.%d\n",
1749
                        ost->file_index, ost->index);
1750
                exit(1);
1751
            }
1752
            if (avcodec_open(ost->st->codec, codec) < 0) {
1753
                fprintf(stderr, "Error while opening codec for output stream #%d.%d - maybe incorrect parameters such as bit_rate, rate, width or height\n",
1754
                        ost->file_index, ost->index);
1755
                exit(1);
1756
            }
1757
            extra_size += ost->st->codec->extradata_size;
1758
        }
1759
    }
1760

    
1761
    /* open each decoder */
1762
    for(i=0;i<nb_istreams;i++) {
1763
        ist = ist_table[i];
1764
        if (ist->decoding_needed) {
1765
            AVCodec *codec;
1766
            codec = avcodec_find_decoder(ist->st->codec->codec_id);
1767
            if (!codec) {
1768
                fprintf(stderr, "Unsupported codec (id=%d) for input stream #%d.%d\n",
1769
                        ist->st->codec->codec_id, ist->file_index, ist->index);
1770
                exit(1);
1771
            }
1772
            if (avcodec_open(ist->st->codec, codec) < 0) {
1773
                fprintf(stderr, "Error while opening codec for input stream #%d.%d\n",
1774
                        ist->file_index, ist->index);
1775
                exit(1);
1776
            }
1777
            //if (ist->st->codec->codec_type == CODEC_TYPE_VIDEO)
1778
            //    ist->st->codec->flags |= CODEC_FLAG_REPEAT_FIELD;
1779
        }
1780
    }
1781

    
1782
    /* init pts */
1783
    for(i=0;i<nb_istreams;i++) {
1784
        ist = ist_table[i];
1785
        is = input_files[ist->file_index];
1786
        ist->pts = 0;
1787
        ist->next_pts = av_rescale_q(ist->st->start_time, ist->st->time_base, AV_TIME_BASE_Q);
1788
        if(ist->st->start_time == AV_NOPTS_VALUE)
1789
            ist->next_pts=0;
1790
        if(input_files_ts_offset[ist->file_index])
1791
            ist->next_pts= AV_NOPTS_VALUE;
1792
        ist->is_start = 1;
1793
    }
1794

    
1795
    /* compute buffer size max (should use a complete heuristic) */
1796
    for(i=0;i<nb_input_files;i++) {
1797
        file_table[i].buffer_size_max = 2048;
1798
    }
1799

    
1800
    /* set meta data information from input file if required */
1801
    for (i=0;i<nb_meta_data_maps;i++) {
1802
        AVFormatContext *out_file;
1803
        AVFormatContext *in_file;
1804

    
1805
        int out_file_index = meta_data_maps[i].out_file;
1806
        int in_file_index = meta_data_maps[i].in_file;
1807
        if ( out_file_index < 0 || out_file_index >= nb_output_files ) {
1808
            fprintf(stderr, "Invalid output file index %d map_meta_data(%d,%d)\n", out_file_index, out_file_index, in_file_index);
1809
            ret = -EINVAL;
1810
            goto fail;
1811
        }
1812
        if ( in_file_index < 0 || in_file_index >= nb_input_files ) {
1813
            fprintf(stderr, "Invalid input file index %d map_meta_data(%d,%d)\n", in_file_index, out_file_index, in_file_index);
1814
            ret = -EINVAL;
1815
            goto fail;
1816
        }
1817

    
1818
        out_file = output_files[out_file_index];
1819
        in_file = input_files[in_file_index];
1820

    
1821
        strcpy(out_file->title, in_file->title);
1822
        strcpy(out_file->author, in_file->author);
1823
        strcpy(out_file->copyright, in_file->copyright);
1824
        strcpy(out_file->comment, in_file->comment);
1825
        strcpy(out_file->album, in_file->album);
1826
        out_file->year = in_file->year;
1827
        out_file->track = in_file->track;
1828
        strcpy(out_file->genre, in_file->genre);
1829
    }
1830

    
1831
    /* open files and write file headers */
1832
    for(i=0;i<nb_output_files;i++) {
1833
        os = output_files[i];
1834
        if (av_write_header(os) < 0) {
1835
            fprintf(stderr, "Could not write header for output file #%d (incorrect codec parameters ?)\n", i);
1836
            ret = -EINVAL;
1837
            goto fail;
1838
        }
1839
    }
1840

    
1841
#ifndef __MINGW32__
1842
    if ( !using_stdin && verbose >= 0) {
1843
        fprintf(stderr, "Press [q] to stop encoding\n");
1844
        url_set_interrupt_cb(decode_interrupt_cb);
1845
    }
1846
#endif
1847
    term_init();
1848

    
1849
    stream_no_data = 0;
1850
    key = -1;
1851

    
1852
    for(; received_sigterm == 0;) {
1853
        int file_index, ist_index;
1854
        AVPacket pkt;
1855
        double ipts_min;
1856
        double opts_min;
1857

    
1858
    redo:
1859
        ipts_min= 1e100;
1860
        opts_min= 1e100;
1861
        /* if 'q' pressed, exits */
1862
        if (!using_stdin) {
1863
            if (q_pressed)
1864
                break;
1865
            /* read_key() returns 0 on EOF */
1866
            key = read_key();
1867
            if (key == 'q')
1868
                break;
1869
        }
1870

    
1871
        /* select the stream that we must read now by looking at the
1872
           smallest output pts */
1873
        file_index = -1;
1874
        for(i=0;i<nb_ostreams;i++) {
1875
            double ipts, opts;
1876
            ost = ost_table[i];
1877
            os = output_files[ost->file_index];
1878
            ist = ist_table[ost->source_index];
1879
            if(ost->st->codec->codec_type == CODEC_TYPE_VIDEO)
1880
                opts = ost->sync_opts * av_q2d(ost->st->codec->time_base);
1881
            else
1882
                opts = ost->st->pts.val * av_q2d(ost->st->time_base);
1883
            ipts = (double)ist->pts;
1884
            if (!file_table[ist->file_index].eof_reached){
1885
                if(ipts < ipts_min) {
1886
                    ipts_min = ipts;
1887
                    if(input_sync ) file_index = ist->file_index;
1888
                }
1889
                if(opts < opts_min) {
1890
                    opts_min = opts;
1891
                    if(!input_sync) file_index = ist->file_index;
1892
                }
1893
            }
1894
            if(ost->frame_number >= max_frames[ost->st->codec->codec_type]){
1895
                file_index= -1;
1896
                break;
1897
            }
1898
        }
1899
        /* if none, if is finished */
1900
        if (file_index < 0) {
1901
            break;
1902
        }
1903

    
1904
        /* finish if recording time exhausted */
1905
        if (recording_time > 0 && opts_min >= (recording_time / 1000000.0))
1906
            break;
1907

    
1908
        /* finish if limit size exhausted */
1909
        if (limit_filesize != 0 && (limit_filesize * 1024) < url_ftell(&output_files[0]->pb))
1910
            break;
1911

    
1912
        /* read a frame from it and output it in the fifo */
1913
        is = input_files[file_index];
1914
        if (av_read_frame(is, &pkt) < 0) {
1915
            file_table[file_index].eof_reached = 1;
1916
            if (opt_shortest) break; else continue; //
1917
        }
1918

    
1919
        if (!pkt.size) {
1920
            stream_no_data = is;
1921
        } else {
1922
            stream_no_data = 0;
1923
        }
1924
        if (do_pkt_dump) {
1925
            av_pkt_dump(stdout, &pkt, do_hex_dump);
1926
        }
1927
        /* the following test is needed in case new streams appear
1928
           dynamically in stream : we ignore them */
1929
        if (pkt.stream_index >= file_table[file_index].nb_streams)
1930
            goto discard_packet;
1931
        ist_index = file_table[file_index].ist_index + pkt.stream_index;
1932
        ist = ist_table[ist_index];
1933
        if (ist->discard)
1934
            goto discard_packet;
1935

    
1936
//        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);
1937
        if (pkt.dts != AV_NOPTS_VALUE && ist->next_pts != AV_NOPTS_VALUE) {
1938
            int64_t delta= av_rescale_q(pkt.dts, ist->st->time_base, AV_TIME_BASE_Q) - ist->next_pts;
1939
            if(ABS(delta) > 1LL*dts_delta_threshold*AV_TIME_BASE && !copy_ts){
1940
                input_files_ts_offset[ist->file_index]-= delta;
1941
                if (verbose > 2)
1942
                    fprintf(stderr, "timestamp discontinuity %"PRId64", new offset= %"PRId64"\n", delta, input_files_ts_offset[ist->file_index]);
1943
                for(i=0; i<file_table[file_index].nb_streams; i++){
1944
                    int index= file_table[file_index].ist_index + i;
1945
                    ist_table[index]->next_pts += delta;
1946
                    ist_table[index]->is_start=1;
1947
                }
1948
            }
1949
        }
1950

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

    
1954
            if (verbose >= 0)
1955
                fprintf(stderr, "Error while decoding stream #%d.%d\n",
1956
                        ist->file_index, ist->index);
1957

    
1958
            av_free_packet(&pkt);
1959
            goto redo;
1960
        }
1961

    
1962
    discard_packet:
1963
        av_free_packet(&pkt);
1964

    
1965
        /* dump report by using the output first video and audio streams */
1966
        print_report(output_files, ost_table, nb_ostreams, 0);
1967
    }
1968

    
1969
    /* at the end of stream, we must flush the decoder buffers */
1970
    for(i=0;i<nb_istreams;i++) {
1971
        ist = ist_table[i];
1972
        if (ist->decoding_needed) {
1973
            output_packet(ist, i, ost_table, nb_ostreams, NULL);
1974
        }
1975
    }
1976

    
1977
    term_exit();
1978

    
1979
    /* write the trailer if needed and close file */
1980
    for(i=0;i<nb_output_files;i++) {
1981
        os = output_files[i];
1982
        av_write_trailer(os);
1983
    }
1984

    
1985
    /* dump report by using the first video and audio streams */
1986
    print_report(output_files, ost_table, nb_ostreams, 1);
1987

    
1988
    /* close each encoder */
1989
    for(i=0;i<nb_ostreams;i++) {
1990
        ost = ost_table[i];
1991
        if (ost->encoding_needed) {
1992
            av_freep(&ost->st->codec->stats_in);
1993
            avcodec_close(ost->st->codec);
1994
        }
1995
    }
1996

    
1997
    /* close each decoder */
1998
    for(i=0;i<nb_istreams;i++) {
1999
        ist = ist_table[i];
2000
        if (ist->decoding_needed) {
2001
            avcodec_close(ist->st->codec);
2002
        }
2003
    }
2004

    
2005
    /* finished ! */
2006

    
2007
    ret = 0;
2008
 fail1:
2009
    av_freep(&bit_buffer);
2010
    av_free(file_table);
2011

    
2012
    if (ist_table) {
2013
        for(i=0;i<nb_istreams;i++) {
2014
            ist = ist_table[i];
2015
            av_free(ist);
2016
        }
2017
        av_free(ist_table);
2018
    }
2019
    if (ost_table) {
2020
        for(i=0;i<nb_ostreams;i++) {
2021
            ost = ost_table[i];
2022
            if (ost) {
2023
                if (ost->logfile) {
2024
                    fclose(ost->logfile);
2025
                    ost->logfile = NULL;
2026
                }
2027
                fifo_free(&ost->fifo); /* works even if fifo is not
2028
                                          initialized but set to zero */
2029
                av_free(ost->pict_tmp.data[0]);
2030
                if (ost->video_resample)
2031
                    sws_freeContext(ost->img_resample_ctx);
2032
                if (ost->audio_resample)
2033
                    audio_resample_close(ost->resample);
2034
                av_free(ost);
2035
            }
2036
        }
2037
        av_free(ost_table);
2038
    }
2039
    return ret;
2040
 fail:
2041
    ret = -ENOMEM;
2042
    goto fail1;
2043
}
2044

    
2045
#if 0
2046
int file_read(const char *filename)
2047
{
2048
    URLContext *h;
2049
    unsigned char buffer[1024];
2050
    int len, i;
2051

2052
    if (url_open(&h, filename, O_RDONLY) < 0) {
2053
        printf("could not open '%s'\n", filename);
2054
        return -1;
2055
    }
2056
    for(;;) {
2057
        len = url_read(h, buffer, sizeof(buffer));
2058
        if (len <= 0)
2059
            break;
2060
        for(i=0;i<len;i++) putchar(buffer[i]);
2061
    }
2062
    url_close(h);
2063
    return 0;
2064
}
2065
#endif
2066

    
2067
static void opt_image_format(const char *arg)
2068
{
2069
    AVImageFormat *f;
2070

    
2071
    for(f = first_image_format; f != NULL; f = f->next) {
2072
        if (!strcmp(arg, f->name))
2073
            break;
2074
    }
2075
    if (!f) {
2076
        fprintf(stderr, "Unknown image format: '%s'\n", arg);
2077
        exit(1);
2078
    }
2079
    image_format = f;
2080
}
2081

    
2082
static void opt_format(const char *arg)
2083
{
2084
    /* compatibility stuff for pgmyuv */
2085
    if (!strcmp(arg, "pgmyuv")) {
2086
        pgmyuv_compatibility_hack=1;
2087
//        opt_image_format(arg);
2088
        arg = "image2";
2089
    }
2090

    
2091
    file_iformat = av_find_input_format(arg);
2092
    file_oformat = guess_format(arg, NULL, NULL);
2093
    if (!file_iformat && !file_oformat) {
2094
        fprintf(stderr, "Unknown input or output format: %s\n", arg);
2095
        exit(1);
2096
    }
2097
}
2098

    
2099
static void opt_video_rc_eq(char *arg)
2100
{
2101
    video_rc_eq = arg;
2102
}
2103

    
2104
static void opt_video_rc_override_string(char *arg)
2105
{
2106
    video_rc_override_string = arg;
2107
}
2108

    
2109

    
2110
static void opt_workaround_bugs(const char *arg)
2111
{
2112
    workaround_bugs = atoi(arg);
2113
}
2114

    
2115
static void opt_me_threshold(const char *arg)
2116
{
2117
    me_threshold = atoi(arg);
2118
}
2119

    
2120
static void opt_mb_threshold(const char *arg)
2121
{
2122
    mb_threshold = atoi(arg);
2123
}
2124

    
2125
static void opt_verbose(const char *arg)
2126
{
2127
    verbose = atoi(arg);
2128
    av_log_set_level(atoi(arg));
2129
}
2130

    
2131
static void opt_frame_rate(const char *arg)
2132
{
2133
    if (parse_frame_rate(&frame_rate, &frame_rate_base, arg) < 0) {
2134
        fprintf(stderr, "Incorrect frame rate\n");
2135
        exit(1);
2136
    }
2137
}
2138

    
2139
static void opt_frame_crop_top(const char *arg)
2140
{
2141
    frame_topBand = atoi(arg);
2142
    if (frame_topBand < 0) {
2143
        fprintf(stderr, "Incorrect top crop size\n");
2144
        exit(1);
2145
    }
2146
    if ((frame_topBand % 2) != 0) {
2147
        fprintf(stderr, "Top crop size must be a multiple of 2\n");
2148
        exit(1);
2149
    }
2150
    if ((frame_topBand) >= frame_height){
2151
        fprintf(stderr, "Vertical crop dimensions are outside the range of the original image.\nRemember to crop first and scale second.\n");
2152
        exit(1);
2153
    }
2154
    frame_height -= frame_topBand;
2155
}
2156

    
2157
static void opt_frame_crop_bottom(const char *arg)
2158
{
2159
    frame_bottomBand = atoi(arg);
2160
    if (frame_bottomBand < 0) {
2161
        fprintf(stderr, "Incorrect bottom crop size\n");
2162
        exit(1);
2163
    }
2164
    if ((frame_bottomBand % 2) != 0) {
2165
        fprintf(stderr, "Bottom crop size must be a multiple of 2\n");
2166
        exit(1);
2167
    }
2168
    if ((frame_bottomBand) >= frame_height){
2169
        fprintf(stderr, "Vertical crop dimensions are outside the range of the original image.\nRemember to crop first and scale second.\n");
2170
        exit(1);
2171
    }
2172
    frame_height -= frame_bottomBand;
2173
}
2174

    
2175
static void opt_frame_crop_left(const char *arg)
2176
{
2177
    frame_leftBand = atoi(arg);
2178
    if (frame_leftBand < 0) {
2179
        fprintf(stderr, "Incorrect left crop size\n");
2180
        exit(1);
2181
    }
2182
    if ((frame_leftBand % 2) != 0) {
2183
        fprintf(stderr, "Left crop size must be a multiple of 2\n");
2184
        exit(1);
2185
    }
2186
    if ((frame_leftBand) >= frame_width){
2187
        fprintf(stderr, "Horizontal crop dimensions are outside the range of the original image.\nRemember to crop first and scale second.\n");
2188
        exit(1);
2189
    }
2190
    frame_width -= frame_leftBand;
2191
}
2192

    
2193
static void opt_frame_crop_right(const char *arg)
2194
{
2195
    frame_rightBand = atoi(arg);
2196
    if (frame_rightBand < 0) {
2197
        fprintf(stderr, "Incorrect right crop size\n");
2198
        exit(1);
2199
    }
2200
    if ((frame_rightBand % 2) != 0) {
2201
        fprintf(stderr, "Right crop size must be a multiple of 2\n");
2202
        exit(1);
2203
    }
2204
    if ((frame_rightBand) >= frame_width){
2205
        fprintf(stderr, "Horizontal crop dimensions are outside the range of the original image.\nRemember to crop first and scale second.\n");
2206
        exit(1);
2207
    }
2208
    frame_width -= frame_rightBand;
2209
}
2210

    
2211
static void opt_frame_size(const char *arg)
2212
{
2213
    if (parse_image_size(&frame_width, &frame_height, arg) < 0) {
2214
        fprintf(stderr, "Incorrect frame size\n");
2215
        exit(1);
2216
    }
2217
    if ((frame_width % 2) != 0 || (frame_height % 2) != 0) {
2218
        fprintf(stderr, "Frame size must be a multiple of 2\n");
2219
        exit(1);
2220
    }
2221
}
2222

    
2223

    
2224
#define SCALEBITS 10
2225
#define ONE_HALF  (1 << (SCALEBITS - 1))
2226
#define FIX(x)    ((int) ((x) * (1<<SCALEBITS) + 0.5))
2227

    
2228
#define RGB_TO_Y(r, g, b) \
2229
((FIX(0.29900) * (r) + FIX(0.58700) * (g) + \
2230
  FIX(0.11400) * (b) + ONE_HALF) >> SCALEBITS)
2231

    
2232
#define RGB_TO_U(r1, g1, b1, shift)\
2233
(((- FIX(0.16874) * r1 - FIX(0.33126) * g1 +         \
2234
     FIX(0.50000) * b1 + (ONE_HALF << shift) - 1) >> (SCALEBITS + shift)) + 128)
2235

    
2236
#define RGB_TO_V(r1, g1, b1, shift)\
2237
(((FIX(0.50000) * r1 - FIX(0.41869) * g1 -           \
2238
   FIX(0.08131) * b1 + (ONE_HALF << shift) - 1) >> (SCALEBITS + shift)) + 128)
2239

    
2240
static void opt_pad_color(const char *arg) {
2241
    /* Input is expected to be six hex digits similar to
2242
       how colors are expressed in html tags (but without the #) */
2243
    int rgb = strtol(arg, NULL, 16);
2244
    int r,g,b;
2245

    
2246
    r = (rgb >> 16);
2247
    g = ((rgb >> 8) & 255);
2248
    b = (rgb & 255);
2249

    
2250
    padcolor[0] = RGB_TO_Y(r,g,b);
2251
    padcolor[1] = RGB_TO_U(r,g,b,0);
2252
    padcolor[2] = RGB_TO_V(r,g,b,0);
2253
}
2254

    
2255
static void opt_frame_pad_top(const char *arg)
2256
{
2257
    frame_padtop = atoi(arg);
2258
    if (frame_padtop < 0) {
2259
        fprintf(stderr, "Incorrect top pad size\n");
2260
        exit(1);
2261
    }
2262
    if ((frame_padtop % 2) != 0) {
2263
        fprintf(stderr, "Top pad size must be a multiple of 2\n");
2264
        exit(1);
2265
    }
2266
}
2267

    
2268
static void opt_frame_pad_bottom(const char *arg)
2269
{
2270
    frame_padbottom = atoi(arg);
2271
    if (frame_padbottom < 0) {
2272
        fprintf(stderr, "Incorrect bottom pad size\n");
2273
        exit(1);
2274
    }
2275
    if ((frame_padbottom % 2) != 0) {
2276
        fprintf(stderr, "Bottom pad size must be a multiple of 2\n");
2277
        exit(1);
2278
    }
2279
}
2280

    
2281

    
2282
static void opt_frame_pad_left(const char *arg)
2283
{
2284
    frame_padleft = atoi(arg);
2285
    if (frame_padleft < 0) {
2286
        fprintf(stderr, "Incorrect left pad size\n");
2287
        exit(1);
2288
    }
2289
    if ((frame_padleft % 2) != 0) {
2290
        fprintf(stderr, "Left pad size must be a multiple of 2\n");
2291
        exit(1);
2292
    }
2293
}
2294

    
2295

    
2296
static void opt_frame_pad_right(const char *arg)
2297
{
2298
    frame_padright = atoi(arg);
2299
    if (frame_padright < 0) {
2300
        fprintf(stderr, "Incorrect right pad size\n");
2301
        exit(1);
2302
    }
2303
    if ((frame_padright % 2) != 0) {
2304
        fprintf(stderr, "Right pad size must be a multiple of 2\n");
2305
        exit(1);
2306
    }
2307
}
2308

    
2309

    
2310
static void opt_frame_pix_fmt(const char *arg)
2311
{
2312
    frame_pix_fmt = avcodec_get_pix_fmt(arg);
2313
}
2314

    
2315
static void opt_frame_aspect_ratio(const char *arg)
2316
{
2317
    int x = 0, y = 0;
2318
    double ar = 0;
2319
    const char *p;
2320

    
2321
    p = strchr(arg, ':');
2322
    if (p) {
2323
        x = strtol(arg, (char **)&arg, 10);
2324
        if (arg == p)
2325
            y = strtol(arg+1, (char **)&arg, 10);
2326
        if (x > 0 && y > 0)
2327
            ar = (double)x / (double)y;
2328
    } else
2329
        ar = strtod(arg, (char **)&arg);
2330

    
2331
    if (!ar) {
2332
        fprintf(stderr, "Incorrect aspect ratio specification.\n");
2333
        exit(1);
2334
    }
2335
    frame_aspect_ratio = ar;
2336
}
2337

    
2338
static void opt_qscale(const char *arg)
2339
{
2340
    video_qscale = atof(arg);
2341
    if (video_qscale <= 0 ||
2342
        video_qscale > 255) {
2343
        fprintf(stderr, "qscale must be > 0.0 and <= 255\n");
2344
        exit(1);
2345
    }
2346
}
2347

    
2348
static void opt_qsquish(const char *arg)
2349
{
2350
    video_qsquish = atof(arg);
2351
    if (video_qsquish < 0.0 ||
2352
        video_qsquish > 99.0) {
2353
        fprintf(stderr, "qsquish must be >= 0.0 and <= 99.0\n");
2354
        exit(1);
2355
    }
2356
}
2357

    
2358
static void opt_lmax(const char *arg)
2359
{
2360
    video_lmax = atof(arg)*FF_QP2LAMBDA;
2361
}
2362

    
2363
static void opt_lmin(const char *arg)
2364
{
2365
    video_lmin = atof(arg)*FF_QP2LAMBDA;
2366
}
2367

    
2368
static void opt_qmin(const char *arg)
2369
{
2370
    video_qmin = atoi(arg);
2371
    if (video_qmin < 1 ||
2372
        video_qmin > 51) {
2373
        fprintf(stderr, "qmin must be >= 1 and <= 51\n");
2374
        exit(1);
2375
    }
2376
}
2377

    
2378
static void opt_qmax(const char *arg)
2379
{
2380
    video_qmax = atoi(arg);
2381
    if (video_qmax < 1 ||
2382
        video_qmax > 51) {
2383
        fprintf(stderr, "qmax must be >= 1 and <= 51\n");
2384
        exit(1);
2385
    }
2386
}
2387

    
2388
static void opt_mb_lmin(const char *arg)
2389
{
2390
    video_mb_lmin = atof(arg)*FF_QP2LAMBDA;
2391
    if (video_mb_lmin < 1 ||
2392
        video_mb_lmin > FF_LAMBDA_MAX) {
2393
        fprintf(stderr, "mblmin must be >= 1 and <= %d\n", FF_LAMBDA_MAX / FF_QP2LAMBDA);
2394
        exit(1);
2395
    }
2396
}
2397

    
2398
static void opt_mb_lmax(const char *arg)
2399
{
2400
    video_mb_lmax = atof(arg)*FF_QP2LAMBDA;
2401
    if (video_mb_lmax < 1 ||
2402
        video_mb_lmax > FF_LAMBDA_MAX) {
2403
        fprintf(stderr, "mblmax must be >= 1 and <= %d\n", FF_LAMBDA_MAX / FF_QP2LAMBDA);
2404
        exit(1);
2405
    }
2406
}
2407

    
2408
static void opt_qdiff(const char *arg)
2409
{
2410
    video_qdiff = atoi(arg);
2411
    if (video_qdiff < 0 ||
2412
        video_qdiff > 31) {
2413
        fprintf(stderr, "qdiff must be >= 1 and <= 31\n");
2414
        exit(1);
2415
    }
2416
}
2417

    
2418
static void opt_packet_size(const char *arg)
2419
{
2420
    packet_size= atoi(arg);
2421
}
2422

    
2423
static void opt_error_rate(const char *arg)
2424
{
2425
    error_rate= atoi(arg);
2426
}
2427

    
2428
static void opt_strict(const char *arg)
2429
{
2430
    strict= atoi(arg);
2431
}
2432

    
2433
static void opt_top_field_first(const char *arg)
2434
{
2435
    top_field_first= atoi(arg);
2436
}
2437

    
2438
static void opt_sc_threshold(const char *arg)
2439
{
2440
    sc_threshold= atoi(arg);
2441
}
2442

    
2443
static void opt_thread_count(const char *arg)
2444
{
2445
    thread_count= atoi(arg);
2446
#if !defined(HAVE_THREADS)
2447
    if (verbose >= 0)
2448
        fprintf(stderr, "Warning: not compiled with thread support, using thread emulation\n");
2449
#endif
2450
}
2451

    
2452
static void opt_audio_bitrate(const char *arg)
2453
{
2454
    audio_bit_rate = atoi(arg) * 1000;
2455
}
2456

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

    
2462
static void opt_audio_channels(const char *arg)
2463
{
2464
    audio_channels = atoi(arg);
2465
}
2466

    
2467
static void opt_video_device(const char *arg)
2468
{
2469
    video_device = av_strdup(arg);
2470
}
2471

    
2472
static void opt_grab_device(const char *arg)
2473
{
2474
    grab_device = av_strdup(arg);
2475
}
2476

    
2477
static void opt_video_channel(const char *arg)
2478
{
2479
    video_channel = strtol(arg, NULL, 0);
2480
}
2481

    
2482
static void opt_video_standard(const char *arg)
2483
{
2484
    video_standard = av_strdup(arg);
2485
}
2486

    
2487
static void opt_audio_device(const char *arg)
2488
{
2489
    audio_device = av_strdup(arg);
2490
}
2491

    
2492
static void opt_codec(int *pstream_copy, int *pcodec_id,
2493
                      int codec_type, const char *arg)
2494
{
2495
    AVCodec *p;
2496

    
2497
    if (!strcmp(arg, "copy")) {
2498
        *pstream_copy = 1;
2499
    } else {
2500
        p = first_avcodec;
2501
        while (p) {
2502
            if (!strcmp(p->name, arg) && p->type == codec_type)
2503
                break;
2504
            p = p->next;
2505
        }
2506
        if (p == NULL) {
2507
            fprintf(stderr, "Unknown codec '%s'\n", arg);
2508
            exit(1);
2509
        } else {
2510
            *pcodec_id = p->id;
2511
        }
2512
    }
2513
}
2514

    
2515
static void opt_audio_codec(const char *arg)
2516
{
2517
    opt_codec(&audio_stream_copy, &audio_codec_id, CODEC_TYPE_AUDIO, arg);
2518
}
2519

    
2520
static void opt_audio_tag(const char *arg)
2521
{
2522
    char *tail;
2523
    audio_codec_tag= strtol(arg, &tail, 0);
2524

    
2525
    if(!tail || *tail)
2526
        audio_codec_tag= arg[0] + (arg[1]<<8) + (arg[2]<<16) + (arg[3]<<24);
2527
}
2528

    
2529
static void opt_video_tag(const char *arg)
2530
{
2531
    char *tail;
2532
    video_codec_tag= strtol(arg, &tail, 0);
2533

    
2534
    if(!tail || *tail)
2535
        video_codec_tag= arg[0] + (arg[1]<<8) + (arg[2]<<16) + (arg[3]<<24);
2536
}
2537

    
2538
static void add_frame_hooker(const char *arg)
2539
{
2540
    int argc = 0;
2541
    char *argv[64];
2542
    int i;
2543
    char *args = av_strdup(arg);
2544

    
2545
    using_vhook = 1;
2546

    
2547
    argv[0] = strtok(args, " ");
2548
    while (argc < 62 && (argv[++argc] = strtok(NULL, " "))) {
2549
    }
2550

    
2551
    i = frame_hook_add(argc, argv);
2552

    
2553
    if (i != 0) {
2554
        fprintf(stderr, "Failed to add video hook function: %s\n", arg);
2555
        exit(1);
2556
    }
2557
}
2558

    
2559
const char *motion_str[] = {
2560
    "zero",
2561
    "full",
2562
    "log",
2563
    "phods",
2564
    "epzs",
2565
    "x1",
2566
    "hex",
2567
    "umh",
2568
    "iter",
2569
    NULL,
2570
};
2571

    
2572
static void opt_motion_estimation(const char *arg)
2573
{
2574
    const char **p;
2575
    p = motion_str;
2576
    for(;;) {
2577
        if (!*p) {
2578
            fprintf(stderr, "Unknown motion estimation method '%s'\n", arg);
2579
            exit(1);
2580
        }
2581
        if (!strcmp(*p, arg))
2582
            break;
2583
        p++;
2584
    }
2585
    me_method = (p - motion_str) + 1;
2586
}
2587

    
2588
static void opt_video_codec(const char *arg)
2589
{
2590
    opt_codec(&video_stream_copy, &video_codec_id, CODEC_TYPE_VIDEO, arg);
2591
}
2592

    
2593
static void opt_subtitle_codec(const char *arg)
2594
{
2595
    opt_codec(&subtitle_stream_copy, &subtitle_codec_id, CODEC_TYPE_SUBTITLE, arg);
2596
}
2597

    
2598
static void opt_map(const char *arg)
2599
{
2600
    AVStreamMap *m;
2601
    const char *p;
2602

    
2603
    p = arg;
2604
    m = &stream_maps[nb_stream_maps++];
2605

    
2606
    m->file_index = strtol(arg, (char **)&p, 0);
2607
    if (*p)
2608
        p++;
2609

    
2610
    m->stream_index = strtol(p, (char **)&p, 0);
2611
    if (*p) {
2612
        p++;
2613
        m->sync_file_index = strtol(p, (char **)&p, 0);
2614
        if (*p)
2615
            p++;
2616
        m->sync_stream_index = strtol(p, (char **)&p, 0);
2617
    } else {
2618
        m->sync_file_index = m->file_index;
2619
        m->sync_stream_index = m->stream_index;
2620
    }
2621
}
2622

    
2623
static void opt_map_meta_data(const char *arg)
2624
{
2625
    AVMetaDataMap *m;
2626
    const char *p;
2627

    
2628
    p = arg;
2629
    m = &meta_data_maps[nb_meta_data_maps++];
2630

    
2631
    m->out_file = strtol(arg, (char **)&p, 0);
2632
    if (*p)
2633
        p++;
2634

    
2635
    m->in_file = strtol(p, (char **)&p, 0);
2636
}
2637

    
2638
static void opt_recording_time(const char *arg)
2639
{
2640
    recording_time = parse_date(arg, 1);
2641
}
2642

    
2643
static void opt_start_time(const char *arg)
2644
{
2645
    start_time = parse_date(arg, 1);
2646
}
2647

    
2648
static void opt_rec_timestamp(const char *arg)
2649
{
2650
    rec_timestamp = parse_date(arg, 0) / 1000000;
2651
}
2652

    
2653
static void opt_input_ts_offset(const char *arg)
2654
{
2655
    input_ts_offset = parse_date(arg, 1);
2656
}
2657

    
2658
static void opt_input_file(const char *filename)
2659
{
2660
    AVFormatContext *ic;
2661
    AVFormatParameters params, *ap = &params;
2662
    int err, i, ret, rfps, rfps_base;
2663
    int64_t timestamp;
2664

    
2665
    if (!strcmp(filename, "-"))
2666
        filename = "pipe:";
2667

    
2668
    using_stdin |= !strncmp(filename, "pipe:", 5) ||
2669
                   !strcmp( filename, "/dev/stdin" );
2670

    
2671
    /* get default parameters from command line */
2672
    ic = av_alloc_format_context();
2673

    
2674
    memset(ap, 0, sizeof(*ap));
2675
    ap->prealloced_context = 1;
2676
    ap->sample_rate = audio_sample_rate;
2677
    ap->channels = audio_channels;
2678
    ap->time_base.den = frame_rate;
2679
    ap->time_base.num = frame_rate_base;
2680
    ap->width = frame_width + frame_padleft + frame_padright;
2681
    ap->height = frame_height + frame_padtop + frame_padbottom;
2682
    ap->image_format = image_format;
2683
    ap->pix_fmt = frame_pix_fmt;
2684
    ap->device  = grab_device;
2685
    ap->channel = video_channel;
2686
    ap->standard = video_standard;
2687
    ap->video_codec_id = video_codec_id;
2688
    ap->audio_codec_id = audio_codec_id;
2689
    if(pgmyuv_compatibility_hack)
2690
        ap->video_codec_id= CODEC_ID_PGMYUV;
2691

    
2692
    for(i=0; i<opt_name_count; i++){
2693
        AVOption *opt;
2694
        double d= av_get_double(avformat_opts, opt_names[i], &opt);
2695
        if(d==d && (opt->flags&AV_OPT_FLAG_DECODING_PARAM))
2696
            av_set_double(ic, opt_names[i], d);
2697
    }
2698
    /* open the input file with generic libav function */
2699
    err = av_open_input_file(&ic, filename, file_iformat, 0, ap);
2700
    if (err < 0) {
2701
        print_error(filename, err);
2702
        exit(1);
2703
    }
2704

    
2705
    ic->loop_input = loop_input;
2706

    
2707
    /* If not enough info to get the stream parameters, we decode the
2708
       first frames to get it. (used in mpeg case for example) */
2709
    ret = av_find_stream_info(ic);
2710
    if (ret < 0 && verbose >= 0) {
2711
        fprintf(stderr, "%s: could not find codec parameters\n", filename);
2712
        exit(1);
2713
    }
2714

    
2715
    timestamp = start_time;
2716
    /* add the stream start time */
2717
    if (ic->start_time != AV_NOPTS_VALUE)
2718
        timestamp += ic->start_time;
2719

    
2720
    /* if seeking requested, we execute it */
2721
    if (start_time != 0) {
2722
        ret = av_seek_frame(ic, -1, timestamp, AVSEEK_FLAG_BACKWARD);
2723
        if (ret < 0) {
2724
            fprintf(stderr, "%s: could not seek to position %0.3f\n",
2725
                    filename, (double)timestamp / AV_TIME_BASE);
2726
        }
2727
        /* reset seek info */
2728
        start_time = 0;
2729
    }
2730

    
2731
    /* update the current parameters so that they match the one of the input stream */
2732
    for(i=0;i<ic->nb_streams;i++) {
2733
        int j;
2734
        AVCodecContext *enc = ic->streams[i]->codec;
2735
#if defined(HAVE_THREADS)
2736
        if(thread_count>1)
2737
            avcodec_thread_init(enc, thread_count);
2738
#endif
2739
        enc->thread_count= thread_count;
2740
        switch(enc->codec_type) {
2741
        case CODEC_TYPE_AUDIO:
2742
            for(j=0; j<opt_name_count; j++){
2743
                AVOption *opt;
2744
                double d= av_get_double(avctx_opts, opt_names[j], &opt);
2745
                if(d==d && (opt->flags&AV_OPT_FLAG_AUDIO_PARAM) && (opt->flags&AV_OPT_FLAG_DECODING_PARAM))
2746
                    av_set_double(enc, opt_names[j], d);
2747
            }
2748
            //fprintf(stderr, "\nInput Audio channels: %d", enc->channels);
2749
            audio_channels = enc->channels;
2750
            audio_sample_rate = enc->sample_rate;
2751
            if(audio_disable)
2752
                ic->streams[i]->discard= AVDISCARD_ALL;
2753
            break;
2754
        case CODEC_TYPE_VIDEO:
2755
            for(j=0; j<opt_name_count; j++){
2756
                AVOption *opt;
2757
                double d= av_get_double(avctx_opts, opt_names[j], &opt);
2758
                if(d==d && (opt->flags&AV_OPT_FLAG_VIDEO_PARAM) && (opt->flags&AV_OPT_FLAG_DECODING_PARAM))
2759
                    av_set_double(enc, opt_names[j], d);
2760
            }
2761
            frame_height = enc->height;
2762
            frame_width = enc->width;
2763
            frame_aspect_ratio = av_q2d(enc->sample_aspect_ratio) * enc->width / enc->height;
2764
            frame_pix_fmt = enc->pix_fmt;
2765
            rfps      = ic->streams[i]->r_frame_rate.num;
2766
            rfps_base = ic->streams[i]->r_frame_rate.den;
2767
            enc->workaround_bugs = workaround_bugs;
2768
            if(enc->lowres) enc->flags |= CODEC_FLAG_EMU_EDGE;
2769
            if(me_threshold)
2770
                enc->debug |= FF_DEBUG_MV;
2771

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

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

    
2778
                    (float)rfps / rfps_base, rfps, rfps_base);
2779
            }
2780
            /* update the current frame rate to match the stream frame rate */
2781
            frame_rate      = rfps;
2782
            frame_rate_base = rfps_base;
2783

    
2784
            enc->rate_emu = rate_emu;
2785
            if(video_disable)
2786
                ic->streams[i]->discard= AVDISCARD_ALL;
2787
            else if(video_discard)
2788
                ic->streams[i]->discard= video_discard;
2789
            break;
2790
        case CODEC_TYPE_DATA:
2791
            break;
2792
        case CODEC_TYPE_SUBTITLE:
2793
            break;
2794
        case CODEC_TYPE_UNKNOWN:
2795
            break;
2796
        default:
2797
            av_abort();
2798
        }
2799
    }
2800

    
2801
    input_files[nb_input_files] = ic;
2802
    input_files_ts_offset[nb_input_files] = input_ts_offset - (copy_ts ? 0 : timestamp);
2803
    /* dump the file content */
2804
    if (verbose >= 0)
2805
        dump_format(ic, nb_input_files, filename, 0);
2806

    
2807
    nb_input_files++;
2808
    file_iformat = NULL;
2809
    file_oformat = NULL;
2810
    image_format = NULL;
2811

    
2812
    grab_device = NULL;
2813
    video_channel = 0;
2814

    
2815
    rate_emu = 0;
2816
}
2817

    
2818
static void opt_grab(const char *arg)
2819
{
2820
    file_iformat = av_find_input_format(arg);
2821
    opt_input_file("");
2822
}
2823

    
2824
static void check_audio_video_inputs(int *has_video_ptr, int *has_audio_ptr)
2825
{
2826
    int has_video, has_audio, i, j;
2827
    AVFormatContext *ic;
2828

    
2829
    has_video = 0;
2830
    has_audio = 0;
2831
    for(j=0;j<nb_input_files;j++) {
2832
        ic = input_files[j];
2833
        for(i=0;i<ic->nb_streams;i++) {
2834
            AVCodecContext *enc = ic->streams[i]->codec;
2835
            switch(enc->codec_type) {
2836
            case CODEC_TYPE_AUDIO:
2837
                has_audio = 1;
2838
                break;
2839
            case CODEC_TYPE_VIDEO:
2840
                has_video = 1;
2841
                break;
2842
            case CODEC_TYPE_DATA:
2843
            case CODEC_TYPE_UNKNOWN:
2844
            case CODEC_TYPE_SUBTITLE:
2845
                break;
2846
            default:
2847
                av_abort();
2848
            }
2849
        }
2850
    }
2851
    *has_video_ptr = has_video;
2852
    *has_audio_ptr = has_audio;
2853
}
2854

    
2855
static void new_video_stream(AVFormatContext *oc)
2856
{
2857
    AVStream *st;
2858
    AVCodecContext *video_enc;
2859
    int codec_id;
2860

    
2861
    st = av_new_stream(oc, oc->nb_streams);
2862
    if (!st) {
2863
        fprintf(stderr, "Could not alloc stream\n");
2864
        exit(1);
2865
    }
2866
    bitstream_filters[nb_output_files][oc->nb_streams - 1]= video_bitstream_filters;
2867
    video_bitstream_filters= NULL;
2868

    
2869
#if defined(HAVE_THREADS)
2870
    if(thread_count>1)
2871
        avcodec_thread_init(st->codec, thread_count);
2872
#endif
2873

    
2874
    video_enc = st->codec;
2875

    
2876
    if(video_codec_tag)
2877
        video_enc->codec_tag= video_codec_tag;
2878

    
2879
    if(   (video_global_header&1)
2880
       || (video_global_header==0 && (oc->oformat->flags & AVFMT_GLOBALHEADER))){
2881
        video_enc->flags |= CODEC_FLAG_GLOBAL_HEADER;
2882
        avctx_opts->flags|= CODEC_FLAG_GLOBAL_HEADER;
2883
    }
2884
    if(video_global_header&2){
2885
        video_enc->flags2 |= CODEC_FLAG2_LOCAL_HEADER;
2886
        avctx_opts->flags2|= CODEC_FLAG2_LOCAL_HEADER;
2887
    }
2888

    
2889
    if (video_stream_copy) {
2890
        st->stream_copy = 1;
2891
        video_enc->codec_type = CODEC_TYPE_VIDEO;
2892
    } else {
2893
        char *p;
2894
        int i;
2895
        AVCodec *codec;
2896

    
2897
        codec_id = av_guess_codec(oc->oformat, NULL, oc->filename, NULL, CODEC_TYPE_VIDEO);
2898
        if (video_codec_id != CODEC_ID_NONE)
2899
            codec_id = video_codec_id;
2900

    
2901
        video_enc->codec_id = codec_id;
2902
        codec = avcodec_find_encoder(codec_id);
2903

    
2904
        for(i=0; i<opt_name_count; i++){
2905
             AVOption *opt;
2906
             double d= av_get_double(avctx_opts, opt_names[i], &opt);
2907
             if(d==d && (opt->flags&AV_OPT_FLAG_VIDEO_PARAM) && (opt->flags&AV_OPT_FLAG_ENCODING_PARAM))
2908
                 av_set_double(video_enc, opt_names[i], d);
2909
        }
2910

    
2911
        video_enc->time_base.den = frame_rate;
2912
        video_enc->time_base.num = frame_rate_base;
2913
        if(codec && codec->supported_framerates){
2914
            const AVRational *p= codec->supported_framerates;
2915
            AVRational req= (AVRational){frame_rate, frame_rate_base};
2916
            const AVRational *best=NULL;
2917
            AVRational best_error= (AVRational){INT_MAX, 1};
2918
            for(; p->den!=0; p++){
2919
                AVRational error= av_sub_q(req, *p);
2920
                if(error.num <0) error.num *= -1;
2921
                if(av_cmp_q(error, best_error) < 0){
2922
                    best_error= error;
2923
                    best= p;
2924
                }
2925
            }
2926
            video_enc->time_base.den= best->num;
2927
            video_enc->time_base.num= best->den;
2928
        }
2929

    
2930
        video_enc->width = frame_width + frame_padright + frame_padleft;
2931
        video_enc->height = frame_height + frame_padtop + frame_padbottom;
2932
        video_enc->sample_aspect_ratio = av_d2q(frame_aspect_ratio*video_enc->height/video_enc->width, 255);
2933
        video_enc->pix_fmt = frame_pix_fmt;
2934

    
2935
        if(codec && codec->pix_fmts){
2936
            const enum PixelFormat *p= codec->pix_fmts;
2937
            for(; *p!=-1; p++){
2938
                if(*p == video_enc->pix_fmt)
2939
                    break;
2940
            }
2941
            if(*p == -1)
2942
                video_enc->pix_fmt = codec->pix_fmts[0];
2943
        }
2944

    
2945
        if (intra_only)
2946
            video_enc->gop_size = 0;
2947
        if (video_qscale || same_quality) {
2948
            video_enc->flags |= CODEC_FLAG_QSCALE;
2949
            video_enc->global_quality=
2950
                st->quality = FF_QP2LAMBDA * video_qscale;
2951
        }
2952

    
2953
        if(intra_matrix)
2954
            video_enc->intra_matrix = intra_matrix;
2955
        if(inter_matrix)
2956
            video_enc->inter_matrix = inter_matrix;
2957

    
2958
        video_enc->qmin = video_qmin;
2959
        video_enc->qmax = video_qmax;
2960
        video_enc->lmin = video_lmin;
2961
        video_enc->lmax = video_lmax;
2962
        video_enc->rc_qsquish = video_qsquish;
2963
        video_enc->mb_lmin = video_mb_lmin;
2964
        video_enc->mb_lmax = video_mb_lmax;
2965
        video_enc->max_qdiff = video_qdiff;
2966
        video_enc->rc_eq = video_rc_eq;
2967
        video_enc->workaround_bugs = workaround_bugs;
2968
        video_enc->thread_count = thread_count;
2969
        p= video_rc_override_string;
2970
        for(i=0; p; i++){
2971
            int start, end, q;
2972
            int e=sscanf(p, "%d,%d,%d", &start, &end, &q);
2973
            if(e!=3){
2974
                fprintf(stderr, "error parsing rc_override\n");
2975
                exit(1);
2976
            }
2977
            video_enc->rc_override=
2978
                av_realloc(video_enc->rc_override,
2979
                           sizeof(RcOverride)*(i+1));
2980
            video_enc->rc_override[i].start_frame= start;
2981
            video_enc->rc_override[i].end_frame  = end;
2982
            if(q>0){
2983
                video_enc->rc_override[i].qscale= q;
2984
                video_enc->rc_override[i].quality_factor= 1.0;
2985
            }
2986
            else{
2987
                video_enc->rc_override[i].qscale= 0;
2988
                video_enc->rc_override[i].quality_factor= -q/100.0;
2989
            }
2990
            p= strchr(p, '/');
2991
            if(p) p++;
2992
        }
2993
        video_enc->rc_override_count=i;
2994
        video_enc->rc_initial_buffer_occupancy = video_enc->rc_buffer_size*3/4;
2995
        video_enc->rc_buffer_aggressivity= video_rc_buffer_aggressivity;
2996
        video_enc->me_threshold= me_threshold;
2997
        video_enc->mb_threshold= mb_threshold;
2998
        video_enc->intra_dc_precision= intra_dc_precision - 8;
2999
        video_enc->strict_std_compliance = strict;
3000
        video_enc->error_rate = error_rate;
3001
        video_enc->scenechange_threshold= sc_threshold;
3002
        video_enc->me_penalty_compensation= me_penalty_compensation;
3003
        video_enc->frame_skip_threshold= frame_skip_threshold;
3004
        video_enc->frame_skip_factor= frame_skip_factor;
3005
        video_enc->frame_skip_exp= frame_skip_exp;
3006

    
3007
        if(packet_size){
3008
            video_enc->rtp_mode= 1;
3009
            video_enc->rtp_payload_size= packet_size;
3010
        }
3011

    
3012
        if (do_psnr)
3013
            video_enc->flags|= CODEC_FLAG_PSNR;
3014

    
3015
        video_enc->me_method = me_method;
3016

    
3017
        /* two pass mode */
3018
        if (do_pass) {
3019
            if (do_pass == 1) {
3020
                video_enc->flags |= CODEC_FLAG_PASS1;
3021
            } else {
3022
                video_enc->flags |= CODEC_FLAG_PASS2;
3023
            }
3024
        }
3025
    }
3026

    
3027
    /* reset some key parameters */
3028
    video_disable = 0;
3029
    video_codec_id = CODEC_ID_NONE;
3030
    video_stream_copy = 0;
3031
}
3032

    
3033
static void new_audio_stream(AVFormatContext *oc)
3034
{
3035
    AVStream *st;
3036
    AVCodecContext *audio_enc;
3037
    int codec_id, i;
3038

    
3039
    st = av_new_stream(oc, oc->nb_streams);
3040
    if (!st) {
3041
        fprintf(stderr, "Could not alloc stream\n");
3042
        exit(1);
3043
    }
3044

    
3045
    bitstream_filters[nb_output_files][oc->nb_streams - 1]= audio_bitstream_filters;
3046
    audio_bitstream_filters= NULL;
3047

    
3048
#if defined(HAVE_THREADS)
3049
    if(thread_count>1)
3050
        avcodec_thread_init(st->codec, thread_count);
3051
#endif
3052

    
3053
    audio_enc = st->codec;
3054
    audio_enc->codec_type = CODEC_TYPE_AUDIO;
3055

    
3056
    if(audio_codec_tag)
3057
        audio_enc->codec_tag= audio_codec_tag;
3058

    
3059
    if (oc->oformat->flags & AVFMT_GLOBALHEADER) {
3060
        audio_enc->flags |= CODEC_FLAG_GLOBAL_HEADER;
3061
        avctx_opts->flags|= CODEC_FLAG_GLOBAL_HEADER;
3062
    }
3063
    if (audio_stream_copy) {
3064
        st->stream_copy = 1;
3065
        audio_enc->channels = audio_channels;
3066
    } else {
3067
        codec_id = av_guess_codec(oc->oformat, NULL, oc->filename, NULL, CODEC_TYPE_AUDIO);
3068

    
3069
        for(i=0; i<opt_name_count; i++){
3070
            AVOption *opt;
3071
            double d= av_get_double(avctx_opts, opt_names[i], &opt);
3072
            if(d==d && (opt->flags&AV_OPT_FLAG_AUDIO_PARAM) && (opt->flags&AV_OPT_FLAG_ENCODING_PARAM))
3073
                av_set_double(audio_enc, opt_names[i], d);
3074
        }
3075

    
3076
        if (audio_codec_id != CODEC_ID_NONE)
3077
            codec_id = audio_codec_id;
3078
        audio_enc->codec_id = codec_id;
3079

    
3080
        audio_enc->bit_rate = audio_bit_rate;
3081
        if (audio_qscale > QSCALE_NONE) {
3082
            audio_enc->flags |= CODEC_FLAG_QSCALE;
3083
            audio_enc->global_quality = st->quality = FF_QP2LAMBDA * audio_qscale;
3084
        }
3085
        audio_enc->strict_std_compliance = strict;
3086
        audio_enc->thread_count = thread_count;
3087
        /* For audio codecs other than AC3 or DTS we limit */
3088
        /* the number of coded channels to stereo   */
3089
        if (audio_channels > 2 && codec_id != CODEC_ID_AC3
3090
            && codec_id != CODEC_ID_DTS) {
3091
            audio_enc->channels = 2;
3092
        } else
3093
            audio_enc->channels = audio_channels;
3094
    }
3095
    audio_enc->sample_rate = audio_sample_rate;
3096
    audio_enc->time_base= (AVRational){1, audio_sample_rate};
3097
    if (audio_language) {
3098
        pstrcpy(st->language, sizeof(st->language), audio_language);
3099
        av_free(audio_language);
3100
        audio_language = NULL;
3101
    }
3102

    
3103
    /* reset some key parameters */
3104
    audio_disable = 0;
3105
    audio_codec_id = CODEC_ID_NONE;
3106
    audio_stream_copy = 0;
3107
}
3108

    
3109
static void opt_new_subtitle_stream(void)
3110
{
3111
    AVFormatContext *oc;
3112
    AVStream *st;
3113
    AVCodecContext *subtitle_enc;
3114
    int i;
3115

    
3116
    if (nb_output_files <= 0) {
3117
        fprintf(stderr, "At least one output file must be specified\n");
3118
        exit(1);
3119
    }
3120
    oc = output_files[nb_output_files - 1];
3121

    
3122
    st = av_new_stream(oc, oc->nb_streams);
3123
    if (!st) {
3124
        fprintf(stderr, "Could not alloc stream\n");
3125
        exit(1);
3126
    }
3127

    
3128
    subtitle_enc = st->codec;
3129
    subtitle_enc->codec_type = CODEC_TYPE_SUBTITLE;
3130
    if (subtitle_stream_copy) {
3131
        st->stream_copy = 1;
3132
    } else {
3133
        for(i=0; i<opt_name_count; i++){
3134
             AVOption *opt;
3135
             double d= av_get_double(avctx_opts, opt_names[i], &opt);
3136
             if(d==d && (opt->flags&AV_OPT_FLAG_SUBTITLE_PARAM) && (opt->flags&AV_OPT_FLAG_ENCODING_PARAM))
3137
                 av_set_double(subtitle_enc, opt_names[i], d);
3138
        }
3139
        subtitle_enc->codec_id = subtitle_codec_id;
3140
    }
3141

    
3142
    if (subtitle_language) {
3143
        pstrcpy(st->language, sizeof(st->language), subtitle_language);
3144
        av_free(subtitle_language);
3145
        subtitle_language = NULL;
3146
    }
3147

    
3148
    subtitle_codec_id = CODEC_ID_NONE;
3149
    subtitle_stream_copy = 0;
3150
}
3151

    
3152
static void opt_new_audio_stream(void)
3153
{
3154
    AVFormatContext *oc;
3155
    if (nb_output_files <= 0) {
3156
        fprintf(stderr, "At least one output file must be specified\n");
3157
        exit(1);
3158
    }
3159
    oc = output_files[nb_output_files - 1];
3160
    new_audio_stream(oc);
3161
}
3162

    
3163
static void opt_new_video_stream(void)
3164
{
3165
    AVFormatContext *oc;
3166
    if (nb_output_files <= 0) {
3167
        fprintf(stderr, "At least one output file must be specified\n");
3168
        exit(1);
3169
    }
3170
    oc = output_files[nb_output_files - 1];
3171
    new_video_stream(oc);
3172
}
3173

    
3174
static void opt_output_file(const char *filename)
3175
{
3176
    AVFormatContext *oc;
3177
    int use_video, use_audio, input_has_video, input_has_audio, i;
3178
    AVFormatParameters params, *ap = &params;
3179

    
3180
    if (!strcmp(filename, "-"))
3181
        filename = "pipe:";
3182

    
3183
    oc = av_alloc_format_context();
3184

    
3185
    if (!file_oformat) {
3186
        file_oformat = guess_format(NULL, filename, NULL);
3187
        if (!file_oformat) {
3188
            fprintf(stderr, "Unable for find a suitable output format for '%s'\n",
3189
                    filename);
3190
            exit(1);
3191
        }
3192
    }
3193

    
3194
    oc->oformat = file_oformat;
3195
    pstrcpy(oc->filename, sizeof(oc->filename), filename);
3196

    
3197
    if (!strcmp(file_oformat->name, "ffm") &&
3198
        strstart(filename, "http:", NULL)) {
3199
        /* special case for files sent to ffserver: we get the stream
3200
           parameters from ffserver */
3201
        if (read_ffserver_streams(oc, filename) < 0) {
3202
            fprintf(stderr, "Could not read stream parameters from '%s'\n", filename);
3203
            exit(1);
3204
        }
3205
    } else {
3206
        use_video = file_oformat->video_codec != CODEC_ID_NONE || video_stream_copy || video_codec_id != CODEC_ID_NONE;
3207
        use_audio = file_oformat->audio_codec != CODEC_ID_NONE || audio_stream_copy || audio_codec_id != CODEC_ID_NONE;
3208

    
3209
        /* disable if no corresponding type found and at least one
3210
           input file */
3211
        if (nb_input_files > 0) {
3212
            check_audio_video_inputs(&input_has_video, &input_has_audio);
3213
            if (!input_has_video)
3214
                use_video = 0;
3215
            if (!input_has_audio)
3216
                use_audio = 0;
3217
        }
3218

    
3219
        /* manual disable */
3220
        if (audio_disable) {
3221
            use_audio = 0;
3222
        }
3223
        if (video_disable) {
3224
            use_video = 0;
3225
        }
3226

    
3227
        if (use_video) {
3228
            new_video_stream(oc);
3229
        }
3230

    
3231
        if (use_audio) {
3232
            new_audio_stream(oc);
3233
        }
3234

    
3235
        if (!oc->nb_streams) {
3236
            fprintf(stderr, "No audio or video streams available\n");
3237
            exit(1);
3238
        }
3239

    
3240
        oc->timestamp = rec_timestamp;
3241

    
3242
        if (str_title)
3243
            pstrcpy(oc->title, sizeof(oc->title), str_title);
3244
        if (str_author)
3245
            pstrcpy(oc->author, sizeof(oc->author), str_author);
3246
        if (str_copyright)
3247
            pstrcpy(oc->copyright, sizeof(oc->copyright), str_copyright);
3248
        if (str_comment)
3249
            pstrcpy(oc->comment, sizeof(oc->comment), str_comment);
3250
        if (str_album)
3251
            pstrcpy(oc->album, sizeof(oc->album), str_album);
3252
    }
3253

    
3254
    output_files[nb_output_files++] = oc;
3255

    
3256
    /* check filename in case of an image number is expected */
3257
    if (oc->oformat->flags & AVFMT_NEEDNUMBER) {
3258
        if (!av_filename_number_test(oc->filename)) {
3259
            print_error(oc->filename, AVERROR_NUMEXPECTED);
3260
            exit(1);
3261
        }
3262
    }
3263

    
3264
    if (!(oc->oformat->flags & AVFMT_NOFILE)) {
3265
        /* test if it already exists to avoid loosing precious files */
3266
        if (!file_overwrite &&
3267
            (strchr(filename, ':') == NULL ||
3268
             strstart(filename, "file:", NULL))) {
3269
            if (url_exist(filename)) {
3270
                int c;
3271

    
3272
                if ( !using_stdin ) {
3273
                    fprintf(stderr,"File '%s' already exists. Overwrite ? [y/N] ", filename);
3274
                    fflush(stderr);
3275
                    c = getchar();
3276
                    if (toupper(c) != 'Y') {
3277
                        fprintf(stderr, "Not overwriting - exiting\n");
3278
                        exit(1);
3279
                    }
3280
                                }
3281
                                else {
3282
                    fprintf(stderr,"File '%s' already exists. Exiting.\n", filename);
3283
                    exit(1);
3284
                                }
3285
            }
3286
        }
3287

    
3288
        /* open the file */
3289
        if (url_fopen(&oc->pb, filename, URL_WRONLY) < 0) {
3290
            fprintf(stderr, "Could not open '%s'\n", filename);
3291
            exit(1);
3292
        }
3293
    }
3294

    
3295
    memset(ap, 0, sizeof(*ap));
3296
    ap->image_format = image_format;
3297
    if (av_set_parameters(oc, ap) < 0) {
3298
        fprintf(stderr, "%s: Invalid encoding parameters\n",
3299
                oc->filename);
3300
        exit(1);
3301
    }
3302

    
3303
    oc->preload= (int)(mux_preload*AV_TIME_BASE);
3304
    oc->max_delay= (int)(mux_max_delay*AV_TIME_BASE);
3305
    oc->loop_output = loop_output;
3306

    
3307
    for(i=0; i<opt_name_count; i++){
3308
        AVOption *opt;
3309
        double d = av_get_double(avformat_opts, opt_names[i], &opt);
3310
        if(d==d && (opt->flags&AV_OPT_FLAG_ENCODING_PARAM))
3311
            av_set_double(oc, opt_names[i], d);
3312
    }
3313

    
3314
    /* reset some options */
3315
    file_oformat = NULL;
3316
    file_iformat = NULL;
3317
    image_format = NULL;
3318
}
3319

    
3320
/* prepare dummy protocols for grab */
3321
static void prepare_grab(void)
3322
{
3323
    int has_video, has_audio, i, j;
3324
    AVFormatContext *oc;
3325
    AVFormatContext *ic;
3326
    AVFormatParameters vp1, *vp = &vp1;
3327
    AVFormatParameters ap1, *ap = &ap1;
3328

    
3329
    /* see if audio/video inputs are needed */
3330
    has_video = 0;
3331
    has_audio = 0;
3332
    memset(ap, 0, sizeof(*ap));
3333
    memset(vp, 0, sizeof(*vp));
3334
    vp->time_base.num= 1;
3335
    for(j=0;j<nb_output_files;j++) {
3336
        oc = output_files[j];
3337
        for(i=0;i<oc->nb_streams;i++) {
3338
            AVCodecContext *enc = oc->streams[i]->codec;
3339
            switch(enc->codec_type) {
3340
            case CODEC_TYPE_AUDIO:
3341
                if (enc->sample_rate > ap->sample_rate)
3342
                    ap->sample_rate = enc->sample_rate;
3343
                if (enc->channels > ap->channels)
3344
                    ap->channels = enc->channels;
3345
                has_audio = 1;
3346
                break;
3347
            case CODEC_TYPE_VIDEO:
3348
                if (enc->width > vp->width)
3349
                    vp->width = enc->width;
3350
                if (enc->height > vp->height)
3351
                    vp->height = enc->height;
3352

    
3353
                if (vp->time_base.num*(int64_t)enc->time_base.den > enc->time_base.num*(int64_t)vp->time_base.den){
3354
                    vp->time_base = enc->time_base;
3355
                    vp->width += frame_leftBand + frame_rightBand;
3356
                    vp->width -= (frame_padleft + frame_padright);
3357
                    vp->height += frame_topBand + frame_bottomBand;
3358
                    vp->height -= (frame_padtop + frame_padbottom);
3359
                }
3360
                has_video = 1;
3361
                break;
3362
            default:
3363
                av_abort();
3364
            }
3365
        }
3366
    }
3367

    
3368
    if (has_video == 0 && has_audio == 0) {
3369
        fprintf(stderr, "Output file must have at least one audio or video stream\n");
3370
        exit(1);
3371
    }
3372

    
3373
    if (has_video) {
3374
        AVInputFormat *fmt1;
3375
        fmt1 = av_find_input_format(video_grab_format);
3376
        vp->device  = video_device;
3377
        vp->channel = video_channel;
3378
        vp->standard = video_standard;
3379
        vp->pix_fmt = frame_pix_fmt;
3380
        if (av_open_input_file(&ic, "", fmt1, 0, vp) < 0) {
3381
            fprintf(stderr, "Could not find video grab device\n");
3382
            exit(1);
3383
        }
3384
        /* If not enough info to get the stream parameters, we decode the
3385
           first frames to get it. */
3386
        if ((ic->ctx_flags & AVFMTCTX_NOHEADER) && av_find_stream_info(ic) < 0) {
3387
            fprintf(stderr, "Could not find video grab parameters\n");
3388
            exit(1);
3389
        }
3390
        /* by now video grab has one stream */
3391
        ic->streams[0]->r_frame_rate.num = vp->time_base.den;
3392
        ic->streams[0]->r_frame_rate.den = vp->time_base.num;
3393
        input_files[nb_input_files] = ic;
3394

    
3395
        if (verbose >= 0)
3396
            dump_format(ic, nb_input_files, "", 0);
3397

    
3398
        nb_input_files++;
3399
    }
3400
    if (has_audio && audio_grab_format) {
3401
        AVInputFormat *fmt1;
3402
        fmt1 = av_find_input_format(audio_grab_format);
3403
        ap->device = audio_device;
3404
        if (av_open_input_file(&ic, "", fmt1, 0, ap) < 0) {
3405
            fprintf(stderr, "Could not find audio grab device\n");
3406
            exit(1);
3407
        }
3408
        input_files[nb_input_files] = ic;
3409

    
3410
        if (verbose >= 0)
3411
            dump_format(ic, nb_input_files, "", 0);
3412

    
3413
        nb_input_files++;
3414
    }
3415
}
3416

    
3417
/* same option as mencoder */
3418
static void opt_pass(const char *pass_str)
3419
{
3420
    int pass;
3421
    pass = atoi(pass_str);
3422
    if (pass != 1 && pass != 2) {
3423
        fprintf(stderr, "pass number can be only 1 or 2\n");
3424
        exit(1);
3425
    }
3426
    do_pass = pass;
3427
}
3428

    
3429
#if defined(__MINGW32__) || defined(CONFIG_OS2)
3430
static int64_t getutime(void)
3431
{
3432
  return av_gettime();
3433
}
3434
#else
3435
static int64_t getutime(void)
3436
{
3437
    struct rusage rusage;
3438

    
3439
    getrusage(RUSAGE_SELF, &rusage);
3440
    return (rusage.ru_utime.tv_sec * 1000000LL) + rusage.ru_utime.tv_usec;
3441
}
3442
#endif
3443

    
3444
#if defined(CONFIG_FFM_DEMUXER) || defined(CONFIG_FFM_MUXER)
3445
extern int ffm_nopts;
3446
#endif
3447

    
3448
static void show_formats(void)
3449
{
3450
    AVInputFormat *ifmt;
3451
    AVOutputFormat *ofmt;
3452
    AVImageFormat *image_fmt;
3453
    URLProtocol *up;
3454
    AVCodec *p, *p2;
3455
    const char **pp, *last_name;
3456

    
3457
    printf("File formats:\n");
3458
    last_name= "000";
3459
    for(;;){
3460
        int decode=0;
3461
        int encode=0;
3462
        const char *name=NULL;
3463
        const char *long_name=NULL;
3464

    
3465
        for(ofmt = first_oformat; ofmt != NULL; ofmt = ofmt->next) {
3466
            if((name == NULL || strcmp(ofmt->name, name)<0) &&
3467
                strcmp(ofmt->name, last_name)>0){
3468
                name= ofmt->name;
3469
                long_name= ofmt->long_name;
3470
                encode=1;
3471
            }
3472
        }
3473
        for(ifmt = first_iformat; ifmt != NULL; ifmt = ifmt->next) {
3474
            if((name == NULL || strcmp(ifmt->name, name)<0) &&
3475
                strcmp(ifmt->name, last_name)>0){
3476
                name= ifmt->name;
3477
                long_name= ifmt->long_name;
3478
                encode=0;
3479
            }
3480
            if(name && strcmp(ifmt->name, name)==0)
3481
                decode=1;
3482
        }
3483
        if(name==NULL)
3484
            break;
3485
        last_name= name;
3486

    
3487
        printf(
3488
            " %s%s %-15s %s\n",
3489
            decode ? "D":" ",
3490
            encode ? "E":" ",
3491
            name,
3492
            long_name ? long_name:" ");
3493
    }
3494
    printf("\n");
3495

    
3496
    printf("Image formats (filename extensions, if any, follow):\n");
3497
    for(image_fmt = first_image_format; image_fmt != NULL;
3498
        image_fmt = image_fmt->next) {
3499
        printf(
3500
            " %s%s %-6s %s\n",
3501
            image_fmt->img_read  ? "D":" ",
3502
            image_fmt->img_write ? "E":" ",
3503
            image_fmt->name,
3504
            image_fmt->extensions ? image_fmt->extensions:" ");
3505
    }
3506
    printf("\n");
3507

    
3508
    printf("Codecs:\n");
3509
    last_name= "000";
3510
    for(;;){
3511
        int decode=0;
3512
        int encode=0;
3513
        int cap=0;
3514
        const char *type_str;
3515

    
3516
        p2=NULL;
3517
        for(p = first_avcodec; p != NULL; p = p->next) {
3518
            if((p2==NULL || strcmp(p->name, p2->name)<0) &&
3519
                strcmp(p->name, last_name)>0){
3520
                p2= p;
3521
                decode= encode= cap=0;
3522
            }
3523
            if(p2 && strcmp(p->name, p2->name)==0){
3524
                if(p->decode) decode=1;
3525
                if(p->encode) encode=1;
3526
                cap |= p->capabilities;
3527
            }
3528
        }
3529
        if(p2==NULL)
3530
            break;
3531
        last_name= p2->name;
3532

    
3533
        switch(p2->type) {
3534
        case CODEC_TYPE_VIDEO:
3535
            type_str = "V";
3536
            break;
3537
        case CODEC_TYPE_AUDIO:
3538
            type_str = "A";
3539
            break;
3540
        case CODEC_TYPE_SUBTITLE:
3541
            type_str = "S";
3542
            break;
3543
        default:
3544
            type_str = "?";
3545
            break;
3546
        }
3547
        printf(
3548
            " %s%s%s%s%s%s %s",
3549
            decode ? "D": (/*p2->decoder ? "d":*/" "),
3550
            encode ? "E":" ",
3551
            type_str,
3552
            cap & CODEC_CAP_DRAW_HORIZ_BAND ? "S":" ",
3553
            cap & CODEC_CAP_DR1 ? "D":" ",
3554
            cap & CODEC_CAP_TRUNCATED ? "T":" ",
3555
            p2->name);
3556
       /* if(p2->decoder && decode==0)
3557
            printf(" use %s for decoding", p2->decoder->name);*/
3558
        printf("\n");
3559
    }
3560
    printf("\n");
3561

    
3562
    printf("Supported file protocols:\n");
3563
    for(up = first_protocol; up != NULL; up = up->next)
3564
        printf(" %s:", up->name);
3565
    printf("\n");
3566

    
3567
    printf("Frame size, frame rate abbreviations:\n ntsc pal qntsc qpal sntsc spal film ntsc-film sqcif qcif cif 4cif\n");
3568
    printf("Motion estimation methods:\n");
3569
    pp = motion_str;
3570
    while (*pp) {
3571
        printf(" %s", *pp);
3572
        if ((pp - motion_str + 1) == ME_ZERO)
3573
            printf("(fastest)");
3574
        else if ((pp - motion_str + 1) == ME_FULL)
3575
            printf("(slowest)");
3576
        else if ((pp - motion_str + 1) == ME_EPZS)
3577
            printf("(default)");
3578
        pp++;
3579
    }
3580
    printf("\n\n");
3581
    printf(
3582
"Note, the names of encoders and decoders dont always match, so there are\n"
3583
"several cases where the above table shows encoder only or decoder only entries\n"
3584
"even though both encoding and decoding are supported for example, the h263\n"
3585
"decoder corresponds to the h263 and h263p encoders, for file formats its even\n"
3586
"worse\n");
3587
    exit(1);
3588
}
3589

    
3590
static void parse_matrix_coeffs(uint16_t *dest, const char *str)
3591
{
3592
    int i;
3593
    const char *p = str;
3594
    for(i = 0;; i++) {
3595
        dest[i] = atoi(p);
3596
        if(i == 63)
3597
            break;
3598
        p = strchr(p, ',');
3599
        if(!p) {
3600
            fprintf(stderr, "Syntax error in matrix \"%s\" at coeff %d\n", str, i);
3601
            exit(1);
3602
        }
3603
        p++;
3604
    }
3605
}
3606

    
3607
static void opt_inter_matrix(const char *arg)
3608
{
3609
    inter_matrix = av_mallocz(sizeof(uint16_t) * 64);
3610
    parse_matrix_coeffs(inter_matrix, arg);
3611
}
3612

    
3613
static void opt_intra_matrix(const char *arg)
3614
{
3615
    intra_matrix = av_mallocz(sizeof(uint16_t) * 64);
3616
    parse_matrix_coeffs(intra_matrix, arg);
3617
}
3618

    
3619
static void opt_target(const char *arg)
3620
{
3621
    int norm = -1;
3622
    static const char *const frame_rates[] = {"25", "30000/1001", "24000/1001"};
3623

    
3624
    if(!strncmp(arg, "pal-", 4)) {
3625
        norm = 0;
3626
        arg += 4;
3627
    } else if(!strncmp(arg, "ntsc-", 5)) {
3628
        norm = 1;
3629
        arg += 5;
3630
    } else if(!strncmp(arg, "film-", 5)) {
3631
        norm = 2;
3632
        arg += 5;
3633
    } else {
3634
        int fr;
3635
        /* Calculate FR via float to avoid int overflow */
3636
        fr = (int)(frame_rate * 1000.0 / frame_rate_base);
3637
        if(fr == 25000) {
3638
            norm = 0;
3639
        } else if((fr == 29970) || (fr == 23976)) {
3640
            norm = 1;
3641
        } else {
3642
            /* Try to determine PAL/NTSC by peeking in the input files */
3643
            if(nb_input_files) {
3644
                int i, j;
3645
                for(j = 0; j < nb_input_files; j++) {
3646
                    for(i = 0; i < input_files[j]->nb_streams; i++) {
3647
                        AVCodecContext *c = input_files[j]->streams[i]->codec;
3648
                        if(c->codec_type != CODEC_TYPE_VIDEO)
3649
                            continue;
3650
                        fr = c->time_base.den * 1000 / c->time_base.num;
3651
                        if(fr == 25000) {
3652
                            norm = 0;
3653
                            break;
3654
                        } else if((fr == 29970) || (fr == 23976)) {
3655
                            norm = 1;
3656
                            break;
3657
                        }
3658
                    }
3659
                    if(norm >= 0)
3660
                        break;
3661
                }
3662
            }
3663
        }
3664
        if(verbose && norm >= 0)
3665
            fprintf(stderr, "Assuming %s for target.\n", norm ? "NTSC" : "PAL");
3666
    }
3667

    
3668
    if(norm < 0) {
3669
        fprintf(stderr, "Could not determine norm (PAL/NTSC/NTSC-Film) for target.\n");
3670
        fprintf(stderr, "Please prefix target with \"pal-\", \"ntsc-\" or \"film-\",\n");
3671
        fprintf(stderr, "or set a framerate with \"-r xxx\".\n");
3672
        exit(1);
3673
    }
3674

    
3675
    if(!strcmp(arg, "vcd")) {
3676

    
3677
        opt_video_codec("mpeg1video");
3678
        opt_audio_codec("mp2");
3679
        opt_format("vcd");
3680

    
3681
        opt_frame_size(norm ? "352x240" : "352x288");
3682
        opt_frame_rate(frame_rates[norm]);
3683
        opt_default("gop", norm ? "18" : "15");
3684

    
3685
        opt_default("b", "1150000");
3686
        opt_default("maxrate", "1150000");
3687
        opt_default("minrate", "1150000");
3688
        opt_default("bufsize", "327680"); // 40*1024*8;
3689

    
3690
        audio_bit_rate = 224000;
3691
        audio_sample_rate = 44100;
3692

    
3693
        opt_default("packetsize", "2324");
3694
        opt_default("muxrate", "1411200"); // 2352 * 75 * 8;
3695

    
3696
        /* We have to offset the PTS, so that it is consistent with the SCR.
3697
           SCR starts at 36000, but the first two packs contain only padding
3698
           and the first pack from the other stream, respectively, may also have
3699
           been written before.
3700
           So the real data starts at SCR 36000+3*1200. */
3701
        mux_preload= (36000+3*1200) / 90000.0; //0.44
3702
    } else if(!strcmp(arg, "svcd")) {
3703

    
3704
        opt_video_codec("mpeg2video");
3705
        opt_audio_codec("mp2");
3706
        opt_format("svcd");
3707

    
3708
        opt_frame_size(norm ? "480x480" : "480x576");
3709
        opt_frame_rate(frame_rates[norm]);
3710
        opt_default("gop", norm ? "18" : "15");
3711

    
3712
        opt_default("b", "2040000");
3713
        opt_default("maxrate", "2516000");
3714
        opt_default("minrate", "0"); //1145000;
3715
        opt_default("bufsize", "1835008"); //224*1024*8;
3716
        opt_default("flags", "+SCAN_OFFSET");
3717

    
3718

    
3719
        audio_bit_rate = 224000;
3720
        audio_sample_rate = 44100;
3721

    
3722
        opt_default("packetsize", "2324");
3723

    
3724
    } else if(!strcmp(arg, "dvd")) {
3725

    
3726
        opt_video_codec("mpeg2video");
3727
        opt_audio_codec("ac3");
3728
        opt_format("dvd");
3729

    
3730
        opt_frame_size(norm ? "720x480" : "720x576");
3731
        opt_frame_rate(frame_rates[norm]);
3732
        opt_default("gop", norm ? "18" : "15");
3733

    
3734
        opt_default("b", "6000000");
3735
        opt_default("maxrate", "9000000");
3736
        opt_default("minrate", "0"); //1500000;
3737
        opt_default("bufsize", "1835008"); //224*1024*8;
3738

    
3739
        opt_default("packetsize", "2048");  // from www.mpucoder.com: DVD sectors contain 2048 bytes of data, this is also the size of one pack.
3740
        opt_default("muxrate", "10080000"); // from mplex project: data_rate = 1260000. mux_rate = data_rate * 8
3741

    
3742
        audio_bit_rate = 448000;
3743
        audio_sample_rate = 48000;
3744

    
3745
    } else if(!strncmp(arg, "dv", 2)) {
3746

    
3747
        opt_format("dv");
3748

    
3749
        opt_frame_size(norm ? "720x480" : "720x576");
3750
        opt_frame_pix_fmt(!strncmp(arg, "dv50", 4) ? "yuv422p" :
3751
                                             (norm ? "yuv411p" : "yuv420p"));
3752
        opt_frame_rate(frame_rates[norm]);
3753

    
3754
        audio_sample_rate = 48000;
3755
        audio_channels = 2;
3756

    
3757
    } else {
3758
        fprintf(stderr, "Unknown target: %s\n", arg);
3759
        exit(1);
3760
    }
3761
}
3762

    
3763
static void opt_video_bsf(const char *arg)
3764
{
3765
    AVBitStreamFilterContext *bsfc= av_bitstream_filter_init(arg); //FIXME split name and args for filter at '='
3766
    AVBitStreamFilterContext **bsfp;
3767

    
3768
    if(!bsfc){
3769
        fprintf(stderr, "Unkown bitstream filter %s\n", arg);
3770
        exit(1);
3771
    }
3772

    
3773
    bsfp= &video_bitstream_filters;
3774
    while(*bsfp)
3775
        bsfp= &(*bsfp)->next;
3776

    
3777
    *bsfp= bsfc;
3778
}
3779

    
3780
//FIXME avoid audio - video code duplication
3781
static void opt_audio_bsf(const char *arg)
3782
{
3783
    AVBitStreamFilterContext *bsfc= av_bitstream_filter_init(arg); //FIXME split name and args for filter at '='
3784
    AVBitStreamFilterContext **bsfp;
3785

    
3786
    if(!bsfc){
3787
        fprintf(stderr, "Unkown bitstream filter %s\n", arg);
3788
        exit(1);
3789
    }
3790

    
3791
    bsfp= &audio_bitstream_filters;
3792
    while(*bsfp)
3793
        bsfp= &(*bsfp)->next;
3794

    
3795
    *bsfp= bsfc;
3796
}
3797

    
3798
static void show_version(void)
3799
{
3800
    /* TODO: add function interface to avutil and avformat */
3801
    fprintf(stderr, "ffmpeg      " FFMPEG_VERSION "\n"
3802
           "libavutil   %d\n"
3803
           "libavcodec  %d\n"
3804
           "libavformat %d\n",
3805
           LIBAVUTIL_BUILD, avcodec_build(), LIBAVFORMAT_BUILD);
3806
    exit(1);
3807
}
3808

    
3809
static int opt_default(const char *opt, const char *arg){
3810
    AVOption *o= av_set_string(avctx_opts, opt, arg);
3811
    if(!o)
3812
        o = av_set_string(avformat_opts, opt, arg);
3813
    if(!o)
3814
        return -1;
3815

    
3816
//    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));
3817

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

    
3822
#if defined(CONFIG_FFM_DEMUXER) || defined(CONFIG_FFM_MUXER)
3823
    /* disable generate of real time pts in ffm (need to be supressed anyway) */
3824
    if(avctx_opts->flags & CODEC_FLAG_BITEXACT)
3825
        ffm_nopts = 1;
3826
#endif
3827

    
3828
    if(avctx_opts->debug)
3829
        av_log_set_level(AV_LOG_DEBUG);
3830
    return 0;
3831
}
3832

    
3833
const OptionDef options[] = {
3834
    /* main options */
3835
    { "L", 0, {(void*)show_license}, "show license" },
3836
    { "h", 0, {(void*)show_help}, "show help" },
3837
    { "version", 0, {(void*)show_version}, "show version" },
3838
    { "formats", 0, {(void*)show_formats}, "show available formats, codecs, protocols, ..." },
3839
    { "f", HAS_ARG, {(void*)opt_format}, "force format", "fmt" },
3840
    { "img", HAS_ARG, {(void*)opt_image_format}, "force image format", "img_fmt" },
3841
    { "i", HAS_ARG, {(void*)opt_input_file}, "input file name", "filename" },
3842
    { "y", OPT_BOOL, {(void*)&file_overwrite}, "overwrite output files" },
3843
    { "map", HAS_ARG | OPT_EXPERT, {(void*)opt_map}, "set input stream mapping", "file:stream[:syncfile:syncstream]" },
3844
    { "map_meta_data", HAS_ARG | OPT_EXPERT, {(void*)opt_map_meta_data}, "set meta data information of outfile from infile", "outfile:infile" },
3845
    { "t", HAS_ARG, {(void*)opt_recording_time}, "set the recording time", "duration" },
3846
    { "fs", HAS_ARG | OPT_INT, {(void*)&limit_filesize}, "set the limit file size", "limit_size" }, //
3847
    { "ss", HAS_ARG, {(void*)opt_start_time}, "set the start time offset", "time_off" },
3848
    { "itsoffset", HAS_ARG, {(void*)opt_input_ts_offset}, "set the input ts offset", "time_off" },
3849
    { "title", HAS_ARG | OPT_STRING, {(void*)&str_title}, "set the title", "string" },
3850
    { "timestamp", HAS_ARG, {(void*)&opt_rec_timestamp}, "set the timestamp", "time" },
3851
    { "author", HAS_ARG | OPT_STRING, {(void*)&str_author}, "set the author", "string" },
3852
    { "copyright", HAS_ARG | OPT_STRING, {(void*)&str_copyright}, "set the copyright", "string" },
3853
    { "comment", HAS_ARG | OPT_STRING, {(void*)&str_comment}, "set the comment", "string" },
3854
    { "album", HAS_ARG | OPT_STRING, {(void*)&str_album}, "set the album", "string" },
3855
    { "benchmark", OPT_BOOL | OPT_EXPERT, {(void*)&do_benchmark},
3856
      "add timings for benchmarking" },
3857
    { "dump", OPT_BOOL | OPT_EXPERT, {(void*)&do_pkt_dump},
3858
      "dump each input packet" },
3859
    { "hex", OPT_BOOL | OPT_EXPERT, {(void*)&do_hex_dump},
3860
      "when dumping packets, also dump the payload" },
3861
    { "re", OPT_BOOL | OPT_EXPERT, {(void*)&rate_emu}, "read input at native frame rate", "" },
3862
    { "loop_input", OPT_BOOL | OPT_EXPERT, {(void*)&loop_input}, "loop (current only works with images)" },
3863
    { "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)", "" },
3864
    { "v", HAS_ARG, {(void*)opt_verbose}, "control amount of logging", "verbose" },
3865
    { "target", HAS_ARG, {(void*)opt_target}, "specify target file type (\"vcd\", \"svcd\", \"dvd\", \"dv\", \"dv50\", \"pal-vcd\", \"ntsc-svcd\", ...)", "type" },
3866
    { "threads", HAS_ARG | OPT_EXPERT, {(void*)opt_thread_count}, "thread count", "count" },
3867
    { "vsync", HAS_ARG | OPT_INT | OPT_EXPERT, {(void*)&video_sync_method}, "video sync method", "" },
3868
    { "async", HAS_ARG | OPT_INT | OPT_EXPERT, {(void*)&audio_sync_method}, "audio sync method", "" },
3869
    { "vglobal", HAS_ARG | OPT_INT | OPT_EXPERT, {(void*)&video_global_header}, "video global header storage type", "" },
3870
    { "copyts", OPT_BOOL | OPT_EXPERT, {(void*)&copy_ts}, "copy timestamps" },
3871
    { "shortest", OPT_BOOL | OPT_EXPERT, {(void*)&opt_shortest}, "finish encoding within shortest input" }, //
3872
    { "dts_delta_threshold", HAS_ARG | OPT_INT | OPT_EXPERT, {(void*)&dts_delta_threshold}, "timestamp discontinuity delta threshold", "" },
3873

    
3874
    /* video options */
3875
    { "vframes", OPT_INT | HAS_ARG | OPT_VIDEO, {(void*)&max_frames[CODEC_TYPE_VIDEO]}, "set the number of video frames to record", "number" },
3876
    { "aframes", OPT_INT | HAS_ARG | OPT_AUDIO, {(void*)&max_frames[CODEC_TYPE_AUDIO]}, "set the number of audio frames to record", "number" },
3877
    { "dframes", OPT_INT | HAS_ARG, {(void*)&max_frames[CODEC_TYPE_DATA]}, "set the number of data frames to record", "number" },
3878
    { "r", HAS_ARG | OPT_VIDEO, {(void*)opt_frame_rate}, "set frame rate (Hz value, fraction or abbreviation)", "rate" },
3879
    { "s", HAS_ARG | OPT_VIDEO, {(void*)opt_frame_size}, "set frame size (WxH or abbreviation)", "size" },
3880
    { "aspect", HAS_ARG | OPT_VIDEO, {(void*)opt_frame_aspect_ratio}, "set aspect ratio (4:3, 16:9 or 1.3333, 1.7777)", "aspect" },
3881
    { "pix_fmt", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_frame_pix_fmt}, "set pixel format", "format" },
3882
    { "croptop", HAS_ARG | OPT_VIDEO, {(void*)opt_frame_crop_top}, "set top crop band size (in pixels)", "size" },
3883
    { "cropbottom", HAS_ARG | OPT_VIDEO, {(void*)opt_frame_crop_bottom}, "set bottom crop band size (in pixels)", "size" },
3884
    { "cropleft", HAS_ARG | OPT_VIDEO, {(void*)opt_frame_crop_left}, "set left crop band size (in pixels)", "size" },
3885
    { "cropright", HAS_ARG | OPT_VIDEO, {(void*)opt_frame_crop_right}, "set right crop band size (in pixels)", "size" },
3886
    { "padtop", HAS_ARG | OPT_VIDEO, {(void*)opt_frame_pad_top}, "set top pad band size (in pixels)", "size" },
3887
    { "padbottom", HAS_ARG | OPT_VIDEO, {(void*)opt_frame_pad_bottom}, "set bottom pad band size (in pixels)", "size" },
3888
    { "padleft", HAS_ARG | OPT_VIDEO, {(void*)opt_frame_pad_left}, "set left pad band size (in pixels)", "size" },
3889
    { "padright", HAS_ARG | OPT_VIDEO, {(void*)opt_frame_pad_right}, "set right pad band size (in pixels)", "size" },
3890
    { "padcolor", HAS_ARG | OPT_VIDEO, {(void*)opt_pad_color}, "set color of pad bands (Hex 000000 thru FFFFFF)", "color" },
3891
    { "intra", OPT_BOOL | OPT_EXPERT | OPT_VIDEO, {(void*)&intra_only}, "use only intra frames"},
3892
    { "vn", OPT_BOOL | OPT_VIDEO, {(void*)&video_disable}, "disable video" },
3893
    { "vdt", OPT_INT | HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)&video_discard}, "discard threshold", "n" },
3894
    { "qscale", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_qscale}, "use fixed video quantiser scale (VBR)", "q" },
3895
    { "qmin", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_qmin}, "min video quantiser scale (VBR)", "q" },
3896
    { "qmax", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_qmax}, "max video quantiser scale (VBR)", "q" },
3897
    { "lmin", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_lmin}, "min video lagrange factor (VBR)", "lambda" },
3898
    { "lmax", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_lmax}, "max video lagrange factor (VBR)", "lambda" },
3899
    { "mblmin", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_mb_lmin}, "min macroblock quantiser scale (VBR)", "q" },
3900
    { "mblmax", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_mb_lmax}, "max macroblock quantiser scale (VBR)", "q" },
3901
    { "qdiff", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_qdiff}, "max difference between the quantiser scale (VBR)", "q" },
3902
    { "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" },
3903
    { "rc_eq", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_video_rc_eq}, "set rate control equation", "equation" },
3904
    { "rc_override", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_video_rc_override_string}, "rate control override for specific intervals", "override" },
3905
    { "vcodec", HAS_ARG | OPT_VIDEO, {(void*)opt_video_codec}, "force video codec ('copy' to copy stream)", "codec" },
3906
    { "me", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_motion_estimation}, "set motion estimation method",
3907
      "method" },
3908
    { "me_threshold", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_me_threshold}, "motion estimaton threshold",  "" },
3909
    { "mb_threshold", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_mb_threshold}, "macroblock threshold",  "" },
3910
    { "bug", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_workaround_bugs}, "workaround not auto detected encoder bugs", "param" },
3911
    { "ps", HAS_ARG | OPT_EXPERT, {(void*)opt_packet_size}, "set packet size in bits", "size" },
3912
    { "error", HAS_ARG | OPT_EXPERT, {(void*)opt_error_rate}, "error rate", "rate" },
3913
    { "strict", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_strict}, "how strictly to follow the standards", "strictness" },
3914
    { "sameq", OPT_BOOL | OPT_VIDEO, {(void*)&same_quality},
3915
      "use same video quality as source (implies VBR)" },
3916
    { "pass", HAS_ARG | OPT_VIDEO, {(void*)&opt_pass}, "select the pass number (1 or 2)", "n" },
3917
    { "passlogfile", HAS_ARG | OPT_STRING | OPT_VIDEO, {(void*)&pass_logfilename}, "select two pass log file name", "file" },
3918
    { "deinterlace", OPT_BOOL | OPT_EXPERT | OPT_VIDEO, {(void*)&do_deinterlace},
3919
      "deinterlace pictures" },
3920
    { "psnr", OPT_BOOL | OPT_EXPERT | OPT_VIDEO, {(void*)&do_psnr}, "calculate PSNR of compressed frames" },
3921
    { "vstats", OPT_BOOL | OPT_EXPERT | OPT_VIDEO, {(void*)&do_vstats}, "dump video coding statistics to file" },
3922
    { "vhook", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)add_frame_hooker}, "insert video processing module", "module" },
3923
    { "intra_matrix", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_intra_matrix}, "specify intra matrix coeffs", "matrix" },
3924
    { "inter_matrix", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_inter_matrix}, "specify inter matrix coeffs", "matrix" },
3925
    { "top", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_top_field_first}, "top=1/bottom=0/auto=-1 field first", "" },
3926
    { "sc_threshold", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_sc_threshold}, "scene change threshold", "threshold" },
3927
    { "dc", OPT_INT | HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)&intra_dc_precision}, "intra_dc_precision", "precision" },
3928
    { "mepc", OPT_INT | HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)&me_penalty_compensation}, "motion estimation bitrate penalty compensation", "factor (1.0 = 256)" },
3929
    { "vtag", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_video_tag}, "force video tag/fourcc", "fourcc/tag" },
3930
    { "skip_threshold", OPT_INT | HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)&frame_skip_threshold}, "frame skip threshold", "threshold" },
3931
    { "skip_factor", OPT_INT | HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)&frame_skip_factor}, "frame skip factor", "factor" },
3932
    { "skip_exp", OPT_INT | HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)&frame_skip_exp}, "frame skip exponent", "exponent" },
3933
    { "newvideo", OPT_VIDEO, {(void*)opt_new_video_stream}, "add a new video stream to the current output stream" },
3934
    { "qphist", OPT_BOOL | OPT_EXPERT | OPT_VIDEO, { (void *)&qp_hist }, "show QP histogram" },
3935

    
3936
    /* audio options */
3937
    { "ab", HAS_ARG | OPT_AUDIO, {(void*)opt_audio_bitrate}, "set audio bitrate (in kbit/s)", "bitrate", },
3938
    { "aq", OPT_FLOAT | HAS_ARG | OPT_AUDIO, {(void*)&audio_qscale}, "set audio quality (codec-specific)", "quality", },
3939
    { "ar", HAS_ARG | OPT_AUDIO, {(void*)opt_audio_rate}, "set audio sampling rate (in Hz)", "rate" },
3940
    { "ac", HAS_ARG | OPT_AUDIO, {(void*)opt_audio_channels}, "set number of audio channels", "channels" },
3941
    { "an", OPT_BOOL | OPT_AUDIO, {(void*)&audio_disable}, "disable audio" },
3942
    { "acodec", HAS_ARG | OPT_AUDIO, {(void*)opt_audio_codec}, "force audio codec ('copy' to copy stream)", "codec" },
3943
    { "atag", HAS_ARG | OPT_EXPERT | OPT_AUDIO, {(void*)opt_audio_tag}, "force audio tag/fourcc", "fourcc/tag" },
3944
    { "vol", OPT_INT | HAS_ARG | OPT_AUDIO, {(void*)&audio_volume}, "change audio volume (256=normal)" , "volume" }, //
3945
    { "newaudio", OPT_AUDIO, {(void*)opt_new_audio_stream}, "add a new audio stream to the current output stream" },
3946
    { "alang", HAS_ARG | OPT_STRING | OPT_AUDIO, {(void *)&audio_language}, "set the ISO 639 language code (3 letters) of the current audio stream" , "code" },
3947

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

    
3953
    /* grab options */
3954
    { "vd", HAS_ARG | OPT_EXPERT | OPT_VIDEO | OPT_GRAB, {(void*)opt_video_device}, "set video grab device", "device" },
3955
    { "vc", HAS_ARG | OPT_EXPERT | OPT_VIDEO | OPT_GRAB, {(void*)opt_video_channel}, "set video grab channel (DV1394 only)", "channel" },
3956
    { "tvstd", HAS_ARG | OPT_EXPERT | OPT_VIDEO | OPT_GRAB, {(void*)opt_video_standard}, "set television standard (NTSC, PAL (SECAM))", "standard" },
3957
    { "ad", HAS_ARG | OPT_EXPERT | OPT_AUDIO | OPT_GRAB, {(void*)opt_audio_device}, "set audio device", "device" },
3958

    
3959
    /* G.2 grab options */
3960
    { "grab", HAS_ARG | OPT_EXPERT | OPT_GRAB, {(void*)opt_grab}, "request grabbing using", "format" },
3961
    { "gd", HAS_ARG | OPT_EXPERT | OPT_VIDEO | OPT_GRAB, {(void*)opt_grab_device}, "set grab device", "device" },
3962

    
3963
    /* muxer options */
3964
    { "muxdelay", OPT_FLOAT | HAS_ARG | OPT_EXPERT, {(void*)&mux_max_delay}, "set the maximum demux-decode delay", "seconds" },
3965
    { "muxpreload", OPT_FLOAT | HAS_ARG | OPT_EXPERT, {(void*)&mux_preload}, "set the initial demux-decode delay", "seconds" },
3966

    
3967
    { "absf", HAS_ARG | OPT_AUDIO | OPT_EXPERT, {(void*)opt_audio_bsf}, "", "bitstream filter" },
3968
    { "vbsf", HAS_ARG | OPT_VIDEO | OPT_EXPERT, {(void*)opt_video_bsf}, "", "bitstream filter" },
3969

    
3970
    { "default", OPT_FUNC2 | HAS_ARG | OPT_AUDIO | OPT_VIDEO | OPT_EXPERT, {(void*)opt_default}, "generic catch all option", "" },
3971
    { NULL, },
3972
};
3973

    
3974
static void show_banner(void)
3975
{
3976
    fprintf(stderr, "FFmpeg version " FFMPEG_VERSION ", Copyright (c) 2000-2004 Fabrice Bellard\n");
3977
    fprintf(stderr, "  configuration: " FFMPEG_CONFIGURATION "\n");
3978
    fprintf(stderr, "  libavutil version: " AV_STRINGIFY(LIBAVUTIL_VERSION) "\n");
3979
    fprintf(stderr, "  libavcodec version: " AV_STRINGIFY(LIBAVCODEC_VERSION) "\n");
3980
    fprintf(stderr, "  libavformat version: " AV_STRINGIFY(LIBAVFORMAT_VERSION) "\n");
3981
    fprintf(stderr, "  built on " __DATE__ " " __TIME__);
3982
#ifdef __GNUC__
3983
    fprintf(stderr, ", gcc: " __VERSION__ "\n");
3984
#else
3985
    fprintf(stderr, ", using a non-gcc compiler\n");
3986
#endif
3987
}
3988

    
3989
static void show_license(void)
3990
{
3991
    show_banner();
3992
#ifdef CONFIG_GPL
3993
    printf(
3994
    "This program is free software; you can redistribute it and/or modify\n"
3995
    "it under the terms of the GNU General Public License as published by\n"
3996
    "the Free Software Foundation; either version 2 of the License, or\n"
3997
    "(at your option) any later version.\n"
3998
    "\n"
3999
    "This program is distributed in the hope that it will be useful,\n"
4000
    "but WITHOUT ANY WARRANTY; without even the implied warranty of\n"
4001
    "MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n"
4002
    "GNU General Public License for more details.\n"
4003
    "\n"
4004
    "You should have received a copy of the GNU General Public License\n"
4005
    "along with this program; if not, write to the Free Software\n"
4006
    "Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA\n"
4007
    );
4008
#else
4009
    printf(
4010
    "This library is free software; you can redistribute it and/or\n"
4011
    "modify it under the terms of the GNU Lesser General Public\n"
4012
    "License as published by the Free Software Foundation; either\n"
4013
    "version 2 of the License, or (at your option) any later version.\n"
4014
    "\n"
4015
    "This library is distributed in the hope that it will be useful,\n"
4016
    "but WITHOUT ANY WARRANTY; without even the implied warranty of\n"
4017
    "MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n"
4018
    "Lesser General Public License for more details.\n"
4019
    "\n"
4020
    "You should have received a copy of the GNU Lesser General Public\n"
4021
    "License along with this library; if not, write to the Free Software\n"
4022
    "Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n"
4023
    );
4024
#endif
4025
    exit(1);
4026
}
4027

    
4028
static void show_help(void)
4029
{
4030
    show_banner();
4031
    printf("usage: ffmpeg [[infile options] -i infile]... {[outfile options] outfile}...\n"
4032
           "Hyper fast Audio and Video encoder\n");
4033
    printf("\n");
4034
    show_help_options(options, "Main options:\n",
4035
                      OPT_EXPERT | OPT_AUDIO | OPT_VIDEO, 0);
4036
    show_help_options(options, "\nVideo options:\n",
4037
                      OPT_EXPERT | OPT_AUDIO | OPT_VIDEO | OPT_GRAB,
4038
                      OPT_VIDEO);
4039
    show_help_options(options, "\nAdvanced Video options:\n",
4040
                      OPT_EXPERT | OPT_AUDIO | OPT_VIDEO | OPT_GRAB,
4041
                      OPT_VIDEO | OPT_EXPERT);
4042
    show_help_options(options, "\nAudio options:\n",
4043
                      OPT_EXPERT | OPT_AUDIO | OPT_VIDEO | OPT_GRAB,
4044
                      OPT_AUDIO);
4045
    show_help_options(options, "\nAdvanced Audio options:\n",
4046
                      OPT_EXPERT | OPT_AUDIO | OPT_VIDEO | OPT_GRAB,
4047
                      OPT_AUDIO | OPT_EXPERT);
4048
    show_help_options(options, "\nSubtitle options:\n",
4049
                      OPT_SUBTITLE | OPT_GRAB,
4050
                      OPT_SUBTITLE);
4051
    show_help_options(options, "\nAudio/Video grab options:\n",
4052
                      OPT_GRAB,
4053
                      OPT_GRAB);
4054
    show_help_options(options, "\nAdvanced options:\n",
4055
                      OPT_EXPERT | OPT_AUDIO | OPT_VIDEO | OPT_GRAB,
4056
                      OPT_EXPERT);
4057
    av_opt_show(avctx_opts, NULL);
4058
    av_opt_show(avformat_opts, NULL);
4059

    
4060
    exit(1);
4061
}
4062

    
4063
void parse_arg_file(const char *filename)
4064
{
4065
    opt_output_file(filename);
4066
}
4067

    
4068
int main(int argc, char **argv)
4069
{
4070
    int i;
4071
    int64_t ti;
4072

    
4073
    av_register_all();
4074

    
4075
    avctx_opts= avcodec_alloc_context();
4076
    avformat_opts = av_alloc_format_context();
4077

    
4078
    if (argc <= 1)
4079
        show_help();
4080
    else
4081
        show_banner();
4082

    
4083
    /* parse options */
4084
    parse_options(argc, argv, options);
4085

    
4086
    /* file converter / grab */
4087
    if (nb_output_files <= 0) {
4088
        fprintf(stderr, "Must supply at least one output file\n");
4089
        exit(1);
4090
    }
4091

    
4092
    if (nb_input_files == 0) {
4093
        input_sync = 1;
4094
        prepare_grab();
4095
    }
4096

    
4097
    ti = getutime();
4098
    av_encode(output_files, nb_output_files, input_files, nb_input_files,
4099
              stream_maps, nb_stream_maps);
4100
    ti = getutime() - ti;
4101
    if (do_benchmark) {
4102
        printf("bench: utime=%0.3fs\n", ti / 1000000.0);
4103
    }
4104

    
4105
    /* close files */
4106
    for(i=0;i<nb_output_files;i++) {
4107
        /* maybe av_close_output_file ??? */
4108
        AVFormatContext *s = output_files[i];
4109
        int j;
4110
        if (!(s->oformat->flags & AVFMT_NOFILE))
4111
            url_fclose(&s->pb);
4112
        for(j=0;j<s->nb_streams;j++)
4113
            av_free(s->streams[j]);
4114
        av_free(s);
4115
    }
4116
    for(i=0;i<nb_input_files;i++)
4117
        av_close_input_file(input_files[i]);
4118

    
4119
    av_free_static();
4120

    
4121
    if(intra_matrix)
4122
        av_free(intra_matrix);
4123
    if(inter_matrix)
4124
        av_free(inter_matrix);
4125

    
4126
#ifdef POWERPC_PERFORMANCE_REPORT
4127
    extern void powerpc_display_perf_report(void);
4128
    powerpc_display_perf_report();
4129
#endif /* POWERPC_PERFORMANCE_REPORT */
4130

    
4131
#ifndef __MINGW32__
4132
    if (received_sigterm) {
4133
        fprintf(stderr,
4134
            "Received signal %d: terminating.\n",
4135
            (int) received_sigterm);
4136
        exit (255);
4137
    }
4138
#endif
4139
    exit(0); /* not all OS-es handle main() return value */
4140
    return 0;
4141
}