Statistics
| Branch: | Revision:

ffmpeg / ffmpeg.c @ f17ec19b

History | View | Annotate | Download (140 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
#include "fifo.h"
27

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

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

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

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

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

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

    
69
extern const OptionDef options[];
70

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

    
75
#define MAX_FILES 20
76

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

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

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

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

    
90
static AVInputFormat *file_iformat;
91
static AVOutputFormat *file_oformat;
92
static AVImageFormat *image_format;
93
static int frame_width  = 0;
94
static int frame_height = 0;
95
static float frame_aspect_ratio = 0;
96
static enum PixelFormat frame_pix_fmt = PIX_FMT_NONE;
97
static int frame_padtop  = 0;
98
static int frame_padbottom = 0;
99
static int frame_padleft  = 0;
100
static int frame_padright = 0;
101
static int padcolor[3] = {16,128,128}; /* default to black */
102
static int frame_topBand  = 0;
103
static int frame_bottomBand = 0;
104
static int frame_leftBand  = 0;
105
static int frame_rightBand = 0;
106
static int max_frames[4] = {INT_MAX, INT_MAX, INT_MAX, INT_MAX};
107
static int frame_rate = 25;
108
static int frame_rate_base = 1;
109
static float video_qscale = 0;
110
static int video_lmin = 2*FF_QP2LAMBDA;
111
static int video_lmax = 31*FF_QP2LAMBDA;
112
static int video_mb_lmin = 2*FF_QP2LAMBDA;
113
static int video_mb_lmax = 31*FF_QP2LAMBDA;
114
static int video_qdiff = 3;
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 int me_method = ME_EPZS;
125
static int video_disable = 0;
126
static int video_discard = 0;
127
static int video_codec_id = CODEC_ID_NONE;
128
static int video_codec_tag = 0;
129
static int same_quality = 0;
130
static int do_deinterlace = 0;
131
static int packet_size = 0;
132
static int error_rate = 0;
133
static int strict = 0;
134
static int top_field_first = -1;
135
static int me_threshold = 0;
136
static int intra_dc_precision = 8;
137
static int me_penalty_compensation= 256;
138
static int frame_skip_exp= 0;
139
static int loop_input = 0;
140
static int loop_output = AVFMT_NOOUTPUTLOOP;
141
static int qp_hist = 0;
142

    
143
static int intra_only = 0;
144
static int audio_sample_rate = 44100;
145
static int audio_bit_rate = 64000;
146
#define QSCALE_NONE -99999
147
static float audio_qscale = QSCALE_NONE;
148
static int audio_disable = 0;
149
static int audio_channels = 1;
150
static int audio_codec_id = CODEC_ID_NONE;
151
static int audio_codec_tag = 0;
152
static char *audio_language = NULL;
153

    
154
static int subtitle_codec_id = CODEC_ID_NONE;
155
static char *subtitle_language = NULL;
156

    
157
static float mux_preload= 0.5;
158
static float mux_max_delay= 0.7;
159

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

    
186
static int rate_emu = 0;
187

    
188
#ifdef CONFIG_BKTR
189
static const char *video_grab_format = "bktr";
190
#else
191
#ifdef CONFIG_VIDEO4LINUX2
192
static const char *video_grab_format = "video4linux2";
193
#else
194
static const char *video_grab_format = "video4linux";
195
#endif
196
#endif
197
static char *video_device = NULL;
198
static char *grab_device = NULL;
199
static int  video_channel = 0;
200
static char *video_standard = "ntsc";
201

    
202
static const char *audio_grab_format = "audio_device";
203
static char *audio_device = NULL;
204
static int audio_volume = 256;
205

    
206
static int using_stdin = 0;
207
static int using_vhook = 0;
208
static int verbose = 1;
209
static int thread_count= 1;
210
static int q_pressed = 0;
211
static int64_t video_size = 0;
212
static int64_t audio_size = 0;
213
static int64_t extra_size = 0;
214
static int nb_frames_dup = 0;
215
static int nb_frames_drop = 0;
216
static int input_sync;
217
static int limit_filesize = 0; //
218

    
219
static int pgmyuv_compatibility_hack=0;
220
static int dts_delta_threshold = 10;
221

    
222
static int sws_flags = SWS_BICUBIC;
223

    
224
const char **opt_names=NULL;
225
int opt_name_count=0;
226
AVCodecContext *avctx_opts;
227
AVFormatContext *avformat_opts;
228

    
229
static AVBitStreamFilterContext *video_bitstream_filters=NULL;
230
static AVBitStreamFilterContext *audio_bitstream_filters=NULL;
231
static AVBitStreamFilterContext *bitstream_filters[MAX_FILES][MAX_STREAMS];
232

    
233
#define DEFAULT_PASS_LOGFILENAME "ffmpeg2pass"
234

    
235
struct AVInputStream;
236

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

    
255
    int video_crop;
256
    int topBand;             /* cropping area sizes */
257
    int leftBand;
258

    
259
    int video_pad;
260
    int padtop;              /* padding area sizes */
261
    int padbottom;
262
    int padleft;
263
    int padright;
264

    
265
    /* audio only */
266
    int audio_resample;
267
    ReSampleContext *resample; /* for audio resampling */
268
    AVFifoBuffer fifo;     /* for compression: one audio fifo per codec */
269
    FILE *logfile;
270
} AVOutputStream;
271

    
272
typedef struct AVInputStream {
273
    int file_index;
274
    int index;
275
    AVStream *st;
276
    int discard;             /* true if stream data should be discarded */
277
    int decoding_needed;     /* true if the packets must be decoded in 'raw_fifo' */
278
    int64_t sample_index;      /* current sample */
279

    
280
    int64_t       start;     /* time when read started */
281
    unsigned long frame;     /* current frame */
282
    int64_t       next_pts;  /* synthetic pts for cases where pkt.pts
283
                                is not defined */
284
    int64_t       pts;       /* current pts */
285
    int is_start;            /* is 1 at the start and after a discontinuity */
286
} AVInputStream;
287

    
288
typedef struct AVInputFile {
289
    int eof_reached;      /* true if eof reached */
290
    int ist_index;        /* index of first stream in ist_table */
291
    int buffer_size;      /* current total buffer size */
292
    int buffer_size_max;  /* buffer size at which we consider we can stop
293
                             buffering */
294
    int nb_streams;       /* nb streams we are aware of */
295
} AVInputFile;
296

    
297
#ifndef __MINGW32__
298

    
299
/* init terminal so that we can grab keys */
300
static struct termios oldtty;
301

    
302
static void term_exit(void)
303
{
304
    tcsetattr (0, TCSANOW, &oldtty);
305
}
306

    
307
static volatile sig_atomic_t received_sigterm = 0;
308

    
309
static void
310
sigterm_handler(int sig)
311
{
312
    received_sigterm = sig;
313
    term_exit();
314
}
315

    
316
static void term_init(void)
317
{
318
    struct termios tty;
319

    
320
    tcgetattr (0, &tty);
321
    oldtty = tty;
322

    
323
    tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
324
                          |INLCR|IGNCR|ICRNL|IXON);
325
    tty.c_oflag |= OPOST;
326
    tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
327
    tty.c_cflag &= ~(CSIZE|PARENB);
328
    tty.c_cflag |= CS8;
329
    tty.c_cc[VMIN] = 1;
330
    tty.c_cc[VTIME] = 0;
331

    
332
    tcsetattr (0, TCSANOW, &tty);
333

    
334
    signal(SIGINT , sigterm_handler); /* Interrupt (ANSI).  */
335
    signal(SIGQUIT, sigterm_handler); /* Quit (POSIX).  */
336
    signal(SIGTERM, sigterm_handler); /* Termination (ANSI).  */
337
    /*
338
    register a function to be called at normal program termination
339
    */
340
    atexit(term_exit);
341
#ifdef CONFIG_BEOS_NETSERVER
342
    fcntl(0, F_SETFL, fcntl(0, F_GETFL) | O_NONBLOCK);
343
#endif
344
}
345

    
346
/* read a key without blocking */
347
static int read_key(void)
348
{
349
    int n = 1;
350
    unsigned char ch;
351
#ifndef CONFIG_BEOS_NETSERVER
352
    struct timeval tv;
353
    fd_set rfds;
354

    
355
    FD_ZERO(&rfds);
356
    FD_SET(0, &rfds);
357
    tv.tv_sec = 0;
358
    tv.tv_usec = 0;
359
    n = select(1, &rfds, NULL, NULL, &tv);
360
#endif
361
    if (n > 0) {
362
        n = read(0, &ch, 1);
363
        if (n == 1)
364
            return ch;
365

    
366
        return n;
367
    }
368
    return -1;
369
}
370

    
371
static int decode_interrupt_cb(void)
372
{
373
    return q_pressed || (q_pressed = read_key() == 'q');
374
}
375

    
376
#else
377

    
378
static volatile int received_sigterm = 0;
379

    
380
/* no interactive support */
381
static void term_exit(void)
382
{
383
}
384

    
385
static void term_init(void)
386
{
387
}
388

    
389
static int read_key(void)
390
{
391
    return 0;
392
}
393

    
394
#endif
395

    
396
static int read_ffserver_streams(AVFormatContext *s, const char *filename)
397
{
398
    int i, err;
399
    AVFormatContext *ic;
400

    
401
    err = av_open_input_file(&ic, filename, NULL, FFM_PACKET_SIZE, NULL);
402
    if (err < 0)
403
        return err;
404
    /* copy stream format */
405
    s->nb_streams = ic->nb_streams;
406
    for(i=0;i<ic->nb_streams;i++) {
407
        AVStream *st;
408

    
409
        // FIXME: a more elegant solution is needed
410
        st = av_mallocz(sizeof(AVStream));
411
        memcpy(st, ic->streams[i], sizeof(AVStream));
412
        st->codec = avcodec_alloc_context();
413
        memcpy(st->codec, ic->streams[i]->codec, sizeof(AVCodecContext));
414
        s->streams[i] = st;
415
    }
416

    
417
    av_close_input_file(ic);
418
    return 0;
419
}
420

    
421
static double
422
get_sync_ipts(const AVOutputStream *ost)
423
{
424
    const AVInputStream *ist = ost->sync_ist;
425
    return (double)(ist->pts + input_files_ts_offset[ist->file_index] - start_time)/AV_TIME_BASE;
426
}
427

    
428
static void write_frame(AVFormatContext *s, AVPacket *pkt, AVCodecContext *avctx, AVBitStreamFilterContext *bsfc){
429
    while(bsfc){
430
        AVPacket new_pkt= *pkt;
431
        int a= av_bitstream_filter_filter(bsfc, avctx, NULL,
432
                                          &new_pkt.data, &new_pkt.size,
433
                                          pkt->data, pkt->size,
434
                                          pkt->flags & PKT_FLAG_KEY);
435
        if(a){
436
            av_free_packet(pkt);
437
            new_pkt.destruct= av_destruct_packet;
438
        }
439
        *pkt= new_pkt;
440

    
441
        bsfc= bsfc->next;
442
    }
443

    
444
    av_interleaved_write_frame(s, pkt);
445
}
446

    
447
#define MAX_AUDIO_PACKET_SIZE (128 * 1024)
448

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

    
459
    int size_out, frame_bytes, ret;
460
    AVCodecContext *enc= ost->st->codec;
461

    
462
    /* SC: dynamic allocation of buffers */
463
    if (!audio_buf)
464
        audio_buf = av_malloc(2*MAX_AUDIO_PACKET_SIZE);
465
    if (!audio_out)
466
        audio_out = av_malloc(audio_out_size);
467
    if (!audio_buf || !audio_out)
468
        return;               /* Should signal an error ! */
