Statistics
| Branch: | Revision:

ffmpeg / ffmpeg.c @ 6bacd250

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

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

    
160
static int subtitle_codec_id = CODEC_ID_NONE;
161
static char *subtitle_language = NULL;
162

    
163
static float mux_preload= 0.5;
164
static float mux_max_delay= 0.7;
165

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

    
192
static int rate_emu = 0;
193

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

    
208
static const char *audio_grab_format = "audio_device";
209
static char *audio_device = NULL;
210
static int audio_volume = 256;
211

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

    
225
static int pgmyuv_compatibility_hack=0;
226
static int dts_delta_threshold = 10;
227

    
228
static int sws_flags = SWS_BICUBIC;
229

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

    
235
static AVBitStreamFilterContext *video_bitstream_filters=NULL;
236
static AVBitStreamFilterContext *audio_bitstream_filters=NULL;
237
static AVBitStreamFilterContext *bitstream_filters[MAX_FILES][MAX_STREAMS];
238

    
239
#define DEFAULT_PASS_LOGFILENAME "ffmpeg2pass"
240

    
241
struct AVInputStream;
242

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

    
261
    int video_crop;
262
    int topBand;             /* cropping area sizes */
263
    int leftBand;
264

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

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

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

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

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

    
303
#ifndef __MINGW32__
304

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

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

    
313
static volatile sig_atomic_t received_sigterm = 0;
314

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

    
322
static void term_init(void)
323
{
324
    struct termios tty;
325

    
326
    tcgetattr (0, &tty);
327
    oldtty = tty;
328

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

    
338
    tcsetattr (0, TCSANOW, &tty);
339

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

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

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

    
372
        return n;
373
    }
374
    return -1;
375
}
376

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

    
382
#else
383

    
384
static volatile int received_sigterm = 0;
385

    
386
/* no interactive support */
387
static void term_exit(void)
388
{
389
}
390

    
391
static void term_init(void)
392
{
393
}
394

    
395
static int read_key(void)
396
{
397
    return 0;
398
}
399

    
400
#endif
401

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

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

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

    
423
    av_close_input_file(ic);
424
    return 0;
425
}
426

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

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

    
447
        bsfc= bsfc->next;
448
    }
449

    
450
    av_interleaved_write_frame(s, pkt);
451
}
452

    
453
#define MAX_AUDIO_PACKET_SIZE (128 * 1024)
454

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

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

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

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

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

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

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

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

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

    
540
        frame_bytes = enc->frame_size * 2 * enc->channels;
541

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

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

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

    
564
        ost->sync_opts += size_out / (2 * enc->channels);
565

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

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

    
611
    dec = ist->st->codec;
612

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

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

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

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

    
641
    frame_hook_process(picture2, dec->pix_fmt, dec->width, dec->height);
642

    
643
    if (picture != picture2)
644
        *picture = *picture2;
645
    *bufp = buf;
646
}
647

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

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

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

    
668
    enc = ost->st->codec;
669

    
670
    if (!subtitle_out) {
671
        subtitle_out = av_malloc(subtitle_out_max_size);
672
    }
673

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

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

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

    
703
static int bit_buffer_size= 1024*256;
704
static uint8_t *bit_buffer= NULL;
705

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

    
718
    avcodec_get_frame_defaults(&picture_crop_temp);
719
    avcodec_get_frame_defaults(&picture_pad_temp);
720

    
721
    enc = ost->st->codec;
722
    dec = ist->st->codec;
723

    
724
    /* by default, we output a single frame */
725
    nb_frames = 1;
726

    
727
    *frame_size = 0;
728

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
951

    
952
    oc = output_files[0];
953

    
954
    total_size = url_ftell(&oc->pb);
955

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

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

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

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

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

    
1026
        fflush(stderr);
1027
    }
1028

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

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

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

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

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

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

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

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

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

    
1187
                ist->frame++;
1188
            }
1189

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

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

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

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

    
1245
                            /* no reencoding needed : output the packet directly */
1246
                            /* force the input stream PTS */
1247

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

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

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

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

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

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

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

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

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

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

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

    
1368
    return 0;
1369
 fail_decode:
1370
    return -1;
1371
}
1372

    
1373

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1537
        codec = ost->st->codec;
1538
        icodec = ist->st->codec;
1539

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

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

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

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

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

    
1710
    if (!bit_buffer)
1711
        bit_buffer = av_malloc(bit_buffer_size);
1712
    if (!bit_buffer)
1713
        goto fail;
1714

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

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

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

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

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

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

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

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

    
1816
        out_file = output_files[out_file_index];
1817
        in_file = input_files[in_file_index];
1818

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

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

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

    
1847
    stream_no_data = 0;
1848
    key = -1;
1849

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

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

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

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

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

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

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

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

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

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

    
1956
            av_free_packet(&pkt);
1957
            goto redo;
1958
        }
1959

    
1960
    discard_packet:
1961
        av_free_packet(&pkt);
1962

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

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

    
1975
    term_exit();
1976

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

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

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

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

    
2003
    /* finished ! */
