Statistics
| Branch: | Revision:

ffmpeg / ffmpeg.c @ f5a478f6

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 mb_threshold = 0;
137
static int intra_dc_precision = 8;
138
static int me_penalty_compensation= 256;
139
static int frame_skip_threshold= 0;
140
static int frame_skip_factor= 0;
141
static int frame_skip_exp= 0;
142
static int loop_input = 0;
143
static int loop_output = AVFMT_NOOUTPUTLOOP;
144
static int qp_hist = 0;
145

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

    
157
static int subtitle_codec_id = CODEC_ID_NONE;
158
static char *subtitle_language = NULL;
159

    
160
static float mux_preload= 0.5;
161
static float mux_max_delay= 0.7;
162

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

    
189
static int rate_emu = 0;
190

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

    
205
static const char *audio_grab_format = "audio_device";
206
static char *audio_device = NULL;
207
static int audio_volume = 256;
208

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

    
222
static int pgmyuv_compatibility_hack=0;
223
static int dts_delta_threshold = 10;
224

    
225
static int sws_flags = SWS_BICUBIC;
226

    
227
const char **opt_names=NULL;
228
int opt_name_count=0;
229
AVCodecContext *avctx_opts;
230
AVFormatContext *avformat_opts;
231

    
232
static AVBitStreamFilterContext *video_bitstream_filters=NULL;
233
static AVBitStreamFilterContext *audio_bitstream_filters=NULL;
234
static AVBitStreamFilterContext *bitstream_filters[MAX_FILES][MAX_STREAMS];
235

    
236
#define DEFAULT_PASS_LOGFILENAME "ffmpeg2pass"
237

    
238
struct AVInputStream;
239

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

    
258
    int video_crop;
259
    int topBand;             /* cropping area sizes */
260
    int leftBand;
261

    
262
    int video_pad;
263
    int padtop;              /* padding area sizes */
264
    int padbottom;
265
    int padleft;
266
    int padright;
267

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

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

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

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

    
300
#ifndef __MINGW32__
301

    
302
/* init terminal so that we can grab keys */
303
static struct termios oldtty;
304

    
305
static void term_exit(void)
306
{
307
    tcsetattr (0, TCSANOW, &oldtty);
308
}
309

    
310
static volatile sig_atomic_t received_sigterm = 0;
311

    
312
static void
313
sigterm_handler(int sig)
314
{
315
    received_sigterm = sig;
316
    term_exit();
317
}
318

    
319
static void term_init(void)
320
{
321
    struct termios tty;
322

    
323
    tcgetattr (0, &tty);
324
    oldtty = tty;
325

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

    
335
    tcsetattr (0, TCSANOW, &tty);
336

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

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

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

    
369
        return n;
370
    }
371
    return -1;
372
}
373

    
374
static int decode_interrupt_cb(void)
375
{
376
    return q_pressed || (q_pressed = read_key() == 'q');
377
}
378

    
379
#else
380

    
381
static volatile int received_sigterm = 0;
382

    
383
/* no interactive support */
384
static void term_exit(void)
385
{
386
}
387

    
388
static void term_init(void)
389
{
390
}
391

    
392
static int read_key(void)
393
{
394
    return 0;
395
}
396

    
397
#endif
398

    
399
static int read_ffserver_streams(AVFormatContext *s, const char *filename)
400
{
401
    int i, err;
402
    AVFormatContext *ic;
403

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

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

    
420
    av_close_input_file(ic);
421
    return 0;
422
}
423

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

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

    
444
        bsfc= bsfc->next;
445
    }
446

    
447
    av_interleaved_write_frame(s, pkt);
448
}
449

    
450
#define MAX_AUDIO_PACKET_SIZE (128 * 1024)
451

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

    
462
    int size_out, frame_bytes, ret;
463
    AVCodecContext *enc= ost->st->codec;
464

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

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

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

    
495
                    if(byte_delta + size <= MAX_AUDIO_PACKET_SIZE)
496
                        ist->is_start=0;
497
                    else
498
                        byte_delta= MAX_AUDIO_PACKET_SIZE - size;
499

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

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

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

    
536
        frame_bytes = enc->frame_size * 2 * enc->channels;
537

    
538
        while (av_fifo_read(&ost->fifo, audio_buf, frame_bytes) == 0) {
539
            AVPacket pkt;
540
            av_init_packet(&pkt);
541

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

    
553
            ost->sync_opts += enc->frame_size;
554
        }
555
    } else {
556
        AVPacket pkt;
557
        av_init_packet(&pkt);
558

    
559
        ost->sync_opts += size_out / (2 * enc->channels);
560

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

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

    
606
    dec = ist->st->codec;
607

    
608
    /* deinterlace : must be done before any resize */
609
    if (do_deinterlace || using_vhook) {
610
        int size;
611

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

    
618
        picture2 = &picture_tmp;
619
        avpicture_fill(picture2, buf, dec->pix_fmt, dec->width, dec->height);
620

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

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

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

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

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

    
658
    if (pts == AV_NOPTS_VALUE) {
659
        fprintf(stderr, "Subtitle packets must have a pts\n");
660
        return;
661
    }
662

    
663
    enc = ost->st->codec;
664

    
665
    if (!subtitle_out) {
666
        subtitle_out = av_malloc(subtitle_out_max_size);
667
    }
668

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

    
677
    for(i = 0; i < nb; i++) {
678
        subtitle_out_size = avcodec_encode_subtitle(enc, subtitle_out,
679
                                                    subtitle_out_max_size, sub);
680

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

    
698
static int bit_buffer_size= 1024*256;
699
static uint8_t *bit_buffer= NULL;
700

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

    
713
    avcodec_get_frame_defaults(&picture_crop_temp);
714
    avcodec_get_frame_defaults(&picture_pad_temp);
715

    
716
    enc = ost->st->codec;
717
    dec = ist->st->codec;
718

    
719
    /* by default, we output a single frame */
720
    nb_frames = 1;
721

    
722
    *frame_size = 0;
723

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

    
745
    nb_frames= FFMIN(nb_frames, max_frames[CODEC_TYPE_VIDEO] - ost->frame_number);
746
    if (nb_frames <= 0)
747
        return;
748

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

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

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

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

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

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

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

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

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

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

    
867
static double psnr(double d){
868
    if(d==0) return INFINITY;
869
    return -10.0*log(d)/log(10.0);
870
}
871

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

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

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

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

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

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

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

    
946

    
947
    oc = output_files[0];
948

    
949
    total_size = url_ftell(&oc->pb);
950

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

    
1007
    if (verbose || is_last_report) {
1008
        bitrate = (double)(total_size * 8) / ti1 / 1000.0;
1009

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

    
1014
        if (verbose > 1)
1015
          snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), " dup=%d drop=%d",
1016
                  nb_frames_dup, nb_frames_drop);
1017

    
1018
        if (verbose >= 0)
1019
            fprintf(stderr, "%s    \r", buf);
1020

    
1021
        fflush(stderr);
1022
    }
1023

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

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

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

    
1062
    if (pkt == NULL) {
1063
        /* EOF handling */
1064
        ptr = NULL;
1065
        len = 0;
1066
        goto handle_eof;
1067
    }
1068

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

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

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

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

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

    
1182
                ist->frame++;
1183
            }
1184

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

    
1204
                    ost = ost_table[i];
1205
                    if (ost->source_index == ist_index) {
1206
                        os = output_files[ost->file_index];
1207

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

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

    
1240
                            /* no reencoding needed : output the packet directly */
1241
                            /* force the input stream PTS */
1242

    
1243
                            avcodec_get_frame_defaults(&avframe);
1244
                            ost->st->codec->coded_frame= &avframe;
1245
                            avframe.key_frame = pkt->flags & PKT_FLAG_KEY;
1246

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

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

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

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

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

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

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

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

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

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

    
1362
    return 0;
1363
 fail_decode:
1364
    return -1;
1365
}
1366

    
1367

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

    
1386
    file_table= (AVInputFile*) av_mallocz(nb_input_files * sizeof(AVInputFile));
1387
    if (!file_table)
1388
        goto fail;
1389

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

    
1400
    ist_table = av_mallocz(nb_istreams * sizeof(AVInputStream *));
1401
    if (!ist_table)
1402
        goto fail;
1403

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

    
1421
            if (ist->st->codec->rate_emu) {
1422
                ist->start = av_gettime();
1423
                ist->frame = 0;
1424
            }
1425
        }
1426
    }
1427

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

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

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

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

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

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

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

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

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

    
1531
        codec = ost->st->codec;
1532
        icodec = ist->st->codec;
1533

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

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

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

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

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

    
1704
    if (!bit_buffer)
1705
        bit_buffer = av_malloc(bit_buffer_size);
1706
    if (!bit_buffer)
1707
        goto fail;
1708

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

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

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

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

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

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

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

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

    
1810
        out_file = output_files[out_file_index];
1811
        in_file = input_files[in_file_index];
1812

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

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

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

    
1841
    stream_no_data = 0;
1842
    key = -1;