469

    
470
    if(audio_sync_method){
471
        double delta = get_sync_ipts(ost) * enc->sample_rate - ost->sync_opts
472
                - av_fifo_size(&ost->fifo)/(ost->st->codec->channels * 2);
473
        double idelta= delta*ist->st->codec->sample_rate / enc->sample_rate;
474
        int byte_delta= ((int)idelta)*2*ist->st->codec->channels;
475

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

    
492
                    if(byte_delta + size <= MAX_AUDIO_PACKET_SIZE)
493
                        ist->is_start=0;
494
                    else
495
                        byte_delta= MAX_AUDIO_PACKET_SIZE - size;
496

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

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

    
528
    /* now encode as many frames as possible */
529
    if (enc->frame_size > 1) {
530
        /* output resampled raw samples */
531
        av_fifo_write(&ost->fifo, buftmp, size_out);
532

    
533
        frame_bytes = enc->frame_size * 2 * enc->channels;
534

    
535
        while (av_fifo_read(&ost->fifo, audio_buf, frame_bytes) == 0) {
536
            AVPacket pkt;
537
            av_init_packet(&pkt);
538

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

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

    
556
        ost->sync_opts += size_out / (2 * enc->channels);
557

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

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

    
603
    dec = ist->st->codec;
604

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

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

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

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

    
633
    frame_hook_process(picture2, dec->pix_fmt, dec->width, dec->height);
634

    
635
    if (picture != picture2)
636
        *picture = *picture2;
637
    *bufp = buf;
638
}
639

    
640
/* we begin to correct av delay at this threshold */
641
#define AV_DELAY_MAX 0.100
642

    
643
static void do_subtitle_out(AVFormatContext *s,
644
                            AVOutputStream *ost,
645
                            AVInputStream *ist,
646
                            AVSubtitle *sub,
647
                            int64_t pts)
648
{
649
    static uint8_t *subtitle_out = NULL;
650
    int subtitle_out_max_size = 65536;
651
    int subtitle_out_size, nb, i;
652
    AVCodecContext *enc;
653
    AVPacket pkt;
654

    
655
    if (pts == AV_NOPTS_VALUE) {
656
        fprintf(stderr, "Subtitle packets must have a pts\n");
657
        return;
658
    }
659

    
660
    enc = ost->st->codec;
661

    
662
    if (!subtitle_out) {
663
        subtitle_out = av_malloc(subtitle_out_max_size);
664
    }
665

    
666
    /* Note: DVB subtitle need one packet to draw them and one other
667
       packet to clear them */
668
    /* XXX: signal it in the codec context ? */
669
    if (enc->codec_id == CODEC_ID_DVB_SUBTITLE)
670
        nb = 2;
671
    else
672
        nb = 1;
673

    
674
    for(i = 0; i < nb; i++) {
675
        subtitle_out_size = avcodec_encode_subtitle(enc, subtitle_out,
676
                                                    subtitle_out_max_size, sub);
677

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

    
695
static int bit_buffer_size= 1024*256;
696
static uint8_t *bit_buffer= NULL;
697

    
698
static void do_video_out(AVFormatContext *s,
699
                         AVOutputStream *ost,
700
                         AVInputStream *ist,
701
                         AVFrame *in_picture,
702
                         int *frame_size)
703
{
704
    int nb_frames, i, ret;
705
    AVFrame *final_picture, *formatted_picture, *resampling_dst, *padding_src;
706
    AVFrame picture_crop_temp, picture_pad_temp;
707
    uint8_t *buf = NULL, *buf1 = NULL;
708
    AVCodecContext *enc, *dec;
709

    
710
    avcodec_get_frame_defaults(&picture_crop_temp);
711
    avcodec_get_frame_defaults(&picture_pad_temp);
712

    
713
    enc = ost->st->codec;
714
    dec = ist->st->codec;
715

    
716
    /* by default, we output a single frame */
717
    nb_frames = 1;
718

    
719
    *frame_size = 0;
720

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

    
742
    nb_frames= FFMIN(nb_frames, max_frames[CODEC_TYPE_VIDEO] - ost->frame_number);
743
    if (nb_frames <= 0)
744
        return;
745

    
746
    if (ost->video_crop) {
747
        if (img_crop((AVPicture *)&picture_crop_temp, (AVPicture *)in_picture, dec->pix_fmt, ost->topBand, ost->leftBand) < 0) {
748
            av_log(NULL, AV_LOG_ERROR, "error cropping picture\n");
749
            goto the_end;
750
        }
751
        formatted_picture = &picture_crop_temp;
752
    } else {
753
        formatted_picture = in_picture;
754
    }
755

    
756
    final_picture = formatted_picture;
757
    padding_src = formatted_picture;
758
    resampling_dst = &ost->pict_tmp;
759
    if (ost->video_pad) {
760
        final_picture = &ost->pict_tmp;
761
        if (ost->video_resample) {
762
            if (img_crop((AVPicture *)&picture_pad_temp, (AVPicture *)final_picture, enc->pix_fmt, ost->padtop, ost->padleft) < 0) {
763
                av_log(NULL, AV_LOG_ERROR, "error padding picture\n");
764
                goto the_end;
765
            }
766
            resampling_dst = &picture_pad_temp;
767
        }
768
    }
769

    
770
    if (ost->video_resample) {
771
        padding_src = NULL;
772
        final_picture = &ost->pict_tmp;
773
        sws_scale(ost->img_resample_ctx, formatted_picture->data, formatted_picture->linesize,
774
              0, ost->resample_height, resampling_dst->data, resampling_dst->linesize);
775
    }
776

    
777
    if (ost->video_pad) {
778
        img_pad((AVPicture*)final_picture, (AVPicture *)padding_src,
779
                enc->height, enc->width, enc->pix_fmt,
780
                ost->padtop, ost->padbottom, ost->padleft, ost->padright, padcolor);
781
    }
782

    
783
    /* duplicates frame if needed */
784
    for(i=0;i<nb_frames;i++) {
785
        AVPacket pkt;
786
        av_init_packet(&pkt);
787
        pkt.stream_index= ost->index;
788

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

    
802
            write_frame(s, &pkt, ost->st->codec, bitstream_filters[ost->file_index][pkt.stream_index]);
803
            enc->coded_frame = old_frame;
804
        } else {
805
            AVFrame big_picture;
806

    
807
            big_picture= *final_picture;
808
            /* better than nothing: use input picture interlaced
809
               settings */
810
            big_picture.interlaced_frame = in_picture->interlaced_frame;
811
            if(avctx_opts->flags & (CODEC_FLAG_INTERLACED_DCT|CODEC_FLAG_INTERLACED_ME)){
812
                if(top_field_first == -1)
813
                    big_picture.top_field_first = in_picture->top_field_first;
814
                else
815
                    big_picture.top_field_first = top_field_first;
816
            }
817

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

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

    
864
static double psnr(double d){
865
    if(d==0) return INFINITY;
866
    return -10.0*log(d)/log(10.0);
867
}
868

    
869
static void do_video_stats(AVFormatContext *os, AVOutputStream *ost,
870
                           int frame_size)
871
{
872
    static FILE *fvstats=NULL;
873
    char filename[40];
874
    time_t today2;
875
    struct tm *today;
876
    AVCodecContext *enc;
877
    int frame_number;
878
    int64_t ti;
879
    double ti1, bitrate, avg_bitrate;
880

    
881
    if (!fvstats) {
882
        today2 = time(NULL);
883
        today = localtime(&today2);
884
        snprintf(filename, sizeof(filename), "vstats_%02d%02d%02d.log", today->tm_hour,
885
                                               today->tm_min,
886
                                               today->tm_sec);
887
        fvstats = fopen(filename,"w");
888
        if (!fvstats) {
889
            perror("fopen");
890
            exit(1);
891
        }
892
    }
893

    
894
    ti = MAXINT64;
895
    enc = ost->st->codec;
896
    if (enc->codec_type == CODEC_TYPE_VIDEO) {
897
        frame_number = ost->frame_number;
898
        fprintf(fvstats, "frame= %5d q= %2.1f ", frame_number, enc->coded_frame->quality/(float)FF_QP2LAMBDA);
899
        if (enc->flags&CODEC_FLAG_PSNR)
900
            fprintf(fvstats, "PSNR= %6.2f ", psnr(enc->coded_frame->error[0]/(enc->width*enc->height*255.0*255.0)));
901

    
902
        fprintf(fvstats,"f_size= %6d ", frame_size);
903
        /* compute pts value */
904
        ti1 = ost->sync_opts * av_q2d(enc->time_base);
905
        if (ti1 < 0.01)
906
            ti1 = 0.01;
907

    
908
        bitrate = (frame_size * 8) / av_q2d(enc->time_base) / 1000.0;
909
        avg_bitrate = (double)(video_size * 8) / ti1 / 1000.0;
910
        fprintf(fvstats, "s_size= %8.0fkB time= %0.3f br= %7.1fkbits/s avg_br= %7.1fkbits/s ",
911
            (double)video_size / 1024, ti1, bitrate, avg_bitrate);
912
        fprintf(fvstats,"type= %c\n", av_get_pict_type_char(enc->coded_frame->pict_type));
913
    }
914
}
915

    
916
static void print_report(AVFormatContext **output_files,
917
                         AVOutputStream **ost_table, int nb_ostreams,
918
                         int is_last_report)
919
{
920
    char buf[1024];
921
    AVOutputStream *ost;
922
    AVFormatContext *oc, *os;
923
    int64_t total_size;
924
    AVCodecContext *enc;
925
    int frame_number, vid, i;
926
    double bitrate, ti1, pts;
927
    static int64_t last_time = -1;
928
    static int qp_histogram[52];
929

    
930
    if (!is_last_report) {
931
        int64_t cur_time;
932
        /* display the report every 0.5 seconds */
933
        cur_time = av_gettime();
934
        if (last_time == -1) {
935
            last_time = cur_time;
936
            return;
937
        }
938
        if ((cur_time - last_time) < 500000)
939
            return;
940
        last_time = cur_time;
941
    }
942

    
943

    
944
    oc = output_files[0];
945

    
946
    total_size = url_ftell(&oc->pb);
947

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

    
1004
    if (verbose || is_last_report) {
1005
        bitrate = (double)(total_size * 8) / ti1 / 1000.0;
1006

    
1007
        snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
1008
            "size=%8.0fkB time=%0.1f bitrate=%6.1fkbits/s",
1009
            (double)total_size / 1024, ti1, bitrate);
1010

    
1011
        if (verbose > 1)
1012
          snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), " dup=%d drop=%d",
1013
                  nb_frames_dup, nb_frames_drop);
1014

    
1015
        if (verbose >= 0)
1016
            fprintf(stderr, "%s    \r", buf);
1017

    
1018
        fflush(stderr);
1019
    }
1020

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

    
1033
/* pkt = NULL means EOF (needed to flush decoder buffers) */
1034
static int output_packet(AVInputStream *ist, int ist_index,
1035
                         AVOutputStream **ost_table, int nb_ostreams,
1036
                         const AVPacket *pkt)
1037
{
1038
    AVFormatContext *os;
1039
    AVOutputStream *ost;
1040
    uint8_t *ptr;
1041
    int len, ret, i;
1042
    uint8_t *data_buf;
1043
    int data_size, got_picture;
1044
    AVFrame picture;
1045
    void *buffer_to_free;
1046
    static unsigned int samples_size= 0;
1047
    static short *samples= NULL;
1048
    AVSubtitle subtitle, *subtitle_to_free;
1049
    int got_subtitle;
1050

    
1051
    if(!pkt){
1052
        ist->pts= ist->next_pts; // needed for last packet if vsync=0
1053
    } else if (pkt->dts != AV_NOPTS_VALUE) { //FIXME seems redundant, as libavformat does this too
1054
        ist->next_pts = ist->pts = av_rescale_q(pkt->dts, ist->st->time_base, AV_TIME_BASE_Q);
1055
    } else {
1056
//        assert(ist->pts == ist->next_pts);
1057
    }
1058

    
1059
    if (pkt == NULL) {
1060
        /* EOF handling */
1061
        ptr = NULL;
1062
        len = 0;
1063
        goto handle_eof;
1064
    }
1065

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

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

    
1152
            buffer_to_free = NULL;
1153
            if (ist->st->codec->codec_type == CODEC_TYPE_VIDEO) {
1154
                pre_process_video_frame(ist, (AVPicture *)&picture,
1155
                                        &buffer_to_free);
1156
            }
1157

    
1158
            // preprocess audio (volume)
1159
            if (ist->st->codec->codec_type == CODEC_TYPE_AUDIO) {
1160
                if (audio_volume != 256) {
1161
                    short *volp;
1162
                    volp = samples;
1163
                    for(i=0;i<(data_size / sizeof(short));i++) {
1164
                        int v = ((*volp) * audio_volume + 128) >> 8;
1165
                        if (v < -32768) v = -32768;
1166
                        if (v >  32767) v = 32767;
1167
                        *volp++ = v;
1168
                    }
1169
                }
1170
            }
1171

    
1172
            /* frame rate emulation */
1173
            if (ist->st->codec->rate_emu) {
1174
                int64_t pts = av_rescale((int64_t) ist->frame * ist->st->codec->time_base.num, 1000000, ist->st->codec->time_base.den);
1175
                int64_t now = av_gettime() - ist->start;
1176
                if (pts > now)
1177
                    usleep(pts - now);
1178

    
1179
                ist->frame++;
1180
            }
1181

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

    
1201
                    ost = ost_table[i];
1202
                    if (ost->source_index == ist_index) {
1203
                        os = output_files[ost->file_index];
1204

    
1205
#if 0
1206
                        printf("%d: got pts=%0.3f %0.3f\n", i,
1207
                               (double)pkt->pts / AV_TIME_BASE,
1208
                               ((double)ist->pts / AV_TIME_BASE) -
1209
                               ((double)ost->st->pts.val * ost->st->time_base.num / ost->st->time_base.den));
1210
#endif
1211
                        /* set the input output pts pairs */
1212
                        //ost->sync_ipts = (double)(ist->pts + input_files_ts_offset[ist->file_index] - start_time)/ AV_TIME_BASE;
1213

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

    
1237
                            /* no reencoding needed : output the packet directly */
1238
                            /* force the input stream PTS */
1239

    
1240
                            avcodec_get_frame_defaults(&avframe);
1241
                            ost->st->codec->coded_frame= &avframe;
1242
                            avframe.key_frame = pkt->flags & PKT_FLAG_KEY;
1243

    
1244
                            if(ost->st->codec->codec_type == CODEC_TYPE_AUDIO)
1245
                                audio_size += data_size;
1246
                            else if (ost->st->codec->codec_type == CODEC_TYPE_VIDEO) {
1247
                                video_size += data_size;
1248
                                ost->sync_opts++;
1249
                            }
1250

    
1251
                            opkt.stream_index= ost->index;
1252
                            if(pkt->pts != AV_NOPTS_VALUE)
1253
                                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);
1254
                            else
1255
                                opkt.pts= AV_NOPTS_VALUE;
1256

    
1257
                            {
1258
                                int64_t dts;
1259
                                if (pkt->dts == AV_NOPTS_VALUE)
1260
                                    dts = ist->next_pts;
1261
                                else
1262
                                    dts= av_rescale_q(pkt->dts, ist->st->time_base, AV_TIME_BASE_Q);
1263
                                opkt.dts= av_rescale_q(dts + input_files_ts_offset[ist->file_index], AV_TIME_BASE_Q,  ost->st->time_base);
1264
                            }
1265
                            opkt.flags= pkt->flags;
1266

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

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

    
1296
        for(i=0;i<nb_ostreams;i++) {
1297
            ost = ost_table[i];
1298
            if (ost->source_index == ist_index) {
1299
                AVCodecContext *enc= ost->st->codec;
1300
                os = output_files[ost->file_index];
1301

    
1302
                if(ost->st->codec->codec_type == CODEC_TYPE_AUDIO && enc->frame_size <=1)
1303
                    continue;
1304
                if(ost->st->codec->codec_type == CODEC_TYPE_VIDEO && (os->oformat->flags & AVFMT_RAWPICTURE))
1305
                    continue;
1306

    
1307
                if (ost->encoding_needed) {
1308
                    for(;;) {
1309
                        AVPacket pkt;
1310
                        int fifo_bytes;
1311
                        av_init_packet(&pkt);
1312
                        pkt.stream_index= ost->index;
1313

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

    
1346
                        if(ret<=0)
1347
                            break;
1348
                        pkt.data= bit_buffer;
1349
                        pkt.size= ret;
1350
                        if(enc->coded_frame && enc->coded_frame->pts != AV_NOPTS_VALUE)
1351
                            pkt.pts= av_rescale_q(enc->coded_frame->pts, enc->time_base, ost->st->time_base);
1352
                        write_frame(os, &pkt, ost->st->codec, bitstream_filters[ost->file_index][pkt.stream_index]);
1353
                    }
1354
                }
1355
            }
1356
        }
1357
    }
1358

    
1359
    return 0;
1360
 fail_decode:
1361
    return -1;
1362
}
1363

    
1364

    
1365
/*
1366
 * The following code is the main loop of the file converter
1367
 */
1368
static int av_encode(AVFormatContext **output_files,
1369
                     int nb_output_files,
1370
                     AVFormatContext **input_files,
1371
                     int nb_input_files,
1372
                     AVStreamMap *stream_maps, int nb_stream_maps)
1373
{
1374
    int ret, i, j, k, n, nb_istreams = 0, nb_ostreams = 0;
1375
    AVFormatContext *is, *os;
1376
    AVCodecContext *codec, *icodec;
1377
    AVOutputStream *ost, **ost_table = NULL;
1378
    AVInputStream *ist, **ist_table = NULL;
1379
    AVInputFile *file_table;
1380
    AVFormatContext *stream_no_data;
1381
    int key;
1382

    
1383
    file_table= (AVInputFile*) av_mallocz(nb_input_files * sizeof(AVInputFile));
1384
    if (!file_table)
1385
        goto fail;
1386

    
1387
    /* input stream init */
1388
    j = 0;
1389
    for(i=0;i<nb_input_files;i++) {
1390
        is = input_files[i];
1391
        file_table[i].ist_index = j;
1392
        file_table[i].nb_streams = is->nb_streams;
1393
        j += is->nb_streams;
1394
    }
1395
    nb_istreams = j;
1396

    
1397
    ist_table = av_mallocz(nb_istreams * sizeof(AVInputStream *));
1398
    if (!ist_table)
1399
        goto fail;
1400

    
1401
    for(i=0;i<nb_istreams;i++) {
1402
        ist = av_mallocz(sizeof(AVInputStream));
1403
        if (!ist)
1404
            goto fail;
1405
        ist_table[i] = ist;
1406
    }
1407
    j = 0;
1408
    for(i=0;i<nb_input_files;i++) {
1409
        is = input_files[i];
1410
        for(k=0;k<is->nb_streams;k++) {
1411
            ist = ist_table[j++];
1412
            ist->st = is->streams[k];
1413
            ist->file_index = i;
1414
            ist->index = k;
1415
            ist->discard = 1; /* the stream is discarded by default
1416
                                 (changed later) */
1417

    
1418
            if (ist->st->codec->rate_emu) {
1419
                ist->start = av_gettime();
1420
                ist->frame = 0;
1421
            }
1422
        }
1423
    }
1424

    
1425
    /* output stream init */
1426
    nb_ostreams = 0;
1427
    for(i=0;i<nb_output_files;i++) {
1428
        os = output_files[i];
1429
        nb_ostreams += os->nb_streams;
1430
    }
1431
    if (nb_stream_maps > 0 && nb_stream_maps != nb_ostreams) {
1432
        fprintf(stderr, "Number of stream maps must match number of output streams\n");
1433
        exit(1);
1434
    }
1435

    
1436
    /* Sanity check the mapping args -- do the input files & streams exist? */
1437
    for(i=0;i<nb_stream_maps;i++) {
1438
        int fi = stream_maps[i].file_index;
1439
        int si = stream_maps[i].stream_index;
1440

    
1441
        if (fi < 0 || fi > nb_input_files - 1 ||
1442
            si < 0 || si > file_table[fi].nb_streams - 1) {
1443
            fprintf(stderr,"Could not find input stream #%d.%d\n", fi, si);
1444
            exit(1);
1445
        }
1446
        fi = stream_maps[i].sync_file_index;
1447
        si = stream_maps[i].sync_stream_index;
1448
        if (fi < 0 || fi > nb_input_files - 1 ||
1449
            si < 0 || si > file_table[fi].nb_streams - 1) {
1450
            fprintf(stderr,"Could not find sync stream #%d.%d\n", fi, si);
1451
            exit(1);
1452
        }
1453
    }
1454

    
1455
    ost_table = av_mallocz(sizeof(AVOutputStream *) * nb_ostreams);
1456
    if (!ost_table)
1457
        goto fail;
1458
    for(i=0;i<nb_ostreams;i++) {
1459
        ost = av_mallocz(sizeof(AVOutputStream));
1460
        if (!ost)
1461
            goto fail;
1462
        ost_table[i] = ost;
1463
    }
1464

    
1465
    n = 0;
1466
    for(k=0;k<nb_output_files;k++) {
1467
        os = output_files[k];
1468
        for(i=0;i<os->nb_streams;i++) {
1469
            int found;
1470
            ost = ost_table[n++];
1471
            ost->file_index = k;
1472
            ost->index = i;
1473
            ost->st = os->streams[i];
1474
            if (nb_stream_maps > 0) {
1475
                ost->source_index = file_table[stream_maps[n-1].file_index].ist_index +
1476
                    stream_maps[n-1].stream_index;
1477

    
1478
                /* Sanity check that the stream types match */
1479
                if (ist_table[ost->source_index]->st->codec->codec_type != ost->st->codec->codec_type) {
1480
                    fprintf(stderr, "Codec type mismatch for mapping #%d.%d -> #%d.%d\n",
1481
                        stream_maps[n-1].file_index, stream_maps[n-1].stream_index,
1482
                        ost->file_index, ost->index);
1483
                    exit(1);
1484
                }
1485

    
1486
            } else {
1487
                /* get corresponding input stream index : we select the first one with the right type */
1488
                found = 0;
1489
                for(j=0;j<nb_istreams;j++) {
1490
                    ist = ist_table[j];
1491
                    if (ist->discard &&
1492
                        ist->st->codec->codec_type == ost->st->codec->codec_type) {
1493
                        ost->source_index = j;
1494
                        found = 1;
1495
                        break;
1496
                    }
1497
                }
1498

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

    
1523
    /* for each output stream, we compute the right encoding parameters */
1524
    for(i=0;i<nb_ostreams;i++) {
1525
        ost = ost_table[i];
1526
        ist = ist_table[ost->source_index];
1527

    
1528
        codec = ost->st->codec;
1529
        icodec = ist->st->codec;
1530

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

    
1564
                if (codec->channels == icodec->channels &&
1565
                    codec->sample_rate == icodec->sample_rate) {
1566
                    ost->audio_resample = 0;
1567
                } else {
1568
                    if (codec->channels != icodec->channels &&
1569
                        (icodec->codec_id == CODEC_ID_AC3 ||
1570
                         icodec->codec_id == CODEC_ID_DTS)) {
1571
                        /* Special case for 5:1 AC3 and DTS input */
1572
                        /* and mono or stereo output      */
1573
                        /* Request specific number of channels */
1574
                        icodec->channels = codec->channels;
1575
                        if (codec->sample_rate == icodec->sample_rate)
1576
                            ost->audio_resample = 0;
1577
                        else {
1578
                            ost->audio_resample = 1;
1579
                        }
1580
                    } else {
1581
                        ost->audio_resample = 1;
1582
                    }
1583
                }
1584
                if(audio_sync_method>1)
1585
                    ost->audio_resample = 1;
1586

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

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

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

    
1701
    if (!bit_buffer)
1702
        bit_buffer = av_malloc(bit_buffer_size);
1703
    if (!bit_buffer)
1704
        goto fail;
1705

    
1706
    /* dump the file output parameters - cannot be done before in case
1707
       of stream copy */
1708
    for(i=0;i<nb_output_files;i++) {
1709
        dump_format(output_files[i], i, output_files[i]->filename, 1);
1710
    }
1711

    
1712
    /* dump the stream mapping */
1713
    if (verbose >= 0) {
1714
        fprintf(stderr, "Stream mapping:\n");
1715
        for(i=0;i<nb_ostreams;i++) {
1716
            ost = ost_table[i];
1717
            fprintf(stderr, "  Stream #%d.%d -> #%d.%d",
1718
                    ist_table[ost->source_index]->file_index,
1719
                    ist_table[ost->source_index]->index,
1720
                    ost->file_index,
1721
                    ost->index);
1722
            if (ost->sync_ist != ist_table[ost->source_index])
1723
                fprintf(stderr, " [sync #%d.%d]",
1724
                        ost->sync_ist->file_index,
1725
                        ost->sync_ist->index);
1726
            fprintf(stderr, "\n");
1727
        }
1728
    }
1729

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

    
1750
    /* open each decoder */
1751
    for(i=0;i<nb_istreams;i++) {
1752
        ist = ist_table[i];
1753
        if (ist->decoding_needed) {
1754
            AVCodec *codec;
1755
            codec = avcodec_find_decoder(ist->st->codec->codec_id);
1756
            if (!codec) {
1757
                fprintf(stderr, "Unsupported codec (id=%d) for input stream #%d.%d\n",
1758
                        ist->st->codec->codec_id, ist->file_index, ist->index);
1759
                exit(1);
1760
            }
1761
            if (avcodec_open(ist->st->codec, codec) < 0) {
1762
                fprintf(stderr, "Error while opening codec for input stream #%d.%d\n",
1763
                        ist->file_index, ist->index);
1764
                exit(1);
1765
            }
1766
            //if (ist->st->codec->codec_type == CODEC_TYPE_VIDEO)
1767
            //    ist->st->codec->flags |= CODEC_FLAG_REPEAT_FIELD;
1768
        }
1769
    }
1770

    
1771
    /* init pts */
1772
    for(i=0;i<nb_istreams;i++) {
1773
        ist = ist_table[i];
1774
        is = input_files[ist->file_index];
1775
        ist->pts = 0;
1776
        ist->next_pts = av_rescale_q(ist->st->start_time, ist->st->time_base, AV_TIME_BASE_Q);
1777
        if(ist->st->start_time == AV_NOPTS_VALUE)
1778
            ist->next_pts=0;
1779
        if(input_files_ts_offset[ist->file_index])
1780
            ist->next_pts= AV_NOPTS_VALUE;
1781
        ist->is_start = 1;
1782
    }
1783

    
1784
    /* compute buffer size max (should use a complete heuristic) */
1785
    for(i=0;i<nb_input_files;i++) {
1786
        file_table[i].buffer_size_max = 2048;
1787
    }
1788

    
1789
    /* set meta data information from input file if required */
1790
    for (i=0;i<nb_meta_data_maps;i++) {
1791
        AVFormatContext *out_file;
1792
        AVFormatContext *in_file;
1793

    
1794
        int out_file_index = meta_data_maps[i].out_file;
1795
        int in_file_index = meta_data_maps[i].in_file;
1796
        if ( out_file_index < 0 || out_file_index >= nb_output_files ) {
1797
            fprintf(stderr, "Invalid output file index %d map_meta_data(%d,%d)\n", out_file_index, out_file_index, in_file_index);
1798
            ret = -EINVAL;
1799
            goto fail;
1800
        }
1801
        if ( in_file_index < 0 || in_file_index >= nb_input_files ) {
1802
            fprintf(stderr, "Invalid input file index %d map_meta_data(%d,%d)\n", in_file_index, out_file_index, in_file_index);
1803
            ret = -EINVAL;
1804
            goto fail;
1805
        }
1806

    
1807
        out_file = output_files[out_file_index];
1808
        in_file = input_files[in_file_index];
1809

    
1810
        strcpy(out_file->title, in_file->title);
1811
        strcpy(out_file->author, in_file->author);
1812
        strcpy(out_file->copyright, in_file->copyright);
1813
        strcpy(out_file->comment, in_file->comment);
1814
        strcpy(out_file->album, in_file->album);
1815
        out_file->year = in_file->year;
1816
        out_file->track = in_file->track;
1817
        strcpy(out_file->genre, in_file->genre);
1818
    }
1819

    
1820
    /* open files and write file headers */
1821
    for(i=0;i<nb_output_files;i++) {
1822
        os = output_files[i];
1823
        if (av_write_header(os) < 0) {
1824
            fprintf(stderr, "Could not write header for output file #%d (incorrect codec parameters ?)\n", i);
1825
            ret = -EINVAL;
1826
            goto fail;
1827
        }
1828
    }
1829

    
1830
#ifndef __MINGW32__
1831
    if ( !using_stdin && verbose >= 0) {
1832
        fprintf(stderr, "Press [q] to stop encoding\n");
1833
        url_set_interrupt_cb(decode_interrupt_cb);
1834
    }
1835
#endif
1836
    term_init();
1837

    
1838
    stream_no_data = 0;
1839
    key = -1;
1840

    
1841
    for(; received_sigterm == 0;) {
1842
        int file_index, ist_index;
1843
        AVPacket pkt;
1844
        double ipts_min;
1845
        double opts_min;
1846

    
1847
    redo:
1848
        ipts_min= 1e100;
1849
        opts_min= 1e100;
1850
        /* if 'q' pressed, exits */
1851
        if (!using_stdin) {
1852
            if (q_pressed)
1853
                break;
1854
            /* read_key() returns 0 on EOF */
1855
            key = read_key();
1856
            if (key == 'q')
1857
                break;
1858
        }
1859

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

    
1893
        /* finish if recording time exhausted */
1894
        if (recording_time > 0 && opts_min >= (recording_time / 1000000.0))
1895
            break;
1896

    
1897
        /* finish if limit size exhausted */
1898
        if (limit_filesize != 0 && (limit_filesize * 1024) < url_ftell(&output_files[0]->pb))
1899
            break;
1900

    
1901
        /* read a frame from it and output it in the fifo */
1902
        is = input_files[file_index];
1903
        if (av_read_frame(is, &pkt) < 0) {
1904
            file_table[file_index].eof_reached = 1;
1905
            if (opt_shortest) break; else continue; //
1906
        }
1907

    
1908
        if (!pkt.size) {
1909
            stream_no_data = is;
1910
        } else {
1911
            stream_no_data = 0;
1912
        }
1913
        if (do_pkt_dump) {
1914
            av_pkt_dump(stdout, &pkt, do_hex_dump);
1915
        }
1916
        /* the following test is needed in case new streams appear
1917
           dynamically in stream : we ignore them */
1918
        if (pkt.stream_index >= file_table[file_index].nb_streams)
1919
            goto discard_packet;
1920
        ist_index = file_table[file_index].ist_index + pkt.stream_index;
1921
        ist = ist_table[ist_index];
1922
        if (ist->discard)
1923
            goto discard_packet;
1924

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

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

    
1943
            if (verbose >= 0)
1944
                fprintf(stderr, "Error while decoding stream #%d.%d\n",
1945
                        ist->file_index, ist->index);
1946

    
1947
            av_free_packet(&pkt);
1948
            goto redo;
1949
        }
1950

    
1951
    discard_packet:
1952
        av_free_packet(&pkt);
1953

    
1954
        /* dump report by using the output first video and audio streams */
1955
        print_report(output_files, ost_table, nb_ostreams, 0);
1956
    }
1957

    
1958
    /* at the end of stream, we must flush the decoder buffers */
1959
    for(i=0;i<nb_istreams;i++) {
1960
        ist = ist_table[i];
1961
        if (ist->decoding_needed) {
1962
            output_packet(ist, i, ost_table, nb_ostreams, NULL);
1963
        }
1964
    }
1965

    
1966
    term_exit();
1967

    
1968
    /* write the trailer if needed and close file */
1969
    for(i=0;i<nb_output_files;i++) {
1970
        os = output_files[i];
1971
        av_write_trailer(os);
1972
    }
1973

    
1974
    /* dump report by using the first video and audio streams */
1975
    print_report(output_files, ost_table, nb_ostreams, 1);
1976

    
1977
    /* close each encoder */
1978
    for(i=0;i<nb_ostreams;i++) {
1979
        ost = ost_table[i];
1980
        if (ost->encoding_needed) {
1981
            av_freep(&ost->st->codec->stats_in);
1982
            avcodec_close(ost->st->codec);
1983
        }
1984
    }
1985

    
1986
    /* close each decoder */
1987
    for(i=0;i<nb_istreams;i++) {
1988
        ist = ist_table[i];
1989
        if (ist->decoding_needed) {
1990
            avcodec_close(ist->st->codec);
1991
        }
1992
    }
1993

    
1994
    /* finished ! */
1995

    
1996
    ret = 0;
1997
 fail1:
1998
    av_freep(&bit_buffer);
1999
    av_free(file_table);
2000

    
2001
    if (ist_table) {
2002
        for(i=0;i<nb_istreams;i++) {
2003
            ist = ist_table[i];
2004
            av_free(ist);
2005
        }
2006
        av_free(ist_table);
2007
    }
2008
    if (ost_table) {
2009
        for(i=0;i<nb_ostreams;i++) {
2010
            ost = ost_table[i];
2011
            if (ost) {
2012
                if (ost->logfile) {
2013
                    fclose(ost->logfile);
2014
                    ost->logfile = NULL;
2015
                }
2016
                av_fifo_free(&ost->fifo); /* works even if fifo is not
2017
                                             initialized but set to zero */
2018
                av_free(ost->pict_tmp.data[0]);
2019
                if (ost->video_resample)
2020
                    sws_freeContext(ost->img_resample_ctx);
2021
                if (ost->audio_resample)
2022
                    audio_resample_close(ost->resample);
2023
                av_free(ost);
2024
            }
2025
        }
2026
        av_free(ost_table);
2027
    }
2028
    return ret;
2029
 fail:
2030
    ret = -ENOMEM;
2031
    goto fail1;
2032
}
2033

    
2034
#if 0
2035
int file_read(const char *filename)
2036
{
2037
    URLContext *h;
2038
    unsigned char buffer[1024];
2039
    int len, i;
2040

2041
    if (url_open(&h, filename, O_RDONLY) < 0) {
2042
        printf("could not open '%s'\n", filename);
2043
        return -1;
2044
    }
2045
    for(;;) {
2046
        len = url_read(h, buffer, sizeof(buffer));
2047
        if (len <= 0)
2048
            break;
2049
        for(i=0;i<len;i++) putchar(buffer[i]);
2050
    }
2051
    url_close(h);
2052
    return 0;
2053
}
2054
#endif
2055

    
2056
static void opt_image_format(const char *arg)
2057
{
2058
    AVImageFormat *f;
2059

    
2060
    for(f = first_image_format; f != NULL; f = f->next) {
2061
        if (!strcmp(arg, f->name))
2062
            break;
2063
    }
2064
    if (!f) {
2065
        fprintf(stderr, "Unknown image format: '%s'\n", arg);
2066
        exit(1);
2067
    }
2068
    image_format = f;
2069
}
2070

    
2071
static void opt_format(const char *arg)
2072
{
2073
    /* compatibility stuff for pgmyuv */
2074
    if (!strcmp(arg, "pgmyuv")) {
2075
        pgmyuv_compatibility_hack=1;
2076
//        opt_image_format(arg);
2077
        arg = "image2";
2078
    }
2079

    
2080
    file_iformat = av_find_input_format(arg);
2081
    file_oformat = guess_format(arg, NULL, NULL);
2082
    if (!file_iformat && !file_oformat) {
2083
        fprintf(stderr, "Unknown input or output format: %s\n", arg);
2084
        exit(1);
2085
    }
2086
}
2087

    
2088
static void opt_video_rc_eq(char *arg)
2089
{
2090
    video_rc_eq = arg;
2091
}
2092

    
2093
static void opt_video_rc_override_string(char *arg)
2094
{
2095
    video_rc_override_string = arg;
2096
}
2097

    
2098
static void opt_me_threshold(const char *arg)
2099
{
2100
    me_threshold = atoi(arg);
2101
}
2102

    
2103
static void opt_verbose(const char *arg)
2104
{
2105
    verbose = atoi(arg);
2106
    av_log_set_level(atoi(arg));
2107
}
2108

    
2109
static void opt_frame_rate(const char *arg)
2110
{
2111
    if (parse_frame_rate(&frame_rate, &frame_rate_base, arg) < 0) {
2112
        fprintf(stderr, "Incorrect frame rate\n");
2113
        exit(1);
2114
    }
2115
}
2116

    
2117
static void opt_frame_crop_top(const char *arg)
2118
{
2119
    frame_topBand = atoi(arg);
2120
    if (frame_topBand < 0) {
2121
        fprintf(stderr, "Incorrect top crop size\n");
2122
        exit(1);
2123
    }
2124
    if ((frame_topBand % 2) != 0) {
2125
        fprintf(stderr, "Top crop size must be a multiple of 2\n");
2126
        exit(1);
2127
    }
2128
    if ((frame_topBand) >= frame_height){
2129
        fprintf(stderr, "Vertical crop dimensions are outside the range of the original image.\nRemember to crop first and scale second.\n");
2130
        exit(1);
2131
    }
2132
    frame_height -= frame_topBand;
2133
}
2134

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

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

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

    
2189
static void opt_frame_size(const char *arg)
2190
{
2191
    if (parse_image_size(&frame_width, &frame_height, arg) < 0) {
2192
        fprintf(stderr, "Incorrect frame size\n");
2193
        exit(1);
2194
    }
2195
    if ((frame_width % 2) != 0 || (frame_height % 2) != 0) {
2196
        fprintf(stderr, "Frame size must be a multiple of 2\n");
2197
        exit(1);
2198
    }
2199
}
2200

    
2201

    
2202
#define SCALEBITS 10
2203
#define ONE_HALF  (1 << (SCALEBITS - 1))
2204
#define FIX(x)    ((int) ((x) * (1<<SCALEBITS) + 0.5))
2205

    
2206
#define RGB_TO_Y(r, g, b) \
2207
((FIX(0.29900) * (r) + FIX(0.58700) * (g) + \
2208
  FIX(0.11400) * (b) + ONE_HALF) >> SCALEBITS)
2209

    
2210
#define RGB_TO_U(r1, g1, b1, shift)\
2211
(((- FIX(0.16874) * r1 - FIX(0.33126) * g1 +         \
2212
     FIX(0.50000) * b1 + (ONE_HALF << shift) - 1) >> (SCALEBITS + shift)) + 128)
2213

    
2214
#define RGB_TO_V(r1, g1, b1, shift)\
2215
(((FIX(0.50000) * r1 - FIX(0.41869) * g1 -           \
2216
   FIX(0.08131) * b1 + (ONE_HALF << shift) - 1) >> (SCALEBITS + shift)) + 128)
2217

    
2218
static void opt_pad_color(const char *arg) {
2219
    /* Input is expected to be six hex digits similar to
2220
       how colors are expressed in html tags (but without the #) */
2221
    int rgb = strtol(arg, NULL, 16);
2222
    int r,g,b;
2223

    
2224
    r = (rgb >> 16);
2225
    g = ((rgb >> 8) & 255);
2226
    b = (rgb & 255);
2227

    
2228
    padcolor[0] = RGB_TO_Y(r,g,b);
2229
    padcolor[1] = RGB_TO_U(r,g,b,0);
2230
    padcolor[2] = RGB_TO_V(r,g,b,0);
2231
}
2232

    
2233
static void opt_frame_pad_top(const char *arg)
2234
{
2235
    frame_padtop = atoi(arg);
2236
    if (frame_padtop < 0) {
2237
        fprintf(stderr, "Incorrect top pad size\n");
2238
        exit(1);
2239
    }
2240
    if ((frame_padtop % 2) != 0) {
2241
        fprintf(stderr, "Top pad size must be a multiple of 2\n");
2242
        exit(1);
2243
    }
2244
}
2245

    
2246
static void opt_frame_pad_bottom(const char *arg)
2247
{
2248
    frame_padbottom = atoi(arg);
2249
    if (frame_padbottom < 0) {
2250
        fprintf(stderr, "Incorrect bottom pad size\n");
2251
        exit(1);
2252
    }
2253
    if ((frame_padbottom % 2) != 0) {
2254
        fprintf(stderr, "Bottom pad size must be a multiple of 2\n");
2255
        exit(1);
2256
    }
2257
}
2258

    
2259

    
2260
static void opt_frame_pad_left(const char *arg)
2261
{
2262
    frame_padleft = atoi(arg);
2263
    if (frame_padleft < 0) {
2264
        fprintf(stderr, "Incorrect left pad size\n");
2265
        exit(1);
2266
    }
2267
    if ((frame_padleft % 2) != 0) {
2268
        fprintf(stderr, "Left pad size must be a multiple of 2\n");
2269
        exit(1);
2270
    }
2271
}
2272

    
2273

    
2274
static void opt_frame_pad_right(const char *arg)
2275
{
2276
    frame_padright = atoi(arg);
2277
    if (frame_padright < 0) {
2278
        fprintf(stderr, "Incorrect right pad size\n");
2279
        exit(1);
2280
    }
2281
    if ((frame_padright % 2) != 0) {
2282
        fprintf(stderr, "Right pad size must be a multiple of 2\n");
2283
        exit(1);
2284
    }
2285
}
2286

    
2287

    
2288
static void opt_frame_pix_fmt(const char *arg)
2289
{
2290
    frame_pix_fmt = avcodec_get_pix_fmt(arg);
2291
}
2292

    
2293
static void opt_frame_aspect_ratio(const char *arg)
2294
{
2295
    int x = 0, y = 0;
2296
    double ar = 0;
2297
    const char *p;
2298

    
2299
    p = strchr(arg, ':');
2300
    if (p) {
2301
        x = strtol(arg, (char **)&arg, 10);
2302
        if (arg == p)
2303
            y = strtol(arg+1, (char **)&arg, 10);
2304
        if (x > 0 && y > 0)
2305
            ar = (double)x / (double)y;
2306
    } else
2307
        ar = strtod(arg, (char **)&arg);
2308

    
2309
    if (!ar) {
2310
        fprintf(stderr, "Incorrect aspect ratio specification.\n");
2311
        exit(1);
2312
    }
2313
    frame_aspect_ratio = ar;
2314
}
2315

    
2316
static void opt_qscale(const char *arg)
2317
{
2318
    video_qscale = atof(arg);
2319
    if (video_qscale <= 0 ||
2320
        video_qscale > 255) {
2321
        fprintf(stderr, "qscale must be > 0.0 and <= 255\n");
2322
        exit(1);
2323
    }
2324
}
2325

    
2326
static void opt_lmax(const char *arg)
2327
{
2328
    video_lmax = atof(arg)*FF_QP2LAMBDA;
2329
}
2330

    
2331
static void opt_lmin(const char *arg)
2332
{
2333
    video_lmin = atof(arg)*FF_QP2LAMBDA;
2334
}
2335

    
2336
static void opt_mb_lmin(const char *arg)
2337
{
2338
    video_mb_lmin = atof(arg)*FF_QP2LAMBDA;
2339
    if (video_mb_lmin < 1 ||
2340
        video_mb_lmin > FF_LAMBDA_MAX) {
2341
        fprintf(stderr, "mblmin must be >= 1 and <= %d\n", FF_LAMBDA_MAX / FF_QP2LAMBDA);
2342
        exit(1);
2343
    }
2344
}
2345

    
2346
static void opt_mb_lmax(const char *arg)
2347
{
2348
    video_mb_lmax = atof(arg)*FF_QP2LAMBDA;
2349
    if (video_mb_lmax < 1 ||
2350
        video_mb_lmax > FF_LAMBDA_MAX) {
2351
        fprintf(stderr, "mblmax must be >= 1 and <= %d\n", FF_LAMBDA_MAX / FF_QP2LAMBDA);
2352
        exit(1);
2353
    }
2354
}
2355

    
2356
static void opt_qdiff(const char *arg)
2357
{
2358
    video_qdiff = atoi(arg);
2359
    if (video_qdiff < 0 ||
2360
        video_qdiff > 31) {
2361
        fprintf(stderr, "qdiff must be >= 1 and <= 31\n");
2362
        exit(1);
2363
    }
2364
}
2365

    
2366
static void opt_packet_size(const char *arg)
2367
{
2368
    packet_size= atoi(arg);
2369
}
2370

    
2371
static void opt_error_rate(const char *arg)
2372
{
2373
    error_rate= atoi(arg);
2374
}
2375

    
2376
static void opt_strict(const char *arg)
2377
{
2378
    strict= atoi(arg);
2379
}
2380

    
2381
static void opt_top_field_first(const char *arg)
2382
{
2383
    top_field_first= atoi(arg);
2384
}
2385

    
2386
static void opt_thread_count(const char *arg)
2387
{
2388
    thread_count= atoi(arg);
2389
#if !defined(HAVE_THREADS)
2390
    if (verbose >= 0)
2391
        fprintf(stderr, "Warning: not compiled with thread support, using thread emulation\n");
2392
#endif
2393
}
2394

    
2395
static void opt_audio_bitrate(const char *arg)
2396
{
2397
    audio_bit_rate = atoi(arg) * 1000;
2398
}
2399

    
2400
static void opt_audio_rate(const char *arg)
2401
{
2402
    audio_sample_rate = atoi(arg);
2403
}
2404

    
2405
static void opt_audio_channels(const char *arg)
2406
{
2407
    audio_channels = atoi(arg);
2408
}
2409

    
2410
static void opt_video_device(const char *arg)
2411
{
2412
    video_device = av_strdup(arg);
2413
}
2414

    
2415
static void opt_grab_device(const char *arg)
2416
{
2417
    grab_device = av_strdup(arg);
2418
}
2419

    
2420
static void opt_video_channel(const char *arg)
2421
{
2422
    video_channel = strtol(arg, NULL, 0);
2423
}
2424

    
2425
static void opt_video_standard(const char *arg)
2426
{
2427
    video_standard = av_strdup(arg);
2428
}
2429

    
2430
static void opt_audio_device(const char *arg)
2431
{
2432
    audio_device = av_strdup(arg);
2433
}
2434

    
2435
static void opt_codec(int *pstream_copy, int *pcodec_id,
2436
                      int codec_type, const char *arg)
2437
{
2438
    AVCodec *p;
2439

    
2440
    if (!strcmp(arg, "copy")) {
2441
        *pstream_copy = 1;
2442
    } else {
2443
        p = first_avcodec;
2444
        while (p) {
2445
            if (!strcmp(p->name, arg) && p->type == codec_type)
2446
                break;
2447
            p = p->next;
2448
        }
2449
        if (p == NULL) {
2450
            fprintf(stderr, "Unknown codec '%s'\n", arg);
2451
            exit(1);
2452
        } else {
2453
            *pcodec_id = p->id;
2454
        }
2455
    }
2456
}
2457

    
2458
static void opt_audio_codec(const char *arg)
2459
{
2460
    opt_codec(&audio_stream_copy, &audio_codec_id, CODEC_TYPE_AUDIO, arg);
2461
}
2462

    
2463
static void opt_audio_tag(const char *arg)
2464
{
2465
    char *tail;
2466
    audio_codec_tag= strtol(arg, &tail, 0);
2467

    
2468
    if(!tail || *tail)
2469
        audio_codec_tag= arg[0] + (arg[1]<<8) + (arg[2]<<16) + (arg[3]<<24);
2470
}
2471

    
2472
static void opt_video_tag(const char *arg)
2473
{
2474
    char *tail;
2475
    video_codec_tag= strtol(arg, &tail, 0);
2476

    
2477
    if(!tail || *tail)
2478
        video_codec_tag= arg[0] + (arg[1]<<8) + (arg[2]<<16) + (arg[3]<<24);
2479
}
2480

    
2481
static void add_frame_hooker(const char *arg)
2482
{
2483
    int argc = 0;
2484
    char *argv[64];
2485
    int i;
2486
    char *args = av_strdup(arg);
2487

    
2488
    using_vhook = 1;
2489

    
2490
    argv[0] = strtok(args, " ");
2491
    while (argc < 62 && (argv[++argc] = strtok(NULL, " "))) {
2492
    }
2493

    
2494
    i = frame_hook_add(argc, argv);
2495

    
2496
    if (i != 0) {
2497
        fprintf(stderr, "Failed to add video hook function: %s\n", arg);
2498
        exit(1);
2499
    }
2500
}
2501

    
2502
const char *motion_str[] = {
2503
    "zero",
2504
    "full",
2505
    "log",
2506
    "phods",
2507
    "epzs",
2508
    "x1",
2509
    "hex",
2510
    "umh",
2511
    "iter",
2512
    NULL,
2513
};
2514

    
2515
static void opt_motion_estimation(const char *arg)
2516
{
2517
    const char **p;
2518
    p = motion_str;
2519
    for(;;) {
2520
        if (!*p) {
2521
            fprintf(stderr, "Unknown motion estimation method '%s'\n", arg);
2522
            exit(1);
2523
        }
2524
        if (!strcmp(*p, arg))
2525
            break;
2526
        p++;
2527
    }
2528
    me_method = (p - motion_str) + 1;
2529
}
2530

    
2531
static void opt_video_codec(const char *arg)
2532
{
2533
    opt_codec(&video_stream_copy, &video_codec_id, CODEC_TYPE_VIDEO, arg);
2534
}
2535

    
2536
static void opt_subtitle_codec(const char *arg)
2537
{
2538
    opt_codec(&subtitle_stream_copy, &subtitle_codec_id, CODEC_TYPE_SUBTITLE, arg);
2539
}
2540

    
2541
static void opt_map(const char *arg)
2542
{
2543
    AVStreamMap *m;
2544
    const char *p;
2545

    
2546
    p = arg;
2547
    m = &stream_maps[nb_stream_maps++];
2548

    
2549
    m->file_index = strtol(arg, (char **)&p, 0);
2550
    if (*p)
2551
        p++;
2552

    
2553
    m->stream_index = strtol(p, (char **)&p, 0);
2554
    if (*p) {
2555
        p++;
2556
        m->sync_file_index = strtol(p, (char **)&p, 0);
2557
        if (*p)
2558
            p++;
2559
        m->sync_stream_index = strtol(p, (char **)&p, 0);
2560
    } else {
2561
        m->sync_file_index = m->file_index;
2562
        m->sync_stream_index = m->stream_index;
2563
    }
2564
}
2565

    
2566
static void opt_map_meta_data(const char *arg)
2567
{
2568
    AVMetaDataMap *m;
2569
    const char *p;
2570

    
2571
    p = arg;
2572
    m = &meta_data_maps[nb_meta_data_maps++];
2573

    
2574
    m->out_file = strtol(arg, (char **)&p, 0);
2575
    if (*p)
2576
        p++;
2577

    
2578
    m->in_file = strtol(p, (char **)&p, 0);
2579
}
2580

    
2581
static void opt_recording_time(const char *arg)
2582
{
2583
    recording_time = parse_date(arg, 1);
2584
}
2585

    
2586
static void opt_start_time(const char *arg)
2587
{
2588
    start_time = parse_date(arg, 1);
2589
}
2590

    
2591
static void opt_rec_timestamp(const char *arg)
2592
{
2593
    rec_timestamp = parse_date(arg, 0) / 1000000;
2594
}
2595

    
2596
static void opt_input_ts_offset(const char *arg)
2597
{
2598
    input_ts_offset = parse_date(arg, 1);
2599
}
2600

    
2601
static void opt_input_file(const char *filename)
2602
{
2603
    AVFormatContext *ic;
2604
    AVFormatParameters params, *ap = &params;
2605
    int err, i, ret, rfps, rfps_base;
2606
    int64_t timestamp;
2607

    
2608
    if (!strcmp(filename, "-"))
2609
        filename = "pipe:";
2610

    
2611
    using_stdin |= !strncmp(filename, "pipe:", 5) ||
2612
                   !strcmp( filename, "/dev/stdin" );
2613

    
2614
    /* get default parameters from command line */
2615
    ic = av_alloc_format_context();
2616

    
2617
    memset(ap, 0, sizeof(*ap));
2618
    ap->prealloced_context = 1;
2619
    ap->sample_rate = audio_sample_rate;
2620
    ap->channels = audio_channels;
2621
    ap->time_base.den = frame_rate;
2622
    ap->time_base.num = frame_rate_base;
2623
    ap->width = frame_width + frame_padleft + frame_padright;
2624
    ap->height = frame_height + frame_padtop + frame_padbottom;
2625
    ap->image_format = image_format;
2626
    ap->pix_fmt = frame_pix_fmt;
2627
    ap->device  = grab_device;
2628
    ap->channel = video_channel;
2629
    ap->standard = video_standard;
2630
    ap->video_codec_id = video_codec_id;
2631
    ap->audio_codec_id = audio_codec_id;
2632
    if(pgmyuv_compatibility_hack)
2633
        ap->video_codec_id= CODEC_ID_PGMYUV;
2634

    
2635
    for(i=0; i<opt_name_count; i++){
2636
        AVOption *opt;
2637
        double d= av_get_double(avformat_opts, opt_names[i], &opt);
2638
        if(d==d && (opt->flags&AV_OPT_FLAG_DECODING_PARAM))
2639
            av_set_double(ic, opt_names[i], d);
2640
    }
2641
    /* open the input file with generic libav function */
2642
    err = av_open_input_file(&ic, filename, file_iformat, 0, ap);
2643
    if (err < 0) {
2644
        print_error(filename, err);
2645
        exit(1);
2646
    }
2647

    
2648
    ic->loop_input = loop_input;
2649

    
2650
    /* If not enough info to get the stream parameters, we decode the
2651
       first frames to get it. (used in mpeg case for example) */
2652
    ret = av_find_stream_info(ic);
2653
    if (ret < 0 && verbose >= 0) {
2654
        fprintf(stderr, "%s: could not find codec parameters\n", filename);
2655
        exit(1);
2656
    }
2657

    
2658
    timestamp = start_time;
2659
    /* add the stream start time */
2660
    if (ic->start_time != AV_NOPTS_VALUE)
2661
        timestamp += ic->start_time;
2662

    
2663
    /* if seeking requested, we execute it */
2664
    if (start_time != 0) {
2665
        ret = av_seek_frame(ic, -1, timestamp, AVSEEK_FLAG_BACKWARD);
2666
        if (ret < 0) {
2667
            fprintf(stderr, "%s: could not seek to position %0.3f\n",
2668
                    filename, (double)timestamp / AV_TIME_BASE);
2669
        }
2670
        /* reset seek info */
2671
        start_time = 0;
2672
    }
2673

    
2674
    /* update the current parameters so that they match the one of the input stream */
2675
    for(i=0;i<ic->nb_streams;i++) {
2676
        int j;
2677
        AVCodecContext *enc = ic->streams[i]->codec;
2678
#if defined(HAVE_THREADS)
2679
        if(thread_count>1)
2680
            avcodec_thread_init(enc, thread_count);
2681
#endif
2682
        enc->thread_count= thread_count;
2683
        switch(enc->codec_type) {
2684
        case CODEC_TYPE_AUDIO:
2685
            for(j=0; j<opt_name_count; j++){
2686
                AVOption *opt;
2687
                double d= av_get_double(avctx_opts, opt_names[j], &opt);
2688
                if(d==d && (opt->flags&AV_OPT_FLAG_AUDIO_PARAM) && (opt->flags&AV_OPT_FLAG_DECODING_PARAM))
2689
                    av_set_double(enc, opt_names[j], d);
2690
            }
2691
            //fprintf(stderr, "\nInput Audio channels: %d", enc->channels);
2692
            audio_channels = enc->channels;
2693
            audio_sample_rate = enc->sample_rate;
2694
            if(audio_disable)
2695
                ic->streams[i]->discard= AVDISCARD_ALL;
2696
            break;
2697
        case CODEC_TYPE_VIDEO:
2698
            for(j=0; j<opt_name_count; j++){
2699
                AVOption *opt;
2700
                double d= av_get_double(avctx_opts, opt_names[j], &opt);
2701
                if(d==d && (opt->flags&AV_OPT_FLAG_VIDEO_PARAM) && (opt->flags&AV_OPT_FLAG_DECODING_PARAM))
2702
                    av_set_double(enc, opt_names[j], d);
2703
            }
2704
            frame_height = enc->height;
2705
            frame_width = enc->width;
2706
            frame_aspect_ratio = av_q2d(enc->sample_aspect_ratio) * enc->width / enc->height;
2707
            frame_pix_fmt = enc->pix_fmt;
2708
            rfps      = ic->streams[i]->r_frame_rate.num;
2709
            rfps_base = ic->streams[i]->r_frame_rate.den;
2710
            if(enc->lowres) enc->flags |= CODEC_FLAG_EMU_EDGE;
2711
            if(me_threshold)
2712
                enc->debug |= FF_DEBUG_MV;
2713

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

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

    
2720
                    (float)rfps / rfps_base, rfps, rfps_base);
2721
            }
2722
            /* update the current frame rate to match the stream frame rate */
2723
            frame_rate      = rfps;
2724
            frame_rate_base = rfps_base;
2725

    
2726
            enc->rate_emu = rate_emu;
2727
            if(video_disable)
2728
                ic->streams[i]->discard= AVDISCARD_ALL;
2729
            else if(video_discard)
2730
                ic->streams[i]->discard= video_discard;
2731
            break;
2732
        case CODEC_TYPE_DATA:
2733
            break;
2734
        case CODEC_TYPE_SUBTITLE:
2735
            break;
2736
        case CODEC_TYPE_UNKNOWN:
2737
            break;
2738
        default:
2739
            av_abort();
2740
        }
2741
    }
2742

    
2743
    input_files[nb_input_files] = ic;
2744
    input_files_ts_offset[nb_input_files] = input_ts_offset - (copy_ts ? 0 : timestamp);
2745
    /* dump the file content */
2746
    if (verbose >= 0)
2747
        dump_format(ic, nb_input_files, filename, 0);
2748

    
2749
    nb_input_files++;
2750
    file_iformat = NULL;
2751
    file_oformat = NULL;
2752
    image_format = NULL;
2753

    
2754
    grab_device = NULL;
2755
    video_channel = 0;
2756

    
2757
    rate_emu = 0;
2758
}
2759

    
2760
static void opt_grab(const char *arg)
2761
{
2762
    file_iformat = av_find_input_format(arg);
2763
    opt_input_file("");
2764
}
2765

    
2766
static void check_audio_video_inputs(int *has_video_ptr, int *has_audio_ptr)
2767
{
2768
    int has_video, has_audio, i, j;
2769
    AVFormatContext *ic;
2770

    
2771
    has_video = 0;
2772
    has_audio = 0;
2773
    for(j=0;j<nb_input_files;j++) {
2774
        ic = input_files[j];
2775
        for(i=0;i<ic->nb_streams;i++) {
2776
            AVCodecContext *enc = ic->streams[i]->codec;
2777
            switch(enc->codec_type) {
2778
            case CODEC_TYPE_AUDIO:
2779
                has_audio = 1;
2780
                break;
2781
            case CODEC_TYPE_VIDEO:
2782
                has_video = 1;
2783
                break;
2784
            case CODEC_TYPE_DATA:
2785
            case CODEC_TYPE_UNKNOWN:
2786
            case CODEC_TYPE_SUBTITLE:
2787
                break;
2788
            default:
2789
                av_abort();
2790
            }
2791
        }
2792
    }
2793
    *has_video_ptr = has_video;
2794
    *has_audio_ptr = has_audio;
2795
}
2796

    
2797
static void new_video_stream(AVFormatContext *oc)
2798
{
2799
    AVStream *st;
2800
    AVCodecContext *video_enc;
2801
    int codec_id;
2802

    
2803
    st = av_new_stream(oc, oc->nb_streams);
2804
    if (!st) {
2805
        fprintf(stderr, "Could not alloc stream\n");
2806
        exit(1);
2807
    }
2808
    bitstream_filters[nb_output_files][oc->nb_streams - 1]= video_bitstream_filters;
2809
    video_bitstream_filters= NULL;
2810

    
2811
#if defined(HAVE_THREADS)
2812
    if(thread_count>1)
2813
        avcodec_thread_init(st->codec, thread_count);
2814
#endif
2815

    
2816
    video_enc = st->codec;
2817

    
2818
    if(video_codec_tag)
2819
        video_enc->codec_tag= video_codec_tag;
2820

    
2821
    if(   (video_global_header&1)
2822
       || (video_global_header==0 && (oc->oformat->flags & AVFMT_GLOBALHEADER))){
2823
        video_enc->flags |= CODEC_FLAG_GLOBAL_HEADER;
2824
        avctx_opts->flags|= CODEC_FLAG_GLOBAL_HEADER;
2825
    }
2826
    if(video_global_header&2){
2827
        video_enc->flags2 |= CODEC_FLAG2_LOCAL_HEADER;
2828
        avctx_opts->flags2|= CODEC_FLAG2_LOCAL_HEADER;
2829
    }
2830

    
2831
    if (video_stream_copy) {
2832
        st->stream_copy = 1;
2833
        video_enc->codec_type = CODEC_TYPE_VIDEO;
2834
    } else {
2835
        char *p;
2836
        int i;
2837
        AVCodec *codec;
2838

    
2839
        codec_id = av_guess_codec(oc->oformat, NULL, oc->filename, NULL, CODEC_TYPE_VIDEO);
2840
        if (video_codec_id != CODEC_ID_NONE)
2841
            codec_id = video_codec_id;
2842

    
2843
        video_enc->codec_id = codec_id;
2844
        codec = avcodec_find_encoder(codec_id);
2845

    
2846
        for(i=0; i<opt_name_count; i++){
2847
             AVOption *opt;
2848
             double d= av_get_double(avctx_opts, opt_names[i], &opt);
2849
             if(d==d && (opt->flags&AV_OPT_FLAG_VIDEO_PARAM) && (opt->flags&AV_OPT_FLAG_ENCODING_PARAM))
2850
                 av_set_double(video_enc, opt_names[i], d);
2851
        }
2852

    
2853
        video_enc->time_base.den = frame_rate;
2854
        video_enc->time_base.num = frame_rate_base;
2855
        if(codec && codec->supported_framerates){
2856
            const AVRational *p= codec->supported_framerates;
2857
            AVRational req= (AVRational){frame_rate, frame_rate_base};
2858
            const AVRational *best=NULL;
2859
            AVRational best_error= (AVRational){INT_MAX, 1};
2860
            for(; p->den!=0; p++){
2861
                AVRational error= av_sub_q(req, *p);
2862
                if(error.num <0) error.num *= -1;
2863
                if(av_cmp_q(error, best_error) < 0){
2864
                    best_error= error;
2865
                    best= p;
2866
                }
2867
            }
2868
            video_enc->time_base.den= best->num;
2869
            video_enc->time_base.num= best->den;
2870
        }
2871

    
2872
        video_enc->width = frame_width + frame_padright + frame_padleft;
2873
        video_enc->height = frame_height + frame_padtop + frame_padbottom;
2874
        video_enc->sample_aspect_ratio = av_d2q(frame_aspect_ratio*video_enc->height/video_enc->width, 255);
2875
        video_enc->pix_fmt = frame_pix_fmt;
2876

    
2877
        if(codec && codec->pix_fmts){
2878
            const enum PixelFormat *p= codec->pix_fmts;
2879
            for(; *p!=-1; p++){
2880
                if(*p == video_enc->pix_fmt)
2881
                    break;
2882
            }
2883
            if(*p == -1)
2884
                video_enc->pix_fmt = codec->pix_fmts[0];
2885
        }
2886

    
2887
        if (intra_only)
2888
            video_enc->gop_size = 0;
2889
        if (video_qscale || same_quality) {
2890
            video_enc->flags |= CODEC_FLAG_QSCALE;
2891
            video_enc->global_quality=
2892
                st->quality = FF_QP2LAMBDA * video_qscale;
2893
        }
2894

    
2895
        if(intra_matrix)
2896
            video_enc->intra_matrix = intra_matrix;
2897
        if(inter_matrix)
2898
            video_enc->inter_matrix = inter_matrix;
2899

    
2900
        video_enc->lmin = video_lmin;
2901
        video_enc->lmax = video_lmax;
2902
        video_enc->mb_lmin = video_mb_lmin;
2903
        video_enc->mb_lmax = video_mb_lmax;
2904
        video_enc->max_qdiff = video_qdiff;
2905
        video_enc->rc_eq = video_rc_eq;
2906
        video_enc->thread_count = thread_count;
2907
        p= video_rc_override_string;
2908
        for(i=0; p; i++){
2909
            int start, end, q;
2910
            int e=sscanf(p, "%d,%d,%d", &start, &end, &q);
2911
            if(e!=3){
2912
                fprintf(stderr, "error parsing rc_override\n");
2913
                exit(1);
2914
            }
2915
            video_enc->rc_override=
2916
                av_realloc(video_enc->rc_override,
2917
                           sizeof(RcOverride)*(i+1));
2918
            video_enc->rc_override[i].start_frame= start;
2919
            video_enc->rc_override[i].end_frame  = end;
2920
            if(q>0){
2921
                video_enc->rc_override[i].qscale= q;
2922
                video_enc->rc_override[i].quality_factor= 1.0;
2923
            }
2924
            else{
2925
                video_enc->rc_override[i].qscale= 0;
2926
                video_enc->rc_override[i].quality_factor= -q/100.0;
2927
            }
2928
            p= strchr(p, '/');
2929
            if(p) p++;
2930
        }
2931
        video_enc->rc_override_count=i;
2932
        video_enc->rc_initial_buffer_occupancy = video_enc->rc_buffer_size*3/4;
2933
        video_enc->me_threshold= me_threshold;
2934
        video_enc->intra_dc_precision= intra_dc_precision - 8;
2935
        video_enc->strict_std_compliance = strict;
2936
        video_enc->error_rate = error_rate;
2937
        video_enc->me_penalty_compensation= me_penalty_compensation;
2938
        video_enc->frame_skip_exp= frame_skip_exp;
2939

    
2940
        if(packet_size){
2941
            video_enc->rtp_mode= 1;
2942
            video_enc->rtp_payload_size= packet_size;
2943
        }
2944

    
2945
        if (do_psnr)
2946
            video_enc->flags|= CODEC_FLAG_PSNR;
2947

    
2948
        video_enc->me_method = me_method;
2949

    
2950
        /* two pass mode */
2951
        if (do_pass) {
2952
            if (do_pass == 1) {
2953
                video_enc->flags |= CODEC_FLAG_PASS1;
2954
            } else {
2955
                video_enc->flags |= CODEC_FLAG_PASS2;
2956
            }
2957
        }
2958
    }
2959

    
2960
    /* reset some key parameters */
2961
    video_disable = 0;
2962
    video_codec_id = CODEC_ID_NONE;
2963
    video_stream_copy = 0;
2964
}
2965

    
2966
static void new_audio_stream(AVFormatContext *oc)
2967
{
2968
    AVStream *st;
2969
    AVCodecContext *audio_enc;
2970
    int codec_id, i;
2971

    
2972
    st = av_new_stream(oc, oc->nb_streams);
2973
    if (!st) {
2974
        fprintf(stderr, "Could not alloc stream\n");
2975
        exit(1);
2976
    }
2977

    
2978
    bitstream_filters[nb_output_files][oc->nb_streams - 1]= audio_bitstream_filters;
2979
    audio_bitstream_filters= NULL;
2980

    
2981
#if defined(HAVE_THREADS)
2982
    if(thread_count>1)
2983
        avcodec_thread_init(st->codec, thread_count);
2984
#endif
2985

    
2986
    audio_enc = st->codec;
2987
    audio_enc->codec_type = CODEC_TYPE_AUDIO;
2988

    
2989
    if(audio_codec_tag)
2990
        audio_enc->codec_tag= audio_codec_tag;
2991

    
2992
    if (oc->oformat->flags & AVFMT_GLOBALHEADER) {
2993
        audio_enc->flags |= CODEC_FLAG_GLOBAL_HEADER;
2994
        avctx_opts->flags|= CODEC_FLAG_GLOBAL_HEADER;
2995
    }
2996
    if (audio_stream_copy) {
2997
        st->stream_copy = 1;
2998
        audio_enc->channels = audio_channels;
2999
    } else {
3000
        codec_id = av_guess_codec(oc->oformat, NULL, oc->filename, NULL, CODEC_TYPE_AUDIO);
3001

    
3002
        for(i=0; i<opt_name_count; i++){
3003
            AVOption *opt;
3004
            double d= av_get_double(avctx_opts, opt_names[i], &opt);
3005
            if(d==d && (opt->flags&AV_OPT_FLAG_AUDIO_PARAM) && (opt->flags&AV_OPT_FLAG_ENCODING_PARAM))
3006
                av_set_double(audio_enc, opt_names[i], d);
3007
        }
3008

    
3009
        if (audio_codec_id != CODEC_ID_NONE)
3010
            codec_id = audio_codec_id;
3011
        audio_enc->codec_id = codec_id;
3012

    
3013
        audio_enc->bit_rate = audio_bit_rate;
3014
        if (audio_qscale > QSCALE_NONE) {
3015
            audio_enc->flags |= CODEC_FLAG_QSCALE;
3016
            audio_enc->global_quality = st->quality = FF_QP2LAMBDA * audio_qscale;
3017
        }
3018
        audio_enc->strict_std_compliance = strict;
3019
        audio_enc->thread_count = thread_count;
3020
        /* For audio codecs other than AC3 or DTS we limit */
3021
        /* the number of coded channels to stereo   */
3022
        if (audio_channels > 2 && codec_id != CODEC_ID_AC3
3023
            && codec_id != CODEC_ID_DTS) {
3024
            audio_enc->channels = 2;
3025
        } else
3026
            audio_enc->channels = audio_channels;
3027
    }
3028
    audio_enc->sample_rate = audio_sample_rate;
3029
    audio_enc->time_base= (AVRational){1, audio_sample_rate};
3030
    if (audio_language) {
3031
        pstrcpy(st->language, sizeof(st->language), audio_language);
3032
        av_free(audio_language);
3033
        audio_language = NULL;
3034
    }
3035

    
3036
    /* reset some key parameters */
3037
    audio_disable = 0;
3038
    audio_codec_id = CODEC_ID_NONE;
3039
    audio_stream_copy = 0;
3040
}
3041

    
3042
static void opt_new_subtitle_stream(void)
3043
{
3044
    AVFormatContext *oc;
3045
    AVStream *st;
3046
    AVCodecContext *subtitle_enc;
3047
    int i;
3048

    
3049
    if (nb_output_files <= 0) {
3050
        fprintf(stderr, "At least one output file must be specified\n");
3051
        exit(1);
3052
    }
3053
    oc = output_files[nb_output_files - 1];
3054

    
3055
    st = av_new_stream(oc, oc->nb_streams);
3056
    if (!st) {
3057
        fprintf(stderr, "Could not alloc stream\n");
3058
        exit(1);
3059
    }
3060

    
3061
    subtitle_enc = st->codec;
3062
    subtitle_enc->codec_type = CODEC_TYPE_SUBTITLE;
3063
    if (subtitle_stream_copy) {
3064
        st->stream_copy = 1;
3065
    } else {
3066
        for(i=0; i<opt_name_count; i++){
3067
             AVOption *opt;
3068
             double d= av_get_double(avctx_opts, opt_names[i], &opt);
3069
             if(d==d && (opt->flags&AV_OPT_FLAG_SUBTITLE_PARAM) && (opt->flags&AV_OPT_FLAG_ENCODING_PARAM))
3070
                 av_set_double(subtitle_enc, opt_names[i], d);
3071
        }
3072
        subtitle_enc->codec_id = subtitle_codec_id;
3073
    }
3074

    
3075
    if (subtitle_language) {
3076
        pstrcpy(st->language, sizeof(st->language), subtitle_language);
3077
        av_free(subtitle_language);
3078
        subtitle_language = NULL;
3079
    }
3080

    
3081
    subtitle_codec_id = CODEC_ID_NONE;
3082
    subtitle_stream_copy = 0;
3083
}
3084

    
3085
static void opt_new_audio_stream(void)
3086
{
3087
    AVFormatContext *oc;
3088
    if (nb_output_files <= 0) {
3089
        fprintf(stderr, "At least one output file must be specified\n");
3090
        exit(1);
3091
    }
3092
    oc = output_files[nb_output_files - 1];
3093
    new_audio_stream(oc);
3094
}
3095

    
3096
static void opt_new_video_stream(void)
3097
{
3098
    AVFormatContext *oc;
3099
    if (nb_output_files <= 0) {
3100
        fprintf(stderr, "At least one output file must be specified\n");
3101
        exit(1);
3102
    }
3103
    oc = output_files[nb_output_files - 1];
3104
    new_video_stream(oc);
3105
}
3106

    
3107
static void opt_output_file(const char *filename)
3108
{
3109
    AVFormatContext *oc;
3110
    int use_video, use_audio, input_has_video, input_has_audio, i;
3111
    AVFormatParameters params, *ap = &params;
3112

    
3113
    if (!strcmp(filename, "-"))
3114
        filename = "pipe:";
3115

    
3116
    oc = av_alloc_format_context();
3117

    
3118
    if (!file_oformat) {
3119
        file_oformat = guess_format(NULL, filename, NULL);
3120
        if (!file_oformat) {
3121
            fprintf(stderr, "Unable for find a suitable output format for '%s'\n",
3122
                    filename);
3123
            exit(1);
3124
        }
3125
    }
3126

    
3127
    oc->oformat = file_oformat;
3128
    pstrcpy(oc->filename, sizeof(oc->filename), filename);
3129

    
3130
    if (!strcmp(file_oformat->name, "ffm") &&
3131
        strstart(filename, "http:", NULL)) {
3132
        /* special case for files sent to ffserver: we get the stream
3133
           parameters from ffserver */
3134
        if (read_ffserver_streams(oc, filename) < 0) {
3135
            fprintf(stderr, "Could not read stream parameters from '%s'\n", filename);
3136
            exit(1);
3137
        }
3138
    } else {
3139
        use_video = file_oformat->video_codec != CODEC_ID_NONE || video_stream_copy || video_codec_id != CODEC_ID_NONE;
3140
        use_audio = file_oformat->audio_codec != CODEC_ID_NONE || audio_stream_copy || audio_codec_id != CODEC_ID_NONE;
3141

    
3142
        /* disable if no corresponding type found and at least one
3143
           input file */
3144
        if (nb_input_files > 0) {
3145
            check_audio_video_inputs(&input_has_video, &input_has_audio);
3146
            if (!input_has_video)
3147
                use_video = 0;
3148
            if (!input_has_audio)
3149
                use_audio = 0;
3150
        }
3151

    
3152
        /* manual disable */
3153
        if (audio_disable) {
3154
            use_audio = 0;
3155
        }
3156
        if (video_disable) {
3157
            use_video = 0;
3158
        }
3159

    
3160
        if (use_video) {
3161
            new_video_stream(oc);
3162
        }
3163

    
3164
        if (use_audio) {
3165
            new_audio_stream(oc);
3166
        }
3167

    
3168
        if (!oc->nb_streams) {
3169
            fprintf(stderr, "No audio or video streams available\n");
3170
            exit(1);
3171
        }
3172

    
3173
        oc->timestamp = rec_timestamp;
3174

    
3175
        if (str_title)
3176
            pstrcpy(oc->title, sizeof(oc->title), str_title);
3177
        if (str_author)
3178
            pstrcpy(oc->author, sizeof(oc->author), str_author);
3179
        if (str_copyright)
3180
            pstrcpy(oc->copyright, sizeof(oc->copyright), str_copyright);
3181
        if (str_comment)
3182
            pstrcpy(oc->comment, sizeof(oc->comment), str_comment);
3183
        if (str_album)
3184
            pstrcpy(oc->album, sizeof(oc->album), str_album);
3185
    }
3186

    
3187
    output_files[nb_output_files++] = oc;
3188

    
3189
    /* check filename in case of an image number is expected */
3190
    if (oc->oformat->flags & AVFMT_NEEDNUMBER) {
3191
        if (!av_filename_number_test(oc->filename)) {
3192
            print_error(oc->filename, AVERROR_NUMEXPECTED);
3193
            exit(1);
3194
        }
3195
    }
3196

    
3197
    if (!(oc->oformat->flags & AVFMT_NOFILE)) {
3198
        /* test if it already exists to avoid loosing precious files */
3199
        if (!file_overwrite &&
3200
            (strchr(filename, ':') == NULL ||
3201
             strstart(filename, "file:", NULL))) {
3202
            if (url_exist(filename)) {
3203
                int c;
3204

    
3205
                if ( !using_stdin ) {
3206
                    fprintf(stderr,"File '%s' already exists. Overwrite ? [y/N] ", filename);
3207
                    fflush(stderr);
3208
                    c = getchar();
3209
                    if (toupper(c) != 'Y') {
3210
                        fprintf(stderr, "Not overwriting - exiting\n");
3211
                        exit(1);
3212
                    }
3213
                                }
3214
                                else {
3215
                    fprintf(stderr,"File '%s' already exists. Exiting.\n", filename);
3216
                    exit(1);
3217
                                }
3218
            }
3219
        }
3220

    
3221
        /* open the file */
3222
        if (url_fopen(&oc->pb, filename, URL_WRONLY) < 0) {
3223
            fprintf(stderr, "Could not open '%s'\n", filename);
3224
            exit(1);
3225
        }
3226
    }
3227

    
3228
    memset(ap, 0, sizeof(*ap));
3229
    ap->image_format = image_format;
3230
    if (av_set_parameters(oc, ap) < 0) {
3231
        fprintf(stderr, "%s: Invalid encoding parameters\n",
3232
                oc->filename);
3233
        exit(1);
3234
    }
3235

    
3236
    oc->preload= (int)(mux_preload*AV_TIME_BASE);
3237
    oc->max_delay= (int)(mux_max_delay*AV_TIME_BASE);
3238
    oc->loop_output = loop_output;
3239

    
3240
    for(i=0; i<opt_name_count; i++){
3241
        AVOption *opt;
3242
        double d = av_get_double(avformat_opts, opt_names[i], &opt);
3243
        if(d==d && (opt->flags&AV_OPT_FLAG_ENCODING_PARAM))
3244
            av_set_double(oc, opt_names[i], d);
3245
    }
3246

    
3247
    /* reset some options */
3248
    file_oformat = NULL;
3249
    file_iformat = NULL;
3250
    image_format = NULL;
3251
}
3252

    
3253
/* prepare dummy protocols for grab */
3254
static void prepare_grab(void)
3255
{
3256
    int has_video, has_audio, i, j;
3257
    AVFormatContext *oc;
3258
    AVFormatContext *ic;
3259
    AVFormatParameters vp1, *vp = &vp1;
3260
    AVFormatParameters ap1, *ap = &ap1;
3261

    
3262
    /* see if audio/video inputs are needed */
3263
    has_video = 0;
3264
    has_audio = 0;
3265
    memset(ap, 0, sizeof(*ap));
3266
    memset(vp, 0, sizeof(*vp));
3267
    vp->time_base.num= 1;
3268
    for(j=0;j<nb_output_files;j++) {
3269
        oc = output_files[j];
3270
        for(i=0;i<oc->nb_streams;i++) {
3271
            AVCodecContext *enc = oc->streams[i]->codec;
3272
            switch(enc->codec_type) {
3273
            case CODEC_TYPE_AUDIO:
3274
                if (enc->sample_rate > ap->sample_rate)
3275
                    ap->sample_rate = enc->sample_rate;
3276
                if (enc->channels > ap->channels)
3277
                    ap->channels = enc->channels;
3278
                has_audio = 1;
3279
                break;
3280
            case CODEC_TYPE_VIDEO:
3281
                if (enc->width > vp->width)
3282
                    vp->width = enc->width;
3283
                if (enc->height > vp->height)
3284
                    vp->height = enc->height;
3285

    
3286
                if (vp->time_base.num*(int64_t)enc->time_base.den > enc->time_base.num*(int64_t)vp->time_base.den){
3287
                    vp->time_base = enc->time_base;
3288
                    vp->width += frame_leftBand + frame_rightBand;
3289
                    vp->width -= (frame_padleft + frame_padright);
3290
                    vp->height += frame_topBand + frame_bottomBand;
3291
                    vp->height -= (frame_padtop + frame_padbottom);
3292
                }
3293
                has_video = 1;
3294
                break;
3295
            default:
3296
                av_abort();
3297
            }
3298
        }
3299
    }
3300

    
3301
    if (has_video == 0 && has_audio == 0) {
3302
        fprintf(stderr, "Output file must have at least one audio or video stream\n");
3303
        exit(1);
3304
    }
3305

    
3306
    if (has_video) {
3307
        AVInputFormat *fmt1;
3308
        fmt1 = av_find_input_format(video_grab_format);
3309
        vp->device  = video_device;
3310
        vp->channel = video_channel;
3311
        vp->standard = video_standard;
3312
        vp->pix_fmt = frame_pix_fmt;
3313
        if (av_open_input_file(&ic, "", fmt1, 0, vp) < 0) {
3314
            fprintf(stderr, "Could not find video grab device\n");
3315
            exit(1);
3316
        }
3317
        /* If not enough info to get the stream parameters, we decode the
3318
           first frames to get it. */
3319
        if ((ic->ctx_flags & AVFMTCTX_NOHEADER) && av_find_stream_info(ic) < 0) {
3320
            fprintf(stderr, "Could not find video grab parameters\n");
3321
            exit(1);
3322
        }
3323
        /* by now video grab has one stream */
3324
        ic->streams[0]->r_frame_rate.num = vp->time_base.den;
3325
        ic->streams[0]->r_frame_rate.den = vp->time_base.num;
3326
        input_files[nb_input_files] = ic;
3327

    
3328
        if (verbose >= 0)
3329
            dump_format(ic, nb_input_files, "", 0);
3330

    
3331
        nb_input_files++;
3332
    }
3333
    if (has_audio && audio_grab_format) {
3334
        AVInputFormat *fmt1;
3335
        fmt1 = av_find_input_format(audio_grab_format);
3336
        ap->device = audio_device;
3337
        if (av_open_input_file(&ic, "", fmt1, 0, ap) < 0) {
3338
            fprintf(stderr, "Could not find audio grab device\n");
3339
            exit(1);
3340
        }
3341
        input_files[nb_input_files] = ic;
3342

    
3343
        if (verbose >= 0)
3344
            dump_format(ic, nb_input_files, "", 0);
3345

    
3346
        nb_input_files++;
3347
    }
3348
}
3349

    
3350
/* same option as mencoder */
3351
static void opt_pass(const char *pass_str)
3352
{
3353
    int pass;
3354
    pass = atoi(pass_str);
3355
    if (pass != 1 && pass != 2) {
3356
        fprintf(stderr, "pass number can be only 1 or 2\n");
3357
        exit(1);
3358
    }
3359
    do_pass = pass;
3360
}
3361

    
3362
#if defined(__MINGW32__) || defined(CONFIG_OS2)
3363
static int64_t getutime(void)
3364
{
3365
  return av_gettime();
3366
}
3367
#else
3368
static int64_t getutime(void)
3369
{
3370
    struct rusage rusage;
3371

    
3372
    getrusage(RUSAGE_SELF, &rusage);
3373
    return (rusage.ru_utime.tv_sec * 1000000LL) + rusage.ru_utime.tv_usec;
3374
}
3375
#endif
3376

    
3377
#if defined(CONFIG_FFM_DEMUXER) || defined(CONFIG_FFM_MUXER)
3378
extern int ffm_nopts;
3379
#endif
3380

    
3381
static void show_formats(void)
3382
{
3383
    AVInputFormat *ifmt;
3384
    AVOutputFormat *ofmt;
3385
    AVImageFormat *image_fmt;
3386
    URLProtocol *up;
3387
    AVCodec *p, *p2;
3388
    const char **pp, *last_name;
3389

    
3390
    printf("File formats:\n");
3391
    last_name= "000";
3392
    for(;;){
3393
        int decode=0;
3394
        int encode=0;
3395
        const char *name=NULL;
3396
        const char *long_name=NULL;
3397

    
3398
        for(ofmt = first_oformat; ofmt != NULL; ofmt = ofmt->next) {
3399
            if((name == NULL || strcmp(ofmt->name, name)<0) &&
3400
                strcmp(ofmt->name, last_name)>0){
3401
                name= ofmt->name;
3402
                long_name= ofmt->long_name;
3403
                encode=1;
3404
            }
3405
        }
3406
        for(ifmt = first_iformat; ifmt != NULL; ifmt = ifmt->next) {
3407
            if((name == NULL || strcmp(ifmt->name, name)<0) &&
3408
                strcmp(ifmt->name, last_name)>0){
3409
                name= ifmt->name;
3410
                long_name= ifmt->long_name;
3411
                encode=0;
3412
            }
3413
            if(name && strcmp(ifmt->name, name)==0)
3414
                decode=1;
3415
        }
3416
        if(name==NULL)
3417
            break;
3418
        last_name= name;
3419

    
3420
        printf(
3421
            " %s%s %-15s %s\n",
3422
            decode ? "D":" ",
3423
            encode ? "E":" ",
3424
            name,
3425
            long_name ? long_name:" ");
3426
    }
3427
    printf("\n");
3428

    
3429
    printf("Image formats (filename extensions, if any, follow):\n");
3430
    for(image_fmt = first_image_format; image_fmt != NULL;
3431
        image_fmt = image_fmt->next) {
3432
        printf(
3433
            " %s%s %-6s %s\n",
3434
            image_fmt->img_read  ? "D":" ",
3435
            image_fmt->img_write ? "E":" ",
3436
            image_fmt->name,
3437
            image_fmt->extensions ? image_fmt->extensions:" ");
3438
    }
3439
    printf("\n");
3440

    
3441
    printf("Codecs:\n");
3442
    last_name= "000";
3443
    for(;;){
3444
        int decode=0;
3445
        int encode=0;
3446
        int cap=0;
3447
        const char *type_str;
3448

    
3449
        p2=NULL;
3450
        for(p = first_avcodec; p != NULL; p = p->next) {
3451
            if((p2==NULL || strcmp(p->name, p2->name)<0) &&
3452
                strcmp(p->name, last_name)>0){
3453
                p2= p;
3454
                decode= encode= cap=0;
3455
            }
3456
            if(p2 && strcmp(p->name, p2->name)==0){
3457
                if(p->decode) decode=1;
3458
                if(p->encode) encode=1;
3459
                cap |= p->capabilities;
3460
            }
3461
        }
3462
        if(p2==NULL)
3463
            break;
3464
        last_name= p2->name;
3465

    
3466
        switch(p2->type) {
3467
        case CODEC_TYPE_VIDEO:
3468
            type_str = "V";
3469
            break;
3470
        case CODEC_TYPE_AUDIO:
3471
            type_str = "A";
3472
            break;
3473
        case CODEC_TYPE_SUBTITLE:
3474
            type_str = "S";
3475
            break;
3476
        default:
3477
            type_str = "?";
3478
            break;
3479
        }
3480
        printf(
3481
            " %s%s%s%s%s%s %s",
3482
            decode ? "D": (/*p2->decoder ? "d":*/" "),
3483
            encode ? "E":" ",
3484
            type_str,
3485
            cap & CODEC_CAP_DRAW_HORIZ_BAND ? "S":" ",
3486
            cap & CODEC_CAP_DR1 ? "D":" ",
3487
            cap & CODEC_CAP_TRUNCATED ? "T":" ",
3488
            p2->name);
3489
       /* if(p2->decoder && decode==0)
3490
            printf(" use %s for decoding", p2->decoder->name);*/
3491
        printf("\n");
3492
    }
3493
    printf("\n");
3494

    
3495
    printf("Supported file protocols:\n");
3496
    for(up = first_protocol; up != NULL; up = up->next)
3497
        printf(" %s:", up->name);
3498
    printf("\n");
3499

    
3500
    printf("Frame size, frame rate abbreviations:\n ntsc pal qntsc qpal sntsc spal film ntsc-film sqcif qcif cif 4cif\n");
3501
    printf("Motion estimation methods:\n");
3502
    pp = motion_str;
3503
    while (*pp) {
3504
        printf(" %s", *pp);
3505
        if ((pp - motion_str + 1) == ME_ZERO)
3506
            printf("(fastest)");
3507
        else if ((pp - motion_str + 1) == ME_FULL)
3508
            printf("(slowest)");
3509
        else if ((pp - motion_str + 1) == ME_EPZS)
3510
            printf("(default)");
3511
        pp++;
3512
    }
3513
    printf("\n\n");
3514
    printf(
3515
"Note, the names of encoders and decoders dont always match, so there are\n"
3516
"several cases where the above table shows encoder only or decoder only entries\n"
3517
"even though both encoding and decoding are supported for example, the h263\n"
3518
"decoder corresponds to the h263 and h263p encoders, for file formats its even\n"
3519
"worse\n");
3520
    exit(1);
3521
}
3522

    
3523
static void parse_matrix_coeffs(uint16_t *dest, const char *str)
3524
{
3525
    int i;
3526
    const char *p = str;
3527
    for(i = 0;; i++) {
3528
        dest[i] = atoi(p);
3529
        if(i == 63)
3530
            break;
3531
        p = strchr(p, ',');
3532
        if(!p) {
3533
            fprintf(stderr, "Syntax error in matrix \"%s\" at coeff %d\n", str, i);
3534
            exit(1);
3535
        }
3536
        p++;
3537
    }
3538
}
3539

    
3540
static void opt_inter_matrix(const char *arg)
3541
{
3542
    inter_matrix = av_mallocz(sizeof(uint16_t) * 64);
3543
    parse_matrix_coeffs(inter_matrix, arg);
3544
}
3545

    
3546
static void opt_intra_matrix(const char *arg)
3547
{
3548
    intra_matrix = av_mallocz(sizeof(uint16_t) * 64);
3549
    parse_matrix_coeffs(intra_matrix, arg);
3550
}
3551

    
3552
static void opt_target(const char *arg)
3553
{
3554
    int norm = -1;
3555
    static const char *const frame_rates[] = {"25", "30000/1001", "24000/1001"};
3556

    
3557
    if(!strncmp(arg, "pal-", 4)) {
3558
        norm = 0;
3559
        arg += 4;
3560
    } else if(!strncmp(arg, "ntsc-", 5)) {
3561
        norm = 1;
3562
        arg += 5;
3563
    } else if(!strncmp(arg, "film-", 5)) {
3564
        norm = 2;
3565
        arg += 5;
3566
    } else {
3567
        int fr;
3568
        /* Calculate FR via float to avoid int overflow */
3569
        fr = (int)(frame_rate * 1000.0 / frame_rate_base);
3570
        if(fr == 25000) {
3571
            norm = 0;
3572
        } else if((fr == 29970) || (fr == 23976)) {
3573
            norm = 1;
3574
        } else {
3575
            /* Try to determine PAL/NTSC by peeking in the input files */
3576
            if(nb_input_files) {
3577
                int i, j;
3578
                for(j = 0; j < nb_input_files; j++) {
3579
                    for(i = 0; i < input_files[j]->nb_streams; i++) {
3580
                        AVCodecContext *c = input_files[j]->streams[i]->codec;
3581
                        if(c->codec_type != CODEC_TYPE_VIDEO)
3582
                            continue;
3583
                        fr = c->time_base.den * 1000 / c->time_base.num;
3584
                        if(fr == 25000) {
3585
                            norm = 0;
3586
                            break;
3587
                        } else if((fr == 29970) || (fr == 23976)) {
3588
                            norm = 1;
3589
                            break;
3590
                        }
3591
                    }
3592
                    if(norm >= 0)
3593
                        break;
3594
                }
3595
            }
3596
        }
3597
        if(verbose && norm >= 0)
3598
            fprintf(stderr, "Assuming %s for target.\n", norm ? "NTSC" : "PAL");
3599
    }
3600

    
3601
    if(norm < 0) {
3602
        fprintf(stderr, "Could not determine norm (PAL/NTSC/NTSC-Film) for target.\n");
3603
        fprintf(stderr, "Please prefix target with \"pal-\", \"ntsc-\" or \"film-\",\n");
3604
        fprintf(stderr, "or set a framerate with \"-r xxx\".\n");
3605
        exit(1);
3606
    }
3607

    
3608
    if(!strcmp(arg, "vcd")) {
3609

    
3610
        opt_video_codec("mpeg1video");
3611
        opt_audio_codec("mp2");
3612
        opt_format("vcd");
3613

    
3614
        opt_frame_size(norm ? "352x240" : "352x288");
3615
        opt_frame_rate(frame_rates[norm]);
3616
        opt_default("gop", norm ? "18" : "15");
3617

    
3618
        opt_default("b", "1150000");
3619
        opt_default("maxrate", "1150000");
3620
        opt_default("minrate", "1150000");
3621
        opt_default("bufsize", "327680"); // 40*1024*8;
3622

    
3623
        audio_bit_rate = 224000;
3624
        audio_sample_rate = 44100;
3625

    
3626
        opt_default("packetsize", "2324");
3627
        opt_default("muxrate", "1411200"); // 2352 * 75 * 8;
3628

    
3629
        /* We have to offset the PTS, so that it is consistent with the SCR.
3630
           SCR starts at 36000, but the first two packs contain only padding
3631
           and the first pack from the other stream, respectively, may also have
3632
           been written before.
3633
           So the real data starts at SCR 36000+3*1200. */
3634
        mux_preload= (36000+3*1200) / 90000.0; //0.44
3635
    } else if(!strcmp(arg, "svcd")) {
3636

    
3637
        opt_video_codec("mpeg2video");
3638
        opt_audio_codec("mp2");
3639
        opt_format("svcd");
3640

    
3641
        opt_frame_size(norm ? "480x480" : "480x576");
3642
        opt_frame_rate(frame_rates[norm]);
3643
        opt_default("gop", norm ? "18" : "15");
3644

    
3645
        opt_default("b", "2040000");
3646
        opt_default("maxrate", "2516000");
3647
        opt_default("minrate", "0"); //1145000;
3648
        opt_default("bufsize", "1835008"); //224*1024*8;
3649
        opt_default("flags", "+SCAN_OFFSET");
3650

    
3651

    
3652
        audio_bit_rate = 224000;
3653
        audio_sample_rate = 44100;
3654

    
3655
        opt_default("packetsize", "2324");
3656

    
3657
    } else if(!strcmp(arg, "dvd")) {
3658

    
3659
        opt_video_codec("mpeg2video");
3660
        opt_audio_codec("ac3");
3661
        opt_format("dvd");
3662

    
3663
        opt_frame_size(norm ? "720x480" : "720x576");
3664
        opt_frame_rate(frame_rates[norm]);
3665
        opt_default("gop", norm ? "18" : "15");
3666

    
3667
        opt_default("b", "6000000");
3668
        opt_default("maxrate", "9000000");
3669
        opt_default("minrate", "0"); //1500000;
3670
        opt_default("bufsize", "1835008"); //224*1024*8;
3671

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

    
3675
        audio_bit_rate = 448000;
3676
        audio_sample_rate = 48000;
3677

    
3678
    } else if(!strncmp(arg, "dv", 2)) {
3679

    
3680
        opt_format("dv");
3681

    
3682
        opt_frame_size(norm ? "720x480" : "720x576");
3683
        opt_frame_pix_fmt(!strncmp(arg, "dv50", 4) ? "yuv422p" :
3684
                                             (norm ? "yuv411p" : "yuv420p"));
3685
        opt_frame_rate(frame_rates[norm]);
3686

    
3687
        audio_sample_rate = 48000;
3688
        audio_channels = 2;
3689

    
3690
    } else {
3691
        fprintf(stderr, "Unknown target: %s\n", arg);
3692
        exit(1);
3693
    }
3694
}
3695

    
3696
static void opt_video_bsf(const char *arg)
3697
{
3698
    AVBitStreamFilterContext *bsfc= av_bitstream_filter_init(arg); //FIXME split name and args for filter at '='
3699
    AVBitStreamFilterContext **bsfp;
3700

    
3701
    if(!bsfc){
3702
        fprintf(stderr, "Unkown bitstream filter %s\n", arg);
3703
        exit(1);
3704
    }
3705

    
3706
    bsfp= &video_bitstream_filters;
3707
    while(*bsfp)
3708
        bsfp= &(*bsfp)->next;
3709

    
3710
    *bsfp= bsfc;
3711
}
3712

    
3713
//FIXME avoid audio - video code duplication
3714
static void opt_audio_bsf(const char *arg)
3715
{
3716
    AVBitStreamFilterContext *bsfc= av_bitstream_filter_init(arg); //FIXME split name and args for filter at '='
3717
    AVBitStreamFilterContext **bsfp;
3718

    
3719
    if(!bsfc){
3720
        fprintf(stderr, "Unkown bitstream filter %s\n", arg);
3721
        exit(1);
3722
    }
3723

    
3724
    bsfp= &audio_bitstream_filters;
3725
    while(*bsfp)
3726
        bsfp= &(*bsfp)->next;
3727

    
3728
    *bsfp= bsfc;
3729
}
3730

    
3731
static void show_version(void)
3732
{
3733
    /* TODO: add function interface to avutil and avformat */
3734
    fprintf(stderr, "ffmpeg      " FFMPEG_VERSION "\n"
3735
           "libavutil   %d\n"
3736
           "libavcodec  %d\n"
3737
           "libavformat %d\n",
3738
           LIBAVUTIL_BUILD, avcodec_build(), LIBAVFORMAT_BUILD);
3739
    exit(1);
3740
}
3741

    
3742
static int opt_default(const char *opt, const char *arg){
3743
    AVOption *o= av_set_string(avctx_opts, opt, arg);
3744
    if(!o)
3745
        o = av_set_string(avformat_opts, opt, arg);
3746
    if(!o)
3747
        return -1;
3748

    
3749
//    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));
3750

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

    
3755
#if defined(CONFIG_FFM_DEMUXER) || defined(CONFIG_FFM_MUXER)
3756
    /* disable generate of real time pts in ffm (need to be supressed anyway) */
3757
    if(avctx_opts->flags & CODEC_FLAG_BITEXACT)
3758
        ffm_nopts = 1;
3759
#endif
3760

    
3761
    if(avctx_opts->debug)
3762
        av_log_set_level(AV_LOG_DEBUG);
3763
    return 0;
3764
}
3765

    
3766
const OptionDef options[] = {
3767
    /* main options */
3768
    { "L", 0, {(void*)show_license}, "show license" },
3769
    { "h", 0, {(void*)show_help}, "show help" },
3770
    { "version", 0, {(void*)show_version}, "show version" },
3771
    { "formats", 0, {(void*)show_formats}, "show available formats, codecs, protocols, ..." },
3772
    { "f", HAS_ARG, {(void*)opt_format}, "force format", "fmt" },
3773
    { "img", HAS_ARG, {(void*)opt_image_format}, "force image format", "img_fmt" },
3774
    { "i", HAS_ARG, {(void*)opt_input_file}, "input file name", "filename" },
3775
    { "y", OPT_BOOL, {(void*)&file_overwrite}, "overwrite output files" },
3776
    { "map", HAS_ARG | OPT_EXPERT, {(void*)opt_map}, "set input stream mapping", "file:stream[:syncfile:syncstream]" },
3777
    { "map_meta_data", HAS_ARG | OPT_EXPERT, {(void*)opt_map_meta_data}, "set meta data information of outfile from infile", "outfile:infile" },
3778
    { "t", HAS_ARG, {(void*)opt_recording_time}, "set the recording time", "duration" },
3779
    { "fs", HAS_ARG | OPT_INT, {(void*)&limit_filesize}, "set the limit file size", "limit_size" }, //
3780
    { "ss", HAS_ARG, {(void*)opt_start_time}, "set the start time offset", "time_off" },
3781
    { "itsoffset", HAS_ARG, {(void*)opt_input_ts_offset}, "set the input ts offset", "time_off" },
3782
    { "title", HAS_ARG | OPT_STRING, {(void*)&str_title}, "set the title", "string" },
3783
    { "timestamp", HAS_ARG, {(void*)&opt_rec_timestamp}, "set the timestamp", "time" },
3784
    { "author", HAS_ARG | OPT_STRING, {(void*)&str_author}, "set the author", "string" },
3785
    { "copyright", HAS_ARG | OPT_STRING, {(void*)&str_copyright}, "set the copyright", "string" },
3786
    { "comment", HAS_ARG | OPT_STRING, {(void*)&str_comment}, "set the comment", "string" },
3787
    { "album", HAS_ARG | OPT_STRING, {(void*)&str_album}, "set the album", "string" },
3788
    { "benchmark", OPT_BOOL | OPT_EXPERT, {(void*)&do_benchmark},
3789
      "add timings for benchmarking" },
3790
    { "dump", OPT_BOOL | OPT_EXPERT, {(void*)&do_pkt_dump},
3791
      "dump each input packet" },
3792
    { "hex", OPT_BOOL | OPT_EXPERT, {(void*)&do_hex_dump},
3793
      "when dumping packets, also dump the payload" },
3794
    { "re", OPT_BOOL | OPT_EXPERT, {(void*)&rate_emu}, "read input at native frame rate", "" },
3795
    { "loop_input", OPT_BOOL | OPT_EXPERT, {(void*)&loop_input}, "loop (current only works with images)" },
3796
    { "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)", "" },
3797
    { "v", HAS_ARG, {(void*)opt_verbose}, "control amount of logging", "verbose" },
3798
    { "target", HAS_ARG, {(void*)opt_target}, "specify target file type (\"vcd\", \"svcd\", \"dvd\", \"dv\", \"dv50\", \"pal-vcd\", \"ntsc-svcd\", ...)", "type" },
3799
    { "threads", HAS_ARG | OPT_EXPERT, {(void*)opt_thread_count}, "thread count", "count" },
3800
    { "vsync", HAS_ARG | OPT_INT | OPT_EXPERT, {(void*)&video_sync_method}, "video sync method", "" },
3801
    { "async", HAS_ARG | OPT_INT | OPT_EXPERT, {(void*)&audio_sync_method}, "audio sync method", "" },
3802
    { "vglobal", HAS_ARG | OPT_INT | OPT_EXPERT, {(void*)&video_global_header}, "video global header storage type", "" },
3803
    { "copyts", OPT_BOOL | OPT_EXPERT, {(void*)&copy_ts}, "copy timestamps" },
3804
    { "shortest", OPT_BOOL | OPT_EXPERT, {(void*)&opt_shortest}, "finish encoding within shortest input" }, //
3805
    { "dts_delta_threshold", HAS_ARG | OPT_INT | OPT_EXPERT, {(void*)&dts_delta_threshold}, "timestamp discontinuity delta threshold", "" },
3806

    
3807
    /* video options */
3808
    { "vframes", OPT_INT | HAS_ARG | OPT_VIDEO, {(void*)&max_frames[CODEC_TYPE_VIDEO]}, "set the number of video frames to record", "number" },
3809
    { "aframes", OPT_INT | HAS_ARG | OPT_AUDIO, {(void*)&max_frames[CODEC_TYPE_AUDIO]}, "set the number of audio frames to record", "number" },
3810
    { "dframes", OPT_INT | HAS_ARG, {(void*)&max_frames[CODEC_TYPE_DATA]}, "set the number of data frames to record", "number" },
3811
    { "r", HAS_ARG | OPT_VIDEO, {(void*)opt_frame_rate}, "set frame rate (Hz value, fraction or abbreviation)", "rate" },
3812
    { "s", HAS_ARG | OPT_VIDEO, {(void*)opt_frame_size}, "set frame size (WxH or abbreviation)", "size" },
3813
    { "aspect", HAS_ARG | OPT_VIDEO, {(void*)opt_frame_aspect_ratio}, "set aspect ratio (4:3, 16:9 or 1.3333, 1.7777)", "aspect" },
3814
    { "pix_fmt", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_frame_pix_fmt}, "set pixel format", "format" },
3815
    { "croptop", HAS_ARG | OPT_VIDEO, {(void*)opt_frame_crop_top}, "set top crop band size (in pixels)", "size" },
3816
    { "cropbottom", HAS_ARG | OPT_VIDEO, {(void*)opt_frame_crop_bottom}, "set bottom crop band size (in pixels)", "size" },
3817
    { "cropleft", HAS_ARG | OPT_VIDEO, {(void*)opt_frame_crop_left}, "set left crop band size (in pixels)", "size" },
3818
    { "cropright", HAS_ARG | OPT_VIDEO, {(void*)opt_frame_crop_right}, "set right crop band size (in pixels)", "size" },
3819
    { "padtop", HAS_ARG | OPT_VIDEO, {(void*)opt_frame_pad_top}, "set top pad band size (in pixels)", "size" },
3820
    { "padbottom", HAS_ARG | OPT_VIDEO, {(void*)opt_frame_pad_bottom}, "set bottom pad band size (in pixels)", "size" },
3821
    { "padleft", HAS_ARG | OPT_VIDEO, {(void*)opt_frame_pad_left}, "set left pad band size (in pixels)", "size" },
3822
    { "padright", HAS_ARG | OPT_VIDEO, {(void*)opt_frame_pad_right}, "set right pad band size (in pixels)", "size" },
3823
    { "padcolor", HAS_ARG | OPT_VIDEO, {(void*)opt_pad_color}, "set color of pad bands (Hex 000000 thru FFFFFF)", "color" },
3824
    { "intra", OPT_BOOL | OPT_EXPERT | OPT_VIDEO, {(void*)&intra_only}, "use only intra frames"},
3825
    { "vn", OPT_BOOL | OPT_VIDEO, {(void*)&video_disable}, "disable video" },
3826
    { "vdt", OPT_INT | HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)&video_discard}, "discard threshold", "n" },
3827
    { "qscale", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_qscale}, "use fixed video quantiser scale (VBR)", "q" },
3828
    { "lmin", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_lmin}, "min video lagrange factor (VBR)", "lambda" },