2004

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

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

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

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

    
2065
static void opt_image_format(const char *arg)
2066
{
2067
    AVImageFormat *f;
2068

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

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

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

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

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

    
2107

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

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

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

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

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

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

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

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

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

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

    
2221

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

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

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

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

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

    
2244
    r = (rgb >> 16);
2245
    g = ((rgb >> 8) & 255);
2246
    b = (rgb & 255);
2247

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

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

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

    
2279

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

    
2293

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

    
2307

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

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

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

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

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

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

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

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

    
2366
static void opt_mb_lmin(const char *arg)
2367
{
2368
    video_mb_lmin = atof(arg)*FF_QP2LAMBDA;
2369
    if (video_mb_lmin < 1 ||
2370
        video_mb_lmin > FF_LAMBDA_MAX) {
2371
        fprintf(stderr, "mblmin must be >= 1 and <= %d\n", FF_LAMBDA_MAX / FF_QP2LAMBDA);
2372
        exit(1);
2373
    }
2374
}
2375

    
2376
static void opt_mb_lmax(const char *arg)
2377
{
2378
    video_mb_lmax = atof(arg)*FF_QP2LAMBDA;
2379
    if (video_mb_lmax < 1 ||
2380
        video_mb_lmax > FF_LAMBDA_MAX) {
2381
        fprintf(stderr, "mblmax must be >= 1 and <= %d\n", FF_LAMBDA_MAX / FF_QP2LAMBDA);
2382
        exit(1);
2383
    }
2384
}
2385

    
2386
static void opt_qdiff(const char *arg)
2387
{
2388
    video_qdiff = atoi(arg);
2389
    if (video_qdiff < 0 ||
2390
        video_qdiff > 31) {
2391
        fprintf(stderr, "qdiff must be >= 1 and <= 31\n");
2392
        exit(1);
2393
    }
2394
}
2395

    
2396
static void opt_packet_size(const char *arg)
2397
{
2398
    packet_size= atoi(arg);
2399
}
2400

    
2401
static void opt_error_rate(const char *arg)
2402
{
2403
    error_rate= atoi(arg);
2404
}
2405

    
2406
static void opt_strict(const char *arg)
2407
{
2408
    strict= atoi(arg);
2409
}
2410

    
2411
static void opt_top_field_first(const char *arg)
2412
{
2413
    top_field_first= atoi(arg);
2414
}
2415

    
2416
static void opt_sc_threshold(const char *arg)
2417
{
2418
    sc_threshold= atoi(arg);
2419
}
2420

    
2421
static void opt_thread_count(const char *arg)
2422
{
2423
    thread_count= atoi(arg);
2424
#if !defined(HAVE_THREADS)
2425
    if (verbose >= 0)
2426
        fprintf(stderr, "Warning: not compiled with thread support, using thread emulation\n");
2427
#endif
2428
}
2429

    
2430
static void opt_audio_bitrate(const char *arg)
2431
{
2432
    audio_bit_rate = atoi(arg) * 1000;
2433
}
2434

    
2435
static void opt_audio_rate(const char *arg)
2436
{
2437
    audio_sample_rate = atoi(arg);
2438
}
2439

    
2440
static void opt_audio_channels(const char *arg)
2441
{
2442
    audio_channels = atoi(arg);
2443
}
2444

    
2445
static void opt_video_device(const char *arg)
2446
{
2447
    video_device = av_strdup(arg);
2448
}
2449

    
2450
static void opt_grab_device(const char *arg)
2451
{
2452
    grab_device = av_strdup(arg);
2453
}
2454

    
2455
static void opt_video_channel(const char *arg)
2456
{
2457
    video_channel = strtol(arg, NULL, 0);
2458
}
2459

    
2460
static void opt_video_standard(const char *arg)
2461
{
2462
    video_standard = av_strdup(arg);
2463
}
2464

    
2465
static void opt_audio_device(const char *arg)
2466
{
2467
    audio_device = av_strdup(arg);
2468
}
2469

    
2470
static void opt_codec(int *pstream_copy, int *pcodec_id,
2471
                      int codec_type, const char *arg)
2472
{
2473
    AVCodec *p;
2474

    
2475
    if (!strcmp(arg, "copy")) {
2476
        *pstream_copy = 1;
2477
    } else {
2478
        p = first_avcodec;
2479
        while (p) {
2480
            if (!strcmp(p->name, arg) && p->type == codec_type)
2481
                break;
2482
            p = p->next;
2483
        }
2484
        if (p == NULL) {
2485
            fprintf(stderr, "Unknown codec '%s'\n", arg);
2486
            exit(1);
2487
        } else {
2488
            *pcodec_id = p->id;
2489
        }
2490
    }
2491
}
2492

    
2493
static void opt_audio_codec(const char *arg)
2494
{
2495
    opt_codec(&audio_stream_copy, &audio_codec_id, CODEC_TYPE_AUDIO, arg);
2496
}
2497

    
2498
static void opt_audio_tag(const char *arg)
2499
{
2500
    char *tail;
2501
    audio_codec_tag= strtol(arg, &tail, 0);
2502

    
2503
    if(!tail || *tail)
2504
        audio_codec_tag= arg[0] + (arg[1]<<8) + (arg[2]<<16) + (arg[3]<<24);
2505
}
2506

    
2507
static void opt_video_tag(const char *arg)
2508
{
2509
    char *tail;
2510
    video_codec_tag= strtol(arg, &tail, 0);
2511

    
2512
    if(!tail || *tail)
2513
        video_codec_tag= arg[0] + (arg[1]<<8) + (arg[2]<<16) + (arg[3]<<24);
2514
}
2515

    
2516
static void add_frame_hooker(const char *arg)
2517
{
2518
    int argc = 0;
2519
    char *argv[64];
2520
    int i;
2521
    char *args = av_strdup(arg);
2522

    
2523
    using_vhook = 1;
2524

    
2525
    argv[0] = strtok(args, " ");
2526
    while (argc < 62 && (argv[++argc] = strtok(NULL, " "))) {
2527
    }
2528

    
2529
    i = frame_hook_add(argc, argv);
2530

    
2531
    if (i != 0) {
2532
        fprintf(stderr, "Failed to add video hook function: %s\n", arg);
2533
        exit(1);
2534
    }
2535
}
2536

    
2537
const char *motion_str[] = {
2538
    "zero",
2539
    "full",
2540
    "log",
2541
    "phods",
2542
    "epzs",
2543
    "x1",
2544
    "hex",
2545
    "umh",
2546
    "iter",
2547
    NULL,
2548
};
2549

    
2550
static void opt_motion_estimation(const char *arg)
2551
{
2552
    const char **p;
2553
    p = motion_str;
2554
    for(;;) {
2555
        if (!*p) {
2556
            fprintf(stderr, "Unknown motion estimation method '%s'\n", arg);
2557
            exit(1);
2558
        }
2559
        if (!strcmp(*p, arg))
2560
            break;
2561
        p++;
2562
    }
2563
    me_method = (p - motion_str) + 1;
2564
}
2565

    
2566
static void opt_video_codec(const char *arg)
2567
{
2568
    opt_codec(&video_stream_copy, &video_codec_id, CODEC_TYPE_VIDEO, arg);
2569
}
2570

    
2571
static void opt_subtitle_codec(const char *arg)
2572
{
2573
    opt_codec(&subtitle_stream_copy, &subtitle_codec_id, CODEC_TYPE_SUBTITLE, arg);
2574
}
2575

    
2576
static void opt_map(const char *arg)
2577
{
2578
    AVStreamMap *m;
2579
    const char *p;
2580

    
2581
    p = arg;
2582
    m = &stream_maps[nb_stream_maps++];
2583

    
2584
    m->file_index = strtol(arg, (char **)&p, 0);
2585
    if (*p)
2586
        p++;
2587

    
2588
    m->stream_index = strtol(p, (char **)&p, 0);
2589
    if (*p) {
2590
        p++;
2591
        m->sync_file_index = strtol(p, (char **)&p, 0);
2592
        if (*p)
2593
            p++;
2594
        m->sync_stream_index = strtol(p, (char **)&p, 0);
2595
    } else {
2596
        m->sync_file_index = m->file_index;
2597
        m->sync_stream_index = m->stream_index;
2598
    }
2599
}
2600

    
2601
static void opt_map_meta_data(const char *arg)
2602
{
2603
    AVMetaDataMap *m;
2604
    const char *p;
2605

    
2606
    p = arg;
2607
    m = &meta_data_maps[nb_meta_data_maps++];
2608

    
2609
    m->out_file = strtol(arg, (char **)&p, 0);
2610
    if (*p)
2611
        p++;
2612

    
2613
    m->in_file = strtol(p, (char **)&p, 0);
2614
}
2615

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

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

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

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

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

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

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

    
2649
    /* get default parameters from command line */
2650
    ic = av_alloc_format_context();
2651

    
2652
    memset(ap, 0, sizeof(*ap));
2653
    ap->prealloced_context = 1;
2654
    ap->sample_rate = audio_sample_rate;
2655
    ap->channels = audio_channels;
2656
    ap->time_base.den = frame_rate;
2657
    ap->time_base.num = frame_rate_base;
2658
    ap->width = frame_width + frame_padleft + frame_padright;
2659
    ap->height = frame_height + frame_padtop + frame_padbottom;
2660
    ap->image_format = image_format;
2661
    ap->pix_fmt = frame_pix_fmt;
2662
    ap->device  = grab_device;
2663
    ap->channel = video_channel;
2664
    ap->standard = video_standard;
2665
    ap->video_codec_id = video_codec_id;
2666
    ap->audio_codec_id = audio_codec_id;
2667
    if(pgmyuv_compatibility_hack)
2668
        ap->video_codec_id= CODEC_ID_PGMYUV;
2669

    
2670
    for(i=0; i<opt_name_count; i++){
2671
        AVOption *opt;
2672
        double d= av_get_double(avformat_opts, opt_names[i], &opt);
2673
        if(d==d && (opt->flags&AV_OPT_FLAG_DECODING_PARAM))
2674
            av_set_double(ic, opt_names[i], d);
2675
    }
2676
    /* open the input file with generic libav function */
2677
    err = av_open_input_file(&ic, filename, file_iformat, 0, ap);
2678
    if (err < 0) {
2679
        print_error(filename, err);
2680
        exit(1);
2681
    }
2682

    
2683
    ic->loop_input = loop_input;
2684

    
2685
    /* If not enough info to get the stream parameters, we decode the
2686
       first frames to get it. (used in mpeg case for example) */
2687
    ret = av_find_stream_info(ic);
2688
    if (ret < 0 && verbose >= 0) {
2689
        fprintf(stderr, "%s: could not find codec parameters\n", filename);
2690
        exit(1);
2691
    }
2692

    
2693
    timestamp = start_time;
2694
    /* add the stream start time */
2695
    if (ic->start_time != AV_NOPTS_VALUE)
2696
        timestamp += ic->start_time;
2697

    
2698
    /* if seeking requested, we execute it */
2699
    if (start_time != 0) {
2700
        ret = av_seek_frame(ic, -1, timestamp, AVSEEK_FLAG_BACKWARD);
2701
        if (ret < 0) {
2702
            fprintf(stderr, "%s: could not seek to position %0.3f\n",
2703
                    filename, (double)timestamp / AV_TIME_BASE);
2704
        }
2705
        /* reset seek info */
2706
        start_time = 0;
2707
    }
2708

    
2709
    /* update the current parameters so that they match the one of the input stream */
2710
    for(i=0;i<ic->nb_streams;i++) {
2711
        int j;
2712
        AVCodecContext *enc = ic->streams[i]->codec;
2713
#if defined(HAVE_THREADS)
2714
        if(thread_count>1)
2715
            avcodec_thread_init(enc, thread_count);
2716
#endif
2717
        enc->thread_count= thread_count;
2718
        switch(enc->codec_type) {
2719
        case CODEC_TYPE_AUDIO:
2720
            for(j=0; j<opt_name_count; j++){
2721
                AVOption *opt;
2722
                double d= av_get_double(avctx_opts, opt_names[j], &opt);
2723
                if(d==d && (opt->flags&AV_OPT_FLAG_AUDIO_PARAM) && (opt->flags&AV_OPT_FLAG_DECODING_PARAM))
2724
                    av_set_double(enc, opt_names[j], d);
2725
            }
2726
            //fprintf(stderr, "\nInput Audio channels: %d", enc->channels);
2727
            audio_channels = enc->channels;
2728
            audio_sample_rate = enc->sample_rate;
2729
            if(audio_disable)
2730
                ic->streams[i]->discard= AVDISCARD_ALL;
2731
            break;
2732
        case CODEC_TYPE_VIDEO:
2733
            for(j=0; j<opt_name_count; j++){
2734
                AVOption *opt;
2735
                double d= av_get_double(avctx_opts, opt_names[j], &opt);
2736
                if(d==d && (opt->flags&AV_OPT_FLAG_VIDEO_PARAM) && (opt->flags&AV_OPT_FLAG_DECODING_PARAM))
2737
                    av_set_double(enc, opt_names[j], d);
2738
            }
2739
            frame_height = enc->height;
2740
            frame_width = enc->width;
2741
            frame_aspect_ratio = av_q2d(enc->sample_aspect_ratio) * enc->width / enc->height;
2742
            frame_pix_fmt = enc->pix_fmt;
2743
            rfps      = ic->streams[i]->r_frame_rate.num;
2744
            rfps_base = ic->streams[i]->r_frame_rate.den;
2745
            enc->workaround_bugs = workaround_bugs;
2746
            if(enc->lowres) enc->flags |= CODEC_FLAG_EMU_EDGE;
2747
            if(me_threshold)
2748
                enc->debug |= FF_DEBUG_MV;
2749

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

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

    
2756
                    (float)rfps / rfps_base, rfps, rfps_base);
2757
            }
2758
            /* update the current frame rate to match the stream frame rate */
2759
            frame_rate      = rfps;
2760
            frame_rate_base = rfps_base;
2761

    
2762
            enc->rate_emu = rate_emu;
2763
            if(video_disable)
2764
                ic->streams[i]->discard= AVDISCARD_ALL;
2765
            else if(video_discard)
2766
                ic->streams[i]->discard= video_discard;
2767
            break;
2768
        case CODEC_TYPE_DATA:
2769
            break;
2770
        case CODEC_TYPE_SUBTITLE:
2771
            break;
2772
        case CODEC_TYPE_UNKNOWN:
2773
            break;
2774
        default:
2775
            av_abort();
2776
        }