1843

    
1844
    for(; received_sigterm == 0;) {
1845
        int file_index, ist_index;
1846
        AVPacket pkt;
1847
        double ipts_min;
1848
        double opts_min;
1849

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

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

    
1896
        /* finish if recording time exhausted */
1897
        if (recording_time > 0 && opts_min >= (recording_time / 1000000.0))
1898
            break;
1899

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

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

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

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

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

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

    
1950
            av_free_packet(&pkt);
1951
            goto redo;
1952
        }
1953

    
1954
    discard_packet:
1955
        av_free_packet(&pkt);
1956

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

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

    
1969
    term_exit();
1970

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

    
1977
    /* dump report by using the first video and audio streams */
1978
    print_report(output_files, ost_table, nb_ostreams, 1);
1979

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

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

    
1997
    /* finished ! */
1998

    
1999
    ret = 0;
2000
 fail1:
2001
    av_freep(&bit_buffer);
2002
    av_free(file_table);
2003

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

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

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

    
2059
static void opt_image_format(const char *arg)
2060
{
2061
    AVImageFormat *f;
2062

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

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

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

    
2091
static void opt_video_rc_eq(char *arg)
2092
{
2093
    video_rc_eq = arg;
2094
}
2095

    
2096
static void opt_video_rc_override_string(char *arg)
2097
{
2098
    video_rc_override_string = arg;
2099
}
2100

    
2101
static void opt_me_threshold(const char *arg)
2102
{
2103
    me_threshold = atoi(arg);
2104
}
2105

    
2106
static void opt_mb_threshold(const char *arg)
2107
{
2108
    mb_threshold = atoi(arg);
2109
}
2110

    
2111
static void opt_verbose(const char *arg)
2112
{
2113
    verbose = atoi(arg);
2114
    av_log_set_level(atoi(arg));
2115
}
2116

    
2117
static void opt_frame_rate(const char *arg)
2118
{
2119
    if (parse_frame_rate(&frame_rate, &frame_rate_base, arg) < 0) {
2120
        fprintf(stderr, "Incorrect frame rate\n");
2121
        exit(1);
2122
    }
2123
}
2124

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

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

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

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

    
2197
static void opt_frame_size(const char *arg)
2198
{
2199
    if (parse_image_size(&frame_width, &frame_height, arg) < 0) {
2200
        fprintf(stderr, "Incorrect frame size\n");
2201
        exit(1);
2202
    }
2203
    if ((frame_width % 2) != 0 || (frame_height % 2) != 0) {
2204
        fprintf(stderr, "Frame size must be a multiple of 2\n");
2205
        exit(1);
2206
    }
2207
}
2208

    
2209

    
2210
#define SCALEBITS 10
2211
#define ONE_HALF  (1 << (SCALEBITS - 1))
2212
#define FIX(x)    ((int) ((x) * (1<<SCALEBITS) + 0.5))
2213

    
2214
#define RGB_TO_Y(r, g, b) \
2215
((FIX(0.29900) * (r) + FIX(0.58700) * (g) + \
2216
  FIX(0.11400) * (b) + ONE_HALF) >> SCALEBITS)
2217

    
2218
#define RGB_TO_U(r1, g1, b1, shift)\
2219
(((- FIX(0.16874) * r1 - FIX(0.33126) * g1 +         \
2220
     FIX(0.50000) * b1 + (ONE_HALF << shift) - 1) >> (SCALEBITS + shift)) + 128)
2221

    
2222
#define RGB_TO_V(r1, g1, b1, shift)\
2223
(((FIX(0.50000) * r1 - FIX(0.41869) * g1 -           \
2224
   FIX(0.08131) * b1 + (ONE_HALF << shift) - 1) >> (SCALEBITS + shift)) + 128)
2225

    
2226
static void opt_pad_color(const char *arg) {
2227
    /* Input is expected to be six hex digits similar to
2228
       how colors are expressed in html tags (but without the #) */
2229
    int rgb = strtol(arg, NULL, 16);
2230
    int r,g,b;
2231

    
2232
    r = (rgb >> 16);
2233
    g = ((rgb >> 8) & 255);
2234
    b = (rgb & 255);
2235

    
2236
    padcolor[0] = RGB_TO_Y(r,g,b);
2237
    padcolor[1] = RGB_TO_U(r,g,b,0);
2238
    padcolor[2] = RGB_TO_V(r,g,b,0);
2239
}
2240

    
2241
static void opt_frame_pad_top(const char *arg)
2242
{
2243
    frame_padtop = atoi(arg);
2244
    if (frame_padtop < 0) {
2245
        fprintf(stderr, "Incorrect top pad size\n");
2246
        exit(1);
2247
    }
2248
    if ((frame_padtop % 2) != 0) {
2249
        fprintf(stderr, "Top pad size must be a multiple of 2\n");
2250
        exit(1);
2251
    }
2252
}
2253

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

    
2267

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

    
2281

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

    
2295

    
2296
static void opt_frame_pix_fmt(const char *arg)
2297
{
2298
    frame_pix_fmt = avcodec_get_pix_fmt(arg);
2299
}
2300

    
2301
static void opt_frame_aspect_ratio(const char *arg)
2302
{
2303
    int x = 0, y = 0;
2304
    double ar = 0;
2305
    const char *p;
2306

    
2307
    p = strchr(arg, ':');
2308
    if (p) {
2309
        x = strtol(arg, (char **)&arg, 10);
2310
        if (arg == p)
2311
            y = strtol(arg+1, (char **)&arg, 10);
2312
        if (x > 0 && y > 0)
2313
            ar = (double)x / (double)y;
2314
    } else
2315
        ar = strtod(arg, (char **)&arg);
2316

    
2317
    if (!ar) {
2318
        fprintf(stderr, "Incorrect aspect ratio specification.\n");
2319
        exit(1);
2320
    }
2321
    frame_aspect_ratio = ar;
2322
}
2323

    
2324
static void opt_qscale(const char *arg)
2325
{
2326
    video_qscale = atof(arg);
2327
    if (video_qscale <= 0 ||
2328
        video_qscale > 255) {
2329
        fprintf(stderr, "qscale must be > 0.0 and <= 255\n");
2330
        exit(1);
2331
    }
2332
}
2333

    
2334
static void opt_lmax(const char *arg)
2335
{
2336
    video_lmax = atof(arg)*FF_QP2LAMBDA;
2337
}
2338

    
2339
static void opt_lmin(const char *arg)
2340
{
2341
    video_lmin = atof(arg)*FF_QP2LAMBDA;
2342
}
2343

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

    
2354
static void opt_mb_lmax(const char *arg)
2355
{
2356
    video_mb_lmax = atof(arg)*FF_QP2LAMBDA;
2357
    if (video_mb_lmax < 1 ||
2358
        video_mb_lmax > FF_LAMBDA_MAX) {
2359
        fprintf(stderr, "mblmax must be >= 1 and <= %d\n", FF_LAMBDA_MAX / FF_QP2LAMBDA);
2360
        exit(1);
2361
    }
2362
}
2363

    
2364
static void opt_qdiff(const char *arg)
2365
{
2366
    video_qdiff = atoi(arg);
2367
    if (video_qdiff < 0 ||
2368
        video_qdiff > 31) {
2369
        fprintf(stderr, "qdiff must be >= 1 and <= 31\n");
2370
        exit(1);
2371
    }
2372
}
2373

    
2374
static void opt_packet_size(const char *arg)
2375
{
2376
    packet_size= atoi(arg);
2377
}
2378

    
2379
static void opt_error_rate(const char *arg)
2380
{
2381
    error_rate= atoi(arg);
2382
}
2383

    
2384
static void opt_strict(const char *arg)
2385
{
2386
    strict= atoi(arg);
2387
}
2388

    
2389
static void opt_top_field_first(const char *arg)
2390
{
2391
    top_field_first= atoi(arg);
2392
}
2393

    
2394
static void opt_thread_count(const char *arg)
2395
{
2396
    thread_count= atoi(arg);
2397
#if !defined(HAVE_THREADS)
2398
    if (verbose >= 0)
2399
        fprintf(stderr, "Warning: not compiled with thread support, using thread emulation\n");
2400
#endif
2401
}
2402

    
2403
static void opt_audio_bitrate(const char *arg)
2404
{
2405
    audio_bit_rate = atoi(arg) * 1000;
2406
}
2407

    
2408
static void opt_audio_rate(const char *arg)
2409
{
2410
    audio_sample_rate = atoi(arg);
2411
}
2412

    
2413
static void opt_audio_channels(const char *arg)
2414
{
2415
    audio_channels = atoi(arg);
2416
}
2417

    
2418
static void opt_video_device(const char *arg)
2419
{
2420
    video_device = av_strdup(arg);
2421
}
2422

    
2423
static void opt_grab_device(const char *arg)
2424
{
2425
    grab_device = av_strdup(arg);
2426
}
2427

    
2428
static void opt_video_channel(const char *arg)
2429
{
2430
    video_channel = strtol(arg, NULL, 0);
2431
}
2432

    
2433
static void opt_video_standard(const char *arg)
2434
{
2435
    video_standard = av_strdup(arg);
2436
}
2437

    
2438
static void opt_audio_device(const char *arg)
2439
{
2440
    audio_device = av_strdup(arg);
2441
}
2442

    
2443
static void opt_codec(int *pstream_copy, int *pcodec_id,
2444
                      int codec_type, const char *arg)
2445
{
2446
    AVCodec *p;
2447

    
2448
    if (!strcmp(arg, "copy")) {
2449
        *pstream_copy = 1;
2450
    } else {
2451
        p = first_avcodec;
2452
        while (p) {
2453
            if (!strcmp(p->name, arg) && p->type == codec_type)
2454
                break;
2455
            p = p->next;
2456
        }
2457
        if (p == NULL) {
2458
            fprintf(stderr, "Unknown codec '%s'\n", arg);
2459
            exit(1);
2460
        } else {
2461
            *pcodec_id = p->id;
2462
        }
2463
    }
2464
}
2465

    
2466
static void opt_audio_codec(const char *arg)
2467
{
2468
    opt_codec(&audio_stream_copy, &audio_codec_id, CODEC_TYPE_AUDIO, arg);
2469
}
2470

    
2471
static void opt_audio_tag(const char *arg)
2472
{
2473
    char *tail;
2474
    audio_codec_tag= strtol(arg, &tail, 0);
2475

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

    
2480
static void opt_video_tag(const char *arg)
2481
{
2482
    char *tail;
2483
    video_codec_tag= strtol(arg, &tail, 0);
2484

    
2485
    if(!tail || *tail)
2486
        video_codec_tag= arg[0] + (arg[1]<<8) + (arg[2]<<16) + (arg[3]<<24);
2487
}
2488

    
2489
static void add_frame_hooker(const char *arg)
2490
{
2491
    int argc = 0;
2492
    char *argv[64];
2493
    int i;
2494
    char *args = av_strdup(arg);
2495

    
2496
    using_vhook = 1;
2497

    
2498
    argv[0] = strtok(args, " ");
2499
    while (argc < 62 && (argv[++argc] = strtok(NULL, " "))) {
2500
    }
2501

    
2502
    i = frame_hook_add(argc, argv);
2503

    
2504
    if (i != 0) {
2505
        fprintf(stderr, "Failed to add video hook function: %s\n", arg);
2506
        exit(1);
2507
    }
2508
}
2509

    
2510
const char *motion_str[] = {
2511
    "zero",
2512
    "full",
2513
    "log",
2514
    "phods",
2515
    "epzs",
2516
    "x1",
2517
    "hex",
2518
    "umh",
2519
    "iter",
2520
    NULL,
2521
};
2522

    
2523
static void opt_motion_estimation(const char *arg)
2524
{
2525
    const char **p;
2526
    p = motion_str;
2527
    for(;;) {
2528
        if (!*p) {
2529
            fprintf(stderr, "Unknown motion estimation method '%s'\n", arg);
2530
            exit(1);
2531
        }
2532
        if (!strcmp(*p, arg))
2533
            break;
2534
        p++;
2535
    }
2536
    me_method = (p - motion_str) + 1;
2537
}
2538

    
2539
static void opt_video_codec(const char *arg)
2540
{
2541
    opt_codec(&video_stream_copy, &video_codec_id, CODEC_TYPE_VIDEO, arg);
2542
}
2543

    
2544
static void opt_subtitle_codec(const char *arg)
2545
{
2546
    opt_codec(&subtitle_stream_copy, &subtitle_codec_id, CODEC_TYPE_SUBTITLE, arg);
2547
}
2548

    
2549
static void opt_map(const char *arg)
2550
{
2551
    AVStreamMap *m;
2552
    const char *p;
2553

    
2554
    p = arg;
2555
    m = &stream_maps[nb_stream_maps++];
2556

    
2557
    m->file_index = strtol(arg, (char **)&p, 0);
2558
    if (*p)
2559
        p++;
2560

    
2561
    m->stream_index = strtol(p, (char **)&p, 0);
2562
    if (*p) {
2563
        p++;
2564
        m->sync_file_index = strtol(p, (char **)&p, 0);
2565
        if (*p)
2566
            p++;
2567
        m->sync_stream_index = strtol(p, (char **)&p, 0);
2568
    } else {
2569
        m->sync_file_index = m->file_index;
2570
        m->sync_stream_index = m->stream_index;
2571
    }
2572
}
2573

    
2574
static void opt_map_meta_data(const char *arg)
2575
{
2576
    AVMetaDataMap *m;
2577
    const char *p;
2578

    
2579
    p = arg;
2580
    m = &meta_data_maps[nb_meta_data_maps++];
2581

    
2582
    m->out_file = strtol(arg, (char **)&p, 0);
2583
    if (*p)
2584
        p++;
2585

    
2586
    m->in_file = strtol(p, (char **)&p, 0);
2587
}
2588

    
2589
static void opt_recording_time(const char *arg)
2590
{
2591
    recording_time = parse_date(arg, 1);
2592
}
2593

    
2594
static void opt_start_time(const char *arg)
2595
{
2596
    start_time = parse_date(arg, 1);
2597
}
2598

    
2599
static void opt_rec_timestamp(const char *arg)
2600
{
2601
    rec_timestamp = parse_date(arg, 0) / 1000000;
2602
}
2603

    
2604
static void opt_input_ts_offset(const char *arg)
2605
{
2606
    input_ts_offset = parse_date(arg, 1);
2607
}
2608

    
2609
static void opt_input_file(const char *filename)
2610
{
2611
    AVFormatContext *ic;
2612
    AVFormatParameters params, *ap = &params;
2613
    int err, i, ret, rfps, rfps_base;
2614
    int64_t timestamp;
2615

    
2616
    if (!strcmp(filename, "-"))
2617
        filename = "pipe:";
2618

    
2619
    using_stdin |= !strncmp(filename, "pipe:", 5) ||
2620
                   !strcmp( filename, "/dev/stdin" );
2621

    
2622
    /* get default parameters from command line */
2623
    ic = av_alloc_format_context();
2624

    
2625
    memset(ap, 0, sizeof(*ap));
2626
    ap->prealloced_context = 1;
2627
    ap->sample_rate = audio_sample_rate;
2628
    ap->channels = audio_channels;
2629
    ap->time_base.den = frame_rate;
2630
    ap->time_base.num = frame_rate_base;
2631
    ap->width = frame_width + frame_padleft + frame_padright;
2632
    ap->height = frame_height + frame_padtop + frame_padbottom;
2633
    ap->image_format = image_format;
2634
    ap->pix_fmt = frame_pix_fmt;
2635
    ap->device  = grab_device;
2636
    ap->channel = video_channel;
2637
    ap->standard = video_standard;
2638
    ap->video_codec_id = video_codec_id;
2639
    ap->audio_codec_id = audio_codec_id;
2640
    if(pgmyuv_compatibility_hack)
2641
        ap->video_codec_id= CODEC_ID_PGMYUV;
2642

    
2643
    for(i=0; i<opt_name_count; i++){
2644
        AVOption *opt;
2645
        double d= av_get_double(avformat_opts, opt_names[i], &opt);
2646
        if(d==d && (opt->flags&AV_OPT_FLAG_DECODING_PARAM))
2647
            av_set_double(ic, opt_names[i], d);
2648
    }
2649
    /* open the input file with generic libav function */
2650
    err = av_open_input_file(&ic, filename, file_iformat, 0, ap);
2651
    if (err < 0) {
2652
        print_error(filename, err);
2653
        exit(1);
2654
    }
2655

    
2656
    ic->loop_input = loop_input;
2657

    
2658
    /* If not enough info to get the stream parameters, we decode the
2659
       first frames to get it. (used in mpeg case for example) */
2660
    ret = av_find_stream_info(ic);
2661
    if (ret < 0 && verbose >= 0) {
2662
        fprintf(stderr, "%s: could not find codec parameters\n", filename);
2663
        exit(1);
2664
    }
2665

    
2666
    timestamp = start_time;
2667
    /* add the stream start time */
2668
    if (ic->start_time != AV_NOPTS_VALUE)
2669
        timestamp += ic->start_time;
2670

    
2671
    /* if seeking requested, we execute it */
2672
    if (start_time != 0) {
2673
        ret = av_seek_frame(ic, -1, timestamp, AVSEEK_FLAG_BACKWARD);
2674
        if (ret < 0) {
2675
            fprintf(stderr, "%s: could not seek to position %0.3f\n",
2676
                    filename, (double)timestamp / AV_TIME_BASE);
2677
        }
2678
        /* reset seek info */
2679
        start_time = 0;
2680
    }
2681

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

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

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

    
2728
                    (float)rfps / rfps_base, rfps, rfps_base);
2729
            }
2730
            /* update the current frame rate to match the stream frame rate */
2731
            frame_rate      = rfps;
2732
            frame_rate_base = rfps_base;
2733

    
2734
            enc->rate_emu = rate_emu;
2735
            if(video_disable)
2736
                ic->streams[i]->discard= AVDISCARD_ALL;
2737
            else if(video_discard)
2738
                ic->streams[i]->discard= video_discard;
2739
            break;
2740
        case CODEC_TYPE_DATA:
2741
            break;
2742
        case CODEC_TYPE_SUBTITLE:
2743
            break;
2744
        case CODEC_TYPE_UNKNOWN:
2745
            break;
2746
        default:
2747
            av_abort();
2748
        }