3829
    { "lmax", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_lmax}, "max video lagrange factor (VBR)", "lambda" },
3830
    { "mblmin", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_mb_lmin}, "min macroblock quantiser scale (VBR)", "q" },
3831
    { "mblmax", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_mb_lmax}, "max macroblock quantiser scale (VBR)", "q" },
3832
    { "qdiff", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_qdiff}, "max difference between the quantiser scale (VBR)", "q" },
3833
    { "rc_eq", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_video_rc_eq}, "set rate control equation", "equation" },
3834
    { "rc_override", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_video_rc_override_string}, "rate control override for specific intervals", "override" },
3835
    { "vcodec", HAS_ARG | OPT_VIDEO, {(void*)opt_video_codec}, "force video codec ('copy' to copy stream)", "codec" },
3836
    { "me", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_motion_estimation}, "set motion estimation method",
3837
      "method" },
3838
    { "me_threshold", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_me_threshold}, "motion estimaton threshold",  "" },
3839
    { "ps", HAS_ARG | OPT_EXPERT, {(void*)opt_packet_size}, "set packet size in bits", "size" },
3840
    { "error", HAS_ARG | OPT_EXPERT, {(void*)opt_error_rate}, "error rate", "rate" },
3841
    { "strict", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_strict}, "how strictly to follow the standards", "strictness" },