2777
    }
2778

    
2779
    input_files[nb_input_files] = ic;
2780
    input_files_ts_offset[nb_input_files] = input_ts_offset - (copy_ts ? 0 : timestamp);
2781
    /* dump the file content */
2782
    if (verbose >= 0)
2783
        dump_format(ic, nb_input_files, filename, 0);
2784

    
2785
    nb_input_files++;
2786
    file_iformat = NULL;
2787
    file_oformat = NULL;
2788
    image_format = NULL;
2789

    
2790
    grab_device = NULL;
2791
    video_channel = 0;
2792

    
2793
    rate_emu = 0;
2794
}
2795

    
2796
static void opt_grab(const char *arg)
2797
{
2798
    file_iformat = av_find_input_format(arg);
2799
    opt_input_file("");
2800
}
2801

    
2802
static void check_audio_video_inputs(int *has_video_ptr, int *has_audio_ptr)
2803
{
2804
    int has_video, has_audio, i, j;
2805
    AVFormatContext *ic;
2806

    
2807
    has_video = 0;
2808
    has_audio = 0;
2809
    for(j=0;j<nb_input_files;j++) {
2810
        ic = input_files[j];
2811
        for(i=0;i<ic->nb_streams;i++) {
2812
            AVCodecContext *enc = ic->streams[i]->codec;
2813
            switch(enc->codec_type) {
2814
            case CODEC_TYPE_AUDIO:
2815
                has_audio = 1;
2816
                break;
2817
            case CODEC_TYPE_VIDEO:
2818
                has_video = 1;
2819
                break;
2820
            case CODEC_TYPE_DATA:
2821
            case CODEC_TYPE_UNKNOWN:
2822
            case CODEC_TYPE_SUBTITLE:
2823
                break;
2824
            default:
2825
                av_abort();
2826
            }
2827
        }
2828
    }
2829
    *has_video_ptr = has_video;
2830
    *has_audio_ptr = has_audio;
2831
}
2832

    
2833
static void new_video_stream(AVFormatContext *oc)
2834
{
2835
    AVStream *st;
2836
    AVCodecContext *video_enc;
2837
    int codec_id;
2838

    
2839
    st = av_new_stream(oc, oc->nb_streams);
2840
    if (!st) {
2841
        fprintf(stderr, "Could not alloc stream\n");
2842
        exit(1);
2843
    }
2844
    bitstream_filters[nb_output_files][oc->nb_streams - 1]= video_bitstream_filters;
2845
    video_bitstream_filters= NULL;
2846

    
2847
#if defined(HAVE_THREADS)
2848
    if(thread_count>1)
2849
        avcodec_thread_init(st->codec, thread_count);
2850
#endif
2851

    
2852
    video_enc = st->codec;
2853

    
2854
    if(video_codec_tag)
2855
        video_enc->codec_tag= video_codec_tag;
2856

    
2857
    if(   (video_global_header&1)
2858
       || (video_global_header==0 && (oc->oformat->flags & AVFMT_GLOBALHEADER))){
2859
        video_enc->flags |= CODEC_FLAG_GLOBAL_HEADER;
2860
        avctx_opts->flags|= CODEC_FLAG_GLOBAL_HEADER;
2861
    }
2862
    if(video_global_header&2){
2863
        video_enc->flags2 |= CODEC_FLAG2_LOCAL_HEADER;
2864
        avctx_opts->flags2|= CODEC_FLAG2_LOCAL_HEADER;
2865
    }
2866

    
2867
    if (video_stream_copy) {
2868
        st->stream_copy = 1;
2869
        video_enc->codec_type = CODEC_TYPE_VIDEO;
2870
    } else {
2871
        char *p;
2872
        int i;
2873
        AVCodec *codec;
2874

    
2875
        codec_id = av_guess_codec(oc->oformat, NULL, oc->filename, NULL, CODEC_TYPE_VIDEO);
2876
        if (video_codec_id != CODEC_ID_NONE)
2877
            codec_id = video_codec_id;
2878

    
2879
        video_enc->codec_id = codec_id;
2880
        codec = avcodec_find_encoder(codec_id);
2881

    
2882
        for(i=0; i<opt_name_count; i++){
2883
             AVOption *opt;
2884
             double d= av_get_double(avctx_opts, opt_names[i], &opt);
2885
             if(d==d && (opt->flags&AV_OPT_FLAG_VIDEO_PARAM) && (opt->flags&AV_OPT_FLAG_ENCODING_PARAM))
2886
                 av_set_double(video_enc, opt_names[i], d);
2887
        }
2888

    
2889
        video_enc->time_base.den = frame_rate;
2890
        video_enc->time_base.num = frame_rate_base;
2891
        if(codec && codec->supported_framerates){
2892
            const AVRational *p= codec->supported_framerates;
2893
            AVRational req= (AVRational){frame_rate, frame_rate_base};
2894
            const AVRational *best=NULL;
2895
            AVRational best_error= (AVRational){INT_MAX, 1};
2896
            for(; p->den!=0; p++){
2897
                AVRational error= av_sub_q(req, *p);
2898
                if(error.num <0) error.num *= -1;
2899
                if(av_cmp_q(error, best_error) < 0){
2900
                    best_error= error;
2901
                    best= p;
2902
                }
2903
            }
2904
            video_enc->time_base.den= best->num;
2905
            video_enc->time_base.num= best->den;
2906
        }
2907

    
2908
        video_enc->width = frame_width + frame_padright + frame_padleft;
2909
        video_enc->height = frame_height + frame_padtop + frame_padbottom;
2910
        video_enc->sample_aspect_ratio = av_d2q(frame_aspect_ratio*video_enc->height/video_enc->width, 255);
2911
        video_enc->pix_fmt = frame_pix_fmt;
2912

    
2913
        if(codec && codec->pix_fmts){
2914
            const enum PixelFormat *p= codec->pix_fmts;
2915
            for(; *p!=-1; p++){
2916
                if(*p == video_enc->pix_fmt)
2917
                    break;
2918
            }
2919
            if(*p == -1)
2920
                video_enc->pix_fmt = codec->pix_fmts[0];
2921
        }
2922

    
2923
        if (intra_only)
2924
            video_enc->gop_size = 0;
2925
        if (video_qscale || same_quality) {
2926
            video_enc->flags |= CODEC_FLAG_QSCALE;
2927
            video_enc->global_quality=
2928
                st->quality = FF_QP2LAMBDA * video_qscale;
2929
        }
2930

    
2931
        if(intra_matrix)
2932
            video_enc->intra_matrix = intra_matrix;
2933
        if(inter_matrix)
2934
            video_enc->inter_matrix = inter_matrix;
2935

    
2936
        video_enc->lmin = video_lmin;
2937
        video_enc->lmax = video_lmax;
2938
        video_enc->rc_qsquish = video_qsquish;
2939
        video_enc->mb_lmin = video_mb_lmin;
2940
        video_enc->mb_lmax = video_mb_lmax;
2941
        video_enc->max_qdiff = video_qdiff;
2942
        video_enc->rc_eq = video_rc_eq;
2943
        video_enc->workaround_bugs = workaround_bugs;
2944
        video_enc->thread_count = thread_count;
2945
        p= video_rc_override_string;
2946
        for(i=0; p; i++){
2947
            int start, end, q;
2948
            int e=sscanf(p, "%d,%d,%d", &start, &end, &q);
2949
            if(e!=3){
2950
                fprintf(stderr, "error parsing rc_override\n");
2951
                exit(1);
2952
            }
2953
            video_enc->rc_override=
2954
                av_realloc(video_enc->rc_override,
2955
                           sizeof(RcOverride)*(i+1));
2956
            video_enc->rc_override[i].start_frame= start;
2957
            video_enc->rc_override[i].end_frame  = end;
2958
            if(q>0){
2959
                video_enc->rc_override[i].qscale= q;
2960
                video_enc->rc_override[i].quality_factor= 1.0;
2961
            }
2962
            else{
2963
                video_enc->rc_override[i].qscale= 0;
2964
                video_enc->rc_override[i].quality_factor= -q/100.0;
2965
            }
2966
            p= strchr(p, '/');
2967
            if(p) p++;
2968
        }
2969
        video_enc->rc_override_count=i;
2970
        video_enc->rc_initial_buffer_occupancy = video_enc->rc_buffer_size*3/4;
2971
        video_enc->rc_buffer_aggressivity= video_rc_buffer_aggressivity;
2972
        video_enc->me_threshold= me_threshold;
2973
        video_enc->mb_threshold= mb_threshold;
2974
        video_enc->intra_dc_precision= intra_dc_precision - 8;
2975
        video_enc->strict_std_compliance = strict;
2976
        video_enc->error_rate = error_rate;
2977
        video_enc->scenechange_threshold= sc_threshold;
2978
        video_enc->me_penalty_compensation= me_penalty_compensation;
2979
        video_enc->frame_skip_threshold= frame_skip_threshold;
2980
        video_enc->frame_skip_factor= frame_skip_factor;
2981
        video_enc->frame_skip_exp= frame_skip_exp;
2982

    
2983
        if(packet_size){
2984
            video_enc->rtp_mode= 1;
2985
            video_enc->rtp_payload_size= packet_size;
2986
        }
2987

    
2988
        if (do_psnr)
2989
            video_enc->flags|= CODEC_FLAG_PSNR;
2990

    
2991
        video_enc->me_method = me_method;
2992

    
2993
        /* two pass mode */
2994
        if (do_pass) {
2995
            if (do_pass == 1) {
2996
                video_enc->flags |= CODEC_FLAG_PASS1;
2997
            } else {
2998
                video_enc->flags |= CODEC_FLAG_PASS2;
2999
            }
3000
        }
3001
    }
3002

    
3003
    /* reset some key parameters */
3004
    video_disable = 0;
3005
    video_codec_id = CODEC_ID_NONE;
3006
    video_stream_copy = 0;
3007
}
3008

    
3009
static void new_audio_stream(AVFormatContext *oc)
3010
{
3011
    AVStream *st;
3012
    AVCodecContext *audio_enc;
3013
    int codec_id, i;
3014

    
3015
    st = av_new_stream(oc, oc->nb_streams);
3016
    if (!st) {
3017
        fprintf(stderr, "Could not alloc stream\n");
3018
        exit(1);
3019
    }
3020

    
3021
    bitstream_filters[nb_output_files][oc->nb_streams - 1]= audio_bitstream_filters;
3022
    audio_bitstream_filters= NULL;
3023

    
3024
#if defined(HAVE_THREADS)
3025
    if(thread_count>1)
3026
        avcodec_thread_init(st->codec, thread_count);
3027
#endif
3028

    
3029
    audio_enc = st->codec;
3030
    audio_enc->codec_type = CODEC_TYPE_AUDIO;
3031

    
3032
    if(audio_codec_tag)
3033
        audio_enc->codec_tag= audio_codec_tag;
3034

    
3035
    if (oc->oformat->flags & AVFMT_GLOBALHEADER) {
3036
        audio_enc->flags |= CODEC_FLAG_GLOBAL_HEADER;
3037
        avctx_opts->flags|= CODEC_FLAG_GLOBAL_HEADER;
3038
    }
3039
    if (audio_stream_copy) {
3040
        st->stream_copy = 1;
3041
        audio_enc->channels = audio_channels;
3042
    } else {
3043
        codec_id = av_guess_codec(oc->oformat, NULL, oc->filename, NULL, CODEC_TYPE_AUDIO);
3044

    
3045
        for(i=0; i<opt_name_count; i++){
3046
            AVOption *opt;
3047
            double d= av_get_double(avctx_opts, opt_names[i], &opt);
3048
            if(d==d && (opt->flags&AV_OPT_FLAG_AUDIO_PARAM) && (opt->flags&AV_OPT_FLAG_ENCODING_PARAM))
3049
                av_set_double(audio_enc, opt_names[i], d);
3050
        }
3051

    
3052
        if (audio_codec_id != CODEC_ID_NONE)
3053
            codec_id = audio_codec_id;
3054
        audio_enc->codec_id = codec_id;
3055

    
3056
        audio_enc->bit_rate = audio_bit_rate;
3057
        if (audio_qscale > QSCALE_NONE) {
3058
            audio_enc->flags |= CODEC_FLAG_QSCALE;
3059
            audio_enc->global_quality = st->quality = FF_QP2LAMBDA * audio_qscale;
3060
        }
3061
        audio_enc->strict_std_compliance = strict;
3062
        audio_enc->thread_count = thread_count;
3063
        /* For audio codecs other than AC3 or DTS we limit */
3064
        /* the number of coded channels to stereo   */
3065
        if (audio_channels > 2 && codec_id != CODEC_ID_AC3
3066
            && codec_id != CODEC_ID_DTS) {
3067
            audio_enc->channels = 2;
3068
        } else
3069
            audio_enc->channels = audio_channels;
3070
    }
3071
    audio_enc->sample_rate = audio_sample_rate;
3072
    audio_enc->time_base= (AVRational){1, audio_sample_rate};
3073
    if (audio_language) {
3074
        pstrcpy(st->language, sizeof(st->language), audio_language);
3075
        av_free(audio_language);
3076
        audio_language = NULL;
3077
    }
3078

    
3079
    /* reset some key parameters */
3080
    audio_disable = 0;
3081
    audio_codec_id = CODEC_ID_NONE;
3082
    audio_stream_copy = 0;
3083
}
3084

    
3085
static void opt_new_subtitle_stream(void)
3086
{
3087
    AVFormatContext *oc;
3088
    AVStream *st;
3089
    AVCodecContext *subtitle_enc;
3090
    int i;
3091

    
3092
    if (nb_output_files <= 0) {
3093
        fprintf(stderr, "At least one output file must be specified\n");
3094
        exit(1);
3095
    }
3096
    oc = output_files[nb_output_files - 1];
3097

    
3098
    st = av_new_stream(oc, oc->nb_streams);
3099
    if (!st) {
3100
        fprintf(stderr, "Could not alloc stream\n");
3101
        exit(1);
3102
    }
3103

    
3104
    subtitle_enc = st->codec;
3105
    subtitle_enc->codec_type = CODEC_TYPE_SUBTITLE;
3106
    if (subtitle_stream_copy) {
3107
        st->stream_copy = 1;
3108
    } else {
3109
        for(i=0; i<opt_name_count; i++){
3110
             AVOption *opt;
3111
             double d= av_get_double(avctx_opts, opt_names[i], &opt);
3112
             if(d==d && (opt->flags&AV_OPT_FLAG_SUBTITLE_PARAM) && (opt->flags&AV_OPT_FLAG_ENCODING_PARAM))
3113
                 av_set_double(subtitle_enc, opt_names[i], d);
3114
        }
3115
        subtitle_enc->codec_id = subtitle_codec_id;
3116
    }
3117

    
3118
    if (subtitle_language) {
3119
        pstrcpy(st->language, sizeof(st->language), subtitle_language);
3120
        av_free(subtitle_language);
3121
        subtitle_language = NULL;
3122
    }
3123

    
3124
    subtitle_codec_id = CODEC_ID_NONE;
3125
    subtitle_stream_copy = 0;
3126
}
3127

    
3128
static void opt_new_audio_stream(void)
3129
{
3130
    AVFormatContext *oc;
3131
    if (nb_output_files <= 0) {
3132
        fprintf(stderr, "At least one output file must be specified\n");
3133
        exit(1);
3134
    }
3135
    oc = output_files[nb_output_files - 1];
3136
    new_audio_stream(oc);
3137
}
3138

    
3139
static void opt_new_video_stream(void)
3140
{
3141
    AVFormatContext *oc;
3142
    if (nb_output_files <= 0) {
3143
        fprintf(stderr, "At least one output file must be specified\n");
3144
        exit(1);
3145
    }
3146
    oc = output_files[nb_output_files - 1];
3147
    new_video_stream(oc);
3148
}
3149

    
3150
static void opt_output_file(const char *filename)
3151
{
3152
    AVFormatContext *oc;
3153
    int use_video, use_audio, input_has_video, input_has_audio, i;
3154
    AVFormatParameters params, *ap = &params;
3155

    
3156
    if (!strcmp(filename, "-"))
3157
        filename = "pipe:";
3158

    
3159
    oc = av_alloc_format_context();
3160

    
3161
    if (!file_oformat) {
3162
        file_oformat = guess_format(NULL, filename, NULL);
3163
        if (!file_oformat) {
3164
            fprintf(stderr, "Unable for find a suitable output format for '%s'\n",
3165
                    filename);
3166
            exit(1);
3167
        }
3168
    }
3169

    
3170
    oc->oformat = file_oformat;
3171
    pstrcpy(oc->filename, sizeof(oc->filename), filename);
3172

    
3173
    if (!strcmp(file_oformat->name, "ffm") &&
3174
        strstart(filename, "http:", NULL)) {
3175
        /* special case for files sent to ffserver: we get the stream
3176
           parameters from ffserver */
3177
        if (read_ffserver_streams(oc, filename) < 0) {
3178
            fprintf(stderr, "Could not read stream parameters from '%s'\n", filename);
3179
            exit(1);
3180
        }
3181
    } else {
3182
        use_video = file_oformat->video_codec != CODEC_ID_NONE || video_stream_copy || video_codec_id != CODEC_ID_NONE;
3183
        use_audio = file_oformat->audio_codec != CODEC_ID_NONE || audio_stream_copy || audio_codec_id != CODEC_ID_NONE;
3184

    
3185
        /* disable if no corresponding type found and at least one
3186
           input file */
3187
        if (nb_input_files > 0) {
3188
            check_audio_video_inputs(&input_has_video, &input_has_audio);
3189
            if (!input_has_video)
3190
                use_video = 0;
3191
            if (!input_has_audio)
3192
                use_audio = 0;
3193
        }
3194

    
3195
        /* manual disable */
3196
        if (audio_disable) {
3197
            use_audio = 0;
3198
        }
3199
        if (video_disable) {
3200
            use_video = 0;
3201
        }
3202

    
3203
        if (use_video) {
3204
            new_video_stream(oc);
3205
        }
3206

    
3207
        if (use_audio) {
3208
            new_audio_stream(oc);
3209
        }
3210

    
3211
        if (!oc->nb_streams) {
3212
            fprintf(stderr, "No audio or video streams available\n");
3213
            exit(1);
3214
        }
3215

    
3216
        oc->timestamp = rec_timestamp;
3217

    
3218
        if (str_title)
3219
            pstrcpy(oc->title, sizeof(oc->title), str_title);
3220
        if (str_author)
3221
            pstrcpy(oc->author, sizeof(oc->author), str_author);
3222
        if (str_copyright)
3223
            pstrcpy(oc->copyright, sizeof(oc->copyright), str_copyright);
3224
        if (str_comment)
3225
            pstrcpy(oc->comment, sizeof(oc->comment), str_comment);
3226
        if (str_album)
3227
            pstrcpy(oc->album, sizeof(oc->album), str_album);
3228
    }
3229

    
3230
    output_files[nb_output_files++] = oc;
3231

    
3232
    /* check filename in case of an image number is expected */
3233
    if (oc->oformat->flags & AVFMT_NEEDNUMBER) {
3234
        if (!av_filename_number_test(oc->filename)) {
3235
            print_error(oc->filename, AVERROR_NUMEXPECTED);
3236
            exit(1);
3237
        }
3238
    }
3239

    
3240
    if (!(oc->oformat->flags & AVFMT_NOFILE)) {
3241
        /* test if it already exists to avoid loosing precious files */
3242
        if (!file_overwrite &&
3243
            (strchr(filename, ':') == NULL ||
3244
             strstart(filename, "file:", NULL))) {
3245
            if (url_exist(filename)) {
3246
                int c;
3247

    
3248
                if ( !using_stdin ) {
3249
                    fprintf(stderr,"File '%s' already exists. Overwrite ? [y/N] ", filename);
3250
                    fflush(stderr);
3251
                    c = getchar();
3252
                    if (toupper(c) != 'Y') {
3253
                        fprintf(stderr, "Not overwriting - exiting\n");
3254
                        exit(1);
3255
                    }
3256
                                }
3257
                                else {
3258
                    fprintf(stderr,"File '%s' already exists. Exiting.\n", filename);
3259
                    exit(1);
3260
                                }
3261
            }
3262
        }
3263

    
3264
        /* open the file */
3265
        if (url_fopen(&oc->pb, filename, URL_WRONLY) < 0) {
3266
            fprintf(stderr, "Could not open '%s'\n", filename);
3267
            exit(1);
3268
        }
3269
    }
3270

    
3271
    memset(ap, 0, sizeof(*ap));
3272
    ap->image_format = image_format;
3273
    if (av_set_parameters(oc, ap) < 0) {
3274
        fprintf(stderr, "%s: Invalid encoding parameters\n",
3275
                oc->filename);
3276
        exit(1);
3277
    }
3278

    
3279
    oc->preload= (int)(mux_preload*AV_TIME_BASE);
3280
    oc->max_delay= (int)(mux_max_delay*AV_TIME_BASE);
3281
    oc->loop_output = loop_output;
3282

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

    
3290
    /* reset some options */
3291
    file_oformat = NULL;
3292
    file_iformat = NULL;
3293
    image_format = NULL;
3294
}
3295

    
3296
/* prepare dummy protocols for grab */
3297
static void prepare_grab(void)
3298
{
3299
    int has_video, has_audio, i, j;
3300
    AVFormatContext *oc;
3301
    AVFormatContext *ic;
3302
    AVFormatParameters vp1, *vp = &vp1;
3303
    AVFormatParameters ap1, *ap = &ap1;
3304

    
3305
    /* see if audio/video inputs are needed */
3306
    has_video = 0;
3307
    has_audio = 0;
3308
    memset(ap, 0, sizeof(*ap));
3309
    memset(vp, 0, sizeof(*vp));
3310
    vp->time_base.num= 1;
3311
    for(j=0;j<nb_output_files;j++) {
3312
        oc = output_files[j];
3313
        for(i=0;i<oc->nb_streams;i++) {
3314
            AVCodecContext *enc = oc->streams[i]->codec;
3315
            switch(enc->codec_type) {
3316
            case CODEC_TYPE_AUDIO:
3317
                if (enc->sample_rate > ap->sample_rate)
3318
                    ap->sample_rate = enc->sample_rate;
3319
                if (enc->channels > ap->channels)
3320
                    ap->channels = enc->channels;
3321
                has_audio = 1;
3322
                break;
3323
            case CODEC_TYPE_VIDEO:
3324
                if (enc->width > vp->width)
3325
                    vp->width = enc->width;
3326
                if (enc->height > vp->height)
3327
                    vp->height = enc->height;
3328

    
3329
                if (vp->time_base.num*(int64_t)enc->time_base.den > enc->time_base.num*(int64_t)vp->time_base.den){
3330
                    vp->time_base = enc->time_base;
3331
                    vp->width += frame_leftBand + frame_rightBand;
3332
                    vp->width -= (frame_padleft + frame_padright);
3333
                    vp->height += frame_topBand + frame_bottomBand;
3334
                    vp->height -= (frame_padtop + frame_padbottom);
3335
                }
3336
                has_video = 1;
3337
                break;
3338
            default:
3339
                av_abort();
3340
            }
3341
        }
3342
    }
3343

    
3344
    if (has_video == 0 && has_audio == 0) {
3345
        fprintf(stderr, "Output file must have at least one audio or video stream\n");
3346
        exit(1);
3347
    }
3348

    
3349
    if (has_video) {
3350
        AVInputFormat *fmt1;
3351
        fmt1 = av_find_input_format(video_grab_format);
3352
        vp->device  = video_device;
3353
        vp->channel = video_channel;
3354
        vp->standard = video_standard;
3355
        vp->pix_fmt = frame_pix_fmt;
3356
        if (av_open_input_file(&ic, "", fmt1, 0, vp) < 0) {
3357
            fprintf(stderr, "Could not find video grab device\n");
3358
            exit(1);
3359
        }
3360
        /* If not enough info to get the stream parameters, we decode the
3361
           first frames to get it. */
3362
        if ((ic->ctx_flags & AVFMTCTX_NOHEADER) && av_find_stream_info(ic) < 0) {
3363
            fprintf(stderr, "Could not find video grab parameters\n");
3364
            exit(1);
3365
        }
3366
        /* by now video grab has one stream */
3367
        ic->streams[0]->r_frame_rate.num = vp->time_base.den;
3368
        ic->streams[0]->r_frame_rate.den = vp->time_base.num;
3369
        input_files[nb_input_files] = ic;
3370

    
3371
        if (verbose >= 0)
3372
            dump_format(ic, nb_input_files, "", 0);
3373

    
3374
        nb_input_files++;
3375
    }
3376
    if (has_audio && audio_grab_format) {
3377
        AVInputFormat *fmt1;
3378
        fmt1 = av_find_input_format(audio_grab_format);
3379
        ap->device = audio_device;
3380
        if (av_open_input_file(&ic, "", fmt1, 0, ap) < 0) {
3381
            fprintf(stderr, "Could not find audio grab device\n");
3382
            exit(1);
3383
        }
3384
        input_files[nb_input_files] = ic;
3385

    
3386
        if (verbose >= 0)
3387
            dump_format(ic, nb_input_files, "", 0);
3388

    
3389
        nb_input_files++;
3390
    }
3391
}
3392

    
3393
/* same option as mencoder */
3394
static void opt_pass(const char *pass_str)
3395
{
3396
    int pass;
3397
    pass = atoi(pass_str);
3398
    if (pass != 1 && pass != 2) {
3399
        fprintf(stderr, "pass number can be only 1 or 2\n");
3400
        exit(1);
3401
    }
3402
    do_pass = pass;
3403
}
3404

    
3405
#if defined(__MINGW32__) || defined(CONFIG_OS2)
3406
static int64_t getutime(void)
3407
{
3408
  return av_gettime();
3409
}
3410
#else
3411
static int64_t getutime(void)
3412
{
3413
    struct rusage rusage;
3414

    
3415
    getrusage(RUSAGE_SELF, &rusage);
3416
    return (rusage.ru_utime.tv_sec * 1000000LL) + rusage.ru_utime.tv_usec;
3417
}
3418
#endif
3419

    
3420
#if defined(CONFIG_FFM_DEMUXER) || defined(CONFIG_FFM_MUXER)
3421
extern int ffm_nopts;
3422
#endif
3423

    
3424
static void show_formats(void)
3425
{
3426
    AVInputFormat *ifmt;
3427
    AVOutputFormat *ofmt;
3428
    AVImageFormat *image_fmt;
3429
    URLProtocol *up;
3430
    AVCodec *p, *p2;
3431
    const char **pp, *last_name;
3432

    
3433
    printf("File formats:\n");
3434
    last_name= "000";
3435
    for(;;){
3436
        int decode=0;
3437
        int encode=0;
3438
        const char *name=NULL;
3439
        const char *long_name=NULL;
3440

    
3441
        for(ofmt = first_oformat; ofmt != NULL; ofmt = ofmt->next) {
3442
            if((name == NULL || strcmp(ofmt->name, name)<0) &&
3443
                strcmp(ofmt->name, last_name)>0){
3444
                name= ofmt->name;
3445
                long_name= ofmt->long_name;
3446
                encode=1;
3447
            }
3448
        }
3449
        for(ifmt = first_iformat; ifmt != NULL; ifmt = ifmt->next) {
3450
            if((name == NULL || strcmp(ifmt->name, name)<0) &&
3451
                strcmp(ifmt->name, last_name)>0){
3452
                name= ifmt->name;
3453
                long_name= ifmt->long_name;
3454
                encode=0;
3455
            }
3456
            if(name && strcmp(ifmt->name, name)==0)
3457
                decode=1;
3458
        }
3459
        if(name==NULL)
3460
            break;
3461
        last_name= name;
3462

    
3463
        printf(
3464
            " %s%s %-15s %s\n",
3465
            decode ? "D":" ",
3466
            encode ? "E":" ",
3467
            name,
3468
            long_name ? long_name:" ");
3469
    }
3470
    printf("\n");
3471

    
3472
    printf("Image formats (filename extensions, if any, follow):\n");
3473
    for(image_fmt = first_image_format; image_fmt != NULL;
3474
        image_fmt = image_fmt->next) {
3475
        printf(
3476
            " %s%s %-6s %s\n",
3477
            image_fmt->img_read  ? "D":" ",
3478
            image_fmt->img_write ? "E":" ",
3479
            image_fmt->name,
3480
            image_fmt->extensions ? image_fmt->extensions:" ");
3481
    }
3482
    printf("\n");
3483

    
3484
    printf("Codecs:\n");
3485
    last_name= "000";
3486
    for(;;){
3487
        int decode=0;
3488
        int encode=0;
3489
        int cap=0;
3490
        const char *type_str;
3491

    
3492
        p2=NULL;
3493
        for(p = first_avcodec; p != NULL; p = p->next) {
3494
            if((p2==NULL || strcmp(p->name, p2->name)<0) &&
3495
                strcmp(p->name, last_name)>0){
3496
                p2= p;
3497
                decode= encode= cap=0;
3498
            }
3499
            if(p2 && strcmp(p->name, p2->name)==0){
3500
                if(p->decode) decode=1;
3501
                if(p->encode) encode=1;
3502
                cap |= p->capabilities;
3503
            }
3504
        }
3505
        if(p2==NULL)
3506
            break;
3507
        last_name= p2->name;
3508

    
3509
        switch(p2->type) {
3510
        case CODEC_TYPE_VIDEO:
3511
            type_str = "V";
3512
            break;
3513
        case CODEC_TYPE_AUDIO:
3514
            type_str = "A";
3515
            break;
3516
        case CODEC_TYPE_SUBTITLE:
3517
            type_str = "S";
3518
            break;
3519
        default:
3520
            type_str = "?";
3521
            break;
3522
        }
3523
        printf(
3524
            " %s%s%s%s%s%s %s",
3525
            decode ? "D": (/*p2->decoder ? "d":*/" "),
3526
            encode ? "E":" ",
3527
            type_str,
3528
            cap & CODEC_CAP_DRAW_HORIZ_BAND ? "S":" ",
3529
            cap & CODEC_CAP_DR1 ? "D":" ",
3530
            cap & CODEC_CAP_TRUNCATED ? "T":" ",
3531
            p2->name);
3532
       /* if(p2->decoder && decode==0)
3533
            printf(" use %s for decoding", p2->decoder->name);*/
3534
        printf("\n");
3535
    }
3536
    printf("\n");
3537

    
3538
    printf("Supported file protocols:\n");
3539
    for(up = first_protocol; up != NULL; up = up->next)
3540
        printf(" %s:", up->name);
3541
    printf("\n");
3542

    
3543
    printf("Frame size, frame rate abbreviations:\n ntsc pal qntsc qpal sntsc spal film ntsc-film sqcif qcif cif 4cif\n");
3544
    printf("Motion estimation methods:\n");
3545
    pp = motion_str;
3546
    while (*pp) {
3547
        printf(" %s", *pp);
3548
        if ((pp - motion_str + 1) == ME_ZERO)
3549
            printf("(fastest)");
3550
        else if ((pp - motion_str + 1) == ME_FULL)
3551
            printf("(slowest)");
3552
        else if ((pp - motion_str + 1) == ME_EPZS)
3553
            printf("(default)");
3554
        pp++;
3555
    }
3556
    printf("\n\n");
3557
    printf(
3558
"Note, the names of encoders and decoders dont always match, so there are\n"
3559
"several cases where the above table shows encoder only or decoder only entries\n"
3560
"even though both encoding and decoding are supported for example, the h263\n"
3561
"decoder corresponds to the h263 and h263p encoders, for file formats its even\n"
3562
"worse\n");
3563
    exit(1);
3564
}
3565

    
3566
static void parse_matrix_coeffs(uint16_t *dest, const char *str)
3567
{
3568
    int i;
3569
    const char *p = str;
3570
    for(i = 0;; i++) {
3571
        dest[i] = atoi(p);
3572
        if(i == 63)
3573
            break;
3574
        p = strchr(p, ',');
3575
        if(!p) {
3576
            fprintf(stderr, "Syntax error in matrix \"%s\" at coeff %d\n", str, i);
3577
            exit(1);
3578
        }
3579
        p++;
3580
    }
3581
}
3582

    
3583
static void opt_inter_matrix(const char *arg)
3584
{
3585
    inter_matrix = av_mallocz(sizeof(uint16_t) * 64);
3586
    parse_matrix_coeffs(inter_matrix, arg);
3587
}
3588

    
3589
static void opt_intra_matrix(const char *arg)
3590
{
3591
    intra_matrix = av_mallocz(sizeof(uint16_t) * 64);
3592
    parse_matrix_coeffs(intra_matrix, arg);
3593
}
3594

    
3595
static void opt_target(const char *arg)
3596
{
3597
    int norm = -1;
3598
    static const char *const frame_rates[] = {"25", "30000/1001", "24000/1001"};
3599

    
3600
    if(!strncmp(arg, "pal-", 4)) {
3601
        norm = 0;
3602
        arg += 4;
3603
    } else if(!strncmp(arg, "ntsc-", 5)) {
3604
        norm = 1;
3605
        arg += 5;
3606
    } else if(!strncmp(arg, "film-", 5)) {
3607
        norm = 2;
3608
        arg += 5;
3609
    } else {
3610
        int fr;
3611
        /* Calculate FR via float to avoid int overflow */
3612
        fr = (int)(frame_rate * 1000.0 / frame_rate_base);
3613
        if(fr == 25000) {
3614
            norm = 0;
3615
        } else if((fr == 29970) || (fr == 23976)) {
3616
            norm = 1;
3617
        } else {
3618
            /* Try to determine PAL/NTSC by peeking in the input files */
3619
            if(nb_input_files) {
3620
                int i, j;
3621
                for(j = 0; j < nb_input_files; j++) {
3622
                    for(i = 0; i < input_files[j]->nb_streams; i++) {
3623
                        AVCodecContext *c = input_files[j]->streams[i]->codec;
3624
                        if(c->codec_type != CODEC_TYPE_VIDEO)
3625
                            continue;
3626
                        fr = c->time_base.den * 1000 / c->time_base.num;
3627
                        if(fr == 25000) {
3628
                            norm = 0;
3629
                            break;
3630
                        } else if((fr == 29970) || (fr == 23976)) {
3631
                            norm = 1;
3632
                            break;
3633
                        }
3634
                    }
3635
                    if(norm >= 0)
3636
                        break;
3637
                }
3638
            }
3639
        }
3640
        if(verbose && norm >= 0)
3641
            fprintf(stderr, "Assuming %s for target.\n", norm ? "NTSC" : "PAL");
3642
    }
3643

    
3644
    if(norm < 0) {
3645
        fprintf(stderr, "Could not determine norm (PAL/NTSC/NTSC-Film) for target.\n");
3646
        fprintf(stderr, "Please prefix target with \"pal-\", \"ntsc-\" or \"film-\",\n");
3647
        fprintf(stderr, "or set a framerate with \"-r xxx\".\n");
3648
        exit(1);
3649
    }
3650

    
3651
    if(!strcmp(arg, "vcd")) {
3652

    
3653
        opt_video_codec("mpeg1video");
3654
        opt_audio_codec("mp2");
3655
        opt_format("vcd");
3656

    
3657
        opt_frame_size(norm ? "352x240" : "352x288");
3658
        opt_frame_rate(frame_rates[norm]);
3659
        opt_default("gop", norm ? "18" : "15");
3660

    
3661
        opt_default("b", "1150000");
3662
        opt_default("maxrate", "1150000");
3663
        opt_default("minrate", "1150000");
3664
        opt_default("bufsize", "327680"); // 40*1024*8;
3665

    
3666
        audio_bit_rate = 224000;
3667
        audio_sample_rate = 44100;
3668

    
3669
        opt_default("packetsize", "2324");
3670
        opt_default("muxrate", "1411200"); // 2352 * 75 * 8;
3671

    
3672
        /* We have to offset the PTS, so that it is consistent with the SCR.
3673
           SCR starts at 36000, but the first two packs contain only padding
3674
           and the first pack from the other stream, respectively, may also have
3675
           been written before.
3676
           So the real data starts at SCR 36000+3*1200. */
3677
        mux_preload= (36000+3*1200) / 90000.0; //0.44
3678
    } else if(!strcmp(arg, "svcd")) {
3679

    
3680
        opt_video_codec("mpeg2video");
3681
        opt_audio_codec("mp2");
3682
        opt_format("svcd");
3683

    
3684
        opt_frame_size(norm ? "480x480" : "480x576");
3685
        opt_frame_rate(frame_rates[norm]);
3686
        opt_default("gop", norm ? "18" : "15");
3687

    
3688
        opt_default("b", "2040000");
3689
        opt_default("maxrate", "2516000");
3690
        opt_default("minrate", "0"); //1145000;
3691
        opt_default("bufsize", "1835008"); //224*1024*8;
3692
        opt_default("flags", "+SCAN_OFFSET");
3693

    
3694

    
3695
        audio_bit_rate = 224000;
3696
        audio_sample_rate = 44100;
3697

    
3698
        opt_default("packetsize", "2324");
3699

    
3700
    } else if(!strcmp(arg, "dvd")) {
3701

    
3702
        opt_video_codec("mpeg2video");
3703
        opt_audio_codec("ac3");
3704
        opt_format("dvd");
3705

    
3706
        opt_frame_size(norm ? "720x480" : "720x576");
3707
        opt_frame_rate(frame_rates[norm]);
3708
        opt_default("gop", norm ? "18" : "15");
3709

    
3710
        opt_default("b", "6000000");
3711
        opt_default("maxrate", "9000000");
3712
        opt_default("minrate", "0"); //1500000;
3713
        opt_default("bufsize", "1835008"); //224*1024*8;
3714

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

    
3718
        audio_bit_rate = 448000;
3719
        audio_sample_rate = 48000;
3720

    
3721
    } else if(!strncmp(arg, "dv", 2)) {
3722

    
3723
        opt_format("dv");
3724

    
3725
        opt_frame_size(norm ? "720x480" : "720x576");
3726
        opt_frame_pix_fmt(!strncmp(arg, "dv50", 4) ? "yuv422p" :
3727
                                             (norm ? "yuv411p" : "yuv420p"));
3728
        opt_frame_rate(frame_rates[norm]);
3729

    
3730
        audio_sample_rate = 48000;
3731
        audio_channels = 2;
3732

    
3733
    } else {
3734
        fprintf(stderr, "Unknown target: %s\n", arg);
3735
        exit(1);
3736
    }
3737
}
3738

    
3739
static void opt_video_bsf(const char *arg)
3740
{
3741
    AVBitStreamFilterContext *bsfc= av_bitstream_filter_init(arg); //FIXME split name and args for filter at '='
3742
    AVBitStreamFilterContext **bsfp;
3743

    
3744
    if(!bsfc){
3745
        fprintf(stderr, "Unkown bitstream filter %s\n", arg);
3746
        exit(1);
3747
    }
3748

    
3749
    bsfp= &video_bitstream_filters;
3750
    while(*bsfp)
3751
        bsfp= &(*bsfp)->next;
3752

    
3753
    *bsfp= bsfc;
3754
}
3755

    
3756
//FIXME avoid audio - video code duplication
3757
static void opt_audio_bsf(const char *arg)
3758
{
3759
    AVBitStreamFilterContext *bsfc= av_bitstream_filter_init(arg); //FIXME split name and args for filter at '='
3760
    AVBitStreamFilterContext **bsfp;
3761

    
3762
    if(!bsfc){
3763
        fprintf(stderr, "Unkown bitstream filter %s\n", arg);
3764
        exit(1);
3765
    }
3766

    
3767
    bsfp= &audio_bitstream_filters;
3768
    while(*bsfp)
3769
        bsfp= &(*bsfp)->next;
3770

    
3771
    *bsfp= bsfc;
3772
}
3773

    
3774
static void show_version(void)
3775
{
3776
    /* TODO: add function interface to avutil and avformat */
3777
    fprintf(stderr, "ffmpeg      " FFMPEG_VERSION "\n"
3778
           "libavutil   %d\n"
3779
           "libavcodec  %d\n"
3780
           "libavformat %d\n",
3781
           LIBAVUTIL_BUILD, avcodec_build(), LIBAVFORMAT_BUILD);
3782
    exit(1);
3783
}
3784

    
3785
static int opt_default(const char *opt, const char *arg){
3786
    AVOption *o= av_set_string(avctx_opts, opt, arg);
3787
    if(!o)
3788
        o = av_set_string(avformat_opts, opt, arg);
3789
    if(!o)
3790
        return -1;
3791

    
3792
//    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));
3793

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

    
3798
#if defined(CONFIG_FFM_DEMUXER) || defined(CONFIG_FFM_MUXER)
3799
    /* disable generate of real time pts in ffm (need to be supressed anyway) */
3800
    if(avctx_opts->flags & CODEC_FLAG_BITEXACT)
3801
        ffm_nopts = 1;
3802
#endif
3803

    
3804
    if(avctx_opts->debug)
3805
        av_log_set_level(AV_LOG_DEBUG);
3806
    return 0;
3807
}
3808

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

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

    
3910
    /* audio options */