2749
    }
2750

    
2751
    input_files[nb_input_files] = ic;
2752
    input_files_ts_offset[nb_input_files] = input_ts_offset - (copy_ts ? 0 : timestamp);
2753
    /* dump the file content */
2754
    if (verbose >= 0)
2755
        dump_format(ic, nb_input_files, filename, 0);
2756

    
2757
    nb_input_files++;
2758
    file_iformat = NULL;
2759
    file_oformat = NULL;
2760
    image_format = NULL;
2761

    
2762
    grab_device = NULL;
2763
    video_channel = 0;
2764

    
2765
    rate_emu = 0;
2766
}
2767

    
2768
static void opt_grab(const char *arg)
2769
{
2770
    file_iformat = av_find_input_format(arg);
2771
    opt_input_file("");
2772
}
2773

    
2774
static void check_audio_video_inputs(int *has_video_ptr, int *has_audio_ptr)
2775
{
2776
    int has_video, has_audio, i, j;
2777
    AVFormatContext *ic;
2778

    
2779
    has_video = 0;
2780
    has_audio = 0;
2781
    for(j=0;j<nb_input_files;j++) {
2782
        ic = input_files[j];
2783
        for(i=0;i<ic->nb_streams;i++) {
2784
            AVCodecContext *enc = ic->streams[i]->codec;
2785
            switch(enc->codec_type) {
2786
            case CODEC_TYPE_AUDIO:
2787
                has_audio = 1;
2788
                break;
2789
            case CODEC_TYPE_VIDEO:
2790
                has_video = 1;
2791
                break;
2792
            case CODEC_TYPE_DATA:
2793
            case CODEC_TYPE_UNKNOWN:
2794
            case CODEC_TYPE_SUBTITLE:
2795
                break;
2796
            default:
2797
                av_abort();
2798
            }
2799
        }
2800
    }
2801
    *has_video_ptr = has_video;
2802
    *has_audio_ptr = has_audio;
2803
}
2804

    
2805
static void new_video_stream(AVFormatContext *oc)
2806
{
2807
    AVStream *st;
2808
    AVCodecContext *video_enc;
2809
    int codec_id;
2810

    
2811
    st = av_new_stream(oc, oc->nb_streams);
2812
    if (!st) {
2813
        fprintf(stderr, "Could not alloc stream\n");
2814
        exit(1);
2815
    }
2816
    bitstream_filters[nb_output_files][oc->nb_streams - 1]= video_bitstream_filters;
2817
    video_bitstream_filters= NULL;
2818

    
2819
#if defined(HAVE_THREADS)
2820
    if(thread_count>1)
2821
        avcodec_thread_init(st->codec, thread_count);
2822
#endif
2823

    
2824
    video_enc = st->codec;
2825

    
2826
    if(video_codec_tag)
2827
        video_enc->codec_tag= video_codec_tag;
2828

    
2829
    if(   (video_global_header&1)
2830
       || (video_global_header==0 && (oc->oformat->flags & AVFMT_GLOBALHEADER))){
2831
        video_enc->flags |= CODEC_FLAG_GLOBAL_HEADER;
2832
        avctx_opts->flags|= CODEC_FLAG_GLOBAL_HEADER;
2833
    }
2834
    if(video_global_header&2){
2835
        video_enc->flags2 |= CODEC_FLAG2_LOCAL_HEADER;
2836
        avctx_opts->flags2|= CODEC_FLAG2_LOCAL_HEADER;
2837
    }
2838

    
2839
    if (video_stream_copy) {
2840
        st->stream_copy = 1;
2841
        video_enc->codec_type = CODEC_TYPE_VIDEO;
2842
    } else {
2843
        char *p;
2844
        int i;
2845
        AVCodec *codec;
2846

    
2847
        codec_id = av_guess_codec(oc->oformat, NULL, oc->filename, NULL, CODEC_TYPE_VIDEO);
2848
        if (video_codec_id != CODEC_ID_NONE)
2849
            codec_id = video_codec_id;
2850

    
2851
        video_enc->codec_id = codec_id;
2852
        codec = avcodec_find_encoder(codec_id);
2853

    
2854
        for(i=0; i<opt_name_count; i++){
2855
             AVOption *opt;
2856
             double d= av_get_double(avctx_opts, opt_names[i], &opt);
2857
             if(d==d && (opt->flags&AV_OPT_FLAG_VIDEO_PARAM) && (opt->flags&AV_OPT_FLAG_ENCODING_PARAM))
2858
                 av_set_double(video_enc, opt_names[i], d);
2859
        }
2860

    
2861
        video_enc->time_base.den = frame_rate;
2862
        video_enc->time_base.num = frame_rate_base;
2863
        if(codec && codec->supported_framerates){
2864
            const AVRational *p= codec->supported_framerates;
2865
            AVRational req= (AVRational){frame_rate, frame_rate_base};
2866
            const AVRational *best=NULL;
2867
            AVRational best_error= (AVRational){INT_MAX, 1};
2868
            for(; p->den!=0; p++){
2869
                AVRational error= av_sub_q(req, *p);
2870
                if(error.num <0) error.num *= -1;
2871
                if(av_cmp_q(error, best_error) < 0){
2872
                    best_error= error;
2873
                    best= p;
2874
                }
2875
            }
2876
            video_enc->time_base.den= best->num;
2877
            video_enc->time_base.num= best->den;
2878
        }
2879

    
2880
        video_enc->width = frame_width + frame_padright + frame_padleft;
2881
        video_enc->height = frame_height + frame_padtop + frame_padbottom;
2882
        video_enc->sample_aspect_ratio = av_d2q(frame_aspect_ratio*video_enc->height/video_enc->width, 255);
2883
        video_enc->pix_fmt = frame_pix_fmt;
2884

    
2885
        if(codec && codec->pix_fmts){
2886
            const enum PixelFormat *p= codec->pix_fmts;
2887
            for(; *p!=-1; p++){
2888
                if(*p == video_enc->pix_fmt)
2889
                    break;
2890
            }
2891
            if(*p == -1)
2892
                video_enc->pix_fmt = codec->pix_fmts[0];
2893
        }
2894

    
2895
        if (intra_only)
2896
            video_enc->gop_size = 0;
2897
        if (video_qscale || same_quality) {
2898
            video_enc->flags |= CODEC_FLAG_QSCALE;
2899
            video_enc->global_quality=
2900
                st->quality = FF_QP2LAMBDA * video_qscale;
2901
        }
2902

    
2903
        if(intra_matrix)
2904
            video_enc->intra_matrix = intra_matrix;
2905
        if(inter_matrix)
2906
            video_enc->inter_matrix = inter_matrix;
2907

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

    
2951
        if(packet_size){
2952
            video_enc->rtp_mode= 1;
2953
            video_enc->rtp_payload_size= packet_size;
2954
        }
2955

    
2956
        if (do_psnr)
2957
            video_enc->flags|= CODEC_FLAG_PSNR;
2958

    
2959
        video_enc->me_method = me_method;
2960

    
2961
        /* two pass mode */
2962
        if (do_pass) {
2963
            if (do_pass == 1) {
2964
                video_enc->flags |= CODEC_FLAG_PASS1;
2965
            } else {
2966
                video_enc->flags |= CODEC_FLAG_PASS2;
2967
            }
2968
        }
2969
    }
2970

    
2971
    /* reset some key parameters */
2972
    video_disable = 0;
2973
    video_codec_id = CODEC_ID_NONE;
2974
    video_stream_copy = 0;
2975
}
2976

    
2977
static void new_audio_stream(AVFormatContext *oc)
2978
{
2979
    AVStream *st;
2980
    AVCodecContext *audio_enc;
2981
    int codec_id, i;
2982

    
2983
    st = av_new_stream(oc, oc->nb_streams);
2984
    if (!st) {
2985
        fprintf(stderr, "Could not alloc stream\n");
2986
        exit(1);
2987
    }
2988

    
2989
    bitstream_filters[nb_output_files][oc->nb_streams - 1]= audio_bitstream_filters;
2990
    audio_bitstream_filters= NULL;
2991

    
2992
#if defined(HAVE_THREADS)
2993
    if(thread_count>1)
2994
        avcodec_thread_init(st->codec, thread_count);
2995
#endif
2996

    
2997
    audio_enc = st->codec;
2998
    audio_enc->codec_type = CODEC_TYPE_AUDIO;
2999

    
3000
    if(audio_codec_tag)
3001
        audio_enc->codec_tag= audio_codec_tag;
3002

    
3003
    if (oc->oformat->flags & AVFMT_GLOBALHEADER) {
3004
        audio_enc->flags |= CODEC_FLAG_GLOBAL_HEADER;
3005
        avctx_opts->flags|= CODEC_FLAG_GLOBAL_HEADER;
3006
    }
3007
    if (audio_stream_copy) {
3008
        st->stream_copy = 1;
3009
        audio_enc->channels = audio_channels;
3010
    } else {
3011
        codec_id = av_guess_codec(oc->oformat, NULL, oc->filename, NULL, CODEC_TYPE_AUDIO);
3012

    
3013
        for(i=0; i<opt_name_count; i++){
3014
            AVOption *opt;
3015
            double d= av_get_double(avctx_opts, opt_names[i], &opt);
3016
            if(d==d && (opt->flags&AV_OPT_FLAG_AUDIO_PARAM) && (opt->flags&AV_OPT_FLAG_ENCODING_PARAM))
3017
                av_set_double(audio_enc, opt_names[i], d);
3018
        }
3019

    
3020
        if (audio_codec_id != CODEC_ID_NONE)
3021
            codec_id = audio_codec_id;
3022
        audio_enc->codec_id = codec_id;
3023

    
3024
        audio_enc->bit_rate = audio_bit_rate;
3025
        if (audio_qscale > QSCALE_NONE) {
3026
            audio_enc->flags |= CODEC_FLAG_QSCALE;
3027
            audio_enc->global_quality = st->quality = FF_QP2LAMBDA * audio_qscale;
3028
        }
3029
        audio_enc->strict_std_compliance = strict;
3030
        audio_enc->thread_count = thread_count;
3031
        /* For audio codecs other than AC3 or DTS we limit */
3032
        /* the number of coded channels to stereo   */
3033
        if (audio_channels > 2 && codec_id != CODEC_ID_AC3
3034
            && codec_id != CODEC_ID_DTS) {
3035
            audio_enc->channels = 2;
3036
        } else
3037
            audio_enc->channels = audio_channels;
3038
    }
3039
    audio_enc->sample_rate = audio_sample_rate;
3040
    audio_enc->time_base= (AVRational){1, audio_sample_rate};
3041
    if (audio_language) {
3042
        pstrcpy(st->language, sizeof(st->language), audio_language);
3043
        av_free(audio_language);
3044
        audio_language = NULL;
3045
    }
3046

    
3047
    /* reset some key parameters */
3048
    audio_disable = 0;
3049
    audio_codec_id = CODEC_ID_NONE;
3050
    audio_stream_copy = 0;
3051
}
3052

    
3053
static void opt_new_subtitle_stream(void)
3054
{
3055
    AVFormatContext *oc;
3056
    AVStream *st;
3057
    AVCodecContext *subtitle_enc;
3058
    int i;
3059

    
3060
    if (nb_output_files <= 0) {
3061
        fprintf(stderr, "At least one output file must be specified\n");
3062
        exit(1);
3063
    }
3064
    oc = output_files[nb_output_files - 1];
3065

    
3066
    st = av_new_stream(oc, oc->nb_streams);
3067
    if (!st) {
3068
        fprintf(stderr, "Could not alloc stream\n");
3069
        exit(1);
3070
    }
3071

    
3072
    subtitle_enc = st->codec;
3073
    subtitle_enc->codec_type = CODEC_TYPE_SUBTITLE;
3074
    if (subtitle_stream_copy) {
3075
        st->stream_copy = 1;
3076
    } else {
3077
        for(i=0; i<opt_name_count; i++){
3078
             AVOption *opt;
3079
             double d= av_get_double(avctx_opts, opt_names[i], &opt);
3080
             if(d==d && (opt->flags&AV_OPT_FLAG_SUBTITLE_PARAM) && (opt->flags&AV_OPT_FLAG_ENCODING_PARAM))
3081
                 av_set_double(subtitle_enc, opt_names[i], d);
3082
        }
3083
        subtitle_enc->codec_id = subtitle_codec_id;
3084
    }
3085

    
3086
    if (subtitle_language) {
3087
        pstrcpy(st->language, sizeof(st->language), subtitle_language);
3088
        av_free(subtitle_language);
3089
        subtitle_language = NULL;
3090
    }
3091

    
3092
    subtitle_codec_id = CODEC_ID_NONE;
3093
    subtitle_stream_copy = 0;
3094
}
3095

    
3096
static void opt_new_audio_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_audio_stream(oc);
3105
}
3106

    
3107
static void opt_new_video_stream(void)
3108
{
3109
    AVFormatContext *oc;
3110
    if (nb_output_files <= 0) {
3111
        fprintf(stderr, "At least one output file must be specified\n");
3112
        exit(1);
3113
    }
3114
    oc = output_files[nb_output_files - 1];
3115
    new_video_stream(oc);
3116
}
3117

    
3118
static void opt_output_file(const char *filename)
3119
{
3120
    AVFormatContext *oc;
3121
    int use_video, use_audio, input_has_video, input_has_audio, i;
3122
    AVFormatParameters params, *ap = &params;
3123

    
3124
    if (!strcmp(filename, "-"))
3125
        filename = "pipe:";
3126

    
3127
    oc = av_alloc_format_context();
3128

    
3129
    if (!file_oformat) {
3130
        file_oformat = guess_format(NULL, filename, NULL);
3131
        if (!file_oformat) {
3132
            fprintf(stderr, "Unable for find a suitable output format for '%s'\n",
3133
                    filename);
3134
            exit(1);
3135
        }
3136
    }
3137

    
3138
    oc->oformat = file_oformat;
3139
    pstrcpy(oc->filename, sizeof(oc->filename), filename);
3140

    
3141
    if (!strcmp(file_oformat->name, "ffm") &&
3142
        strstart(filename, "http:", NULL)) {
3143
        /* special case for files sent to ffserver: we get the stream
3144
           parameters from ffserver */
3145
        if (read_ffserver_streams(oc, filename) < 0) {
3146
            fprintf(stderr, "Could not read stream parameters from '%s'\n", filename);
3147
            exit(1);
3148
        }
3149
    } else {
3150
        use_video = file_oformat->video_codec != CODEC_ID_NONE || video_stream_copy || video_codec_id != CODEC_ID_NONE;
3151
        use_audio = file_oformat->audio_codec != CODEC_ID_NONE || audio_stream_copy || audio_codec_id != CODEC_ID_NONE;
3152

    
3153
        /* disable if no corresponding type found and at least one
3154
           input file */
3155
        if (nb_input_files > 0) {
3156
            check_audio_video_inputs(&input_has_video, &input_has_audio);
3157
            if (!input_has_video)
3158
                use_video = 0;
3159
            if (!input_has_audio)
3160
                use_audio = 0;
3161
        }
3162

    
3163
        /* manual disable */
3164
        if (audio_disable) {
3165
            use_audio = 0;
3166
        }
3167
        if (video_disable) {
3168
            use_video = 0;
3169
        }
3170

    
3171
        if (use_video) {
3172
            new_video_stream(oc);
3173
        }
3174

    
3175
        if (use_audio) {
3176
            new_audio_stream(oc);
3177
        }
3178

    
3179
        if (!oc->nb_streams) {
3180
            fprintf(stderr, "No audio or video streams available\n");
3181
            exit(1);
3182
        }
3183

    
3184
        oc->timestamp = rec_timestamp;
3185

    
3186
        if (str_title)
3187
            pstrcpy(oc->title, sizeof(oc->title), str_title);
3188
        if (str_author)
3189
            pstrcpy(oc->author, sizeof(oc->author), str_author);
3190
        if (str_copyright)
3191
            pstrcpy(oc->copyright, sizeof(oc->copyright), str_copyright);
3192
        if (str_comment)
3193
            pstrcpy(oc->comment, sizeof(oc->comment), str_comment);
3194
        if (str_album)
3195
            pstrcpy(oc->album, sizeof(oc->album), str_album);
3196
    }
3197

    
3198
    output_files[nb_output_files++] = oc;
3199

    
3200
    /* check filename in case of an image number is expected */
3201
    if (oc->oformat->flags & AVFMT_NEEDNUMBER) {
3202
        if (!av_filename_number_test(oc->filename)) {
3203
            print_error(oc->filename, AVERROR_NUMEXPECTED);
3204
            exit(1);
3205
        }
3206
    }
3207

    
3208
    if (!(oc->oformat->flags & AVFMT_NOFILE)) {
3209
        /* test if it already exists to avoid loosing precious files */
3210
        if (!file_overwrite &&
3211
            (strchr(filename, ':') == NULL ||
3212
             strstart(filename, "file:", NULL))) {
3213
            if (url_exist(filename)) {
3214
                int c;
3215

    
3216
                if ( !using_stdin ) {
3217
                    fprintf(stderr,"File '%s' already exists. Overwrite ? [y/N] ", filename);
3218
                    fflush(stderr);
3219
                    c = getchar();
3220
                    if (toupper(c) != 'Y') {
3221
                        fprintf(stderr, "Not overwriting - exiting\n");
3222
                        exit(1);
3223
                    }
3224
                                }
3225
                                else {
3226
                    fprintf(stderr,"File '%s' already exists. Exiting.\n", filename);
3227
                    exit(1);
3228
                                }
3229
            }
3230
        }
3231

    
3232
        /* open the file */
3233
        if (url_fopen(&oc->pb, filename, URL_WRONLY) < 0) {
3234
            fprintf(stderr, "Could not open '%s'\n", filename);
3235
            exit(1);
3236
        }
3237
    }
3238

    
3239
    memset(ap, 0, sizeof(*ap));
3240
    ap->image_format = image_format;
3241
    if (av_set_parameters(oc, ap) < 0) {
3242
        fprintf(stderr, "%s: Invalid encoding parameters\n",
3243
                oc->filename);
3244
        exit(1);
3245
    }
3246

    
3247
    oc->preload= (int)(mux_preload*AV_TIME_BASE);
3248
    oc->max_delay= (int)(mux_max_delay*AV_TIME_BASE);
3249
    oc->loop_output = loop_output;
3250

    
3251
    for(i=0; i<opt_name_count; i++){
3252
        AVOption *opt;
3253
        double d = av_get_double(avformat_opts, opt_names[i], &opt);
3254
        if(d==d && (opt->flags&AV_OPT_FLAG_ENCODING_PARAM))
3255
            av_set_double(oc, opt_names[i], d);
3256
    }
3257

    
3258
    /* reset some options */
3259
    file_oformat = NULL;
3260
    file_iformat = NULL;
3261
    image_format = NULL;
3262
}
3263

    
3264
/* prepare dummy protocols for grab */
3265
static void prepare_grab(void)
3266
{
3267
    int has_video, has_audio, i, j;
3268
    AVFormatContext *oc;
3269
    AVFormatContext *ic;
3270
    AVFormatParameters vp1, *vp = &vp1;
3271
    AVFormatParameters ap1, *ap = &ap1;
3272

    
3273
    /* see if audio/video inputs are needed */
3274
    has_video = 0;
3275
    has_audio = 0;
3276
    memset(ap, 0, sizeof(*ap));
3277
    memset(vp, 0, sizeof(*vp));
3278
    vp->time_base.num= 1;
3279
    for(j=0;j<nb_output_files;j++) {
3280
        oc = output_files[j];
3281
        for(i=0;i<oc->nb_streams;i++) {
3282
            AVCodecContext *enc = oc->streams[i]->codec;
3283
            switch(enc->codec_type) {
3284
            case CODEC_TYPE_AUDIO:
3285
                if (enc->sample_rate > ap->sample_rate)
3286
                    ap->sample_rate = enc->sample_rate;
3287
                if (enc->channels > ap->channels)
3288
                    ap->channels = enc->channels;
3289
                has_audio = 1;
3290
                break;
3291
            case CODEC_TYPE_VIDEO:
3292
                if (enc->width > vp->width)
3293
                    vp->width = enc->width;
3294
                if (enc->height > vp->height)
3295
                    vp->height = enc->height;
3296

    
3297
                if (vp->time_base.num*(int64_t)enc->time_base.den > enc->time_base.num*(int64_t)vp->time_base.den){
3298
                    vp->time_base = enc->time_base;
3299
                    vp->width += frame_leftBand + frame_rightBand;
3300
                    vp->width -= (frame_padleft + frame_padright);
3301
                    vp->height += frame_topBand + frame_bottomBand;
3302
                    vp->height -= (frame_padtop + frame_padbottom);
3303
                }
3304
                has_video = 1;
3305
                break;
3306
            default:
3307
                av_abort();
3308
            }
3309
        }
3310
    }
3311

    
3312
    if (has_video == 0 && has_audio == 0) {
3313
        fprintf(stderr, "Output file must have at least one audio or video stream\n");
3314
        exit(1);
3315
    }
3316

    
3317
    if (has_video) {
3318
        AVInputFormat *fmt1;
3319
        fmt1 = av_find_input_format(video_grab_format);
3320
        vp->device  = video_device;
3321
        vp->channel = video_channel;
3322
        vp->standard = video_standard;
3323
        vp->pix_fmt = frame_pix_fmt;
3324
        if (av_open_input_file(&ic, "", fmt1, 0, vp) < 0) {
3325
            fprintf(stderr, "Could not find video grab device\n");
3326
            exit(1);
3327
        }
3328
        /* If not enough info to get the stream parameters, we decode the
3329
           first frames to get it. */
3330
        if ((ic->ctx_flags & AVFMTCTX_NOHEADER) && av_find_stream_info(ic) < 0) {
3331
            fprintf(stderr, "Could not find video grab parameters\n");
3332
            exit(1);
3333
        }
3334
        /* by now video grab has one stream */
3335
        ic->streams[0]->r_frame_rate.num = vp->time_base.den;
3336
        ic->streams[0]->r_frame_rate.den = vp->time_base.num;
3337
        input_files[nb_input_files] = ic;
3338

    
3339
        if (verbose >= 0)
3340
            dump_format(ic, nb_input_files, "", 0);
3341

    
3342
        nb_input_files++;
3343
    }
3344
    if (has_audio && audio_grab_format) {
3345
        AVInputFormat *fmt1;
3346
        fmt1 = av_find_input_format(audio_grab_format);
3347
        ap->device = audio_device;
3348
        if (av_open_input_file(&ic, "", fmt1, 0, ap) < 0) {
3349
            fprintf(stderr, "Could not find audio grab device\n");
3350
            exit(1);
3351
        }
3352
        input_files[nb_input_files] = ic;
3353

    
3354
        if (verbose >= 0)
3355
            dump_format(ic, nb_input_files, "", 0);
3356

    
3357
        nb_input_files++;
3358
    }
3359
}
3360

    
3361
/* same option as mencoder */
3362
static void opt_pass(const char *pass_str)
3363
{
3364
    int pass;
3365
    pass = atoi(pass_str);
3366
    if (pass != 1 && pass != 2) {
3367
        fprintf(stderr, "pass number can be only 1 or 2\n");
3368
        exit(1);
3369
    }
3370
    do_pass = pass;
3371
}
3372

    
3373
#if defined(__MINGW32__) || defined(CONFIG_OS2)
3374
static int64_t getutime(void)
3375
{
3376
  return av_gettime();
3377
}
3378
#else
3379
static int64_t getutime(void)
3380
{
3381
    struct rusage rusage;
3382

    
3383
    getrusage(RUSAGE_SELF, &rusage);
3384
    return (rusage.ru_utime.tv_sec * 1000000LL) + rusage.ru_utime.tv_usec;
3385
}
3386
#endif
3387

    
3388
#if defined(CONFIG_FFM_DEMUXER) || defined(CONFIG_FFM_MUXER)
3389
extern int ffm_nopts;
3390
#endif
3391

    
3392
static void show_formats(void)
3393
{
3394
    AVInputFormat *ifmt;
3395
    AVOutputFormat *ofmt;
3396
    AVImageFormat *image_fmt;
3397
    URLProtocol *up;
3398
    AVCodec *p, *p2;
3399
    const char **pp, *last_name;
3400

    
3401
    printf("File formats:\n");
3402
    last_name= "000";
3403
    for(;;){
3404
        int decode=0;
3405
        int encode=0;
3406
        const char *name=NULL;
3407
        const char *long_name=NULL;
3408

    
3409
        for(ofmt = first_oformat; ofmt != NULL; ofmt = ofmt->next) {
3410
            if((name == NULL || strcmp(ofmt->name, name)<0) &&
3411
                strcmp(ofmt->name, last_name)>0){
3412
                name= ofmt->name;
3413
                long_name= ofmt->long_name;
3414
                encode=1;
3415
            }
3416
        }
3417
        for(ifmt = first_iformat; ifmt != NULL; ifmt = ifmt->next) {
3418
            if((name == NULL || strcmp(ifmt->name, name)<0) &&
3419
                strcmp(ifmt->name, last_name)>0){
3420
                name= ifmt->name;
3421
                long_name= ifmt->long_name;
3422
                encode=0;
3423
            }
3424
            if(name && strcmp(ifmt->name, name)==0)
3425
                decode=1;
3426
        }
3427
        if(name==NULL)
3428
            break;
3429
        last_name= name;
3430

    
3431
        printf(
3432
            " %s%s %-15s %s\n",
3433
            decode ? "D":" ",
3434
            encode ? "E":" ",
3435
            name,
3436
            long_name ? long_name:" ");
3437
    }
3438
    printf("\n");
3439

    
3440
    printf("Image formats (filename extensions, if any, follow):\n");
3441
    for(image_fmt = first_image_format; image_fmt != NULL;
3442
        image_fmt = image_fmt->next) {
3443
        printf(
3444
            " %s%s %-6s %s\n",
3445
            image_fmt->img_read  ? "D":" ",
3446
            image_fmt->img_write ? "E":" ",
3447
            image_fmt->name,
3448
            image_fmt->extensions ? image_fmt->extensions:" ");
3449
    }
3450
    printf("\n");
3451

    
3452
    printf("Codecs:\n");
3453
    last_name= "000";
3454
    for(;;){
3455
        int decode=0;
3456
        int encode=0;
3457
        int cap=0;
3458
        const char *type_str;
3459

    
3460
        p2=NULL;
3461
        for(p = first_avcodec; p != NULL; p = p->next) {
3462
            if((p2==NULL || strcmp(p->name, p2->name)<0) &&
3463
                strcmp(p->name, last_name)>0){
3464
                p2= p;
3465
                decode= encode= cap=0;
3466
            }
3467
            if(p2 && strcmp(p->name, p2->name)==0){
3468
                if(p->decode) decode=1;
3469
                if(p->encode) encode=1;
3470
                cap |= p->capabilities;
3471
            }
3472
        }
3473
        if(p2==NULL)
3474
            break;
3475
        last_name= p2->name;
3476

    
3477
        switch(p2->type) {
3478
        case CODEC_TYPE_VIDEO:
3479
            type_str = "V";
3480
            break;
3481
        case CODEC_TYPE_AUDIO:
3482
            type_str = "A";
3483
            break;
3484
        case CODEC_TYPE_SUBTITLE:
3485
            type_str = "S";
3486
            break;
3487
        default:
3488
            type_str = "?";
3489
            break;
3490
        }
3491
        printf(
3492
            " %s%s%s%s%s%s %s",
3493
            decode ? "D": (/*p2->decoder ? "d":*/" "),
3494
            encode ? "E":" ",
3495
            type_str,
3496
            cap & CODEC_CAP_DRAW_HORIZ_BAND ? "S":" ",
3497
            cap & CODEC_CAP_DR1 ? "D":" ",
3498
            cap & CODEC_CAP_TRUNCATED ? "T":" ",
3499
            p2->name);
3500
       /* if(p2->decoder && decode==0)
3501
            printf(" use %s for decoding", p2->decoder->name);*/
3502
        printf("\n");
3503
    }
3504
    printf("\n");
3505

    
3506
    printf("Supported file protocols:\n");
3507
    for(up = first_protocol; up != NULL; up = up->next)
3508
        printf(" %s:", up->name);
3509
    printf("\n");
3510

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

    
3534
static void parse_matrix_coeffs(uint16_t *dest, const char *str)
3535
{
3536
    int i;
3537
    const char *p = str;
3538
    for(i = 0;; i++) {
3539
        dest[i] = atoi(p);
3540
        if(i == 63)
3541
            break;
3542
        p = strchr(p, ',');
3543
        if(!p) {
3544
            fprintf(stderr, "Syntax error in matrix \"%s\" at coeff %d\n", str, i);
3545
            exit(1);
3546
        }
3547
        p++;
3548
    }
3549
}
3550

    
3551
static void opt_inter_matrix(const char *arg)
3552
{
3553
    inter_matrix = av_mallocz(sizeof(uint16_t) * 64);
3554
    parse_matrix_coeffs(inter_matrix, arg);
3555
}
3556

    
3557
static void opt_intra_matrix(const char *arg)
3558
{
3559
    intra_matrix = av_mallocz(sizeof(uint16_t) * 64);
3560
    parse_matrix_coeffs(intra_matrix, arg);
3561
}
3562

    
3563
static void opt_target(const char *arg)
3564
{
3565
    int norm = -1;
3566
    static const char *const frame_rates[] = {"25", "30000/1001", "24000/1001"};
3567

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

    
3612
    if(norm < 0) {
3613
        fprintf(stderr, "Could not determine norm (PAL/NTSC/NTSC-Film) for target.\n");
3614
        fprintf(stderr, "Please prefix target with \"pal-\", \"ntsc-\" or \"film-\",\n");
3615
        fprintf(stderr, "or set a framerate with \"-r xxx\".\n");
3616
        exit(1);
3617
    }
3618

    
3619
    if(!strcmp(arg, "vcd")) {
3620

    
3621
        opt_video_codec("mpeg1video");
3622
        opt_audio_codec("mp2");
3623
        opt_format("vcd");
3624

    
3625
        opt_frame_size(norm ? "352x240" : "352x288");
3626
        opt_frame_rate(frame_rates[norm]);
3627
        opt_default("gop", norm ? "18" : "15");
3628

    
3629
        opt_default("b", "1150000");
3630
        opt_default("maxrate", "1150000");
3631
        opt_default("minrate", "1150000");
3632
        opt_default("bufsize", "327680"); // 40*1024*8;
3633

    
3634
        audio_bit_rate = 224000;
3635
        audio_sample_rate = 44100;
3636

    
3637
        opt_default("packetsize", "2324");
3638
        opt_default("muxrate", "1411200"); // 2352 * 75 * 8;
3639

    
3640
        /* We have to offset the PTS, so that it is consistent with the SCR.
3641
           SCR starts at 36000, but the first two packs contain only padding
3642
           and the first pack from the other stream, respectively, may also have
3643
           been written before.
3644
           So the real data starts at SCR 36000+3*1200. */
3645
        mux_preload= (36000+3*1200) / 90000.0; //0.44
3646
    } else if(!strcmp(arg, "svcd")) {
3647

    
3648
        opt_video_codec("mpeg2video");
3649
        opt_audio_codec("mp2");
3650
        opt_format("svcd");
3651

    
3652
        opt_frame_size(norm ? "480x480" : "480x576");
3653
        opt_frame_rate(frame_rates[norm]);
3654
        opt_default("gop", norm ? "18" : "15");
3655

    
3656
        opt_default("b", "2040000");
3657
        opt_default("maxrate", "2516000");
3658
        opt_default("minrate", "0"); //1145000;
3659
        opt_default("bufsize", "1835008"); //224*1024*8;
3660
        opt_default("flags", "+SCAN_OFFSET");
3661

    
3662

    
3663
        audio_bit_rate = 224000;
3664
        audio_sample_rate = 44100;
3665

    
3666
        opt_default("packetsize", "2324");
3667

    
3668
    } else if(!strcmp(arg, "dvd")) {
3669

    
3670
        opt_video_codec("mpeg2video");
3671
        opt_audio_codec("ac3");
3672
        opt_format("dvd");
3673

    
3674
        opt_frame_size(norm ? "720x480" : "720x576");
3675
        opt_frame_rate(frame_rates[norm]);
3676
        opt_default("gop", norm ? "18" : "15");
3677

    
3678
        opt_default("b", "6000000");
3679
        opt_default("maxrate", "9000000");
3680
        opt_default("minrate", "0"); //1500000;
3681
        opt_default("bufsize", "1835008"); //224*1024*8;
3682

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

    
3686
        audio_bit_rate = 448000;
3687
        audio_sample_rate = 48000;
3688

    
3689
    } else if(!strncmp(arg, "dv", 2)) {
3690

    
3691
        opt_format("dv");
3692

    
3693
        opt_frame_size(norm ? "720x480" : "720x576");
3694
        opt_frame_pix_fmt(!strncmp(arg, "dv50", 4) ? "yuv422p" :
3695
                                             (norm ? "yuv411p" : "yuv420p"));
3696
        opt_frame_rate(frame_rates[norm]);
3697

    
3698
        audio_sample_rate = 48000;
3699
        audio_channels = 2;
3700

    
3701
    } else {
3702
        fprintf(stderr, "Unknown target: %s\n", arg);
3703
        exit(1);
3704
    }
3705
}
3706

    
3707
static void opt_video_bsf(const char *arg)
3708
{
3709
    AVBitStreamFilterContext *bsfc= av_bitstream_filter_init(arg); //FIXME split name and args for filter at '='
3710
    AVBitStreamFilterContext **bsfp;
3711

    
3712
    if(!bsfc){
3713
        fprintf(stderr, "Unkown bitstream filter %s\n", arg);
3714
        exit(1);
3715
    }
3716

    
3717
    bsfp= &video_bitstream_filters;
3718
    while(*bsfp)
3719
        bsfp= &(*bsfp)->next;
3720

    
3721
    *bsfp= bsfc;
3722
}
3723

    
3724
//FIXME avoid audio - video code duplication
3725
static void opt_audio_bsf(const char *arg)
3726
{
3727
    AVBitStreamFilterContext *bsfc= av_bitstream_filter_init(arg); //FIXME split name and args for filter at '='
3728
    AVBitStreamFilterContext **bsfp;
3729

    
3730
    if(!bsfc){
3731
        fprintf(stderr, "Unkown bitstream filter %s\n", arg);
3732
        exit(1);
3733
    }
3734

    
3735
    bsfp= &audio_bitstream_filters;
3736
    while(*bsfp)
3737
        bsfp= &(*bsfp)->next;
3738

    
3739
    *bsfp= bsfc;
3740
}
3741

    
3742
static void show_version(void)
3743
{
3744
    /* TODO: add function interface to avutil and avformat */
3745
    fprintf(stderr, "ffmpeg      " FFMPEG_VERSION "\n"
3746
           "libavutil   %d\n"
3747
           "libavcodec  %d\n"
3748
           "libavformat %d\n",
3749
           LIBAVUTIL_BUILD, avcodec_build(), LIBAVFORMAT_BUILD);
3750
    exit(1);
3751
}
3752

    
3753
static int opt_default(const char *opt, const char *arg){
3754
    AVOption *o= av_set_string(avctx_opts, opt, arg);
3755
    if(!o)
3756
        o = av_set_string(avformat_opts, opt, arg);
3757
    if(!o)
3758
        return -1;
3759

    
3760
//    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));
3761

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

    
3766
#if defined(CONFIG_FFM_DEMUXER) || defined(CONFIG_FFM_MUXER)
3767
    /* disable generate of real time pts in ffm (need to be supressed anyway) */
3768
    if(avctx_opts->flags & CODEC_FLAG_BITEXACT)
3769
        ffm_nopts = 1;
3770
#endif
3771

    
3772
    if(avctx_opts->debug)
3773
        av_log_set_level(AV_LOG_DEBUG);
3774
    return 0;
3775
}
3776

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

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

    
3875
    /* audio options */
3876
    { "ab", HAS_ARG | OPT_AUDIO, {(void*)opt_audio_bitrate}, "set audio bitrate (in kbit/s)", "bitrate", },
3877
    { "aq", OPT_FLOAT | HAS_ARG | OPT_AUDIO, {(void*)&audio_qscale}, "set audio quality (codec-specific)", "quality", },
3878
    { "ar", HAS_ARG | OPT_AUDIO, {(void*)opt_audio_rate}, "set audio sampling rate (in Hz)", "rate" },
3879
    { "ac", HAS_ARG | OPT_AUDIO, {(void*)opt_audio_channels}, "set number of audio channels", "channels" },
3880
    { "an", OPT_BOOL | OPT_AUDIO, {(void*)&audio_disable}, "disable audio" },
3881
    { "acodec", HAS_ARG | OPT_AUDIO, {(void*)opt_audio_codec}, "force audio codec ('copy' to copy stream)", "codec" },
3882
    { "atag", HAS_ARG | OPT_EXPERT | OPT_AUDIO, {(void*)opt_audio_tag}, "force audio tag/fourcc", "fourcc/tag" },
3883
    { "vol", OPT_INT | HAS_ARG | OPT_AUDIO, {(void*)&audio_volume}, "change audio volume (256=normal)" , "volume" }, //
3884
    { "newaudio", OPT_AUDIO, {(void*)opt_new_audio_stream}, "add a new audio stream to the current output stream" },
3885
    { "alang", HAS_ARG | OPT_STRING | OPT_AUDIO, {(void *)&audio_language}, "set the ISO 639 language code (3 letters) of the current audio stream" , "code" },
3886

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

    
3892
    /* grab options */
3893
    { "vd", HAS_ARG | OPT_EXPERT | OPT_VIDEO | OPT_GRAB, {(void*)opt_video_device}, "set video grab device", "device" },
3894
    { "vc", HAS_ARG | OPT_EXPERT | OPT_VIDEO | OPT_GRAB, {(void*)opt_video_channel}, "set video grab channel (DV1394 only)", "channel" },
3895
    { "tvstd", HAS_ARG | OPT_EXPERT | OPT_VIDEO | OPT_GRAB, {(void*)opt_video_standard}, "set television standard (NTSC, PAL (SECAM))", "standard" },
3896
    { "ad", HAS_ARG | OPT_EXPERT | OPT_AUDIO | OPT_GRAB, {(void*)opt_audio_device}, "set audio device", "device" },
3897

    
3898
    /* G.2 grab options */
3899
    { "grab", HAS_ARG | OPT_EXPERT | OPT_GRAB, {(void*)opt_grab}, "request grabbing using", "format" },
3900
    { "gd", HAS_ARG | OPT_EXPERT | OPT_VIDEO | OPT_GRAB, {(void*)opt_grab_device}, "set grab device", "device" },
3901

    
3902
    /* muxer options */
3903
    { "muxdelay", OPT_FLOAT | HAS_ARG | OPT_EXPERT, {(void*)&mux_max_delay}, "set the maximum demux-decode delay", "seconds" },
3904
    { "muxpreload", OPT_FLOAT | HAS_ARG | OPT_EXPERT, {(void*)&mux_preload}, "set the initial demux-decode delay", "seconds" },
3905

    
3906
    { "absf", HAS_ARG | OPT_AUDIO | OPT_EXPERT, {(void*)opt_audio_bsf}, "", "bitstream filter" },
3907
    { "vbsf", HAS_ARG | OPT_VIDEO | OPT_EXPERT, {(void*)opt_video_bsf}, "", "bitstream filter" },
3908

    
3909
    { "default", OPT_FUNC2 | HAS_ARG | OPT_AUDIO | OPT_VIDEO | OPT_EXPERT, {(void*)opt_default}, "generic catch all option", "" },
3910
    { NULL, },
3911
};
3912

    
3913
static void show_banner(void)
3914
{
3915
    fprintf(stderr, "FFmpeg version " FFMPEG_VERSION ", Copyright (c) 2000-2004 Fabrice Bellard\n");
3916
    fprintf(stderr, "  configuration: " FFMPEG_CONFIGURATION "\n");
3917
    fprintf(stderr, "  libavutil version: " AV_STRINGIFY(LIBAVUTIL_VERSION) "\n");
3918
    fprintf(stderr, "  libavcodec version: " AV_STRINGIFY(LIBAVCODEC_VERSION) "\n");
3919
    fprintf(stderr, "  libavformat version: " AV_STRINGIFY(LIBAVFORMAT_VERSION) "\n");
3920
    fprintf(stderr, "  built on " __DATE__ " " __TIME__);
3921
#ifdef __GNUC__
3922
    fprintf(stderr, ", gcc: " __VERSION__ "\n");
3923
#else
3924
    fprintf(stderr, ", using a non-gcc compiler\n");
3925
#endif
3926
}
3927

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

    
3967
static void show_help(void)
3968
{
3969
    show_banner();
3970
    printf("usage: ffmpeg [[infile options] -i infile]... {[outfile options] outfile}...\n"
3971
           "Hyper fast Audio and Video encoder\n");
3972
    printf("\n");
3973
    show_help_options(options, "Main options:\n",
3974
                      OPT_EXPERT | OPT_AUDIO | OPT_VIDEO, 0);
3975
    show_help_options(options, "\nVideo options:\n",
3976
                      OPT_EXPERT | OPT_AUDIO | OPT_VIDEO | OPT_GRAB,
3977
                      OPT_VIDEO);
3978
    show_help_options(options, "\nAdvanced Video options:\n",
3979
                      OPT_EXPERT | OPT_AUDIO | OPT_VIDEO | OPT_GRAB,
3980
                      OPT_VIDEO | OPT_EXPERT);
3981
    show_help_options(options, "\nAudio options:\n",
3982
                      OPT_EXPERT | OPT_AUDIO | OPT_VIDEO | OPT_GRAB,
3983
                      OPT_AUDIO);
3984
    show_help_options(options, "\nAdvanced Audio options:\n",
3985
                      OPT_EXPERT | OPT_AUDIO | OPT_VIDEO | OPT_GRAB,
3986
                      OPT_AUDIO | OPT_EXPERT);
3987
    show_help_options(options, "\nSubtitle options:\n",
3988
                      OPT_SUBTITLE | OPT_GRAB,
3989
                      OPT_SUBTITLE);
3990
    show_help_options(options, "\nAudio/Video grab options:\n",
3991
                      OPT_GRAB,
3992
                      OPT_GRAB);
3993
    show_help_options(options, "\nAdvanced options:\n",
3994
                      OPT_EXPERT | OPT_AUDIO | OPT_VIDEO | OPT_GRAB,
3995
                      OPT_EXPERT);
3996
    av_opt_show(avctx_opts, NULL);
3997
    av_opt_show(avformat_opts, NULL);
3998

    
3999
    exit(1);
4000
}
4001

    
4002
void parse_arg_file(const char *filename)
4003
{
4004
    opt_output_file(filename);
4005
}
4006

    
4007
int main(int argc, char **argv)
4008
{
4009
    int i;
4010
    int64_t ti;
4011

    
4012
    av_register_all();
4013

    
4014
    avctx_opts= avcodec_alloc_context();
4015
    avformat_opts = av_alloc_format_context();
4016

    
4017
    if (argc <= 1)
4018
        show_help();
4019
    else
4020
        show_banner();
4021

    
4022
    /* parse options */
4023
    parse_options(argc, argv, options);
4024

    
4025
    /* file converter / grab */
4026
    if (nb_output_files <= 0) {
4027
        fprintf(stderr, "Must supply at least one output file\n");
4028
        exit(1);
4029
    }
4030

    
4031
    if (nb_input_files == 0) {
4032
        input_sync = 1;
4033
        prepare_grab();
4034
    }
4035

    
4036
    ti = getutime();
4037
    av_encode(output_files, nb_output_files, input_files, nb_input_files,
4038
              stream_maps, nb_stream_maps);
4039
    ti = getutime() - ti;
4040
    if (do_benchmark) {
4041
        printf("bench: utime=%0.3fs\n", ti / 1000000.0);
4042
    }
4043

    
4044
    /* close files */
4045
    for(i=0;i<nb_output_files;i++) {
4046
        /* maybe av_close_output_file ??? */
4047
        AVFormatContext *s = output_files[i];
4048
        int j;
4049
        if (!(s->oformat->flags & AVFMT_NOFILE))
4050
            url_fclose(&s->pb);
4051
        for(j=0;j<s->nb_streams;j++)
4052
            av_free(s->streams[j]);
4053
        av_free(s);
4054
    }
4055
    for(i=0;i<nb_input_files;i++)
4056
        av_close_input_file(input_files[i]);
4057

    
4058
    av_free_static();
4059

    
4060
    if(intra_matrix)
4061
        av_free(intra_matrix);
4062
    if(inter_matrix)
4063
        av_free(inter_matrix);
4064

    
4065
#ifdef POWERPC_PERFORMANCE_REPORT
4066
    extern void powerpc_display_perf_report(void);
4067
    powerpc_display_perf_report();
4068
#endif /* POWERPC_PERFORMANCE_REPORT */
4069

    
4070
#ifndef __MINGW32__
4071
    if (received_sigterm) {
4072
        fprintf(stderr,
4073
            "Received signal %d: terminating.\n",
4074
            (int) received_sigterm);
4075
        exit (255);
4076
    }
4077
#endif
4078
    exit(0); /* not all OS-es handle main() return value */
4079
    return 0;
4080
}