3842
    { "sameq", OPT_BOOL | OPT_VIDEO, {(void*)&same_quality},
3843
      "use same video quality as source (implies VBR)" },
3844
    { "pass", HAS_ARG | OPT_VIDEO, {(void*)&opt_pass}, "select the pass number (1 or 2)", "n" },
3845
    { "passlogfile", HAS_ARG | OPT_STRING | OPT_VIDEO, {(void*)&pass_logfilename}, "select two pass log file name", "file" },
3846
    { "deinterlace", OPT_BOOL | OPT_EXPERT | OPT_VIDEO, {(void*)&do_deinterlace},
3847
      "deinterlace pictures" },
3848
    { "psnr", OPT_BOOL | OPT_EXPERT | OPT_VIDEO, {(void*)&do_psnr}, "calculate PSNR of compressed frames" },
3849
    { "vstats", OPT_BOOL | OPT_EXPERT | OPT_VIDEO, {(void*)&do_vstats}, "dump video coding statistics to file" },
3850
    { "vhook", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)add_frame_hooker}, "insert video processing module", "module" },
3851
    { "intra_matrix", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_intra_matrix}, "specify intra matrix coeffs", "matrix" },
3852
    { "inter_matrix", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_inter_matrix}, "specify inter matrix coeffs", "matrix" },