3911
    { "ab", HAS_ARG | OPT_AUDIO, {(void*)opt_audio_bitrate}, "set audio bitrate (in kbit/s)", "bitrate", },
3912
    { "aq", OPT_FLOAT | HAS_ARG | OPT_AUDIO, {(void*)&audio_qscale}, "set audio quality (codec-specific)", "quality", },
3913
    { "ar", HAS_ARG | OPT_AUDIO, {(void*)opt_audio_rate}, "set audio sampling rate (in Hz)", "rate" },
3914
    { "ac", HAS_ARG | OPT_AUDIO, {(void*)opt_audio_channels}, "set number of audio channels", "channels" },
3915
    { "an", OPT_BOOL | OPT_AUDIO, {(void*)&audio_disable}, "disable audio" },
3916
    { "acodec", HAS_ARG | OPT_AUDIO, {(void*)opt_audio_codec}, "force audio codec ('copy' to copy stream)", "codec" },
3917
    { "atag", HAS_ARG | OPT_EXPERT | OPT_AUDIO, {(void*)opt_audio_tag}, "force audio tag/fourcc", "fourcc/tag" },
3918
    { "vol", OPT_INT | HAS_ARG | OPT_AUDIO, {(void*)&audio_volume}, "change audio volume (256=normal)" , "volume" }, //