3853
    { "top", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_top_field_first}, "top=1/bottom=0/auto=-1 field first", "" },
3854
    { "dc", OPT_INT | HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)&intra_dc_precision}, "intra_dc_precision", "precision" },
3855
    { "mepc", OPT_INT | HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)&me_penalty_compensation}, "motion estimation bitrate penalty compensation", "factor (1.0 = 256)" },
3856
    { "vtag", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_video_tag}, "force video tag/fourcc", "fourcc/tag" },
3857
    { "skip_exp", OPT_INT | HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)&frame_skip_exp}, "frame skip exponent", "exponent" },
3858
    { "newvideo", OPT_VIDEO, {(void*)opt_new_video_stream}, "add a new video stream to the current output stream" },
3859
    { "qphist", OPT_BOOL | OPT_EXPERT | OPT_VIDEO, { (void *)&qp_hist }, "show QP histogram" },
3860

    
3861
    /* audio options */
3862
    { "ab", HAS_ARG | OPT_AUDIO, {(void*)opt_audio_bitrate}, "set audio bitrate (in kbit/s)", "bitrate", },
3863
    { "aq", OPT_FLOAT | HAS_ARG | OPT_AUDIO, {(void*)&audio_qscale}, "set audio quality (codec-specific)", "quality", },
3864
    { "ar", HAS_ARG | OPT_AUDIO, {(void*)opt_audio_rate}, "set audio sampling rate (in Hz)", "rate" },
3865
    { "ac", HAS_ARG | OPT_AUDIO, {(void*)opt_audio_channels}, "set number of audio channels", "channels" },
3866
    { "an", OPT_BOOL | OPT_AUDIO, {(void*)&audio_disable}, "disable audio" },
3867
    { "acodec", HAS_ARG | OPT_AUDIO, {(void*)opt_audio_codec}, "force audio codec ('copy' to copy stream)", "codec" },
3868
    { "atag", HAS_ARG | OPT_EXPERT | OPT_AUDIO, {(void*)opt_audio_tag}, "force audio tag/fourcc", "fourcc/tag" },
3869
    { "vol", OPT_INT | HAS_ARG | OPT_AUDIO, {(void*)&audio_volume}, "change audio volume (256=normal)" , "volume" }, //
3870
    { "newaudio", OPT_AUDIO, {(void*)opt_new_audio_stream}, "add a new audio stream to the current output stream" },
3871
    { "alang", HAS_ARG | OPT_STRING | OPT_AUDIO, {(void *)&audio_language}, "set the ISO 639 language code (3 letters) of the current audio stream" , "code" },
3872

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

    
3878
    /* grab options */
3879
    { "vd", HAS_ARG | OPT_EXPERT | OPT_VIDEO | OPT_GRAB, {(void*)opt_video_device}, "set video grab device", "device" },