3919
    { "newaudio", OPT_AUDIO, {(void*)opt_new_audio_stream}, "add a new audio stream to the current output stream" },
3920
    { "alang", HAS_ARG | OPT_STRING | OPT_AUDIO, {(void *)&audio_language}, "set the ISO 639 language code (3 letters) of the current audio stream" , "code" },
3921

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

    
3927
    /* grab options */
3928
    { "vd", HAS_ARG | OPT_EXPERT | OPT_VIDEO | OPT_GRAB, {(void*)opt_video_device}, "set video grab device", "device" },
3929
    { "vc", HAS_ARG | OPT_EXPERT | OPT_VIDEO | OPT_GRAB, {(void*)opt_video_channel}, "set video grab channel (DV1394 only)", "channel" },
3930
    { "tvstd", HAS_ARG | OPT_EXPERT | OPT_VIDEO | OPT_GRAB, {(void*)opt_video_standard}, "set television standard (NTSC, PAL (SECAM))", "standard" },
3931
    { "ad", HAS_ARG | OPT_EXPERT | OPT_AUDIO | OPT_GRAB, {(void*)opt_audio_device}, "set audio device", "device" },
3932

    
3933
    /* G.2 grab options */
3934
    { "grab", HAS_ARG | OPT_EXPERT | OPT_GRAB, {(void*)opt_grab}, "request grabbing using", "format" },