3880
    { "vc", HAS_ARG | OPT_EXPERT | OPT_VIDEO | OPT_GRAB, {(void*)opt_video_channel}, "set video grab channel (DV1394 only)", "channel" },
3881
    { "tvstd", HAS_ARG | OPT_EXPERT | OPT_VIDEO | OPT_GRAB, {(void*)opt_video_standard}, "set television standard (NTSC, PAL (SECAM))", "standard" },
3882
    { "ad", HAS_ARG | OPT_EXPERT | OPT_AUDIO | OPT_GRAB, {(void*)opt_audio_device}, "set audio device", "device" },
3883

    
3884
    /* G.2 grab options */
3885
    { "grab", HAS_ARG | OPT_EXPERT | OPT_GRAB, {(void*)opt_grab}, "request grabbing using", "format" },
3886
    { "gd", HAS_ARG | OPT_EXPERT | OPT_VIDEO | OPT_GRAB, {(void*)opt_grab_device}, "set grab device", "device" },
3887

    
3888
    /* muxer options */
3889
    { "muxdelay", OPT_FLOAT | HAS_ARG | OPT_EXPERT, {(void*)&mux_max_delay}, "set the maximum demux-decode delay", "seconds" },
3890
    { "muxpreload", OPT_FLOAT | HAS_ARG | OPT_EXPERT, {(void*)&mux_preload}, "set the initial demux-decode delay", "seconds" },
3891

    
3892
    { "absf", HAS_ARG | OPT_AUDIO | OPT_EXPERT, {(void*)opt_audio_bsf}, "", "bitstream filter" },
3893
    { "vbsf", HAS_ARG | OPT_VIDEO | OPT_EXPERT, {(void*)opt_video_bsf}, "", "bitstream filter" },
3894

    
3895
    { "default", OPT_FUNC2 | HAS_ARG | OPT_AUDIO | OPT_VIDEO | OPT_EXPERT, {(void*)opt_default}, "generic catch all option", "" },
3896
    { NULL, },
3897
};
3898

    
3899
static void show_banner(void)
3900
{
3901
    fprintf(stderr, "FFmpeg version " FFMPEG_VERSION ", Copyright (c) 2000-2004 Fabrice Bellard\n");
3902
    fprintf(stderr, "  configuration: " FFMPEG_CONFIGURATION "\n");
3903
    fprintf(stderr, "  libavutil version: " AV_STRINGIFY(LIBAVUTIL_VERSION) "\n");
3904
    fprintf(stderr, "  libavcodec version: " AV_STRINGIFY(LIBAVCODEC_VERSION) "\n");
3905
    fprintf(stderr, "  libavformat version: " AV_STRINGIFY(LIBAVFORMAT_VERSION) "\n");
3906
    fprintf(stderr, "  built on " __DATE__ " " __TIME__);
3907
#ifdef __GNUC__
3908
    fprintf(stderr, ", gcc: " __VERSION__ "\n");
3909
#else
3910
    fprintf(stderr, ", using a non-gcc compiler\n");
3911
#endif
3912
}
3913

    
3914
static void show_license(void)
3915
{
3916
    show_banner();
3917
#ifdef CONFIG_GPL
3918
    printf(
3919
    "This program is free software; you can redistribute it and/or modify\n"
3920
    "it under the terms of the GNU General Public License as published by\n"
3921
    "the Free Software Foundation; either version 2 of the License, or\n"
3922
    "(at your option) any later version.\n"
3923
    "\n"
3924
    "This program is distributed in the hope that it will be useful,\n"
3925
    "but WITHOUT ANY WARRANTY; without even the implied warranty of\n"
3926
    "MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n"
3927
    "GNU General Public License for more details.\n"
3928
    "\n"
3929
    "You should have received a copy of the GNU General Public License\n"
3930
    "along with this program; if not, write to the Free Software\n"
3931
    "Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA\n"
3932
    );
3933
#else
3934
    printf(
3935
    "This library is free software; you can redistribute it and/or\n"
3936
    "modify it under the terms of the GNU Lesser General Public\n"
3937
    "License as published by the Free Software Foundation; either\n"
3938
    "version 2 of the License, or (at your option) any later version.\n"
3939
    "\n"
3940
    "This library is distributed in the hope that it will be useful,\n"
3941
    "but WITHOUT ANY WARRANTY; without even the implied warranty of\n"
3942
    "MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n"
3943
    "Lesser General Public License for more details.\n"
3944
    "\n"
3945
    "You should have received a copy of the GNU Lesser General Public\n"
3946
    "License along with this library; if not, write to the Free Software\n"
3947
    "Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n"
3948
    );
3949
#endif
3950
    exit(1);
3951
}
3952

    
3953
static void show_help(void)
3954
{
3955
    show_banner();
3956
    printf("usage: ffmpeg [[infile options] -i infile]... {[outfile options] outfile}...\n"
3957
           "Hyper fast Audio and Video encoder\n");
3958
    printf("\n");
3959
    show_help_options(options, "Main options:\n",
3960
                      OPT_EXPERT | OPT_AUDIO | OPT_VIDEO, 0);
3961
    show_help_options(options, "\nVideo options:\n",
3962
                      OPT_EXPERT | OPT_AUDIO | OPT_VIDEO | OPT_GRAB,
3963
                      OPT_VIDEO);
3964
    show_help_options(options, "\nAdvanced Video options:\n",
3965
                      OPT_EXPERT | OPT_AUDIO | OPT_VIDEO | OPT_GRAB,
3966
                      OPT_VIDEO | OPT_EXPERT);
3967
    show_help_options(options, "\nAudio options:\n",
3968
                      OPT_EXPERT | OPT_AUDIO | OPT_VIDEO | OPT_GRAB,
3969
                      OPT_AUDIO);
3970
    show_help_options(options, "\nAdvanced Audio options:\n",
3971
                      OPT_EXPERT | OPT_AUDIO | OPT_VIDEO | OPT_GRAB,
3972
                      OPT_AUDIO | OPT_EXPERT);
3973
    show_help_options(options, "\nSubtitle options:\n",
3974
                      OPT_SUBTITLE | OPT_GRAB,
3975
                      OPT_SUBTITLE);
3976
    show_help_options(options, "\nAudio/Video grab options:\n",
3977
                      OPT_GRAB,
3978
                      OPT_GRAB);
3979
    show_help_options(options, "\nAdvanced options:\n",
3980
                      OPT_EXPERT | OPT_AUDIO | OPT_VIDEO | OPT_GRAB,
3981
                      OPT_EXPERT);
3982
    av_opt_show(avctx_opts, NULL);
3983
    av_opt_show(avformat_opts, NULL);
3984

    
3985
    exit(1);
3986
}
3987

    
3988
void parse_arg_file(const char *filename)
3989
{
3990
    opt_output_file(filename);
3991
}
3992

    
3993
int main(int argc, char **argv)
3994
{
3995
    int i;
3996
    int64_t ti;
3997

    
3998
    av_register_all();
3999

    
4000
    avctx_opts= avcodec_alloc_context();
4001
    avformat_opts = av_alloc_format_context();
4002

    
4003
    if (argc <= 1)
4004
        show_help();
4005
    else
4006
        show_banner();
4007

    
4008
    /* parse options */
4009
    parse_options(argc, argv, options);
4010

    
4011
    /* file converter / grab */
4012
    if (nb_output_files <= 0) {
4013
        fprintf(stderr, "Must supply at least one output file\n");
4014
        exit(1);
4015
    }
4016

    
4017
    if (nb_input_files == 0) {
4018
        input_sync = 1;
4019
        prepare_grab();
4020
    }
4021

    
4022
    ti = getutime();
4023
    av_encode(output_files, nb_output_files, input_files, nb_input_files,
4024
              stream_maps, nb_stream_maps);
4025
    ti = getutime() - ti;
4026
    if (do_benchmark) {
4027
        printf("bench: utime=%0.3fs\n", ti / 1000000.0);
4028
    }
4029

    
4030
    /* close files */
4031
    for(i=0;i<nb_output_files;i++) {
4032
        /* maybe av_close_output_file ??? */
4033
        AVFormatContext *s = output_files[i];
4034
        int j;
4035
        if (!(s->oformat->flags & AVFMT_NOFILE))
4036
            url_fclose(&s->pb);
4037
        for(j=0;j<s->nb_streams;j++)
4038
            av_free(s->streams[j]);
4039
        av_free(s);
4040
    }
4041
    for(i=0;i<nb_input_files;i++)
4042
        av_close_input_file(input_files[i]);
4043

    
4044
    av_free_static();
4045

    
4046
    if(intra_matrix)
4047
        av_free(intra_matrix);
4048
    if(inter_matrix)
4049
        av_free(inter_matrix);
4050

    
4051
#ifdef POWERPC_PERFORMANCE_REPORT
4052
    extern void powerpc_display_perf_report(void);
4053
    powerpc_display_perf_report();
4054
#endif /* POWERPC_PERFORMANCE_REPORT */
4055

    
4056
#ifndef __MINGW32__
4057
    if (received_sigterm) {
4058
        fprintf(stderr,
4059
            "Received signal %d: terminating.\n",
4060
            (int) received_sigterm);
4061
        exit (255);
4062
    }
4063
#endif
4064
    exit(0); /* not all OS-es handle main() return value */
4065
    return 0;
4066
}