3935
    { "gd", HAS_ARG | OPT_EXPERT | OPT_VIDEO | OPT_GRAB, {(void*)opt_grab_device}, "set grab device", "device" },
3936

    
3937
    /* muxer options */
3938
    { "muxdelay", OPT_FLOAT | HAS_ARG | OPT_EXPERT, {(void*)&mux_max_delay}, "set the maximum demux-decode delay", "seconds" },
3939
    { "muxpreload", OPT_FLOAT | HAS_ARG | OPT_EXPERT, {(void*)&mux_preload}, "set the initial demux-decode delay", "seconds" },
3940

    
3941
    { "absf", HAS_ARG | OPT_AUDIO | OPT_EXPERT, {(void*)opt_audio_bsf}, "", "bitstream filter" },
3942
    { "vbsf", HAS_ARG | OPT_VIDEO | OPT_EXPERT, {(void*)opt_video_bsf}, "", "bitstream filter" },
3943

    
3944
    { "default", OPT_FUNC2 | HAS_ARG | OPT_AUDIO | OPT_VIDEO | OPT_EXPERT, {(void*)opt_default}, "generic catch all option", "" },
3945
    { NULL, },
3946
};
3947

    
3948
static void show_banner(void)
3949
{
3950
    fprintf(stderr, "FFmpeg version " FFMPEG_VERSION ", Copyright (c) 2000-2004 Fabrice Bellard\n");
3951
    fprintf(stderr, "  configuration: " FFMPEG_CONFIGURATION "\n");
3952
    fprintf(stderr, "  libavutil version: " AV_STRINGIFY(LIBAVUTIL_VERSION) "\n");
3953
    fprintf(stderr, "  libavcodec version: " AV_STRINGIFY(LIBAVCODEC_VERSION) "\n");
3954
    fprintf(stderr, "  libavformat version: " AV_STRINGIFY(LIBAVFORMAT_VERSION) "\n");
3955
    fprintf(stderr, "  built on " __DATE__ " " __TIME__);
3956
#ifdef __GNUC__
3957
    fprintf(stderr, ", gcc: " __VERSION__ "\n");
3958
#else
3959
    fprintf(stderr, ", using a non-gcc compiler\n");
3960
#endif
3961
}
3962

    
3963
static void show_license(void)
3964
{
3965
    show_banner();
3966
#ifdef CONFIG_GPL
3967
    printf(
3968
    "This program is free software; you can redistribute it and/or modify\n"
3969
    "it under the terms of the GNU General Public License as published by\n"
3970
    "the Free Software Foundation; either version 2 of the License, or\n"
3971
    "(at your option) any later version.\n"
3972
    "\n"
3973
    "This program is distributed in the hope that it will be useful,\n"
3974
    "but WITHOUT ANY WARRANTY; without even the implied warranty of\n"
3975
    "MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n"
3976
    "GNU General Public License for more details.\n"
3977
    "\n"
3978
    "You should have received a copy of the GNU General Public License\n"
3979
    "along with this program; if not, write to the Free Software\n"
3980
    "Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA\n"
3981
    );
3982
#else
3983
    printf(
3984
    "This library is free software; you can redistribute it and/or\n"
3985
    "modify it under the terms of the GNU Lesser General Public\n"
3986
    "License as published by the Free Software Foundation; either\n"
3987
    "version 2 of the License, or (at your option) any later version.\n"
3988
    "\n"
3989
    "This library is distributed in the hope that it will be useful,\n"
3990
    "but WITHOUT ANY WARRANTY; without even the implied warranty of\n"
3991
    "MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n"
3992
    "Lesser General Public License for more details.\n"
3993
    "\n"
3994
    "You should have received a copy of the GNU Lesser General Public\n"
3995
    "License along with this library; if not, write to the Free Software\n"
3996
    "Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n"
3997
    );
3998
#endif
3999
    exit(1);
4000
}
4001

    
4002
static void show_help(void)
4003
{
4004
    show_banner();
4005
    printf("usage: ffmpeg [[infile options] -i infile]... {[outfile options] outfile}...\n"
4006
           "Hyper fast Audio and Video encoder\n");
4007
    printf("\n");
4008
    show_help_options(options, "Main options:\n",
4009
                      OPT_EXPERT | OPT_AUDIO | OPT_VIDEO, 0);
4010
    show_help_options(options, "\nVideo options:\n",
4011
                      OPT_EXPERT | OPT_AUDIO | OPT_VIDEO | OPT_GRAB,
4012
                      OPT_VIDEO);
4013
    show_help_options(options, "\nAdvanced Video options:\n",
4014
                      OPT_EXPERT | OPT_AUDIO | OPT_VIDEO | OPT_GRAB,
4015
                      OPT_VIDEO | OPT_EXPERT);
4016
    show_help_options(options, "\nAudio options:\n",
4017
                      OPT_EXPERT | OPT_AUDIO | OPT_VIDEO | OPT_GRAB,
4018
                      OPT_AUDIO);
4019
    show_help_options(options, "\nAdvanced Audio options:\n",
4020
                      OPT_EXPERT | OPT_AUDIO | OPT_VIDEO | OPT_GRAB,
4021
                      OPT_AUDIO | OPT_EXPERT);
4022
    show_help_options(options, "\nSubtitle options:\n",
4023
                      OPT_SUBTITLE | OPT_GRAB,
4024
                      OPT_SUBTITLE);
4025
    show_help_options(options, "\nAudio/Video grab options:\n",
4026
                      OPT_GRAB,
4027
                      OPT_GRAB);
4028
    show_help_options(options, "\nAdvanced options:\n",
4029
                      OPT_EXPERT | OPT_AUDIO | OPT_VIDEO | OPT_GRAB,
4030
                      OPT_EXPERT);
4031
    av_opt_show(avctx_opts, NULL);
4032
    av_opt_show(avformat_opts, NULL);
4033

    
4034
    exit(1);
4035
}
4036

    
4037
void parse_arg_file(const char *filename)
4038
{
4039
    opt_output_file(filename);
4040
}
4041

    
4042
int main(int argc, char **argv)
4043
{
4044
    int i;
4045
    int64_t ti;
4046

    
4047
    av_register_all();
4048

    
4049
    avctx_opts= avcodec_alloc_context();
4050
    avformat_opts = av_alloc_format_context();
4051

    
4052
    if (argc <= 1)
4053
        show_help();
4054
    else
4055
        show_banner();
4056

    
4057
    /* parse options */
4058
    parse_options(argc, argv, options);
4059

    
4060
    /* file converter / grab */
4061
    if (nb_output_files <= 0) {
4062
        fprintf(stderr, "Must supply at least one output file\n");
4063
        exit(1);
4064
    }
4065

    
4066
    if (nb_input_files == 0) {
4067
        input_sync = 1;
4068
        prepare_grab();
4069
    }
4070

    
4071
    ti = getutime();
4072
    av_encode(output_files, nb_output_files, input_files, nb_input_files,
4073
              stream_maps, nb_stream_maps);
4074
    ti = getutime() - ti;
4075
    if (do_benchmark) {
4076
        printf("bench: utime=%0.3fs\n", ti / 1000000.0);
4077
    }
4078

    
4079
    /* close files */
4080
    for(i=0;i<nb_output_files;i++) {
4081
        /* maybe av_close_output_file ??? */
4082
        AVFormatContext *s = output_files[i];
4083
        int j;
4084
        if (!(s->oformat->flags & AVFMT_NOFILE))
4085
            url_fclose(&s->pb);
4086
        for(j=0;j<s->nb_streams;j++)
4087
            av_free(s->streams[j]);
4088
        av_free(s);
4089
    }
4090
    for(i=0;i<nb_input_files;i++)
4091
        av_close_input_file(input_files[i]);
4092

    
4093
    av_free_static();
4094

    
4095
    if(intra_matrix)
4096
        av_free(intra_matrix);
4097
    if(inter_matrix)
4098
        av_free(inter_matrix);
4099

    
4100
#ifdef POWERPC_PERFORMANCE_REPORT
4101
    extern void powerpc_display_perf_report(void);
4102
    powerpc_display_perf_report();
4103
#endif /* POWERPC_PERFORMANCE_REPORT */
4104

    
4105
#ifndef __MINGW32__
4106
    if (received_sigterm) {
4107
        fprintf(stderr,
4108
            "Received signal %d: terminating.\n",
4109
            (int) received_sigterm);
4110
        exit (255);
4111
    }
4112
#endif
4113
    exit(0); /* not all OS-es handle main() return value */
4114
    return 0;
4115
}