Statistics
| Branch: | Revision:

ffmpeg / ffmpeg.c @ 0871ae1a

History | View | Annotate | Download (134 KB)

1
/*
2
 * FFmpeg main
3
 * Copyright (c) 2000-2003 Fabrice Bellard
4
 *
5
 * This file is part of FFmpeg.
6
 *
7
 * FFmpeg is free software; you can redistribute it and/or
8
 * modify it under the terms of the GNU Lesser General Public
9
 * License as published by the Free Software Foundation; either
10
 * version 2.1 of the License, or (at your option) any later version.
11
 *
12
 * FFmpeg is distributed in the hope that it will be useful,
13
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15
 * Lesser General Public License for more details.
16
 *
17
 * You should have received a copy of the GNU Lesser General Public
18
 * License along with FFmpeg; if not, write to the Free Software
19
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20
 */
21

    
22
#include "config.h"
23
#include <ctype.h>
24
#include <string.h>
25
#include <math.h>
26
#include <stdlib.h>
27
#include <errno.h>
28
#include <signal.h>
29
#include <limits.h>
30
#include "libavformat/avformat.h"
31
#include "libavdevice/avdevice.h"
32
#include "libswscale/swscale.h"
33
#include "libavformat/framehook.h"
34
#include "libavcodec/opt.h"
35
#include "libavutil/fifo.h"
36
#include "libavutil/avstring.h"
37
#include "libavformat/os_support.h"
38

    
39
#ifdef HAVE_SYS_RESOURCE_H
40
#include <sys/types.h>
41
#include <sys/resource.h>
42
#elif defined(HAVE_GETPROCESSTIMES)
43
#include <windows.h>
44
#endif
45

    
46
#if defined(HAVE_TERMIOS_H)
47
#include <unistd.h>
48
#include <fcntl.h>
49
#include <sys/ioctl.h>
50
#include <sys/time.h>
51
#include <termios.h>
52
#elif defined(HAVE_CONIO_H)
53
#include <conio.h>
54
#endif
55
#undef time //needed because HAVE_AV_CONFIG_H is defined on top
56
#include <time.h>
57

    
58
#include "version.h"
59
#include "cmdutils.h"
60

    
61
#undef NDEBUG
62
#include <assert.h>
63

    
64
#undef exit
65

    
66
const char program_name[] = "FFmpeg";
67
static const int program_birth_year = 2000;
68

    
69
/* select an input stream for an output stream */
70
typedef struct AVStreamMap {
71
    int file_index;
72
    int stream_index;
73
    int sync_file_index;
74
    int sync_stream_index;
75
} AVStreamMap;
76

    
77
/** select an input file for an output file */
78
typedef struct AVMetaDataMap {
79
    int out_file;
80
    int in_file;
81
} AVMetaDataMap;
82

    
83
static const OptionDef options[];
84

    
85
#define MAX_FILES 20
86

    
87
static AVFormatContext *input_files[MAX_FILES];
88
static int64_t input_files_ts_offset[MAX_FILES];
89
static int nb_input_files = 0;
90

    
91
static AVFormatContext *output_files[MAX_FILES];
92
static int nb_output_files = 0;
93

    
94
static AVStreamMap stream_maps[MAX_FILES];
95
static int nb_stream_maps;
96

    
97
static AVMetaDataMap meta_data_maps[MAX_FILES];
98
static int nb_meta_data_maps;
99

    
100
static AVInputFormat *file_iformat;
101
static AVOutputFormat *file_oformat;
102
static int frame_width  = 0;
103
static int frame_height = 0;
104
static float frame_aspect_ratio = 0;
105
static enum PixelFormat frame_pix_fmt = PIX_FMT_NONE;
106
static int frame_padtop  = 0;
107
static int frame_padbottom = 0;
108
static int frame_padleft  = 0;
109
static int frame_padright = 0;
110
static int padcolor[3] = {16,128,128}; /* default to black */
111
static int frame_topBand  = 0;
112
static int frame_bottomBand = 0;
113
static int frame_leftBand  = 0;
114
static int frame_rightBand = 0;
115
static int max_frames[4] = {INT_MAX, INT_MAX, INT_MAX, INT_MAX};
116
static AVRational frame_rate = (AVRational) {0,0};
117
static float video_qscale = 0;
118
static int video_qdiff = 3;
119
static uint16_t *intra_matrix = NULL;
120
static uint16_t *inter_matrix = NULL;
121
#if 0 //experimental, (can be removed)
122
static float video_rc_qsquish=1.0;
123
static float video_rc_qmod_amp=0;
124
static int video_rc_qmod_freq=0;
125
#endif
126
static const char *video_rc_override_string=NULL;
127
static int video_disable = 0;
128
static int video_discard = 0;
129
static char *video_codec_name = NULL;
130
static int video_codec_tag = 0;
131
static int same_quality = 0;
132
static int do_deinterlace = 0;
133
static int strict = 0;
134
static int top_field_first = -1;
135
static int me_threshold = 0;
136
static int intra_dc_precision = 8;
137
static int loop_input = 0;
138
static int loop_output = AVFMT_NOOUTPUTLOOP;
139
static int qp_hist = 0;
140

    
141
static int intra_only = 0;
142
static int audio_sample_rate = 44100;
143
#define QSCALE_NONE -99999
144
static float audio_qscale = QSCALE_NONE;
145
static int audio_disable = 0;
146
static int audio_channels = 1;
147
static char  *audio_codec_name = NULL;
148
static int audio_codec_tag = 0;
149
static char *audio_language = NULL;
150

    
151
static int subtitle_disable = 0;
152
static char *subtitle_codec_name = NULL;
153
static char *subtitle_language = NULL;
154

    
155
static float mux_preload= 0.5;
156
static float mux_max_delay= 0.7;
157

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

    
188
static int rate_emu = 0;
189

    
190
static int  video_channel = 0;
191
static char *video_standard;
192

    
193
static int audio_volume = 256;
194

    
195
static int using_stdin = 0;
196
static int using_vhook = 0;
197
static int verbose = 1;
198
static int thread_count= 1;
199
static int q_pressed = 0;
200
static int64_t video_size = 0;
201
static int64_t audio_size = 0;
202
static int64_t extra_size = 0;
203
static int nb_frames_dup = 0;
204
static int nb_frames_drop = 0;
205
static int input_sync;
206
static uint64_t limit_filesize = 0; //
207

    
208
static int pgmyuv_compatibility_hack=0;
209
static float dts_delta_threshold = 10;
210

    
211
static unsigned int sws_flags = SWS_BICUBIC;
212

    
213
static const char **opt_names;
214
static int opt_name_count;
215
static AVCodecContext *avctx_opts[CODEC_TYPE_NB];
216
static AVFormatContext *avformat_opts;
217
static struct SwsContext *sws_opts;
218
static int64_t timer_start;
219

    
220
static AVBitStreamFilterContext *video_bitstream_filters=NULL;
221
static AVBitStreamFilterContext *audio_bitstream_filters=NULL;
222
static AVBitStreamFilterContext *subtitle_bitstream_filters=NULL;
223
static AVBitStreamFilterContext *bitstream_filters[MAX_FILES][MAX_STREAMS];
224

    
225
#define DEFAULT_PASS_LOGFILENAME "ffmpeg2pass"
226

    
227
struct AVInputStream;
228

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

    
247
    int video_crop;
248
    int topBand;             /* cropping area sizes */
249
    int leftBand;
250

    
251
    int video_pad;
252
    int padtop;              /* padding area sizes */
253
    int padbottom;
254
    int padleft;
255
    int padright;
256

    
257
    /* audio only */
258
    int audio_resample;
259
    ReSampleContext *resample; /* for audio resampling */
260
    AVFifoBuffer fifo;     /* for compression: one audio fifo per codec */
261
    FILE *logfile;
262
} AVOutputStream;
263

    
264
typedef struct AVInputStream {
265
    int file_index;
266
    int index;
267
    AVStream *st;
268
    int discard;             /* true if stream data should be discarded */
269
    int decoding_needed;     /* true if the packets must be decoded in 'raw_fifo' */
270
    int64_t sample_index;      /* current sample */
271

    
272
    int64_t       start;     /* time when read started */
273
    unsigned long frame;     /* current frame */
274
    int64_t       next_pts;  /* synthetic pts for cases where pkt.pts
275
                                is not defined */
276
    int64_t       pts;       /* current pts */
277
    int is_start;            /* is 1 at the start and after a discontinuity */
278
} AVInputStream;
279

    
280
typedef struct AVInputFile {
281
    int eof_reached;      /* true if eof reached */
282
    int ist_index;        /* index of first stream in ist_table */
283
    int buffer_size;      /* current total buffer size */
284
    int nb_streams;       /* nb streams we are aware of */
285
} AVInputFile;
286

    
287
#ifdef HAVE_TERMIOS_H
288

    
289
/* init terminal so that we can grab keys */
290
static struct termios oldtty;
291
#endif
292

    
293
static void term_exit(void)
294
{
295
#ifdef HAVE_TERMIOS_H
296
    tcsetattr (0, TCSANOW, &oldtty);
297
#endif
298
}
299

    
300
static volatile sig_atomic_t received_sigterm = 0;
301

    
302
static void
303
sigterm_handler(int sig)
304
{
305
    received_sigterm = sig;
306
    term_exit();
307
}
308

    
309
static void term_init(void)
310
{
311
#ifdef HAVE_TERMIOS_H
312
    struct termios tty;
313

    
314
    tcgetattr (0, &tty);
315
    oldtty = tty;
316

    
317
    tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
318
                          |INLCR|IGNCR|ICRNL|IXON);
319
    tty.c_oflag |= OPOST;
320
    tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
321
    tty.c_cflag &= ~(CSIZE|PARENB);
322
    tty.c_cflag |= CS8;
323
    tty.c_cc[VMIN] = 1;
324
    tty.c_cc[VTIME] = 0;
325

    
326
    tcsetattr (0, TCSANOW, &tty);
327
    signal(SIGQUIT, sigterm_handler); /* Quit (POSIX).  */
328
#endif
329

    
330
    signal(SIGINT , sigterm_handler); /* Interrupt (ANSI).  */
331
    signal(SIGTERM, sigterm_handler); /* Termination (ANSI).  */
332
    /*
333
    register a function to be called at normal program termination
334
    */
335
    atexit(term_exit);
336
#ifdef CONFIG_BEOS_NETSERVER
337
    fcntl(0, F_SETFL, fcntl(0, F_GETFL) | O_NONBLOCK);
338
#endif
339
}
340

    
341
/* read a key without blocking */
342
static int read_key(void)
343
{
344
#if defined(HAVE_TERMIOS_H)
345
    int n = 1;
346
    unsigned char ch;
347
#ifndef CONFIG_BEOS_NETSERVER
348
    struct timeval tv;
349
    fd_set rfds;
350

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

    
362
        return n;
363
    }
364
#elif defined(HAVE_CONIO_H)
365
    if(kbhit())
366
        return(getch());
367
#endif
368
    return -1;
369
}
370

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

    
376
static int av_exit(int ret)
377
{
378
    int i;
379

    
380
    /* close files */
381
    for(i=0;i<nb_output_files;i++) {
382
        /* maybe av_close_output_file ??? */
383
        AVFormatContext *s = output_files[i];
384
        int j;
385
        if (!(s->oformat->flags & AVFMT_NOFILE) && s->pb)
386
            url_fclose(s->pb);
387
        for(j=0;j<s->nb_streams;j++) {
388
            av_free(s->streams[j]->codec);
389
            av_free(s->streams[j]);
390
        }
391
        av_free(s);
392
    }
393
    for(i=0;i<nb_input_files;i++)
394
        av_close_input_file(input_files[i]);
395

    
396
    av_free_static();
397

    
398
    av_free(intra_matrix);
399
    av_free(inter_matrix);
400

    
401
    if (vstats_file)
402
        fclose(vstats_file);
403
    av_free(vstats_filename);
404

    
405
    av_free(opt_names);
406

    
407
    av_free(video_codec_name);
408
    av_free(audio_codec_name);
409
    av_free(subtitle_codec_name);
410

    
411
    av_free(video_standard);
412

    
413
#ifdef CONFIG_POWERPC_PERF
414
    extern void powerpc_display_perf_report(void);
415
    powerpc_display_perf_report();
416
#endif /* CONFIG_POWERPC_PERF */
417

    
418
    if (received_sigterm) {
419
        fprintf(stderr,
420
            "Received signal %d: terminating.\n",
421
            (int) received_sigterm);
422
        exit (255);
423
    }
424

    
425
    exit(ret); /* not all OS-es handle main() return value */
426
    return ret;
427
}
428

    
429
static int read_ffserver_streams(AVFormatContext *s, const char *filename)
430
{
431
    int i, err;
432
    AVFormatContext *ic;
433

    
434
    err = av_open_input_file(&ic, filename, NULL, FFM_PACKET_SIZE, NULL);
435
    if (err < 0)
436
        return err;
437
    /* copy stream format */
438
    s->nb_streams = ic->nb_streams;
439
    for(i=0;i<ic->nb_streams;i++) {
440
        AVStream *st;
441

    
442
        // FIXME: a more elegant solution is needed
443
        st = av_mallocz(sizeof(AVStream));
444
        memcpy(st, ic->streams[i], sizeof(AVStream));
445
        st->codec = avcodec_alloc_context();
446
        memcpy(st->codec, ic->streams[i]->codec, sizeof(AVCodecContext));
447
        s->streams[i] = st;
448
    }
449

    
450
    av_close_input_file(ic);
451
    return 0;
452
}
453

    
454
static double
455
get_sync_ipts(const AVOutputStream *ost)
456
{
457
    const AVInputStream *ist = ost->sync_ist;
458
    return (double)(ist->pts - start_time)/AV_TIME_BASE;
459
}
460

    
461
static void write_frame(AVFormatContext *s, AVPacket *pkt, AVCodecContext *avctx, AVBitStreamFilterContext *bsfc){
462
    int ret;
463

    
464
    while(bsfc){
465
        AVPacket new_pkt= *pkt;
466
        int a= av_bitstream_filter_filter(bsfc, avctx, NULL,
467
                                          &new_pkt.data, &new_pkt.size,
468
                                          pkt->data, pkt->size,
469
                                          pkt->flags & PKT_FLAG_KEY);
470
        if(a>0){
471
            av_free_packet(pkt);
472
            new_pkt.destruct= av_destruct_packet;
473
        } else if(a<0){
474
            fprintf(stderr, "%s failed for stream %d, codec %s",
475
                    bsfc->filter->name, pkt->stream_index,
476
                    avctx->codec ? avctx->codec->name : "copy");
477
            print_error("", a);
478
        }
479
        *pkt= new_pkt;
480

    
481
        bsfc= bsfc->next;
482
    }
483

    
484
    ret= av_interleaved_write_frame(s, pkt);
485
    if(ret < 0){
486
        print_error("av_interleaved_write_frame()", ret);
487
        av_exit(1);
488
    }
489
}
490

    
491
#define MAX_AUDIO_PACKET_SIZE (128 * 1024)
492

    
493
static void do_audio_out(AVFormatContext *s,
494
                         AVOutputStream *ost,
495
                         AVInputStream *ist,
496
                         unsigned char *buf, int size)
497
{
498
    uint8_t *buftmp;
499
    static uint8_t *audio_buf = NULL;
500
    static uint8_t *audio_out = NULL;
501
    const int audio_out_size= 4*MAX_AUDIO_PACKET_SIZE;
502

    
503
    int size_out, frame_bytes, ret;
504
    AVCodecContext *enc= ost->st->codec;
505
    AVCodecContext *dec= ist->st->codec;
506

    
507
    /* SC: dynamic allocation of buffers */
508
    if (!audio_buf)
509
        audio_buf = av_malloc(2*MAX_AUDIO_PACKET_SIZE);
510
    if (!audio_out)
511
        audio_out = av_malloc(audio_out_size);
512
    if (!audio_buf || !audio_out)
513
        return;               /* Should signal an error ! */
514

    
515
    if (enc->channels != dec->channels)
516
        ost->audio_resample = 1;
517

    
518
    if (ost->audio_resample && !ost->resample) {
519
        ost->resample = audio_resample_init(enc->channels,    dec->channels,
520
                                            enc->sample_rate, dec->sample_rate);
521
        if (!ost->resample) {
522
            fprintf(stderr, "Can not resample %d channels @ %d Hz to %d channels @ %d Hz\n",
523
                    dec->channels, dec->sample_rate,
524
                    enc->channels, enc->sample_rate);
525
            av_exit(1);
526
        }
527
    }
528

    
529
    if(audio_sync_method){
530
        double delta = get_sync_ipts(ost) * enc->sample_rate - ost->sync_opts
531
                - av_fifo_size(&ost->fifo)/(ost->st->codec->channels * 2);
532
        double idelta= delta*ist->st->codec->sample_rate / enc->sample_rate;
533
        int byte_delta= ((int)idelta)*2*ist->st->codec->channels;
534

    
535
        //FIXME resample delay
536
        if(fabs(delta) > 50){
537
            if(ist->is_start || fabs(delta) > audio_drift_threshold*enc->sample_rate){
538
                if(byte_delta < 0){
539
                    byte_delta= FFMAX(byte_delta, -size);
540
                    size += byte_delta;
541
                    buf  -= byte_delta;
542
                    if(verbose > 2)
543
                        fprintf(stderr, "discarding %d audio samples\n", (int)-delta);
544
                    if(!size)
545
                        return;
546
                    ist->is_start=0;
547
                }else{
548
                    static uint8_t *input_tmp= NULL;
549
                    input_tmp= av_realloc(input_tmp, byte_delta + size);
550

    
551
                    if(byte_delta + size <= MAX_AUDIO_PACKET_SIZE)
552
                        ist->is_start=0;
553
                    else
554
                        byte_delta= MAX_AUDIO_PACKET_SIZE - size;
555

    
556
                    memset(input_tmp, 0, byte_delta);
557
                    memcpy(input_tmp + byte_delta, buf, size);
558
                    buf= input_tmp;
559
                    size += byte_delta;
560
                    if(verbose > 2)
561
                        fprintf(stderr, "adding %d audio samples of silence\n", (int)delta);
562
                }
563
            }else if(audio_sync_method>1){
564
                int comp= av_clip(delta, -audio_sync_method, audio_sync_method);
565
                assert(ost->audio_resample);
566
                if(verbose > 2)
567
                    fprintf(stderr, "compensating audio timestamp drift:%f compensation:%d in:%d\n", delta, comp, enc->sample_rate);
568
//                fprintf(stderr, "drift:%f len:%d opts:%"PRId64" ipts:%"PRId64" 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));
569
                av_resample_compensate(*(struct AVResampleContext**)ost->resample, comp, enc->sample_rate);
570
            }
571
        }
572
    }else
573
        ost->sync_opts= lrintf(get_sync_ipts(ost) * enc->sample_rate)
574
                        - av_fifo_size(&ost->fifo)/(ost->st->codec->channels * 2); //FIXME wrong
575

    
576
    if (ost->audio_resample) {
577
        buftmp = audio_buf;
578
        size_out = audio_resample(ost->resample,
579
                                  (short *)buftmp, (short *)buf,
580
                                  size / (ist->st->codec->channels * 2));
581
        size_out = size_out * enc->channels * 2;
582
    } else {
583
        buftmp = buf;
584
        size_out = size;
585
    }
586

    
587
    /* now encode as many frames as possible */
588
    if (enc->frame_size > 1) {
589
        /* output resampled raw samples */
590
        av_fifo_realloc(&ost->fifo, av_fifo_size(&ost->fifo) + size_out + 1);
591
        av_fifo_write(&ost->fifo, buftmp, size_out);
592

    
593
        frame_bytes = enc->frame_size * 2 * enc->channels;
594

    
595
        while (av_fifo_size(&ost->fifo) >= frame_bytes) {
596
            AVPacket pkt;
597
            av_init_packet(&pkt);
598

    
599
            av_fifo_read(&ost->fifo, audio_buf, frame_bytes);
600

    
601
            //FIXME pass ost->sync_opts as AVFrame.pts in avcodec_encode_audio()
602

    
603
            ret = avcodec_encode_audio(enc, audio_out, audio_out_size,
604
                                       (short *)audio_buf);
605
            audio_size += ret;
606
            pkt.stream_index= ost->index;
607
            pkt.data= audio_out;
608
            pkt.size= ret;
609
            if(enc->coded_frame && enc->coded_frame->pts != AV_NOPTS_VALUE)
610
                pkt.pts= av_rescale_q(enc->coded_frame->pts, enc->time_base, ost->st->time_base);
611
            pkt.flags |= PKT_FLAG_KEY;
612
            write_frame(s, &pkt, ost->st->codec, bitstream_filters[ost->file_index][pkt.stream_index]);
613

    
614
            ost->sync_opts += enc->frame_size;
615
        }
616
    } else {
617
        AVPacket pkt;
618
        av_init_packet(&pkt);
619

    
620
        ost->sync_opts += size_out / (2 * enc->channels);
621

    
622
        /* output a pcm frame */
623
        /* XXX: change encoding codec API to avoid this ? */
624
        switch(enc->codec->id) {
625
        case CODEC_ID_PCM_S32LE:
626
        case CODEC_ID_PCM_S32BE:
627
        case CODEC_ID_PCM_U32LE:
628
        case CODEC_ID_PCM_U32BE:
629
            size_out = size_out << 1;
630
            break;
631
        case CODEC_ID_PCM_S24LE:
632
        case CODEC_ID_PCM_S24BE:
633
        case CODEC_ID_PCM_U24LE:
634
        case CODEC_ID_PCM_U24BE:
635
        case CODEC_ID_PCM_S24DAUD:
636
            size_out = size_out / 2 * 3;
637
            break;
638
        case CODEC_ID_PCM_S16LE:
639
        case CODEC_ID_PCM_S16BE:
640
        case CODEC_ID_PCM_U16LE:
641
        case CODEC_ID_PCM_U16BE:
642
            break;
643
        default:
644
            size_out = size_out >> 1;
645
            break;
646
        }
647
        //FIXME pass ost->sync_opts as AVFrame.pts in avcodec_encode_audio()
648
        ret = avcodec_encode_audio(enc, audio_out, size_out,
649
                                   (short *)buftmp);
650
        audio_size += ret;
651
        pkt.stream_index= ost->index;
652
        pkt.data= audio_out;
653
        pkt.size= ret;
654
        if(enc->coded_frame && enc->coded_frame->pts != AV_NOPTS_VALUE)
655
            pkt.pts= av_rescale_q(enc->coded_frame->pts, enc->time_base, ost->st->time_base);
656
        pkt.flags |= PKT_FLAG_KEY;
657
        write_frame(s, &pkt, ost->st->codec, bitstream_filters[ost->file_index][pkt.stream_index]);
658
    }
659
}
660

    
661
static void pre_process_video_frame(AVInputStream *ist, AVPicture *picture, void **bufp)
662
{
663
    AVCodecContext *dec;
664
    AVPicture *picture2;
665
    AVPicture picture_tmp;
666
    uint8_t *buf = 0;
667

    
668
    dec = ist->st->codec;
669

    
670
    /* deinterlace : must be done before any resize */
671
    if (do_deinterlace || using_vhook) {
672
        int size;
673

    
674
        /* create temporary picture */
675
        size = avpicture_get_size(dec->pix_fmt, dec->width, dec->height);
676
        buf = av_malloc(size);
677
        if (!buf)
678
            return;
679

    
680
        picture2 = &picture_tmp;
681
        avpicture_fill(picture2, buf, dec->pix_fmt, dec->width, dec->height);
682

    
683
        if (do_deinterlace){
684
            if(avpicture_deinterlace(picture2, picture,
685
                                     dec->pix_fmt, dec->width, dec->height) < 0) {
686
                /* if error, do not deinterlace */
687
                av_free(buf);
688
                buf = NULL;
689
                picture2 = picture;
690
            }
691
        } else {
692
            av_picture_copy(picture2, picture, dec->pix_fmt, dec->width, dec->height);
693
        }
694
    } else {
695
        picture2 = picture;
696
    }
697

    
698
    if (ENABLE_VHOOK)
699
        frame_hook_process(picture2, dec->pix_fmt, dec->width, dec->height,
700
                           1000000 * ist->pts / AV_TIME_BASE);
701

    
702
    if (picture != picture2)
703
        *picture = *picture2;
704
    *bufp = buf;
705
}
706

    
707
/* we begin to correct av delay at this threshold */
708
#define AV_DELAY_MAX 0.100
709

    
710
static void do_subtitle_out(AVFormatContext *s,
711
                            AVOutputStream *ost,
712
                            AVInputStream *ist,
713
                            AVSubtitle *sub,
714
                            int64_t pts)
715
{
716
    static uint8_t *subtitle_out = NULL;
717
    int subtitle_out_max_size = 65536;
718
    int subtitle_out_size, nb, i;
719
    AVCodecContext *enc;
720
    AVPacket pkt;
721

    
722
    if (pts == AV_NOPTS_VALUE) {
723
        fprintf(stderr, "Subtitle packets must have a pts\n");
724
        return;
725
    }
726

    
727
    enc = ost->st->codec;
728

    
729
    if (!subtitle_out) {
730
        subtitle_out = av_malloc(subtitle_out_max_size);
731
    }
732

    
733
    /* Note: DVB subtitle need one packet to draw them and one other
734
       packet to clear them */
735
    /* XXX: signal it in the codec context ? */
736
    if (enc->codec_id == CODEC_ID_DVB_SUBTITLE)
737
        nb = 2;
738
    else
739
        nb = 1;
740

    
741
    for(i = 0; i < nb; i++) {
742
        subtitle_out_size = avcodec_encode_subtitle(enc, subtitle_out,
743
                                                    subtitle_out_max_size, sub);
744

    
745
        av_init_packet(&pkt);
746
        pkt.stream_index = ost->index;
747
        pkt.data = subtitle_out;
748
        pkt.size = subtitle_out_size;
749
        pkt.pts = av_rescale_q(pts, ist->st->time_base, ost->st->time_base);
750
        if (enc->codec_id == CODEC_ID_DVB_SUBTITLE) {
751
            /* XXX: the pts correction is handled here. Maybe handling
752
               it in the codec would be better */
753
            if (i == 0)
754
                pkt.pts += 90 * sub->start_display_time;
755
            else
756
                pkt.pts += 90 * sub->end_display_time;
757
        }
758
        write_frame(s, &pkt, ost->st->codec, bitstream_filters[ost->file_index][pkt.stream_index]);
759
    }
760
}
761

    
762
static int bit_buffer_size= 1024*256;
763
static uint8_t *bit_buffer= NULL;
764

    
765
static void do_video_out(AVFormatContext *s,
766
                         AVOutputStream *ost,
767
                         AVInputStream *ist,
768
                         AVFrame *in_picture,
769
                         int *frame_size)
770
{
771
    int nb_frames, i, ret;
772
    AVFrame *final_picture, *formatted_picture, *resampling_dst, *padding_src;
773
    AVFrame picture_crop_temp, picture_pad_temp;
774
    AVCodecContext *enc, *dec;
775

    
776
    avcodec_get_frame_defaults(&picture_crop_temp);
777
    avcodec_get_frame_defaults(&picture_pad_temp);
778

    
779
    enc = ost->st->codec;
780
    dec = ist->st->codec;
781

    
782
    /* by default, we output a single frame */
783
    nb_frames = 1;
784

    
785
    *frame_size = 0;
786

    
787
    if(video_sync_method){
788
        double vdelta;
789
        vdelta = get_sync_ipts(ost) / av_q2d(enc->time_base) - ost->sync_opts;
790
        //FIXME set to 0.5 after we fix some dts/pts bugs like in avidec.c
791
        if (vdelta < -1.1)
792
            nb_frames = 0;
793
        else if (video_sync_method == 2)
794
            ost->sync_opts= lrintf(get_sync_ipts(ost) / av_q2d(enc->time_base));
795
        else if (vdelta > 1.1)
796
            nb_frames = lrintf(vdelta);
797
//fprintf(stderr, "vdelta:%f, ost->sync_opts:%"PRId64", ost->sync_ipts:%f nb_frames:%d\n", vdelta, ost->sync_opts, ost->sync_ipts, nb_frames);
798
        if (nb_frames == 0){
799
            ++nb_frames_drop;
800
            if (verbose>2)
801
                fprintf(stderr, "*** drop!\n");
802
        }else if (nb_frames > 1) {
803
            nb_frames_dup += nb_frames;
804
            if (verbose>2)
805
                fprintf(stderr, "*** %d dup!\n", nb_frames-1);
806
        }
807
    }else
808
        ost->sync_opts= lrintf(get_sync_ipts(ost) / av_q2d(enc->time_base));
809

    
810
    nb_frames= FFMIN(nb_frames, max_frames[CODEC_TYPE_VIDEO] - ost->frame_number);
811
    if (nb_frames <= 0)
812
        return;
813

    
814
    if (ost->video_crop) {
815
        if (av_picture_crop((AVPicture *)&picture_crop_temp, (AVPicture *)in_picture, dec->pix_fmt, ost->topBand, ost->leftBand) < 0) {
816
            av_log(NULL, AV_LOG_ERROR, "error cropping picture\n");
817
            return;
818
        }
819
        formatted_picture = &picture_crop_temp;
820
    } else {
821
        formatted_picture = in_picture;
822
    }
823

    
824
    final_picture = formatted_picture;
825
    padding_src = formatted_picture;
826
    resampling_dst = &ost->pict_tmp;
827
    if (ost->video_pad) {
828
        final_picture = &ost->pict_tmp;
829
        if (ost->video_resample) {
830
            if (av_picture_crop((AVPicture *)&picture_pad_temp, (AVPicture *)final_picture, enc->pix_fmt, ost->padtop, ost->padleft) < 0) {
831
                av_log(NULL, AV_LOG_ERROR, "error padding picture\n");
832
                return;
833
            }
834
            resampling_dst = &picture_pad_temp;
835
        }
836
    }
837

    
838
    if (ost->video_resample) {
839
        padding_src = NULL;
840
        final_picture = &ost->pict_tmp;
841
        sws_scale(ost->img_resample_ctx, formatted_picture->data, formatted_picture->linesize,
842
              0, ost->resample_height, resampling_dst->data, resampling_dst->linesize);
843
    }
844

    
845
    if (ost->video_pad) {
846
        av_picture_pad((AVPicture*)final_picture, (AVPicture *)padding_src,
847
                enc->height, enc->width, enc->pix_fmt,
848
                ost->padtop, ost->padbottom, ost->padleft, ost->padright, padcolor);
849
    }
850

    
851
    /* duplicates frame if needed */
852
    for(i=0;i<nb_frames;i++) {
853
        AVPacket pkt;
854
        av_init_packet(&pkt);
855
        pkt.stream_index= ost->index;
856

    
857
        if (s->oformat->flags & AVFMT_RAWPICTURE) {
858
            /* raw pictures are written as AVPicture structure to
859
               avoid any copies. We support temorarily the older
860
               method. */
861
            AVFrame* old_frame = enc->coded_frame;
862
            enc->coded_frame = dec->coded_frame; //FIXME/XXX remove this hack
863
            pkt.data= (uint8_t *)final_picture;
864
            pkt.size=  sizeof(AVPicture);
865
            pkt.pts= av_rescale_q(ost->sync_opts, enc->time_base, ost->st->time_base);
866
            pkt.flags |= PKT_FLAG_KEY;
867

    
868
            write_frame(s, &pkt, ost->st->codec, bitstream_filters[ost->file_index][pkt.stream_index]);
869
            enc->coded_frame = old_frame;
870
        } else {
871
            AVFrame big_picture;
872

    
873
            big_picture= *final_picture;
874
            /* better than nothing: use input picture interlaced
875
               settings */
876
            big_picture.interlaced_frame = in_picture->interlaced_frame;
877
            if(avctx_opts[CODEC_TYPE_VIDEO]->flags & (CODEC_FLAG_INTERLACED_DCT|CODEC_FLAG_INTERLACED_ME)){
878
                if(top_field_first == -1)
879
                    big_picture.top_field_first = in_picture->top_field_first;
880
                else
881
                    big_picture.top_field_first = top_field_first;
882
            }
883

    
884
            /* handles sameq here. This is not correct because it may
885
               not be a global option */
886
            if (same_quality) {
887
                big_picture.quality = ist->st->quality;
888
            }else
889
                big_picture.quality = ost->st->quality;
890
            if(!me_threshold)
891
                big_picture.pict_type = 0;
892
//            big_picture.pts = AV_NOPTS_VALUE;
893
            big_picture.pts= ost->sync_opts;
894
//            big_picture.pts= av_rescale(ost->sync_opts, AV_TIME_BASE*(int64_t)enc->time_base.num, enc->time_base.den);
895
//av_log(NULL, AV_LOG_DEBUG, "%"PRId64" -> encoder\n", ost->sync_opts);
896
            ret = avcodec_encode_video(enc,
897
                                       bit_buffer, bit_buffer_size,
898
                                       &big_picture);
899
            if (ret == -1) {
900
                fprintf(stderr, "Video encoding failed\n");
901
                av_exit(1);
902
            }
903
            //enc->frame_number = enc->real_pict_num;
904
            if(ret>0){
905
                pkt.data= bit_buffer;
906
                pkt.size= ret;
907
                if(enc->coded_frame && enc->coded_frame->pts != AV_NOPTS_VALUE)
908
                    pkt.pts= av_rescale_q(enc->coded_frame->pts, enc->time_base, ost->st->time_base);
909
/*av_log(NULL, AV_LOG_DEBUG, "encoder -> %"PRId64"/%"PRId64"\n",
910
   pkt.pts != AV_NOPTS_VALUE ? av_rescale(pkt.pts, enc->time_base.den, AV_TIME_BASE*(int64_t)enc->time_base.num) : -1,
911
   pkt.dts != AV_NOPTS_VALUE ? av_rescale(pkt.dts, enc->time_base.den, AV_TIME_BASE*(int64_t)enc->time_base.num) : -1);*/
912

    
913
                if(enc->coded_frame && enc->coded_frame->key_frame)
914
                    pkt.flags |= PKT_FLAG_KEY;
915
                write_frame(s, &pkt, ost->st->codec, bitstream_filters[ost->file_index][pkt.stream_index]);
916
                *frame_size = ret;
917
                //fprintf(stderr,"\nFrame: %3d %3d size: %5d type: %d",
918
                //        enc->frame_number-1, enc->real_pict_num, ret,
919
                //        enc->pict_type);
920
                /* if two pass, output log */
921
                if (ost->logfile && enc->stats_out) {
922
                    fprintf(ost->logfile, "%s", enc->stats_out);
923
                }
924
            }
925
        }
926
        ost->sync_opts++;
927
        ost->frame_number++;
928
    }
929
}
930

    
931
static double psnr(double d){
932
    return -10.0*log(d)/log(10.0);
933
}
934

    
935
static void do_video_stats(AVFormatContext *os, AVOutputStream *ost,
936
                           int frame_size)
937
{
938
    AVCodecContext *enc;
939
    int frame_number;
940
    double ti1, bitrate, avg_bitrate;
941

    
942
    /* this is executed just the first time do_video_stats is called */
943
    if (!vstats_file) {
944
        vstats_file = fopen(vstats_filename, "w");
945
        if (!vstats_file) {
946
            perror("fopen");
947
            av_exit(1);
948
        }
949
    }
950

    
951
    enc = ost->st->codec;
952
    if (enc->codec_type == CODEC_TYPE_VIDEO) {
953
        frame_number = ost->frame_number;
954
        fprintf(vstats_file, "frame= %5d q= %2.1f ", frame_number, enc->coded_frame->quality/(float)FF_QP2LAMBDA);
955
        if (enc->flags&CODEC_FLAG_PSNR)
956
            fprintf(vstats_file, "PSNR= %6.2f ", psnr(enc->coded_frame->error[0]/(enc->width*enc->height*255.0*255.0)));
957

    
958
        fprintf(vstats_file,"f_size= %6d ", frame_size);
959
        /* compute pts value */
960
        ti1 = ost->sync_opts * av_q2d(enc->time_base);
961
        if (ti1 < 0.01)
962
            ti1 = 0.01;
963

    
964
        bitrate = (frame_size * 8) / av_q2d(enc->time_base) / 1000.0;
965
        avg_bitrate = (double)(video_size * 8) / ti1 / 1000.0;
966
        fprintf(vstats_file, "s_size= %8.0fkB time= %0.3f br= %7.1fkbits/s avg_br= %7.1fkbits/s ",
967
            (double)video_size / 1024, ti1, bitrate, avg_bitrate);
968
        fprintf(vstats_file,"type= %c\n", av_get_pict_type_char(enc->coded_frame->pict_type));
969
    }
970
}
971

    
972
static void print_report(AVFormatContext **output_files,
973
                         AVOutputStream **ost_table, int nb_ostreams,
974
                         int is_last_report)
975
{
976
    char buf[1024];
977
    AVOutputStream *ost;
978
    AVFormatContext *oc, *os;
979
    int64_t total_size;
980
    AVCodecContext *enc;
981
    int frame_number, vid, i;
982
    double bitrate, ti1, pts;
983
    static int64_t last_time = -1;
984
    static int qp_histogram[52];
985

    
986
    if (!is_last_report) {
987
        int64_t cur_time;
988
        /* display the report every 0.5 seconds */
989
        cur_time = av_gettime();
990
        if (last_time == -1) {
991
            last_time = cur_time;
992
            return;
993
        }
994
        if ((cur_time - last_time) < 500000)
995
            return;
996
        last_time = cur_time;
997
    }
998

    
999

    
1000
    oc = output_files[0];
1001

    
1002
    total_size = url_fsize(oc->pb);
1003
    if(total_size<0) // FIXME improve url_fsize() so it works with non seekable output too
1004
        total_size= url_ftell(oc->pb);
1005

    
1006
    buf[0] = '\0';
1007
    ti1 = 1e10;
1008
    vid = 0;
1009
    for(i=0;i<nb_ostreams;i++) {
1010
        ost = ost_table[i];
1011
        os = output_files[ost->file_index];
1012
        enc = ost->st->codec;
1013
        if (vid && enc->codec_type == CODEC_TYPE_VIDEO) {
1014
            snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "q=%2.1f ",
1015
                     enc->coded_frame && !ost->st->stream_copy ?
1016
                     enc->coded_frame->quality/(float)FF_QP2LAMBDA : -1);
1017
        }
1018
        if (!vid && enc->codec_type == CODEC_TYPE_VIDEO) {
1019
            float t = (av_gettime()-timer_start) / 1000000.0;
1020

    
1021
            frame_number = ost->frame_number;
1022
            snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "frame=%5d fps=%3d q=%3.1f ",
1023
                     frame_number, (t>1)?(int)(frame_number/t+0.5) : 0,
1024
                     enc->coded_frame && !ost->st->stream_copy ?
1025
                     enc->coded_frame->quality/(float)FF_QP2LAMBDA : -1);
1026
            if(is_last_report)
1027
                snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "L");
1028
            if(qp_hist && enc->coded_frame){
1029
                int j;
1030
                int qp= lrintf(enc->coded_frame->quality/(float)FF_QP2LAMBDA);
1031
                if(qp>=0 && qp<sizeof(qp_histogram)/sizeof(int))
1032
                    qp_histogram[qp]++;
1033
                for(j=0; j<32; j++)
1034
                    snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "%X", (int)lrintf(log(qp_histogram[j]+1)/log(2)));
1035
            }
1036
            if (enc->flags&CODEC_FLAG_PSNR){
1037
                int j;
1038
                double error, error_sum=0;
1039
                double scale, scale_sum=0;
1040
                char type[3]= {'Y','U','V'};
1041
                snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "PSNR=");
1042
                for(j=0; j<3; j++){
1043
                    if(is_last_report){
1044
                        error= enc->error[j];
1045
                        scale= enc->width*enc->height*255.0*255.0*frame_number;
1046
                    }else{
1047
                        error= enc->coded_frame->error[j];
1048
                        scale= enc->width*enc->height*255.0*255.0;
1049
                    }
1050
                    if(j) scale/=4;
1051
                    error_sum += error;
1052
                    scale_sum += scale;
1053
                    snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "%c:%2.2f ", type[j], psnr(error/scale));
1054
                }
1055
                snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "*:%2.2f ", psnr(error_sum/scale_sum));
1056
            }
1057
            vid = 1;
1058
        }
1059
        /* compute min output value */
1060
        pts = (double)ost->st->pts.val * av_q2d(ost->st->time_base);
1061
        if ((pts < ti1) && (pts > 0))
1062
            ti1 = pts;
1063
    }
1064
    if (ti1 < 0.01)
1065
        ti1 = 0.01;
1066

    
1067
    if (verbose || is_last_report) {
1068
        bitrate = (double)(total_size * 8) / ti1 / 1000.0;
1069

    
1070
        snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
1071
            "size=%8.0fkB time=%0.2f bitrate=%6.1fkbits/s",
1072
            (double)total_size / 1024, ti1, bitrate);
1073

    
1074
        if (verbose > 1)
1075
          snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), " dup=%d drop=%d",
1076
                  nb_frames_dup, nb_frames_drop);
1077

    
1078
        if (verbose >= 0)
1079
            fprintf(stderr, "%s    \r", buf);
1080

    
1081
        fflush(stderr);
1082
    }
1083

    
1084
    if (is_last_report && verbose >= 0){
1085
        int64_t raw= audio_size + video_size + extra_size;
1086
        fprintf(stderr, "\n");
1087
        fprintf(stderr, "video:%1.0fkB audio:%1.0fkB global headers:%1.0fkB muxing overhead %f%%\n",
1088
                video_size/1024.0,
1089
                audio_size/1024.0,
1090
                extra_size/1024.0,
1091
                100.0*(total_size - raw)/raw
1092
        );
1093
    }
1094
}
1095

    
1096
/* pkt = NULL means EOF (needed to flush decoder buffers) */
1097
static int output_packet(AVInputStream *ist, int ist_index,
1098
                         AVOutputStream **ost_table, int nb_ostreams,
1099
                         const AVPacket *pkt)
1100
{
1101
    AVFormatContext *os;
1102
    AVOutputStream *ost;
1103
    uint8_t *ptr;
1104
    int len, ret, i;
1105
    uint8_t *data_buf;
1106
    int data_size, got_picture;
1107
    AVFrame picture;
1108
    void *buffer_to_free;
1109
    static unsigned int samples_size= 0;
1110
    static short *samples= NULL;
1111
    AVSubtitle subtitle, *subtitle_to_free;
1112
    int got_subtitle;
1113

    
1114
    if(ist->next_pts == AV_NOPTS_VALUE)
1115
        ist->next_pts= ist->pts;
1116

    
1117
    if (pkt == NULL) {
1118
        /* EOF handling */
1119
        ptr = NULL;
1120
        len = 0;
1121
        goto handle_eof;
1122
    }
1123

    
1124
    if(pkt->dts != AV_NOPTS_VALUE)
1125
        ist->next_pts = ist->pts = av_rescale_q(pkt->dts, ist->st->time_base, AV_TIME_BASE_Q);
1126

    
1127
    len = pkt->size;
1128
    ptr = pkt->data;
1129
    while (len > 0) {
1130
    handle_eof:
1131
        ist->pts= ist->next_pts;
1132

    
1133
        if(len && len != pkt->size && verbose>0)
1134
            fprintf(stderr, "Multiple frames in a packet from stream %d\n", pkt->stream_index);
1135

    
1136
        /* decode the packet if needed */
1137
        data_buf = NULL; /* fail safe */
1138
        data_size = 0;
1139
        subtitle_to_free = NULL;
1140
        if (ist->decoding_needed) {
1141
            switch(ist->st->codec->codec_type) {
1142
            case CODEC_TYPE_AUDIO:{
1143
                if(pkt)
1144
                    samples= av_fast_realloc(samples, &samples_size, FFMAX(pkt->size*sizeof(*samples), AVCODEC_MAX_AUDIO_FRAME_SIZE));
1145
                data_size= samples_size;
1146
                    /* XXX: could avoid copy if PCM 16 bits with same
1147
                       endianness as CPU */
1148
                ret = avcodec_decode_audio2(ist->st->codec, samples, &data_size,
1149
                                           ptr, len);
1150
                if (ret < 0)
1151
                    goto fail_decode;
1152
                ptr += ret;
1153
                len -= ret;
1154
                /* Some bug in mpeg audio decoder gives */
1155
                /* data_size < 0, it seems they are overflows */
1156
                if (data_size <= 0) {
1157
                    /* no audio frame */
1158
                    continue;
1159
                }
1160
                data_buf = (uint8_t *)samples;
1161
                ist->next_pts += ((int64_t)AV_TIME_BASE/2 * data_size) /
1162
                    (ist->st->codec->sample_rate * ist->st->codec->channels);
1163
                break;}
1164
            case CODEC_TYPE_VIDEO:
1165
                    data_size = (ist->st->codec->width * ist->st->codec->height * 3) / 2;
1166
                    /* XXX: allocate picture correctly */
1167
                    avcodec_get_frame_defaults(&picture);
1168

    
1169
                    ret = avcodec_decode_video(ist->st->codec,
1170
                                               &picture, &got_picture, ptr, len);
1171
                    ist->st->quality= picture.quality;
1172
                    if (ret < 0)
1173
                        goto fail_decode;
1174
                    if (!got_picture) {
1175
                        /* no picture yet */
1176
                        goto discard_packet;
1177
                    }
1178
                    if (ist->st->codec->time_base.num != 0) {
1179
                        ist->next_pts += ((int64_t)AV_TIME_BASE *
1180
                                          ist->st->codec->time_base.num) /
1181
                            ist->st->codec->time_base.den;
1182
                    }
1183
                    len = 0;
1184
                    break;
1185
            case CODEC_TYPE_SUBTITLE:
1186
                ret = avcodec_decode_subtitle(ist->st->codec,
1187
                                              &subtitle, &got_subtitle, ptr, len);
1188
                if (ret < 0)
1189
                    goto fail_decode;
1190
                if (!got_subtitle) {
1191
                    goto discard_packet;
1192
                }
1193
                subtitle_to_free = &subtitle;
1194
                len = 0;
1195
                break;
1196
            default:
1197
                goto fail_decode;
1198
            }
1199
        } else {
1200
            switch(ist->st->codec->codec_type) {
1201
            case CODEC_TYPE_AUDIO:
1202
                ist->next_pts += ((int64_t)AV_TIME_BASE * ist->st->codec->frame_size) /
1203
                    ist->st->codec->sample_rate;
1204
                break;
1205
            case CODEC_TYPE_VIDEO:
1206
                if (ist->st->codec->time_base.num != 0) {
1207
                    ist->next_pts += ((int64_t)AV_TIME_BASE *
1208
                                      ist->st->codec->time_base.num) /
1209
                        ist->st->codec->time_base.den;
1210
                }
1211
                break;
1212
            }
1213
            data_buf = ptr;
1214
            data_size = len;
1215
            ret = len;
1216
            len = 0;
1217
        }
1218

    
1219
        buffer_to_free = NULL;
1220
        if (ist->st->codec->codec_type == CODEC_TYPE_VIDEO) {
1221
            pre_process_video_frame(ist, (AVPicture *)&picture,
1222
                                    &buffer_to_free);
1223
        }
1224

    
1225
        // preprocess audio (volume)
1226
        if (ist->st->codec->codec_type == CODEC_TYPE_AUDIO) {
1227
            if (audio_volume != 256) {
1228
                short *volp;
1229
                volp = samples;
1230
                for(i=0;i<(data_size / sizeof(short));i++) {
1231
                    int v = ((*volp) * audio_volume + 128) >> 8;
1232
                    if (v < -32768) v = -32768;
1233
                    if (v >  32767) v = 32767;
1234
                    *volp++ = v;
1235
                }
1236
            }
1237
        }
1238

    
1239
        /* frame rate emulation */
1240
        if (ist->st->codec->rate_emu) {
1241
            int64_t pts = av_rescale((int64_t) ist->frame * ist->st->codec->time_base.num, 1000000, ist->st->codec->time_base.den);
1242
            int64_t now = av_gettime() - ist->start;
1243
            if (pts > now)
1244
                usleep(pts - now);
1245

    
1246
            ist->frame++;
1247
        }
1248

    
1249
#if 0
1250
        /* mpeg PTS deordering : if it is a P or I frame, the PTS
1251
           is the one of the next displayed one */
1252
        /* XXX: add mpeg4 too ? */
1253
        if (ist->st->codec->codec_id == CODEC_ID_MPEG1VIDEO) {
1254
            if (ist->st->codec->pict_type != B_TYPE) {
1255
                int64_t tmp;
1256
                tmp = ist->last_ip_pts;
1257
                ist->last_ip_pts  = ist->frac_pts.val;
1258
                ist->frac_pts.val = tmp;
1259
            }
1260
        }
1261
#endif
1262
        /* if output time reached then transcode raw format,
1263
           encode packets and output them */
1264
        if (start_time == 0 || ist->pts >= start_time)
1265
            for(i=0;i<nb_ostreams;i++) {
1266
                int frame_size;
1267

    
1268
                ost = ost_table[i];
1269
                if (ost->source_index == ist_index) {
1270
                    os = output_files[ost->file_index];
1271

    
1272
#if 0
1273
                    printf("%d: got pts=%0.3f %0.3f\n", i,
1274
                           (double)pkt->pts / AV_TIME_BASE,
1275
                           ((double)ist->pts / AV_TIME_BASE) -
1276
                           ((double)ost->st->pts.val * ost->st->time_base.num / ost->st->time_base.den));
1277
#endif
1278
                    /* set the input output pts pairs */
1279
                    //ost->sync_ipts = (double)(ist->pts + input_files_ts_offset[ist->file_index] - start_time)/ AV_TIME_BASE;
1280

    
1281
                    if (ost->encoding_needed) {
1282
                        switch(ost->st->codec->codec_type) {
1283
                        case CODEC_TYPE_AUDIO:
1284
                            do_audio_out(os, ost, ist, data_buf, data_size);
1285
                            break;
1286
                        case CODEC_TYPE_VIDEO:
1287
                            do_video_out(os, ost, ist, &picture, &frame_size);
1288
                            video_size += frame_size;
1289
                            if (vstats_filename && frame_size)
1290
                                do_video_stats(os, ost, frame_size);
1291
                            break;
1292
                        case CODEC_TYPE_SUBTITLE:
1293
                            do_subtitle_out(os, ost, ist, &subtitle,
1294
                                            pkt->pts);
1295
                            break;
1296
                        default:
1297
                            abort();
1298
                        }
1299
                    } else {
1300
                        AVFrame avframe; //FIXME/XXX remove this
1301
                        AVPacket opkt;
1302
                        av_init_packet(&opkt);
1303

    
1304
                        if (!ost->frame_number && !(pkt->flags & PKT_FLAG_KEY))
1305
                            continue;
1306

    
1307
                        /* no reencoding needed : output the packet directly */
1308
                        /* force the input stream PTS */
1309

    
1310
                        avcodec_get_frame_defaults(&avframe);
1311
                        ost->st->codec->coded_frame= &avframe;
1312
                        avframe.key_frame = pkt->flags & PKT_FLAG_KEY;
1313

    
1314
                        if(ost->st->codec->codec_type == CODEC_TYPE_AUDIO)
1315
                            audio_size += data_size;
1316
                        else if (ost->st->codec->codec_type == CODEC_TYPE_VIDEO) {
1317
                            video_size += data_size;
1318
                            ost->sync_opts++;
1319
                        }
1320

    
1321
                        opkt.stream_index= ost->index;
1322
                        if(pkt->pts != AV_NOPTS_VALUE)
1323
                            opkt.pts= av_rescale_q(pkt->pts, ist->st->time_base, ost->st->time_base);
1324
                        else
1325
                            opkt.pts= AV_NOPTS_VALUE;
1326

    
1327
                            if (pkt->dts == AV_NOPTS_VALUE)
1328
                                opkt.dts = av_rescale_q(ist->next_pts, AV_TIME_BASE_Q, ost->st->time_base);
1329
                            else
1330
                                opkt.dts = av_rescale_q(pkt->dts, ist->st->time_base, ost->st->time_base);
1331

    
1332
                        opkt.duration = av_rescale_q(pkt->duration, ist->st->time_base, ost->st->time_base);
1333
                        opkt.flags= pkt->flags;
1334

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

    
1339
                        write_frame(os, &opkt, ost->st->codec, bitstream_filters[ost->file_index][opkt.stream_index]);
1340
                        ost->st->codec->frame_number++;
1341
                        ost->frame_number++;
1342
                        av_free_packet(&opkt);
1343
                    }
1344
                }
1345
            }
1346
        av_free(buffer_to_free);
1347
        /* XXX: allocate the subtitles in the codec ? */
1348
        if (subtitle_to_free) {
1349
            if (subtitle_to_free->rects != NULL) {
1350
                for (i = 0; i < subtitle_to_free->num_rects; i++) {
1351
                    av_free(subtitle_to_free->rects[i].bitmap);
1352
                    av_free(subtitle_to_free->rects[i].rgba_palette);
1353
                }
1354
                av_freep(&subtitle_to_free->rects);
1355
            }
1356
            subtitle_to_free->num_rects = 0;
1357
            subtitle_to_free = NULL;
1358
        }
1359
    }
1360
 discard_packet:
1361
    if (pkt == NULL) {
1362
        /* EOF handling */
1363

    
1364
        for(i=0;i<nb_ostreams;i++) {
1365
            ost = ost_table[i];
1366
            if (ost->source_index == ist_index) {
1367
                AVCodecContext *enc= ost->st->codec;
1368
                os = output_files[ost->file_index];
1369

    
1370
                if(ost->st->codec->codec_type == CODEC_TYPE_AUDIO && enc->frame_size <=1)
1371
                    continue;
1372
                if(ost->st->codec->codec_type == CODEC_TYPE_VIDEO && (os->oformat->flags & AVFMT_RAWPICTURE))
1373
                    continue;
1374

    
1375
                if (ost->encoding_needed) {
1376
                    for(;;) {
1377
                        AVPacket pkt;
1378
                        int fifo_bytes;
1379
                        av_init_packet(&pkt);
1380
                        pkt.stream_index= ost->index;
1381

    
1382
                        switch(ost->st->codec->codec_type) {
1383
                        case CODEC_TYPE_AUDIO:
1384
                            fifo_bytes = av_fifo_size(&ost->fifo);
1385
                            ret = 0;
1386
                            /* encode any samples remaining in fifo */
1387
                            if(fifo_bytes > 0 && enc->codec->capabilities & CODEC_CAP_SMALL_LAST_FRAME) {
1388
                                int fs_tmp = enc->frame_size;
1389
                                enc->frame_size = fifo_bytes / (2 * enc->channels);
1390
                                av_fifo_read(&ost->fifo, (uint8_t *)samples, fifo_bytes);
1391
                                    ret = avcodec_encode_audio(enc, bit_buffer, bit_buffer_size, samples);
1392
                                enc->frame_size = fs_tmp;
1393
                            }
1394
                            if(ret <= 0) {
1395
                                ret = avcodec_encode_audio(enc, bit_buffer, bit_buffer_size, NULL);
1396
                            }
1397
                            audio_size += ret;
1398
                            pkt.flags |= PKT_FLAG_KEY;
1399
                            break;
1400
                        case CODEC_TYPE_VIDEO:
1401
                            ret = avcodec_encode_video(enc, bit_buffer, bit_buffer_size, NULL);
1402
                            video_size += ret;
1403
                            if(enc->coded_frame && enc->coded_frame->key_frame)
1404
                                pkt.flags |= PKT_FLAG_KEY;
1405
                            if (ost->logfile && enc->stats_out) {
1406
                                fprintf(ost->logfile, "%s", enc->stats_out);
1407
                            }
1408
                            break;
1409
                        default:
1410
                            ret=-1;
1411
                        }
1412

    
1413
                        if(ret<=0)
1414
                            break;
1415
                        pkt.data= bit_buffer;
1416
                        pkt.size= ret;
1417
                        if(enc->coded_frame && enc->coded_frame->pts != AV_NOPTS_VALUE)
1418
                            pkt.pts= av_rescale_q(enc->coded_frame->pts, enc->time_base, ost->st->time_base);
1419
                        write_frame(os, &pkt, ost->st->codec, bitstream_filters[ost->file_index][pkt.stream_index]);
1420
                    }
1421
                }
1422
            }
1423
        }
1424
    }
1425

    
1426
    return 0;
1427
 fail_decode:
1428
    return -1;
1429
}
1430

    
1431
static void print_sdp(AVFormatContext **avc, int n)
1432
{
1433
    char sdp[2048];
1434

    
1435
    avf_sdp_create(avc, n, sdp, sizeof(sdp));
1436
    printf("SDP:\n%s\n", sdp);
1437
}
1438

    
1439
static int stream_index_from_inputs(AVFormatContext **input_files,
1440
                                    int nb_input_files,
1441
                                    AVInputFile *file_table,
1442
                                    AVInputStream **ist_table,
1443
                                    enum CodecType type,
1444
                                    int programid)
1445
{
1446
    int p, q, z;
1447
    for(z=0; z<nb_input_files; z++) {
1448
        AVFormatContext *ic = input_files[z];
1449
        for(p=0; p<ic->nb_programs; p++) {
1450
            AVProgram *program = ic->programs[p];
1451
            if(program->id != programid)
1452
                continue;
1453
            for(q=0; q<program->nb_stream_indexes; q++) {
1454
                int sidx = program->stream_index[q];
1455
                int ris = file_table[z].ist_index + sidx;
1456
                if(ist_table[ris]->discard && ic->streams[sidx]->codec->codec_type == type)
1457
                    return ris;
1458
            }
1459
        }
1460
    }
1461

    
1462
    return -1;
1463
}
1464

    
1465
/*
1466
 * The following code is the main loop of the file converter
1467
 */
1468
static int av_encode(AVFormatContext **output_files,
1469
                     int nb_output_files,
1470
                     AVFormatContext **input_files,
1471
                     int nb_input_files,
1472
                     AVStreamMap *stream_maps, int nb_stream_maps)
1473
{
1474
    int ret, i, j, k, n, nb_istreams = 0, nb_ostreams = 0;
1475
    AVFormatContext *is, *os;
1476
    AVCodecContext *codec, *icodec;
1477
    AVOutputStream *ost, **ost_table = NULL;
1478
    AVInputStream *ist, **ist_table = NULL;
1479
    AVInputFile *file_table;
1480
    int key;
1481
    int want_sdp = 1;
1482

    
1483
    file_table= av_mallocz(nb_input_files * sizeof(AVInputFile));
1484
    if (!file_table)
1485
        goto fail;
1486

    
1487
    /* input stream init */
1488
    j = 0;
1489
    for(i=0;i<nb_input_files;i++) {
1490
        is = input_files[i];
1491
        file_table[i].ist_index = j;
1492
        file_table[i].nb_streams = is->nb_streams;
1493
        j += is->nb_streams;
1494
    }
1495
    nb_istreams = j;
1496

    
1497
    ist_table = av_mallocz(nb_istreams * sizeof(AVInputStream *));
1498
    if (!ist_table)
1499
        goto fail;
1500

    
1501
    for(i=0;i<nb_istreams;i++) {
1502
        ist = av_mallocz(sizeof(AVInputStream));
1503
        if (!ist)
1504
            goto fail;
1505
        ist_table[i] = ist;
1506
    }
1507
    j = 0;
1508
    for(i=0;i<nb_input_files;i++) {
1509
        is = input_files[i];
1510
        for(k=0;k<is->nb_streams;k++) {
1511
            ist = ist_table[j++];
1512
            ist->st = is->streams[k];
1513
            ist->file_index = i;
1514
            ist->index = k;
1515
            ist->discard = 1; /* the stream is discarded by default
1516
                                 (changed later) */
1517

    
1518
            if (ist->st->codec->rate_emu) {
1519
                ist->start = av_gettime();
1520
                ist->frame = 0;
1521
            }
1522
        }
1523
    }
1524

    
1525
    /* output stream init */
1526
    nb_ostreams = 0;
1527
    for(i=0;i<nb_output_files;i++) {
1528
        os = output_files[i];
1529
        if (!os->nb_streams) {
1530
            fprintf(stderr, "Output file does not contain any stream\n");
1531
            av_exit(1);
1532
        }
1533
        nb_ostreams += os->nb_streams;
1534
    }
1535
    if (nb_stream_maps > 0 && nb_stream_maps != nb_ostreams) {
1536
        fprintf(stderr, "Number of stream maps must match number of output streams\n");
1537
        av_exit(1);
1538
    }
1539

    
1540
    /* Sanity check the mapping args -- do the input files & streams exist? */
1541
    for(i=0;i<nb_stream_maps;i++) {
1542
        int fi = stream_maps[i].file_index;
1543
        int si = stream_maps[i].stream_index;
1544

    
1545
        if (fi < 0 || fi > nb_input_files - 1 ||
1546
            si < 0 || si > file_table[fi].nb_streams - 1) {
1547
            fprintf(stderr,"Could not find input stream #%d.%d\n", fi, si);
1548
            av_exit(1);
1549
        }
1550
        fi = stream_maps[i].sync_file_index;
1551
        si = stream_maps[i].sync_stream_index;
1552
        if (fi < 0 || fi > nb_input_files - 1 ||
1553
            si < 0 || si > file_table[fi].nb_streams - 1) {
1554
            fprintf(stderr,"Could not find sync stream #%d.%d\n", fi, si);
1555
            av_exit(1);
1556
        }
1557
    }
1558

    
1559
    ost_table = av_mallocz(sizeof(AVOutputStream *) * nb_ostreams);
1560
    if (!ost_table)
1561
        goto fail;
1562
    for(i=0;i<nb_ostreams;i++) {
1563
        ost = av_mallocz(sizeof(AVOutputStream));
1564
        if (!ost)
1565
            goto fail;
1566
        ost_table[i] = ost;
1567
    }
1568

    
1569
    n = 0;
1570
    for(k=0;k<nb_output_files;k++) {
1571
        os = output_files[k];
1572
        for(i=0;i<os->nb_streams;i++) {
1573
            int found;
1574
            ost = ost_table[n++];
1575
            ost->file_index = k;
1576
            ost->index = i;
1577
            ost->st = os->streams[i];
1578
            if (nb_stream_maps > 0) {
1579
                ost->source_index = file_table[stream_maps[n-1].file_index].ist_index +
1580
                    stream_maps[n-1].stream_index;
1581

    
1582
                /* Sanity check that the stream types match */
1583
                if (ist_table[ost->source_index]->st->codec->codec_type != ost->st->codec->codec_type) {
1584
                    fprintf(stderr, "Codec type mismatch for mapping #%d.%d -> #%d.%d\n",
1585
                        stream_maps[n-1].file_index, stream_maps[n-1].stream_index,
1586
                        ost->file_index, ost->index);
1587
                    av_exit(1);
1588
                }
1589

    
1590
            } else {
1591
                if(opt_programid) {
1592
                    found = 0;
1593
                    j = stream_index_from_inputs(input_files, nb_input_files, file_table, ist_table, ost->st->codec->codec_type, opt_programid);
1594
                    if(j != -1) {
1595
                        ost->source_index = j;
1596
                        found = 1;
1597
                    }
1598
                } else {
1599
                    /* get corresponding input stream index : we select the first one with the right type */
1600
                    found = 0;
1601
                    for(j=0;j<nb_istreams;j++) {
1602
                        ist = ist_table[j];
1603
                        if (ist->discard &&
1604
                            ist->st->codec->codec_type == ost->st->codec->codec_type) {
1605
                            ost->source_index = j;
1606
                            found = 1;
1607
                            break;
1608
                        }
1609
                    }
1610
                }
1611

    
1612
                if (!found) {
1613
                    if(! opt_programid) {
1614
                        /* try again and reuse existing stream */
1615
                        for(j=0;j<nb_istreams;j++) {
1616
                            ist = ist_table[j];
1617
                            if (ist->st->codec->codec_type == ost->st->codec->codec_type) {
1618
                                ost->source_index = j;
1619
                                found = 1;
1620
                            }
1621
                        }
1622
                    }
1623
                    if (!found) {
1624
                        fprintf(stderr, "Could not find input stream matching output stream #%d.%d\n",
1625
                                ost->file_index, ost->index);
1626
                        av_exit(1);
1627
                    }
1628
                }
1629
            }
1630
            ist = ist_table[ost->source_index];
1631
            ist->discard = 0;
1632
            ost->sync_ist = (nb_stream_maps > 0) ?
1633
                ist_table[file_table[stream_maps[n-1].sync_file_index].ist_index +
1634
                         stream_maps[n-1].sync_stream_index] : ist;
1635
        }
1636
    }
1637

    
1638
    /* for each output stream, we compute the right encoding parameters */
1639
    for(i=0;i<nb_ostreams;i++) {
1640
        ost = ost_table[i];
1641
        os = output_files[ost->file_index];
1642
        ist = ist_table[ost->source_index];
1643

    
1644
        codec = ost->st->codec;
1645
        icodec = ist->st->codec;
1646

    
1647
        if (!ost->st->language[0])
1648
            av_strlcpy(ost->st->language, ist->st->language,
1649
                       sizeof(ost->st->language));
1650

    
1651
        ost->st->disposition = ist->st->disposition;
1652

    
1653
        if (ost->st->stream_copy) {
1654
            /* if stream_copy is selected, no need to decode or encode */
1655
            codec->codec_id = icodec->codec_id;
1656
            codec->codec_type = icodec->codec_type;
1657

    
1658
            if(!codec->codec_tag){
1659
                if(   !os->oformat->codec_tag
1660
                   || av_codec_get_id (os->oformat->codec_tag, icodec->codec_tag) > 0
1661
                   || av_codec_get_tag(os->oformat->codec_tag, icodec->codec_id) <= 0)
1662
                    codec->codec_tag = icodec->codec_tag;
1663
            }
1664

    
1665
            codec->bit_rate = icodec->bit_rate;
1666
            codec->extradata= icodec->extradata;
1667
            codec->extradata_size= icodec->extradata_size;
1668
            if(av_q2d(icodec->time_base) > av_q2d(ist->st->time_base) && av_q2d(ist->st->time_base) < 1.0/1000)
1669
                codec->time_base = icodec->time_base;
1670
            else
1671
                codec->time_base = ist->st->time_base;
1672
            switch(codec->codec_type) {
1673
            case CODEC_TYPE_AUDIO:
1674
                codec->sample_rate = icodec->sample_rate;
1675
                codec->channels = icodec->channels;
1676
                codec->frame_size = icodec->frame_size;
1677
                codec->block_align= icodec->block_align;
1678
                if(codec->block_align == 1 && codec->codec_id == CODEC_ID_MP3)
1679
                    codec->block_align= 0;
1680
                break;
1681
            case CODEC_TYPE_VIDEO:
1682
                if(using_vhook) {
1683
                    fprintf(stderr,"-vcodec copy and -vhook are incompatible (frames are not decoded)\n");
1684
                    av_exit(1);
1685
                }
1686
                codec->pix_fmt = icodec->pix_fmt;
1687
                codec->width = icodec->width;
1688
                codec->height = icodec->height;
1689
                codec->has_b_frames = icodec->has_b_frames;
1690
                break;
1691
            case CODEC_TYPE_SUBTITLE:
1692
                break;
1693
            default:
1694
                abort();
1695
            }
1696
        } else {
1697
            switch(codec->codec_type) {
1698
            case CODEC_TYPE_AUDIO:
1699
                if (av_fifo_init(&ost->fifo, 1024))
1700
                    goto fail;
1701
                ost->audio_resample = codec->sample_rate != icodec->sample_rate || audio_sync_method > 1;
1702
                icodec->request_channels = codec->channels;
1703
                ist->decoding_needed = 1;
1704
                ost->encoding_needed = 1;
1705
                break;
1706
            case CODEC_TYPE_VIDEO:
1707
                ost->video_crop = ((frame_leftBand + frame_rightBand + frame_topBand + frame_bottomBand) != 0);
1708
                ost->video_pad = ((frame_padleft + frame_padright + frame_padtop + frame_padbottom) != 0);
1709
                ost->video_resample = ((codec->width != icodec->width -
1710
                                (frame_leftBand + frame_rightBand) +
1711
                                (frame_padleft + frame_padright)) ||
1712
                        (codec->height != icodec->height -
1713
                                (frame_topBand  + frame_bottomBand) +
1714
                                (frame_padtop + frame_padbottom)) ||
1715
                        (codec->pix_fmt != icodec->pix_fmt));
1716
                if (ost->video_crop) {
1717
                    ost->topBand = frame_topBand;
1718
                    ost->leftBand = frame_leftBand;
1719
                }
1720
                if (ost->video_pad) {
1721
                    ost->padtop = frame_padtop;
1722
                    ost->padleft = frame_padleft;
1723
                    ost->padbottom = frame_padbottom;
1724
                    ost->padright = frame_padright;
1725
                    if (!ost->video_resample) {
1726
                        avcodec_get_frame_defaults(&ost->pict_tmp);
1727
                        if( avpicture_alloc( (AVPicture*)&ost->pict_tmp, codec->pix_fmt,
1728
                                         codec->width, codec->height ) )
1729
                            goto fail;
1730
                    }
1731
                }
1732
                if (ost->video_resample) {
1733
                    avcodec_get_frame_defaults(&ost->pict_tmp);
1734
                    if( avpicture_alloc( (AVPicture*)&ost->pict_tmp, codec->pix_fmt,
1735
                                         codec->width, codec->height ) ) {
1736
                        fprintf(stderr, "Cannot allocate temp picture, check pix fmt\n");
1737
                        av_exit(1);
1738
                    }
1739
                    sws_flags = av_get_int(sws_opts, "sws_flags", NULL);
1740
                    ost->img_resample_ctx = sws_getContext(
1741
                            icodec->width - (frame_leftBand + frame_rightBand),
1742
                            icodec->height - (frame_topBand + frame_bottomBand),
1743
                            icodec->pix_fmt,
1744
                            codec->width - (frame_padleft + frame_padright),
1745
                            codec->height - (frame_padtop + frame_padbottom),
1746
                            codec->pix_fmt,
1747
                            sws_flags, NULL, NULL, NULL);
1748
                    if (ost->img_resample_ctx == NULL) {
1749
                        fprintf(stderr, "Cannot get resampling context\n");
1750
                        av_exit(1);
1751
                    }
1752
                    ost->resample_height = icodec->height - (frame_topBand + frame_bottomBand);
1753
                }
1754
                ost->encoding_needed = 1;
1755
                ist->decoding_needed = 1;
1756
                break;
1757
            case CODEC_TYPE_SUBTITLE:
1758
                ost->encoding_needed = 1;
1759
                ist->decoding_needed = 1;
1760
                break;
1761
            default:
1762
                abort();
1763
                break;
1764
            }
1765
            /* two pass mode */
1766
            if (ost->encoding_needed &&
1767
                (codec->flags & (CODEC_FLAG_PASS1 | CODEC_FLAG_PASS2))) {
1768
                char logfilename[1024];
1769
                FILE *f;
1770
                int size;
1771
                char *logbuffer;
1772

    
1773
                snprintf(logfilename, sizeof(logfilename), "%s-%d.log",
1774
                         pass_logfilename ?
1775
                         pass_logfilename : DEFAULT_PASS_LOGFILENAME, i);
1776
                if (codec->flags & CODEC_FLAG_PASS1) {
1777
                    f = fopen(logfilename, "w");
1778
                    if (!f) {
1779
                        perror(logfilename);
1780
                        av_exit(1);
1781
                    }
1782
                    ost->logfile = f;
1783
                } else {
1784
                    /* read the log file */
1785
                    f = fopen(logfilename, "r");
1786
                    if (!f) {
1787
                        perror(logfilename);
1788
                        av_exit(1);
1789
                    }
1790
                    fseek(f, 0, SEEK_END);
1791
                    size = ftell(f);
1792
                    fseek(f, 0, SEEK_SET);
1793
                    logbuffer = av_malloc(size + 1);
1794
                    if (!logbuffer) {
1795
                        fprintf(stderr, "Could not allocate log buffer\n");
1796
                        av_exit(1);
1797
                    }
1798
                    size = fread(logbuffer, 1, size, f);
1799
                    fclose(f);
1800
                    logbuffer[size] = '\0';
1801
                    codec->stats_in = logbuffer;
1802
                }
1803
            }
1804
        }
1805
        if(codec->codec_type == CODEC_TYPE_VIDEO){
1806
            int size= codec->width * codec->height;
1807
            bit_buffer_size= FFMAX(bit_buffer_size, 4*size);
1808
        }
1809
    }
1810

    
1811
    if (!bit_buffer)
1812
        bit_buffer = av_malloc(bit_buffer_size);
1813
    if (!bit_buffer)
1814
        goto fail;
1815

    
1816
    /* dump the file output parameters - cannot be done before in case
1817
       of stream copy */
1818
    for(i=0;i<nb_output_files;i++) {
1819
        dump_format(output_files[i], i, output_files[i]->filename, 1);
1820
    }
1821

    
1822
    /* dump the stream mapping */
1823
    if (verbose >= 0) {
1824
        fprintf(stderr, "Stream mapping:\n");
1825
        for(i=0;i<nb_ostreams;i++) {
1826
            ost = ost_table[i];
1827
            fprintf(stderr, "  Stream #%d.%d -> #%d.%d",
1828
                    ist_table[ost->source_index]->file_index,
1829
                    ist_table[ost->source_index]->index,
1830
                    ost->file_index,
1831
                    ost->index);
1832
            if (ost->sync_ist != ist_table[ost->source_index])
1833
                fprintf(stderr, " [sync #%d.%d]",
1834
                        ost->sync_ist->file_index,
1835
                        ost->sync_ist->index);
1836
            fprintf(stderr, "\n");
1837
        }
1838
    }
1839

    
1840
    /* open each encoder */
1841
    for(i=0;i<nb_ostreams;i++) {
1842
        ost = ost_table[i];
1843
        if (ost->encoding_needed) {
1844
            AVCodec *codec;
1845
            codec = avcodec_find_encoder(ost->st->codec->codec_id);
1846
            if (!codec) {
1847
                fprintf(stderr, "Unsupported codec for output stream #%d.%d\n",
1848
                        ost->file_index, ost->index);
1849
                av_exit(1);
1850
            }
1851
            if (avcodec_open(ost->st->codec, codec) < 0) {
1852
                fprintf(stderr, "Error while opening codec for output stream #%d.%d - maybe incorrect parameters such as bit_rate, rate, width or height\n",
1853
                        ost->file_index, ost->index);
1854
                av_exit(1);
1855
            }
1856
            extra_size += ost->st->codec->extradata_size;
1857
        }
1858
    }
1859

    
1860
    /* open each decoder */
1861
    for(i=0;i<nb_istreams;i++) {
1862
        ist = ist_table[i];
1863
        if (ist->decoding_needed) {
1864
            AVCodec *codec;
1865
            codec = avcodec_find_decoder(ist->st->codec->codec_id);
1866
            if (!codec) {
1867
                fprintf(stderr, "Unsupported codec (id=%d) for input stream #%d.%d\n",
1868
                        ist->st->codec->codec_id, ist->file_index, ist->index);
1869
                av_exit(1);
1870
            }
1871
            if (avcodec_open(ist->st->codec, codec) < 0) {
1872
                fprintf(stderr, "Error while opening codec for input stream #%d.%d\n",
1873
                        ist->file_index, ist->index);
1874
                av_exit(1);
1875
            }
1876
            //if (ist->st->codec->codec_type == CODEC_TYPE_VIDEO)
1877
            //    ist->st->codec->flags |= CODEC_FLAG_REPEAT_FIELD;
1878
        }
1879
    }
1880

    
1881
    /* init pts */
1882
    for(i=0;i<nb_istreams;i++) {
1883
        ist = ist_table[i];
1884
        is = input_files[ist->file_index];
1885
        ist->pts = 0;
1886
        ist->next_pts = AV_NOPTS_VALUE;
1887
        ist->is_start = 1;
1888
    }
1889

    
1890
    /* set meta data information from input file if required */
1891
    for (i=0;i<nb_meta_data_maps;i++) {
1892
        AVFormatContext *out_file;
1893
        AVFormatContext *in_file;
1894

    
1895
        int out_file_index = meta_data_maps[i].out_file;
1896
        int in_file_index = meta_data_maps[i].in_file;
1897
        if ( out_file_index < 0 || out_file_index >= nb_output_files ) {
1898
            fprintf(stderr, "Invalid output file index %d map_meta_data(%d,%d)\n", out_file_index, out_file_index, in_file_index);
1899
            ret = AVERROR(EINVAL);
1900
            goto fail;
1901
        }
1902
        if ( in_file_index < 0 || in_file_index >= nb_input_files ) {
1903
            fprintf(stderr, "Invalid input file index %d map_meta_data(%d,%d)\n", in_file_index, out_file_index, in_file_index);
1904
            ret = AVERROR(EINVAL);
1905
            goto fail;
1906
        }
1907

    
1908
        out_file = output_files[out_file_index];
1909
        in_file = input_files[in_file_index];
1910

    
1911
        strcpy(out_file->title, in_file->title);
1912
        strcpy(out_file->author, in_file->author);
1913
        strcpy(out_file->copyright, in_file->copyright);
1914
        strcpy(out_file->comment, in_file->comment);
1915
        strcpy(out_file->album, in_file->album);
1916
        out_file->year = in_file->year;
1917
        out_file->track = in_file->track;
1918
        strcpy(out_file->genre, in_file->genre);
1919
    }
1920

    
1921
    /* open files and write file headers */
1922
    for(i=0;i<nb_output_files;i++) {
1923
        os = output_files[i];
1924
        if (av_write_header(os) < 0) {
1925
            fprintf(stderr, "Could not write header for output file #%d (incorrect codec parameters ?)\n", i);
1926
            ret = AVERROR(EINVAL);
1927
            goto fail;
1928
        }
1929
        if (strcmp(output_files[i]->oformat->name, "rtp")) {
1930
            want_sdp = 0;
1931
        }
1932
    }
1933
    if (want_sdp) {
1934
        print_sdp(output_files, nb_output_files);
1935
    }
1936

    
1937
    if ( !using_stdin && verbose >= 0) {
1938
        fprintf(stderr, "Press [q] to stop encoding\n");
1939
        url_set_interrupt_cb(decode_interrupt_cb);
1940
    }
1941
    term_init();
1942

    
1943
    key = -1;
1944
    timer_start = av_gettime();
1945

    
1946
    for(; received_sigterm == 0;) {
1947
        int file_index, ist_index;
1948
        AVPacket pkt;
1949
        double ipts_min;
1950
        double opts_min;
1951

    
1952
    redo:
1953
        ipts_min= 1e100;
1954
        opts_min= 1e100;
1955
        /* if 'q' pressed, exits */
1956
        if (!using_stdin) {
1957
            if (q_pressed)
1958
                break;
1959
            /* read_key() returns 0 on EOF */
1960
            key = read_key();
1961
            if (key == 'q')
1962
                break;
1963
        }
1964

    
1965
        /* select the stream that we must read now by looking at the
1966
           smallest output pts */
1967
        file_index = -1;
1968
        for(i=0;i<nb_ostreams;i++) {
1969
            double ipts, opts;
1970
            ost = ost_table[i];
1971
            os = output_files[ost->file_index];
1972
            ist = ist_table[ost->source_index];
1973
            if(ost->st->codec->codec_type == CODEC_TYPE_VIDEO)
1974
                opts = ost->sync_opts * av_q2d(ost->st->codec->time_base);
1975
            else
1976
                opts = ost->st->pts.val * av_q2d(ost->st->time_base);
1977
            ipts = (double)ist->pts;
1978
            if (!file_table[ist->file_index].eof_reached){
1979
                if(ipts < ipts_min) {
1980
                    ipts_min = ipts;
1981
                    if(input_sync ) file_index = ist->file_index;
1982
                }
1983
                if(opts < opts_min) {
1984
                    opts_min = opts;
1985
                    if(!input_sync) file_index = ist->file_index;
1986
                }
1987
            }
1988
            if(ost->frame_number >= max_frames[ost->st->codec->codec_type]){
1989
                file_index= -1;
1990
                break;
1991
            }
1992
        }
1993
        /* if none, if is finished */
1994
        if (file_index < 0) {
1995
            break;
1996
        }
1997

    
1998
        /* finish if recording time exhausted */
1999
        if (recording_time > 0 && opts_min >= (recording_time / 1000000.0))
2000
            break;
2001

    
2002
        /* finish if limit size exhausted */
2003
        if (limit_filesize != 0 && limit_filesize < url_ftell(output_files[0]->pb))
2004
            break;
2005

    
2006
        /* read a frame from it and output it in the fifo */
2007
        is = input_files[file_index];
2008
        if (av_read_frame(is, &pkt) < 0) {
2009
            file_table[file_index].eof_reached = 1;
2010
            if (opt_shortest)
2011
                break;
2012
            else
2013
                continue;
2014
        }
2015

    
2016
        if (do_pkt_dump) {
2017
            av_pkt_dump_log(NULL, AV_LOG_DEBUG, &pkt, do_hex_dump);
2018
        }
2019
        /* the following test is needed in case new streams appear
2020
           dynamically in stream : we ignore them */
2021
        if (pkt.stream_index >= file_table[file_index].nb_streams)
2022
            goto discard_packet;
2023
        ist_index = file_table[file_index].ist_index + pkt.stream_index;
2024
        ist = ist_table[ist_index];
2025
        if (ist->discard)
2026
            goto discard_packet;
2027

    
2028
        if (pkt.dts != AV_NOPTS_VALUE)
2029
            pkt.dts += av_rescale_q(input_files_ts_offset[ist->file_index], AV_TIME_BASE_Q, ist->st->time_base);
2030
        if (pkt.pts != AV_NOPTS_VALUE)
2031
            pkt.pts += av_rescale_q(input_files_ts_offset[ist->file_index], AV_TIME_BASE_Q, ist->st->time_base);
2032

    
2033
//        fprintf(stderr, "next:%"PRId64" dts:%"PRId64" off:%"PRId64" %d\n", ist->next_pts, pkt.dts, input_files_ts_offset[ist->file_index], ist->st->codec->codec_type);
2034
        if (pkt.dts != AV_NOPTS_VALUE && ist->next_pts != AV_NOPTS_VALUE) {
2035
            int64_t pkt_dts= av_rescale_q(pkt.dts, ist->st->time_base, AV_TIME_BASE_Q);
2036
            int64_t delta= pkt_dts - ist->next_pts;
2037
            if((FFABS(delta) > 1LL*dts_delta_threshold*AV_TIME_BASE || pkt_dts+1<ist->pts)&& !copy_ts){
2038
                input_files_ts_offset[ist->file_index]-= delta;
2039
                if (verbose > 2)
2040
                    fprintf(stderr, "timestamp discontinuity %"PRId64", new offset= %"PRId64"\n", delta, input_files_ts_offset[ist->file_index]);
2041
                pkt.dts-= av_rescale_q(delta, AV_TIME_BASE_Q, ist->st->time_base);
2042
                if(pkt.pts != AV_NOPTS_VALUE)
2043
                    pkt.pts-= av_rescale_q(delta, AV_TIME_BASE_Q, ist->st->time_base);
2044
            }
2045
        }
2046

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

    
2050
            if (verbose >= 0)
2051
                fprintf(stderr, "Error while decoding stream #%d.%d\n",
2052
                        ist->file_index, ist->index);
2053

    
2054
            av_free_packet(&pkt);
2055
            goto redo;
2056
        }
2057

    
2058
    discard_packet:
2059
        av_free_packet(&pkt);
2060

    
2061
        /* dump report by using the output first video and audio streams */
2062
        print_report(output_files, ost_table, nb_ostreams, 0);
2063
    }
2064

    
2065
    /* at the end of stream, we must flush the decoder buffers */
2066
    for(i=0;i<nb_istreams;i++) {
2067
        ist = ist_table[i];
2068
        if (ist->decoding_needed) {
2069
            output_packet(ist, i, ost_table, nb_ostreams, NULL);
2070
        }
2071
    }
2072

    
2073
    term_exit();
2074

    
2075
    /* write the trailer if needed and close file */
2076
    for(i=0;i<nb_output_files;i++) {
2077
        os = output_files[i];
2078
        av_write_trailer(os);
2079
    }
2080

    
2081
    /* dump report by using the first video and audio streams */
2082
    print_report(output_files, ost_table, nb_ostreams, 1);
2083

    
2084
    /* close each encoder */
2085
    for(i=0;i<nb_ostreams;i++) {
2086
        ost = ost_table[i];
2087
        if (ost->encoding_needed) {
2088
            av_freep(&ost->st->codec->stats_in);
2089
            avcodec_close(ost->st->codec);
2090
        }
2091
    }
2092

    
2093
    /* close each decoder */
2094
    for(i=0;i<nb_istreams;i++) {
2095
        ist = ist_table[i];
2096
        if (ist->decoding_needed) {
2097
            avcodec_close(ist->st->codec);
2098
        }
2099
    }
2100

    
2101
    /* finished ! */
2102

    
2103
    ret = 0;
2104
 fail1:
2105
    av_freep(&bit_buffer);
2106
    av_free(file_table);
2107

    
2108
    if (ist_table) {
2109
        for(i=0;i<nb_istreams;i++) {
2110
            ist = ist_table[i];
2111
            av_free(ist);
2112
        }
2113
        av_free(ist_table);
2114
    }
2115
    if (ost_table) {
2116
        for(i=0;i<nb_ostreams;i++) {
2117
            ost = ost_table[i];
2118
            if (ost) {
2119
                if (ost->logfile) {
2120
                    fclose(ost->logfile);
2121
                    ost->logfile = NULL;
2122
                }
2123
                av_fifo_free(&ost->fifo); /* works even if fifo is not
2124
                                             initialized but set to zero */
2125
                av_free(ost->pict_tmp.data[0]);
2126
                if (ost->video_resample)
2127
                    sws_freeContext(ost->img_resample_ctx);
2128
                if (ost->resample)
2129
                    audio_resample_close(ost->resample);
2130
                av_free(ost);
2131
            }
2132
        }
2133
        av_free(ost_table);
2134
    }
2135
    return ret;
2136
 fail:
2137
    ret = AVERROR(ENOMEM);
2138
    goto fail1;
2139
}
2140

    
2141
#if 0
2142
int file_read(const char *filename)
2143
{
2144
    URLContext *h;
2145
    unsigned char buffer[1024];
2146
    int len, i;
2147

2148
    if (url_open(&h, filename, O_RDONLY) < 0) {
2149
        printf("could not open '%s'\n", filename);
2150
        return -1;
2151
    }
2152
    for(;;) {
2153
        len = url_read(h, buffer, sizeof(buffer));
2154
        if (len <= 0)
2155
            break;
2156
        for(i=0;i<len;i++) putchar(buffer[i]);
2157
    }
2158
    url_close(h);
2159
    return 0;
2160
}
2161
#endif
2162

    
2163
static void opt_format(const char *arg)
2164
{
2165
    /* compatibility stuff for pgmyuv */
2166
    if (!strcmp(arg, "pgmyuv")) {
2167
        pgmyuv_compatibility_hack=1;
2168
//        opt_image_format(arg);
2169
        arg = "image2";
2170
        fprintf(stderr, "pgmyuv format is deprecated, use image2\n");
2171
    }
2172

    
2173
    file_iformat = av_find_input_format(arg);
2174
    file_oformat = guess_format(arg, NULL, NULL);
2175
    if (!file_iformat && !file_oformat) {
2176
        fprintf(stderr, "Unknown input or output format: %s\n", arg);
2177
        av_exit(1);
2178
    }
2179
}
2180

    
2181
extern int ffm_nopts;
2182

    
2183
static int opt_default(const char *opt, const char *arg){
2184
    int type;
2185
    const AVOption *o= NULL;
2186
    int opt_types[]={AV_OPT_FLAG_VIDEO_PARAM, AV_OPT_FLAG_AUDIO_PARAM, 0, AV_OPT_FLAG_SUBTITLE_PARAM, 0};
2187

    
2188
    for(type=0; type<CODEC_TYPE_NB; type++){
2189
        const AVOption *o2 = av_find_opt(avctx_opts[0], opt, NULL, opt_types[type], opt_types[type]);
2190
        if(o2)
2191
            o = av_set_string(avctx_opts[type], opt, arg);
2192
    }
2193
    if(!o)
2194
        o = av_set_string(avformat_opts, opt, arg);
2195
    if(!o)
2196
        o = av_set_string(sws_opts, opt, arg);
2197
    if(!o){
2198
        if(opt[0] == 'a')
2199
            o = av_set_string(avctx_opts[CODEC_TYPE_AUDIO], opt+1, arg);
2200
        else if(opt[0] == 'v')
2201
            o = av_set_string(avctx_opts[CODEC_TYPE_VIDEO], opt+1, arg);
2202
        else if(opt[0] == 's')
2203
            o = av_set_string(avctx_opts[CODEC_TYPE_SUBTITLE], opt+1, arg);
2204
    }
2205
    if(!o)
2206
        return -1;
2207

    
2208
//    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));
2209

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

    
2214
#if defined(CONFIG_FFM_DEMUXER) || defined(CONFIG_FFM_MUXER)
2215
    /* disable generate of real time pts in ffm (need to be supressed anyway) */
2216
    if(avctx_opts[0]->flags & CODEC_FLAG_BITEXACT)
2217
        ffm_nopts = 1;
2218
#endif
2219

    
2220
    if(avctx_opts[0]->debug)
2221
        av_log_set_level(AV_LOG_DEBUG);
2222
    return 0;
2223
}
2224

    
2225
static void opt_video_rc_override_string(const char *arg)
2226
{
2227
    video_rc_override_string = arg;
2228
}
2229

    
2230
static int opt_me_threshold(const char *opt, const char *arg)
2231
{
2232
    me_threshold = parse_number_or_die(opt, arg, OPT_INT64, INT_MIN, INT_MAX);
2233
    return 0;
2234
}
2235

    
2236
static int opt_verbose(const char *opt, const char *arg)
2237
{
2238
    verbose = parse_number_or_die(opt, arg, OPT_INT64, -10, 10);
2239
    av_log_set_level(verbose);
2240
    return 0;
2241
}
2242

    
2243
static void opt_frame_rate(const char *arg)
2244
{
2245
    if (av_parse_video_frame_rate(&frame_rate, arg) < 0) {
2246
        fprintf(stderr, "Incorrect frame rate\n");
2247
        av_exit(1);
2248
    }
2249
}
2250

    
2251
static int opt_bitrate(const char *opt, const char *arg)
2252
{
2253
    int codec_type = opt[0]=='a' ? CODEC_TYPE_AUDIO : CODEC_TYPE_VIDEO;
2254

    
2255
    opt_default(opt, arg);
2256

    
2257
    if (av_get_int(avctx_opts[codec_type], "b", NULL) < 1000)
2258
        fprintf(stderr, "WARNING: The bitrate parameter is set too low. It takes bits/s as argument, not kbits/s\n");
2259

    
2260
    return 0;
2261
}
2262

    
2263
static void opt_frame_crop_top(const char *arg)
2264
{
2265
    frame_topBand = atoi(arg);
2266
    if (frame_topBand < 0) {
2267
        fprintf(stderr, "Incorrect top crop size\n");
2268
        av_exit(1);
2269
    }
2270
    if ((frame_topBand % 2) != 0) {
2271
        fprintf(stderr, "Top crop size must be a multiple of 2\n");
2272
        av_exit(1);
2273
    }
2274
    if ((frame_topBand) >= frame_height){
2275
        fprintf(stderr, "Vertical crop dimensions are outside the range of the original image.\nRemember to crop first and scale second.\n");
2276
        av_exit(1);
2277
    }
2278
    frame_height -= frame_topBand;
2279
}
2280

    
2281
static void opt_frame_crop_bottom(const char *arg)
2282
{
2283
    frame_bottomBand = atoi(arg);
2284
    if (frame_bottomBand < 0) {
2285
        fprintf(stderr, "Incorrect bottom crop size\n");
2286
        av_exit(1);
2287
    }
2288
    if ((frame_bottomBand % 2) != 0) {
2289
        fprintf(stderr, "Bottom crop size must be a multiple of 2\n");
2290
        av_exit(1);
2291
    }
2292
    if ((frame_bottomBand) >= frame_height){
2293
        fprintf(stderr, "Vertical crop dimensions are outside the range of the original image.\nRemember to crop first and scale second.\n");
2294
        av_exit(1);
2295
    }
2296
    frame_height -= frame_bottomBand;
2297
}
2298

    
2299
static void opt_frame_crop_left(const char *arg)
2300
{
2301
    frame_leftBand = atoi(arg);
2302
    if (frame_leftBand < 0) {
2303
        fprintf(stderr, "Incorrect left crop size\n");
2304
        av_exit(1);
2305
    }
2306
    if ((frame_leftBand % 2) != 0) {
2307
        fprintf(stderr, "Left crop size must be a multiple of 2\n");
2308
        av_exit(1);
2309
    }
2310
    if ((frame_leftBand) >= frame_width){
2311
        fprintf(stderr, "Horizontal crop dimensions are outside the range of the original image.\nRemember to crop first and scale second.\n");
2312
        av_exit(1);
2313
    }
2314
    frame_width -= frame_leftBand;
2315
}
2316

    
2317
static void opt_frame_crop_right(const char *arg)
2318
{
2319
    frame_rightBand = atoi(arg);
2320
    if (frame_rightBand < 0) {
2321
        fprintf(stderr, "Incorrect right crop size\n");
2322
        av_exit(1);
2323
    }
2324
    if ((frame_rightBand % 2) != 0) {
2325
        fprintf(stderr, "Right crop size must be a multiple of 2\n");
2326
        av_exit(1);
2327
    }
2328
    if ((frame_rightBand) >= frame_width){
2329
        fprintf(stderr, "Horizontal crop dimensions are outside the range of the original image.\nRemember to crop first and scale second.\n");
2330
        av_exit(1);
2331
    }
2332
    frame_width -= frame_rightBand;
2333
}
2334

    
2335
static void opt_frame_size(const char *arg)
2336
{
2337
    if (av_parse_video_frame_size(&frame_width, &frame_height, arg) < 0) {
2338
        fprintf(stderr, "Incorrect frame size\n");
2339
        av_exit(1);
2340
    }
2341
    if ((frame_width % 2) != 0 || (frame_height % 2) != 0) {
2342
        fprintf(stderr, "Frame size must be a multiple of 2\n");
2343
        av_exit(1);
2344
    }
2345
}
2346

    
2347

    
2348
#define SCALEBITS 10
2349
#define ONE_HALF  (1 << (SCALEBITS - 1))
2350
#define FIX(x)    ((int) ((x) * (1<<SCALEBITS) + 0.5))
2351

    
2352
#define RGB_TO_Y(r, g, b) \
2353
((FIX(0.29900) * (r) + FIX(0.58700) * (g) + \
2354
  FIX(0.11400) * (b) + ONE_HALF) >> SCALEBITS)
2355

    
2356
#define RGB_TO_U(r1, g1, b1, shift)\
2357
(((- FIX(0.16874) * r1 - FIX(0.33126) * g1 +         \
2358
     FIX(0.50000) * b1 + (ONE_HALF << shift) - 1) >> (SCALEBITS + shift)) + 128)
2359

    
2360
#define RGB_TO_V(r1, g1, b1, shift)\
2361
(((FIX(0.50000) * r1 - FIX(0.41869) * g1 -           \
2362
   FIX(0.08131) * b1 + (ONE_HALF << shift) - 1) >> (SCALEBITS + shift)) + 128)
2363

    
2364
static void opt_pad_color(const char *arg) {
2365
    /* Input is expected to be six hex digits similar to
2366
       how colors are expressed in html tags (but without the #) */
2367
    int rgb = strtol(arg, NULL, 16);
2368
    int r,g,b;
2369

    
2370
    r = (rgb >> 16);
2371
    g = ((rgb >> 8) & 255);
2372
    b = (rgb & 255);
2373

    
2374
    padcolor[0] = RGB_TO_Y(r,g,b);
2375
    padcolor[1] = RGB_TO_U(r,g,b,0);
2376
    padcolor[2] = RGB_TO_V(r,g,b,0);
2377
}
2378

    
2379
static void opt_frame_pad_top(const char *arg)
2380
{
2381
    frame_padtop = atoi(arg);
2382
    if (frame_padtop < 0) {
2383
        fprintf(stderr, "Incorrect top pad size\n");
2384
        av_exit(1);
2385
    }
2386
    if ((frame_padtop % 2) != 0) {
2387
        fprintf(stderr, "Top pad size must be a multiple of 2\n");
2388
        av_exit(1);
2389
    }
2390
}
2391

    
2392
static void opt_frame_pad_bottom(const char *arg)
2393
{
2394
    frame_padbottom = atoi(arg);
2395
    if (frame_padbottom < 0) {
2396
        fprintf(stderr, "Incorrect bottom pad size\n");
2397
        av_exit(1);
2398
    }
2399
    if ((frame_padbottom % 2) != 0) {
2400
        fprintf(stderr, "Bottom pad size must be a multiple of 2\n");
2401
        av_exit(1);
2402
    }
2403
}
2404

    
2405

    
2406
static void opt_frame_pad_left(const char *arg)
2407
{
2408
    frame_padleft = atoi(arg);
2409
    if (frame_padleft < 0) {
2410
        fprintf(stderr, "Incorrect left pad size\n");
2411
        av_exit(1);
2412
    }
2413
    if ((frame_padleft % 2) != 0) {
2414
        fprintf(stderr, "Left pad size must be a multiple of 2\n");
2415
        av_exit(1);
2416
    }
2417
}
2418

    
2419

    
2420
static void opt_frame_pad_right(const char *arg)
2421
{
2422
    frame_padright = atoi(arg);
2423
    if (frame_padright < 0) {
2424
        fprintf(stderr, "Incorrect right pad size\n");
2425
        av_exit(1);
2426
    }
2427
    if ((frame_padright % 2) != 0) {
2428
        fprintf(stderr, "Right pad size must be a multiple of 2\n");
2429
        av_exit(1);
2430
    }
2431
}
2432

    
2433
static void list_pix_fmts(void)
2434
{
2435
    int i;
2436
    char pix_fmt_str[128];
2437
    for (i=-1; i < PIX_FMT_NB; i++) {
2438
        avcodec_pix_fmt_string (pix_fmt_str, sizeof(pix_fmt_str), i);
2439
        fprintf(stdout, "%s\n", pix_fmt_str);
2440
    }
2441
}
2442

    
2443
static void opt_frame_pix_fmt(const char *arg)
2444
{
2445
    if (strcmp(arg, "list"))
2446
        frame_pix_fmt = avcodec_get_pix_fmt(arg);
2447
    else {
2448
        list_pix_fmts();
2449
        av_exit(0);
2450
    }
2451
}
2452

    
2453
static void opt_frame_aspect_ratio(const char *arg)
2454
{
2455
    int x = 0, y = 0;
2456
    double ar = 0;
2457
    const char *p;
2458
    char *end;
2459

    
2460
    p = strchr(arg, ':');
2461
    if (p) {
2462
        x = strtol(arg, &end, 10);
2463
        if (end == p)
2464
            y = strtol(end+1, &end, 10);
2465
        if (x > 0 && y > 0)
2466
            ar = (double)x / (double)y;
2467
    } else
2468
        ar = strtod(arg, NULL);
2469

    
2470
    if (!ar) {
2471
        fprintf(stderr, "Incorrect aspect ratio specification.\n");
2472
        av_exit(1);
2473
    }
2474
    frame_aspect_ratio = ar;
2475
}
2476

    
2477
static void opt_qscale(const char *arg)
2478
{
2479
    video_qscale = atof(arg);
2480
    if (video_qscale <= 0 ||
2481
        video_qscale > 255) {
2482
        fprintf(stderr, "qscale must be > 0.0 and <= 255\n");
2483
        av_exit(1);
2484
    }
2485
}
2486

    
2487
static void opt_qdiff(const char *arg)
2488
{
2489
    video_qdiff = atoi(arg);
2490
    if (video_qdiff < 0 ||
2491
        video_qdiff > 31) {
2492
        fprintf(stderr, "qdiff must be >= 1 and <= 31\n");
2493
        av_exit(1);
2494
    }
2495
}
2496

    
2497
static void opt_strict(const char *arg)
2498
{
2499
    strict= atoi(arg);
2500
}
2501

    
2502
static void opt_top_field_first(const char *arg)
2503
{
2504
    top_field_first= atoi(arg);
2505
}
2506

    
2507
static void opt_thread_count(const char *arg)
2508
{
2509
    thread_count= atoi(arg);
2510
#if !defined(HAVE_THREADS)
2511
    if (verbose >= 0)
2512
        fprintf(stderr, "Warning: not compiled with thread support, using thread emulation\n");
2513
#endif
2514
}
2515

    
2516
static int opt_audio_rate(const char *opt, const char *arg)
2517
{
2518
    audio_sample_rate = parse_number_or_die(opt, arg, OPT_INT64, 0, INT_MAX);
2519
    return 0;
2520
}
2521

    
2522
static int opt_audio_channels(const char *opt, const char *arg)
2523
{
2524
    audio_channels = parse_number_or_die(opt, arg, OPT_INT64, 0, INT_MAX);
2525
    return 0;
2526
}
2527

    
2528
static void opt_video_channel(const char *arg)
2529
{
2530
    video_channel = strtol(arg, NULL, 0);
2531
}
2532

    
2533
static void opt_video_standard(const char *arg)
2534
{
2535
    video_standard = av_strdup(arg);
2536
}
2537

    
2538
static void opt_codec(int *pstream_copy, char **pcodec_name,
2539
                      int codec_type, const char *arg)
2540
{
2541
    av_freep(pcodec_name);
2542
    if (!strcmp(arg, "copy")) {
2543
        *pstream_copy = 1;
2544
    } else {
2545
        *pcodec_name = av_strdup(arg);
2546
    }
2547
}
2548

    
2549
static void opt_audio_codec(const char *arg)
2550
{
2551
    opt_codec(&audio_stream_copy, &audio_codec_name, CODEC_TYPE_AUDIO, arg);
2552
}
2553

    
2554
static void opt_audio_tag(const char *arg)
2555
{
2556
    char *tail;
2557
    audio_codec_tag= strtol(arg, &tail, 0);
2558

    
2559
    if(!tail || *tail)
2560
        audio_codec_tag= arg[0] + (arg[1]<<8) + (arg[2]<<16) + (arg[3]<<24);
2561
}
2562

    
2563
static void opt_video_tag(const char *arg)
2564
{
2565
    char *tail;
2566
    video_codec_tag= strtol(arg, &tail, 0);
2567

    
2568
    if(!tail || *tail)
2569
        video_codec_tag= arg[0] + (arg[1]<<8) + (arg[2]<<16) + (arg[3]<<24);
2570
}
2571

    
2572
#ifdef CONFIG_VHOOK
2573
static void add_frame_hooker(const char *arg)
2574
{
2575
    int argc = 0;
2576
    char *argv[64];
2577
    int i;
2578
    char *args = av_strdup(arg);
2579

    
2580
    using_vhook = 1;
2581

    
2582
    argv[0] = strtok(args, " ");
2583
    while (argc < 62 && (argv[++argc] = strtok(NULL, " "))) {
2584
    }
2585

    
2586
    i = frame_hook_add(argc, argv);
2587

    
2588
    if (i != 0) {
2589
        fprintf(stderr, "Failed to add video hook function: %s\n", arg);
2590
        av_exit(1);
2591
    }
2592
}
2593
#endif
2594

    
2595
static void opt_video_codec(const char *arg)
2596
{
2597
    opt_codec(&video_stream_copy, &video_codec_name, CODEC_TYPE_VIDEO, arg);
2598
}
2599

    
2600
static void opt_subtitle_codec(const char *arg)
2601
{
2602
    opt_codec(&subtitle_stream_copy, &subtitle_codec_name, CODEC_TYPE_SUBTITLE, arg);
2603
}
2604

    
2605
static void opt_map(const char *arg)
2606
{
2607
    AVStreamMap *m;
2608
    char *p;
2609

    
2610
    m = &stream_maps[nb_stream_maps++];
2611

    
2612
    m->file_index = strtol(arg, &p, 0);
2613
    if (*p)
2614
        p++;
2615

    
2616
    m->stream_index = strtol(p, &p, 0);
2617
    if (*p) {
2618
        p++;
2619
        m->sync_file_index = strtol(p, &p, 0);
2620
        if (*p)
2621
            p++;
2622
        m->sync_stream_index = strtol(p, &p, 0);
2623
    } else {
2624
        m->sync_file_index = m->file_index;
2625
        m->sync_stream_index = m->stream_index;
2626
    }
2627
}
2628

    
2629
static void opt_map_meta_data(const char *arg)
2630
{
2631
    AVMetaDataMap *m;
2632
    char *p;
2633

    
2634
    m = &meta_data_maps[nb_meta_data_maps++];
2635

    
2636
    m->out_file = strtol(arg, &p, 0);
2637
    if (*p)
2638
        p++;
2639

    
2640
    m->in_file = strtol(p, &p, 0);
2641
}
2642

    
2643
static int opt_recording_time(const char *opt, const char *arg)
2644
{
2645
    recording_time = parse_time_or_die(opt, arg, 1);
2646
    return 0;
2647
}
2648

    
2649
static int opt_start_time(const char *opt, const char *arg)
2650
{
2651
    start_time = parse_time_or_die(opt, arg, 1);
2652
    return 0;
2653
}
2654

    
2655
static int opt_rec_timestamp(const char *opt, const char *arg)
2656
{
2657
    rec_timestamp = parse_time_or_die(opt, arg, 0) / 1000000;
2658
    return 0;
2659
}
2660

    
2661
static int opt_input_ts_offset(const char *opt, const char *arg)
2662
{
2663
    input_ts_offset = parse_time_or_die(opt, arg, 1);
2664
    return 0;
2665
}
2666

    
2667
static enum CodecID find_codec_or_die(const char *name, int type, int encoder)
2668
{
2669
    const char *codec_string = encoder ? "encoder" : "decoder";
2670
    AVCodec *codec;
2671

    
2672
    if(!name)
2673
        return CODEC_ID_NONE;
2674
    codec = encoder ?
2675
        avcodec_find_encoder_by_name(name) :
2676
        avcodec_find_decoder_by_name(name);
2677
    if(!codec) {
2678
        av_log(NULL, AV_LOG_ERROR, "Unknown %s '%s'\n", codec_string, name);
2679
        av_exit(1);
2680
    }
2681
    if(codec->type != type) {
2682
        av_log(NULL, AV_LOG_ERROR, "Invalid %s type '%s'\n", codec_string, name);
2683
        av_exit(1);
2684
    }
2685
    return codec->id;
2686
}
2687

    
2688
static void opt_input_file(const char *filename)
2689
{
2690
    AVFormatContext *ic;
2691
    AVFormatParameters params, *ap = &params;
2692
    int err, i, ret, rfps, rfps_base;
2693
    int64_t timestamp;
2694

    
2695
    if (!strcmp(filename, "-"))
2696
        filename = "pipe:";
2697

    
2698
    using_stdin |= !strncmp(filename, "pipe:", 5) ||
2699
                   !strcmp( filename, "/dev/stdin" );
2700

    
2701
    /* get default parameters from command line */
2702
    ic = av_alloc_format_context();
2703

    
2704
    memset(ap, 0, sizeof(*ap));
2705
    ap->prealloced_context = 1;
2706
    ap->sample_rate = audio_sample_rate;
2707
    ap->channels = audio_channels;
2708
    ap->time_base.den = frame_rate.num;
2709
    ap->time_base.num = frame_rate.den;
2710
    ap->width = frame_width + frame_padleft + frame_padright;
2711
    ap->height = frame_height + frame_padtop + frame_padbottom;
2712
    ap->pix_fmt = frame_pix_fmt;
2713
    ap->channel = video_channel;
2714
    ap->standard = video_standard;
2715
    ap->video_codec_id = find_codec_or_die(video_codec_name, CODEC_TYPE_VIDEO, 0);
2716
    ap->audio_codec_id = find_codec_or_die(audio_codec_name, CODEC_TYPE_AUDIO, 0);
2717
    if(pgmyuv_compatibility_hack)
2718
        ap->video_codec_id= CODEC_ID_PGMYUV;
2719

    
2720
    for(i=0; i<opt_name_count; i++){
2721
        char buf[256];
2722
        const AVOption *opt;
2723
        const char *str= av_get_string(avformat_opts, opt_names[i], &opt, buf, sizeof(buf));
2724
        if(str && (opt->flags & AV_OPT_FLAG_DECODING_PARAM))
2725
            av_set_string(ic, opt_names[i], str);
2726
    }
2727

    
2728
    ic->video_codec_id   = find_codec_or_die(video_codec_name   , CODEC_TYPE_VIDEO   , 0);
2729
    ic->audio_codec_id   = find_codec_or_die(audio_codec_name   , CODEC_TYPE_AUDIO   , 0);
2730
    ic->subtitle_codec_id= find_codec_or_die(subtitle_codec_name, CODEC_TYPE_SUBTITLE, 0);
2731

    
2732
    /* open the input file with generic libav function */
2733
    err = av_open_input_file(&ic, filename, file_iformat, 0, ap);
2734
    if (err < 0) {
2735
        print_error(filename, err);
2736
        av_exit(1);
2737
    }
2738
    if(opt_programid) {
2739
        int i;
2740
        for(i=0; i<ic->nb_programs; i++)
2741
            if(ic->programs[i]->id != opt_programid)
2742
                ic->programs[i]->discard = AVDISCARD_ALL;
2743
    }
2744

    
2745
    ic->loop_input = loop_input;
2746

    
2747
    /* If not enough info to get the stream parameters, we decode the
2748
       first frames to get it. (used in mpeg case for example) */
2749
    ret = av_find_stream_info(ic);
2750
    if (ret < 0 && verbose >= 0) {
2751
        fprintf(stderr, "%s: could not find codec parameters\n", filename);
2752
        av_exit(1);
2753
    }
2754

    
2755
    timestamp = start_time;
2756
    /* add the stream start time */
2757
    if (ic->start_time != AV_NOPTS_VALUE)
2758
        timestamp += ic->start_time;
2759

    
2760
    /* if seeking requested, we execute it */
2761
    if (start_time != 0) {
2762
        ret = av_seek_frame(ic, -1, timestamp, AVSEEK_FLAG_BACKWARD);
2763
        if (ret < 0) {
2764
            fprintf(stderr, "%s: could not seek to position %0.3f\n",
2765
                    filename, (double)timestamp / AV_TIME_BASE);
2766
        }
2767
        /* reset seek info */
2768
        start_time = 0;
2769
    }
2770

    
2771
    /* update the current parameters so that they match the one of the input stream */
2772
    for(i=0;i<ic->nb_streams;i++) {
2773
        int j;
2774
        AVCodecContext *enc = ic->streams[i]->codec;
2775
        if(thread_count>1)
2776
            avcodec_thread_init(enc, thread_count);
2777
        enc->thread_count= thread_count;
2778
        switch(enc->codec_type) {
2779
        case CODEC_TYPE_AUDIO:
2780
            for(j=0; j<opt_name_count; j++){
2781
                char buf[256];
2782
                const AVOption *opt;
2783
                const char *str= av_get_string(avctx_opts[CODEC_TYPE_AUDIO], opt_names[j], &opt, buf, sizeof(buf));
2784
                if(str && (opt->flags & AV_OPT_FLAG_AUDIO_PARAM) && (opt->flags & AV_OPT_FLAG_DECODING_PARAM))
2785
                    av_set_string(enc, opt_names[j], str);
2786
            }
2787
            //fprintf(stderr, "\nInput Audio channels: %d", enc->channels);
2788
            audio_channels = enc->channels;
2789
            audio_sample_rate = enc->sample_rate;
2790
            if(audio_disable)
2791
                ic->streams[i]->discard= AVDISCARD_ALL;
2792
            break;
2793
        case CODEC_TYPE_VIDEO:
2794
            for(j=0; j<opt_name_count; j++){
2795
                char buf[256];
2796
                const AVOption *opt;
2797
                const char *str= av_get_string(avctx_opts[CODEC_TYPE_VIDEO], opt_names[j], &opt, buf, sizeof(buf));
2798
                if(str && (opt->flags & AV_OPT_FLAG_VIDEO_PARAM) && (opt->flags & AV_OPT_FLAG_DECODING_PARAM))
2799
                    av_set_string(enc, opt_names[j], str);
2800
            }
2801
            frame_height = enc->height;
2802
            frame_width = enc->width;
2803
            frame_aspect_ratio = av_q2d(enc->sample_aspect_ratio) * enc->width / enc->height;
2804
            frame_pix_fmt = enc->pix_fmt;
2805
            rfps      = ic->streams[i]->r_frame_rate.num;
2806
            rfps_base = ic->streams[i]->r_frame_rate.den;
2807
            if(enc->lowres) enc->flags |= CODEC_FLAG_EMU_EDGE;
2808
            if(me_threshold)
2809
                enc->debug |= FF_DEBUG_MV;
2810

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

    
2813
                if (verbose >= 0)
2814
                    fprintf(stderr,"\nSeems stream %d codec frame rate differs from container frame rate: %2.2f (%d/%d) -> %2.2f (%d/%d)\n",
2815
                            i, (float)enc->time_base.den / enc->time_base.num, enc->time_base.den, enc->time_base.num,
2816

    
2817
                    (float)rfps / rfps_base, rfps, rfps_base);
2818
            }
2819
            /* update the current frame rate to match the stream frame rate */
2820
            frame_rate.num = rfps;
2821
            frame_rate.den = rfps_base;
2822

    
2823
            enc->rate_emu = rate_emu;
2824
            if(video_disable)
2825
                ic->streams[i]->discard= AVDISCARD_ALL;
2826
            else if(video_discard)
2827
                ic->streams[i]->discard= video_discard;
2828
            break;
2829
        case CODEC_TYPE_DATA:
2830
            break;
2831
        case CODEC_TYPE_SUBTITLE:
2832
            if(subtitle_disable)
2833
                ic->streams[i]->discard = AVDISCARD_ALL;
2834
            break;
2835
        case CODEC_TYPE_ATTACHMENT:
2836
        case CODEC_TYPE_UNKNOWN:
2837
            break;
2838
        default:
2839
            abort();
2840
        }
2841
    }
2842

    
2843
    input_files[nb_input_files] = ic;
2844
    input_files_ts_offset[nb_input_files] = input_ts_offset - (copy_ts ? 0 : timestamp);
2845
    /* dump the file content */
2846
    if (verbose >= 0)
2847
        dump_format(ic, nb_input_files, filename, 0);
2848

    
2849
    nb_input_files++;
2850
    file_iformat = NULL;
2851
    file_oformat = NULL;
2852

    
2853
    video_channel = 0;
2854

    
2855
    rate_emu = 0;
2856
    av_freep(&video_codec_name);
2857
    av_freep(&audio_codec_name);
2858
    av_freep(&subtitle_codec_name);
2859
}
2860

    
2861
static void check_audio_video_sub_inputs(int *has_video_ptr, int *has_audio_ptr,
2862
                                         int *has_subtitle_ptr)
2863
{
2864
    int has_video, has_audio, has_subtitle, i, j;
2865
    AVFormatContext *ic;
2866

    
2867
    has_video = 0;
2868
    has_audio = 0;
2869
    has_subtitle = 0;
2870
    for(j=0;j<nb_input_files;j++) {
2871
        ic = input_files[j];
2872
        for(i=0;i<ic->nb_streams;i++) {
2873
            AVCodecContext *enc = ic->streams[i]->codec;
2874
            switch(enc->codec_type) {
2875
            case CODEC_TYPE_AUDIO:
2876
                has_audio = 1;
2877
                break;
2878
            case CODEC_TYPE_VIDEO:
2879
                has_video = 1;
2880
                break;
2881
            case CODEC_TYPE_SUBTITLE:
2882
                has_subtitle = 1;
2883
                break;
2884
            case CODEC_TYPE_DATA:
2885
            case CODEC_TYPE_ATTACHMENT:
2886
            case CODEC_TYPE_UNKNOWN:
2887
                break;
2888
            default:
2889
                abort();
2890
            }
2891
        }
2892
    }
2893
    *has_video_ptr = has_video;
2894
    *has_audio_ptr = has_audio;
2895
    *has_subtitle_ptr = has_subtitle;
2896
}
2897

    
2898
static void new_video_stream(AVFormatContext *oc)
2899
{
2900
    AVStream *st;
2901
    AVCodecContext *video_enc;
2902
    int codec_id;
2903

    
2904
    st = av_new_stream(oc, oc->nb_streams);
2905
    if (!st) {
2906
        fprintf(stderr, "Could not alloc stream\n");
2907
        av_exit(1);
2908
    }
2909
    avcodec_get_context_defaults2(st->codec, CODEC_TYPE_VIDEO);
2910
    bitstream_filters[nb_output_files][oc->nb_streams - 1]= video_bitstream_filters;
2911
    video_bitstream_filters= NULL;
2912

    
2913
    if(thread_count>1)
2914
        avcodec_thread_init(st->codec, thread_count);
2915

    
2916
    video_enc = st->codec;
2917

    
2918
    if(video_codec_tag)
2919
        video_enc->codec_tag= video_codec_tag;
2920

    
2921
    if(   (video_global_header&1)
2922
       || (video_global_header==0 && (oc->oformat->flags & AVFMT_GLOBALHEADER))){
2923
        video_enc->flags |= CODEC_FLAG_GLOBAL_HEADER;
2924
        avctx_opts[CODEC_TYPE_VIDEO]->flags|= CODEC_FLAG_GLOBAL_HEADER;
2925
    }
2926
    if(video_global_header&2){
2927
        video_enc->flags2 |= CODEC_FLAG2_LOCAL_HEADER;
2928
        avctx_opts[CODEC_TYPE_VIDEO]->flags2|= CODEC_FLAG2_LOCAL_HEADER;
2929
    }
2930

    
2931
    if (video_stream_copy) {
2932
        st->stream_copy = 1;
2933
        video_enc->codec_type = CODEC_TYPE_VIDEO;
2934
    } else {
2935
        const char *p;
2936
        int i;
2937
        AVCodec *codec;
2938
        AVRational fps= frame_rate.num ? frame_rate : (AVRational){25,1};
2939

    
2940
        codec_id = av_guess_codec(oc->oformat, NULL, oc->filename, NULL, CODEC_TYPE_VIDEO);
2941
        if (video_codec_name)
2942
            codec_id = find_codec_or_die(video_codec_name, CODEC_TYPE_VIDEO, 1);
2943

    
2944
        video_enc->codec_id = codec_id;
2945
        codec = avcodec_find_encoder(codec_id);
2946

    
2947
        for(i=0; i<opt_name_count; i++){
2948
            char buf[256];
2949
            const AVOption *opt;
2950
            const char *str= av_get_string(avctx_opts[CODEC_TYPE_VIDEO], opt_names[i], &opt, buf, sizeof(buf));
2951
            if(str && (opt->flags & AV_OPT_FLAG_VIDEO_PARAM) && (opt->flags & AV_OPT_FLAG_ENCODING_PARAM))
2952
                av_set_string(video_enc, opt_names[i], str);
2953
        }
2954

    
2955
        video_enc->time_base.den = fps.num;
2956
        video_enc->time_base.num = fps.den;
2957
        if(codec && codec->supported_framerates){
2958
            const AVRational *p= codec->supported_framerates;
2959
            const AVRational *best=NULL;
2960
            AVRational best_error= (AVRational){INT_MAX, 1};
2961
            for(; p->den!=0; p++){
2962
                AVRational error= av_sub_q(fps, *p);
2963
                if(error.num <0) error.num *= -1;
2964
                if(av_cmp_q(error, best_error) < 0){
2965
                    best_error= error;
2966
                    best= p;
2967
                }
2968
            }
2969
            video_enc->time_base.den= best->num;
2970
            video_enc->time_base.num= best->den;
2971
        }
2972

    
2973
        video_enc->width = frame_width + frame_padright + frame_padleft;
2974
        video_enc->height = frame_height + frame_padtop + frame_padbottom;
2975
        video_enc->sample_aspect_ratio = av_d2q(frame_aspect_ratio*video_enc->height/video_enc->width, 255);
2976
        video_enc->pix_fmt = frame_pix_fmt;
2977

    
2978
        if(codec && codec->pix_fmts){
2979
            const enum PixelFormat *p= codec->pix_fmts;
2980
            for(; *p!=-1; p++){
2981
                if(*p == video_enc->pix_fmt)
2982
                    break;
2983
            }
2984
            if(*p == -1)
2985
                video_enc->pix_fmt = codec->pix_fmts[0];
2986
        }
2987

    
2988
        if (intra_only)
2989
            video_enc->gop_size = 0;
2990
        if (video_qscale || same_quality) {
2991
            video_enc->flags |= CODEC_FLAG_QSCALE;
2992
            video_enc->global_quality=
2993
                st->quality = FF_QP2LAMBDA * video_qscale;
2994
        }
2995

    
2996
        if(intra_matrix)
2997
            video_enc->intra_matrix = intra_matrix;
2998
        if(inter_matrix)
2999
            video_enc->inter_matrix = inter_matrix;
3000

    
3001
        video_enc->max_qdiff = video_qdiff;
3002
        video_enc->thread_count = thread_count;
3003
        p= video_rc_override_string;
3004
        for(i=0; p; i++){
3005
            int start, end, q;
3006
            int e=sscanf(p, "%d,%d,%d", &start, &end, &q);
3007
            if(e!=3){
3008
                fprintf(stderr, "error parsing rc_override\n");
3009
                av_exit(1);
3010
            }
3011
            video_enc->rc_override=
3012
                av_realloc(video_enc->rc_override,
3013
                           sizeof(RcOverride)*(i+1));
3014
            video_enc->rc_override[i].start_frame= start;
3015
            video_enc->rc_override[i].end_frame  = end;
3016
            if(q>0){
3017
                video_enc->rc_override[i].qscale= q;
3018
                video_enc->rc_override[i].quality_factor= 1.0;
3019
            }
3020
            else{
3021
                video_enc->rc_override[i].qscale= 0;
3022
                video_enc->rc_override[i].quality_factor= -q/100.0;
3023
            }
3024
            p= strchr(p, '/');
3025
            if(p) p++;
3026
        }
3027
        video_enc->rc_override_count=i;
3028
        if (!video_enc->rc_initial_buffer_occupancy)
3029
            video_enc->rc_initial_buffer_occupancy = video_enc->rc_buffer_size*3/4;
3030
        video_enc->me_threshold= me_threshold;
3031
        video_enc->intra_dc_precision= intra_dc_precision - 8;
3032
        video_enc->strict_std_compliance = strict;
3033

    
3034
        if (do_psnr)
3035
            video_enc->flags|= CODEC_FLAG_PSNR;
3036

    
3037
        /* two pass mode */
3038
        if (do_pass) {
3039
            if (do_pass == 1) {
3040
                video_enc->flags |= CODEC_FLAG_PASS1;
3041
            } else {
3042
                video_enc->flags |= CODEC_FLAG_PASS2;
3043
            }
3044
        }
3045
    }
3046

    
3047
    /* reset some key parameters */
3048
    video_disable = 0;
3049
    av_freep(&video_codec_name);
3050
    video_stream_copy = 0;
3051
}
3052

    
3053
static void new_audio_stream(AVFormatContext *oc)
3054
{
3055
    AVStream *st;
3056
    AVCodecContext *audio_enc;
3057
    int codec_id, i;
3058

    
3059
    st = av_new_stream(oc, oc->nb_streams);
3060
    if (!st) {
3061
        fprintf(stderr, "Could not alloc stream\n");
3062
        av_exit(1);
3063
    }
3064
    avcodec_get_context_defaults2(st->codec, CODEC_TYPE_AUDIO);
3065

    
3066
    bitstream_filters[nb_output_files][oc->nb_streams - 1]= audio_bitstream_filters;
3067
    audio_bitstream_filters= NULL;
3068

    
3069
    if(thread_count>1)
3070
        avcodec_thread_init(st->codec, thread_count);
3071

    
3072
    audio_enc = st->codec;
3073
    audio_enc->codec_type = CODEC_TYPE_AUDIO;
3074
    audio_enc->strict_std_compliance = strict;
3075

    
3076
    if(audio_codec_tag)
3077
        audio_enc->codec_tag= audio_codec_tag;
3078

    
3079
    if (oc->oformat->flags & AVFMT_GLOBALHEADER) {
3080
        audio_enc->flags |= CODEC_FLAG_GLOBAL_HEADER;
3081
        avctx_opts[CODEC_TYPE_AUDIO]->flags|= CODEC_FLAG_GLOBAL_HEADER;
3082
    }
3083
    if (audio_stream_copy) {
3084
        st->stream_copy = 1;
3085
        audio_enc->channels = audio_channels;
3086
    } else {
3087
        codec_id = av_guess_codec(oc->oformat, NULL, oc->filename, NULL, CODEC_TYPE_AUDIO);
3088

    
3089
        for(i=0; i<opt_name_count; i++){
3090
            char buf[256];
3091
            const AVOption *opt;
3092
            const char *str= av_get_string(avctx_opts[CODEC_TYPE_AUDIO], opt_names[i], &opt, buf, sizeof(buf));
3093
            if(str && (opt->flags & AV_OPT_FLAG_AUDIO_PARAM) && (opt->flags & AV_OPT_FLAG_ENCODING_PARAM))
3094
                av_set_string(audio_enc, opt_names[i], str);
3095
        }
3096

    
3097
        if (audio_codec_name)
3098
            codec_id = find_codec_or_die(audio_codec_name, CODEC_TYPE_AUDIO, 1);
3099
        audio_enc->codec_id = codec_id;
3100

    
3101
        if (audio_qscale > QSCALE_NONE) {
3102
            audio_enc->flags |= CODEC_FLAG_QSCALE;
3103
            audio_enc->global_quality = st->quality = FF_QP2LAMBDA * audio_qscale;
3104
        }
3105
        audio_enc->thread_count = thread_count;
3106
        audio_enc->channels = audio_channels;
3107
    }
3108
    audio_enc->sample_rate = audio_sample_rate;
3109
    audio_enc->time_base= (AVRational){1, audio_sample_rate};
3110
    if (audio_language) {
3111
        av_strlcpy(st->language, audio_language, sizeof(st->language));
3112
        av_free(audio_language);
3113
        audio_language = NULL;
3114
    }
3115

    
3116
    /* reset some key parameters */
3117
    audio_disable = 0;
3118
    av_freep(&audio_codec_name);
3119
    audio_stream_copy = 0;
3120
}
3121

    
3122
static void new_subtitle_stream(AVFormatContext *oc)
3123
{
3124
    AVStream *st;
3125
    AVCodecContext *subtitle_enc;
3126
    int i;
3127

    
3128
    st = av_new_stream(oc, oc->nb_streams);
3129
    if (!st) {
3130
        fprintf(stderr, "Could not alloc stream\n");
3131
        av_exit(1);
3132
    }
3133
    avcodec_get_context_defaults2(st->codec, CODEC_TYPE_SUBTITLE);
3134

    
3135
    bitstream_filters[nb_output_files][oc->nb_streams - 1]= subtitle_bitstream_filters;
3136
    subtitle_bitstream_filters= NULL;
3137

    
3138
    subtitle_enc = st->codec;
3139
    subtitle_enc->codec_type = CODEC_TYPE_SUBTITLE;
3140
    if (subtitle_stream_copy) {
3141
        st->stream_copy = 1;
3142
    } else {
3143
        for(i=0; i<opt_name_count; i++){
3144
            char buf[256];
3145
            const AVOption *opt;
3146
            const char *str= av_get_string(avctx_opts[CODEC_TYPE_SUBTITLE], opt_names[i], &opt, buf, sizeof(buf));
3147
            if(str && (opt->flags & AV_OPT_FLAG_SUBTITLE_PARAM) && (opt->flags & AV_OPT_FLAG_ENCODING_PARAM))
3148
                av_set_string(subtitle_enc, opt_names[i], str);
3149
        }
3150
        subtitle_enc->codec_id = find_codec_or_die(subtitle_codec_name, CODEC_TYPE_SUBTITLE, 1);
3151
    }
3152

    
3153
    if (subtitle_language) {
3154
        av_strlcpy(st->language, subtitle_language, sizeof(st->language));
3155
        av_free(subtitle_language);
3156
        subtitle_language = NULL;
3157
    }
3158

    
3159
    subtitle_disable = 0;
3160
    av_freep(&subtitle_codec_name);
3161
    subtitle_stream_copy = 0;
3162
}
3163

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

    
3175
static void opt_new_video_stream(void)
3176
{
3177
    AVFormatContext *oc;
3178
    if (nb_output_files <= 0) {
3179
        fprintf(stderr, "At least one output file must be specified\n");
3180
        av_exit(1);
3181
    }
3182
    oc = output_files[nb_output_files - 1];
3183
    new_video_stream(oc);
3184
}
3185

    
3186
static void opt_new_subtitle_stream(void)
3187
{
3188
    AVFormatContext *oc;
3189
    if (nb_output_files <= 0) {
3190
        fprintf(stderr, "At least one output file must be specified\n");
3191
        av_exit(1);
3192
    }
3193
    oc = output_files[nb_output_files - 1];
3194
    new_subtitle_stream(oc);
3195
}
3196

    
3197
static void opt_output_file(const char *filename)
3198
{
3199
    AVFormatContext *oc;
3200
    int use_video, use_audio, use_subtitle;
3201
    int input_has_video, input_has_audio, input_has_subtitle, i;
3202
    AVFormatParameters params, *ap = &params;
3203

    
3204
    if (!strcmp(filename, "-"))
3205
        filename = "pipe:";
3206

    
3207
    oc = av_alloc_format_context();
3208

    
3209
    if (!file_oformat) {
3210
        file_oformat = guess_format(NULL, filename, NULL);
3211
        if (!file_oformat) {
3212
            fprintf(stderr, "Unable to find a suitable output format for '%s'\n",
3213
                    filename);
3214
            av_exit(1);
3215
        }
3216
    }
3217

    
3218
    oc->oformat = file_oformat;
3219
    av_strlcpy(oc->filename, filename, sizeof(oc->filename));
3220

    
3221
    if (!strcmp(file_oformat->name, "ffm") &&
3222
        av_strstart(filename, "http:", NULL)) {
3223
        /* special case for files sent to ffserver: we get the stream
3224
           parameters from ffserver */
3225
        if (read_ffserver_streams(oc, filename) < 0) {
3226
            fprintf(stderr, "Could not read stream parameters from '%s'\n", filename);
3227
            av_exit(1);
3228
        }
3229
    } else {
3230
        use_video = file_oformat->video_codec != CODEC_ID_NONE || video_stream_copy || video_codec_name;
3231
        use_audio = file_oformat->audio_codec != CODEC_ID_NONE || audio_stream_copy || audio_codec_name;
3232
        use_subtitle = file_oformat->subtitle_codec != CODEC_ID_NONE || subtitle_stream_copy || subtitle_codec_name;
3233

    
3234
        /* disable if no corresponding type found and at least one
3235
           input file */
3236
        if (nb_input_files > 0) {
3237
            check_audio_video_sub_inputs(&input_has_video, &input_has_audio,
3238
                                         &input_has_subtitle);
3239
            if (!input_has_video)
3240
                use_video = 0;
3241
            if (!input_has_audio)
3242
                use_audio = 0;
3243
            if (!input_has_subtitle)
3244
                use_subtitle = 0;
3245
        }
3246

    
3247
        /* manual disable */
3248
        if (audio_disable) {
3249
            use_audio = 0;
3250
        }
3251
        if (video_disable) {
3252
            use_video = 0;
3253
        }
3254
        if (subtitle_disable) {
3255
            use_subtitle = 0;
3256
        }
3257

    
3258
        if (use_video) {
3259
            new_video_stream(oc);
3260
        }
3261

    
3262
        if (use_audio) {
3263
            new_audio_stream(oc);
3264
        }
3265

    
3266
        if (use_subtitle) {
3267
            new_subtitle_stream(oc);
3268
        }
3269

    
3270
        oc->timestamp = rec_timestamp;
3271

    
3272
        if (str_title)
3273
            av_strlcpy(oc->title, str_title, sizeof(oc->title));
3274
        if (str_author)
3275
            av_strlcpy(oc->author, str_author, sizeof(oc->author));
3276
        if (str_copyright)
3277
            av_strlcpy(oc->copyright, str_copyright, sizeof(oc->copyright));
3278
        if (str_comment)
3279
            av_strlcpy(oc->comment, str_comment, sizeof(oc->comment));
3280
        if (str_album)
3281
            av_strlcpy(oc->album, str_album, sizeof(oc->album));
3282
        if (str_genre)
3283
            av_strlcpy(oc->genre, str_genre, sizeof(oc->genre));
3284
    }
3285

    
3286
    output_files[nb_output_files++] = oc;
3287

    
3288
    /* check filename in case of an image number is expected */
3289
    if (oc->oformat->flags & AVFMT_NEEDNUMBER) {
3290
        if (!av_filename_number_test(oc->filename)) {
3291
            print_error(oc->filename, AVERROR_NUMEXPECTED);
3292
            av_exit(1);
3293
        }
3294
    }
3295

    
3296
    if (!(oc->oformat->flags & AVFMT_NOFILE)) {
3297
        /* test if it already exists to avoid loosing precious files */
3298
        if (!file_overwrite &&
3299
            (strchr(filename, ':') == NULL ||
3300
             filename[1] == ':' ||
3301
             av_strstart(filename, "file:", NULL))) {
3302
            if (url_exist(filename)) {
3303
                int c;
3304

    
3305
                if ( !using_stdin ) {
3306
                    fprintf(stderr,"File '%s' already exists. Overwrite ? [y/N] ", filename);
3307
                    fflush(stderr);
3308
                    c = getchar();
3309
                    if (toupper(c) != 'Y') {
3310
                        fprintf(stderr, "Not overwriting - exiting\n");
3311
                        av_exit(1);
3312
                    }
3313
                                }
3314
                                else {
3315
                    fprintf(stderr,"File '%s' already exists. Exiting.\n", filename);
3316
                    av_exit(1);
3317
                                }
3318
            }
3319
        }
3320

    
3321
        /* open the file */
3322
        if (url_fopen(&oc->pb, filename, URL_WRONLY) < 0) {
3323
            fprintf(stderr, "Could not open '%s'\n", filename);
3324
            av_exit(1);
3325
        }
3326
    }
3327

    
3328
    memset(ap, 0, sizeof(*ap));
3329
    if (av_set_parameters(oc, ap) < 0) {
3330
        fprintf(stderr, "%s: Invalid encoding parameters\n",
3331
                oc->filename);
3332
        av_exit(1);
3333
    }
3334

    
3335
    oc->preload= (int)(mux_preload*AV_TIME_BASE);
3336
    oc->max_delay= (int)(mux_max_delay*AV_TIME_BASE);
3337
    oc->loop_output = loop_output;
3338

    
3339
    for(i=0; i<opt_name_count; i++){
3340
        char buf[256];
3341
        const AVOption *opt;
3342
        const char *str= av_get_string(avformat_opts, opt_names[i], &opt, buf, sizeof(buf));
3343
        if(str && (opt->flags & AV_OPT_FLAG_ENCODING_PARAM))
3344
            av_set_string(oc, opt_names[i], str);
3345
    }
3346

    
3347
    /* reset some options */
3348
    file_oformat = NULL;
3349
    file_iformat = NULL;
3350
}
3351

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

    
3364
static int64_t getutime(void)
3365
{
3366
#ifdef HAVE_GETRUSAGE
3367
    struct rusage rusage;
3368

    
3369
    getrusage(RUSAGE_SELF, &rusage);
3370
    return (rusage.ru_utime.tv_sec * 1000000LL) + rusage.ru_utime.tv_usec;
3371
#elif defined(HAVE_GETPROCESSTIMES)
3372
    HANDLE proc;
3373
    FILETIME c, e, k, u;
3374
    proc = GetCurrentProcess();
3375
    GetProcessTimes(proc, &c, &e, &k, &u);
3376
    return ((int64_t) u.dwHighDateTime << 32 | u.dwLowDateTime) / 10;
3377
#else
3378
    return av_gettime();
3379
#endif
3380
}
3381

    
3382
static void parse_matrix_coeffs(uint16_t *dest, const char *str)
3383
{
3384
    int i;
3385
    const char *p = str;
3386
    for(i = 0;; i++) {
3387
        dest[i] = atoi(p);
3388
        if(i == 63)
3389
            break;
3390
        p = strchr(p, ',');
3391
        if(!p) {
3392
            fprintf(stderr, "Syntax error in matrix \"%s\" at coeff %d\n", str, i);
3393
            av_exit(1);
3394
        }
3395
        p++;
3396
    }
3397
}
3398

    
3399
static void opt_inter_matrix(const char *arg)
3400
{
3401
    inter_matrix = av_mallocz(sizeof(uint16_t) * 64);
3402
    parse_matrix_coeffs(inter_matrix, arg);
3403
}
3404

    
3405
static void opt_intra_matrix(const char *arg)
3406
{
3407
    intra_matrix = av_mallocz(sizeof(uint16_t) * 64);
3408
    parse_matrix_coeffs(intra_matrix, arg);
3409
}
3410

    
3411
/**
3412
 * Trivial log callback.
3413
 * Only suitable for show_help and similar since it lacks prefix handling.
3414
 */
3415
static void log_callback_help(void* ptr, int level, const char* fmt, va_list vl)
3416
{
3417
    vfprintf(stdout, fmt, vl);
3418
}
3419

    
3420
static void show_help(void)
3421
{
3422
    av_log_set_callback(log_callback_help);
3423
    printf("usage: ffmpeg [[infile options] -i infile]... {[outfile options] outfile}...\n"
3424
           "Hyper fast Audio and Video encoder\n");
3425
    printf("\n");
3426
    show_help_options(options, "Main options:\n",
3427
                      OPT_EXPERT | OPT_AUDIO | OPT_VIDEO, 0);
3428
    show_help_options(options, "\nVideo options:\n",
3429
                      OPT_EXPERT | OPT_AUDIO | OPT_VIDEO | OPT_GRAB,
3430
                      OPT_VIDEO);
3431
    show_help_options(options, "\nAdvanced Video options:\n",
3432
                      OPT_EXPERT | OPT_AUDIO | OPT_VIDEO | OPT_GRAB,
3433
                      OPT_VIDEO | OPT_EXPERT);
3434
    show_help_options(options, "\nAudio options:\n",
3435
                      OPT_EXPERT | OPT_AUDIO | OPT_VIDEO | OPT_GRAB,
3436
                      OPT_AUDIO);
3437
    show_help_options(options, "\nAdvanced Audio options:\n",
3438
                      OPT_EXPERT | OPT_AUDIO | OPT_VIDEO | OPT_GRAB,
3439
                      OPT_AUDIO | OPT_EXPERT);
3440
    show_help_options(options, "\nSubtitle options:\n",
3441
                      OPT_SUBTITLE | OPT_GRAB,
3442
                      OPT_SUBTITLE);
3443
    show_help_options(options, "\nAudio/Video grab options:\n",
3444
                      OPT_GRAB,
3445
                      OPT_GRAB);
3446
    show_help_options(options, "\nAdvanced options:\n",
3447
                      OPT_EXPERT | OPT_AUDIO | OPT_VIDEO | OPT_GRAB,
3448
                      OPT_EXPERT);
3449
    av_opt_show(avctx_opts[0], NULL);
3450
    av_opt_show(avformat_opts, NULL);
3451
    av_opt_show(sws_opts, NULL);
3452
}
3453

    
3454
static void opt_target(const char *arg)
3455
{
3456
    int norm = -1;
3457
    static const char *const frame_rates[] = {"25", "30000/1001", "24000/1001"};
3458

    
3459
    if(!strncmp(arg, "pal-", 4)) {
3460
        norm = 0;
3461
        arg += 4;
3462
    } else if(!strncmp(arg, "ntsc-", 5)) {
3463
        norm = 1;
3464
        arg += 5;
3465
    } else if(!strncmp(arg, "film-", 5)) {
3466
        norm = 2;
3467
        arg += 5;
3468
    } else {
3469
        int fr;
3470
        /* Calculate FR via float to avoid int overflow */
3471
        fr = (int)(frame_rate.num * 1000.0 / frame_rate.den);
3472
        if(fr == 25000) {
3473
            norm = 0;
3474
        } else if((fr == 29970) || (fr == 23976)) {
3475
            norm = 1;
3476
        } else {
3477
            /* Try to determine PAL/NTSC by peeking in the input files */
3478
            if(nb_input_files) {
3479
                int i, j;
3480
                for(j = 0; j < nb_input_files; j++) {
3481
                    for(i = 0; i < input_files[j]->nb_streams; i++) {
3482
                        AVCodecContext *c = input_files[j]->streams[i]->codec;
3483
                        if(c->codec_type != CODEC_TYPE_VIDEO)
3484
                            continue;
3485
                        fr = c->time_base.den * 1000 / c->time_base.num;
3486
                        if(fr == 25000) {
3487
                            norm = 0;
3488
                            break;
3489
                        } else if((fr == 29970) || (fr == 23976)) {
3490
                            norm = 1;
3491
                            break;
3492
                        }
3493
                    }
3494
                    if(norm >= 0)
3495
                        break;
3496
                }
3497
            }
3498
        }
3499
        if(verbose && norm >= 0)
3500
            fprintf(stderr, "Assuming %s for target.\n", norm ? "NTSC" : "PAL");
3501
    }
3502

    
3503
    if(norm < 0) {
3504
        fprintf(stderr, "Could not determine norm (PAL/NTSC/NTSC-Film) for target.\n");
3505
        fprintf(stderr, "Please prefix target with \"pal-\", \"ntsc-\" or \"film-\",\n");
3506
        fprintf(stderr, "or set a framerate with \"-r xxx\".\n");
3507
        av_exit(1);
3508
    }
3509

    
3510
    if(!strcmp(arg, "vcd")) {
3511

    
3512
        opt_video_codec("mpeg1video");
3513
        opt_audio_codec("mp2");
3514
        opt_format("vcd");
3515

    
3516
        opt_frame_size(norm ? "352x240" : "352x288");
3517
        opt_frame_rate(frame_rates[norm]);
3518
        opt_default("gop", norm ? "18" : "15");
3519

    
3520
        opt_default("b", "1150000");
3521
        opt_default("maxrate", "1150000");
3522
        opt_default("minrate", "1150000");
3523
        opt_default("bufsize", "327680"); // 40*1024*8;
3524

    
3525
        opt_default("ab", "224000");
3526
        audio_sample_rate = 44100;
3527
        audio_channels = 2;
3528

    
3529
        opt_default("packetsize", "2324");
3530
        opt_default("muxrate", "1411200"); // 2352 * 75 * 8;
3531

    
3532
        /* We have to offset the PTS, so that it is consistent with the SCR.
3533
           SCR starts at 36000, but the first two packs contain only padding
3534
           and the first pack from the other stream, respectively, may also have
3535
           been written before.
3536
           So the real data starts at SCR 36000+3*1200. */
3537
        mux_preload= (36000+3*1200) / 90000.0; //0.44
3538
    } else if(!strcmp(arg, "svcd")) {
3539

    
3540
        opt_video_codec("mpeg2video");
3541
        opt_audio_codec("mp2");
3542
        opt_format("svcd");
3543

    
3544
        opt_frame_size(norm ? "480x480" : "480x576");
3545
        opt_frame_rate(frame_rates[norm]);
3546
        opt_default("gop", norm ? "18" : "15");
3547

    
3548
        opt_default("b", "2040000");
3549
        opt_default("maxrate", "2516000");
3550
        opt_default("minrate", "0"); //1145000;
3551
        opt_default("bufsize", "1835008"); //224*1024*8;
3552
        opt_default("flags", "+SCAN_OFFSET");
3553

    
3554

    
3555
        opt_default("ab", "224000");
3556
        audio_sample_rate = 44100;
3557

    
3558
        opt_default("packetsize", "2324");
3559

    
3560
    } else if(!strcmp(arg, "dvd")) {
3561

    
3562
        opt_video_codec("mpeg2video");
3563
        opt_audio_codec("ac3");
3564
        opt_format("dvd");
3565

    
3566
        opt_frame_size(norm ? "720x480" : "720x576");
3567
        opt_frame_rate(frame_rates[norm]);
3568
        opt_default("gop", norm ? "18" : "15");
3569

    
3570
        opt_default("b", "6000000");
3571
        opt_default("maxrate", "9000000");
3572
        opt_default("minrate", "0"); //1500000;
3573
        opt_default("bufsize", "1835008"); //224*1024*8;
3574

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

    
3578
        opt_default("ab", "448000");
3579
        audio_sample_rate = 48000;
3580

    
3581
    } else if(!strncmp(arg, "dv", 2)) {
3582

    
3583
        opt_format("dv");
3584

    
3585
        opt_frame_size(norm ? "720x480" : "720x576");
3586
        opt_frame_pix_fmt(!strncmp(arg, "dv50", 4) ? "yuv422p" :
3587
                                             (norm ? "yuv411p" : "yuv420p"));
3588
        opt_frame_rate(frame_rates[norm]);
3589

    
3590
        audio_sample_rate = 48000;
3591
        audio_channels = 2;
3592

    
3593
    } else {
3594
        fprintf(stderr, "Unknown target: %s\n", arg);
3595
        av_exit(1);
3596
    }
3597
}
3598

    
3599
static void opt_vstats_file (const char *arg)
3600
{
3601
    av_free (vstats_filename);
3602
    vstats_filename=av_strdup (arg);
3603
}
3604

    
3605
static void opt_vstats (void)
3606
{
3607
    char filename[40];
3608
    time_t today2 = time(NULL);
3609
    struct tm *today = localtime(&today2);
3610

    
3611
    snprintf(filename, sizeof(filename), "vstats_%02d%02d%02d.log", today->tm_hour, today->tm_min,
3612
             today->tm_sec);
3613
    opt_vstats_file(filename);
3614
}
3615

    
3616
static int opt_bsf(const char *opt, const char *arg)
3617
{
3618
    AVBitStreamFilterContext *bsfc= av_bitstream_filter_init(arg); //FIXME split name and args for filter at '='
3619
    AVBitStreamFilterContext **bsfp;
3620

    
3621
    if(!bsfc){
3622
        fprintf(stderr, "Unknown bitstream filter %s\n", arg);
3623
        av_exit(1);
3624
    }
3625

    
3626
    bsfp= *opt == 'v' ? &video_bitstream_filters :
3627
          *opt == 'a' ? &audio_bitstream_filters :
3628
                        &subtitle_bitstream_filters;
3629
    while(*bsfp)
3630
        bsfp= &(*bsfp)->next;
3631

    
3632
    *bsfp= bsfc;
3633

    
3634
    return 0;
3635
}
3636

    
3637
static const OptionDef options[] = {
3638
    /* main options */
3639
    { "L", OPT_EXIT, {(void*)show_license}, "show license" },
3640
    { "h", OPT_EXIT, {(void*)show_help}, "show help" },
3641
    { "version", OPT_EXIT, {(void*)show_version}, "show version" },
3642
    { "formats", OPT_EXIT, {(void*)show_formats}, "show available formats, codecs, protocols, ..." },
3643
    { "f", HAS_ARG, {(void*)opt_format}, "force format", "fmt" },
3644
    { "i", HAS_ARG, {(void*)opt_input_file}, "input file name", "filename" },
3645
    { "y", OPT_BOOL, {(void*)&file_overwrite}, "overwrite output files" },
3646
    { "map", HAS_ARG | OPT_EXPERT, {(void*)opt_map}, "set input stream mapping", "file:stream[:syncfile:syncstream]" },
3647
    { "map_meta_data", HAS_ARG | OPT_EXPERT, {(void*)opt_map_meta_data}, "set meta data information of outfile from infile", "outfile:infile" },
3648
    { "t", OPT_FUNC2 | HAS_ARG, {(void*)opt_recording_time}, "record or transcode \"duration\" seconds of audio/video", "duration" },
3649
    { "fs", HAS_ARG | OPT_INT64, {(void*)&limit_filesize}, "set the limit file size in bytes", "limit_size" }, //
3650
    { "ss", OPT_FUNC2 | HAS_ARG, {(void*)opt_start_time}, "set the start time offset", "time_off" },
3651
    { "itsoffset", OPT_FUNC2 | HAS_ARG, {(void*)opt_input_ts_offset}, "set the input ts offset", "time_off" },
3652
    { "title", HAS_ARG | OPT_STRING, {(void*)&str_title}, "set the title", "string" },
3653
    { "timestamp", OPT_FUNC2 | HAS_ARG, {(void*)&opt_rec_timestamp}, "set the timestamp", "time" },
3654
    { "author", HAS_ARG | OPT_STRING, {(void*)&str_author}, "set the author", "string" },
3655
    { "copyright", HAS_ARG | OPT_STRING, {(void*)&str_copyright}, "set the copyright", "string" },
3656
    { "comment", HAS_ARG | OPT_STRING, {(void*)&str_comment}, "set the comment", "string" },
3657
    { "genre", HAS_ARG | OPT_STRING, {(void*)&str_genre}, "set the genre", "string" },
3658
    { "album", HAS_ARG | OPT_STRING, {(void*)&str_album}, "set the album", "string" },
3659
    { "benchmark", OPT_BOOL | OPT_EXPERT, {(void*)&do_benchmark},
3660
      "add timings for benchmarking" },
3661
    { "dump", OPT_BOOL | OPT_EXPERT, {(void*)&do_pkt_dump},
3662
      "dump each input packet" },
3663
    { "hex", OPT_BOOL | OPT_EXPERT, {(void*)&do_hex_dump},
3664
      "when dumping packets, also dump the payload" },
3665
    { "re", OPT_BOOL | OPT_EXPERT, {(void*)&rate_emu}, "read input at native frame rate", "" },
3666
    { "loop_input", OPT_BOOL | OPT_EXPERT, {(void*)&loop_input}, "loop (current only works with images)" },
3667
    { "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)", "" },
3668
    { "v", HAS_ARG | OPT_FUNC2, {(void*)opt_verbose}, "set the logging verbosity level", "number" },
3669
    { "target", HAS_ARG, {(void*)opt_target}, "specify target file type (\"vcd\", \"svcd\", \"dvd\", \"dv\", \"dv50\", \"pal-vcd\", \"ntsc-svcd\", ...)", "type" },
3670
    { "threads", HAS_ARG | OPT_EXPERT, {(void*)opt_thread_count}, "thread count", "count" },
3671
    { "vsync", HAS_ARG | OPT_INT | OPT_EXPERT, {(void*)&video_sync_method}, "video sync method", "" },
3672
    { "async", HAS_ARG | OPT_INT | OPT_EXPERT, {(void*)&audio_sync_method}, "audio sync method", "" },
3673
    { "adrift_threshold", HAS_ARG | OPT_FLOAT | OPT_EXPERT, {(void*)&audio_drift_threshold}, "audio drift threshold", "threshold" },
3674
    { "vglobal", HAS_ARG | OPT_INT | OPT_EXPERT, {(void*)&video_global_header}, "video global header storage type", "" },
3675
    { "copyts", OPT_BOOL | OPT_EXPERT, {(void*)&copy_ts}, "copy timestamps" },
3676
    { "shortest", OPT_BOOL | OPT_EXPERT, {(void*)&opt_shortest}, "finish encoding within shortest input" }, //
3677
    { "dts_delta_threshold", HAS_ARG | OPT_FLOAT | OPT_EXPERT, {(void*)&dts_delta_threshold}, "timestamp discontinuity delta threshold", "threshold" },
3678
    { "programid", HAS_ARG | OPT_INT | OPT_EXPERT, {(void*)&opt_programid}, "desired program number", "" },
3679

    
3680
    /* video options */
3681
    { "b", OPT_FUNC2 | HAS_ARG | OPT_VIDEO, {(void*)opt_bitrate}, "set bitrate (in bits/s)", "bitrate" },
3682
    { "vb", OPT_FUNC2 | HAS_ARG | OPT_VIDEO, {(void*)opt_bitrate}, "set bitrate (in bits/s)", "bitrate" },
3683
    { "vframes", OPT_INT | HAS_ARG | OPT_VIDEO, {(void*)&max_frames[CODEC_TYPE_VIDEO]}, "set the number of video frames to record", "number" },
3684
    { "dframes", OPT_INT | HAS_ARG, {(void*)&max_frames[CODEC_TYPE_DATA]}, "set the number of data frames to record", "number" },
3685
    { "r", HAS_ARG | OPT_VIDEO, {(void*)opt_frame_rate}, "set frame rate (Hz value, fraction or abbreviation)", "rate" },
3686
    { "s", HAS_ARG | OPT_VIDEO, {(void*)opt_frame_size}, "set frame size (WxH or abbreviation)", "size" },
3687
    { "aspect", HAS_ARG | OPT_VIDEO, {(void*)opt_frame_aspect_ratio}, "set aspect ratio (4:3, 16:9 or 1.3333, 1.7777)", "aspect" },
3688
    { "pix_fmt", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_frame_pix_fmt}, "set pixel format, 'list' as argument shows all the pixel formats supported", "format" },
3689
    { "croptop", HAS_ARG | OPT_VIDEO, {(void*)opt_frame_crop_top}, "set top crop band size (in pixels)", "size" },
3690
    { "cropbottom", HAS_ARG | OPT_VIDEO, {(void*)opt_frame_crop_bottom}, "set bottom crop band size (in pixels)", "size" },
3691
    { "cropleft", HAS_ARG | OPT_VIDEO, {(void*)opt_frame_crop_left}, "set left crop band size (in pixels)", "size" },
3692
    { "cropright", HAS_ARG | OPT_VIDEO, {(void*)opt_frame_crop_right}, "set right crop band size (in pixels)", "size" },
3693
    { "padtop", HAS_ARG | OPT_VIDEO, {(void*)opt_frame_pad_top}, "set top pad band size (in pixels)", "size" },
3694
    { "padbottom", HAS_ARG | OPT_VIDEO, {(void*)opt_frame_pad_bottom}, "set bottom pad band size (in pixels)", "size" },
3695
    { "padleft", HAS_ARG | OPT_VIDEO, {(void*)opt_frame_pad_left}, "set left pad band size (in pixels)", "size" },
3696
    { "padright", HAS_ARG | OPT_VIDEO, {(void*)opt_frame_pad_right}, "set right pad band size (in pixels)", "size" },
3697
    { "padcolor", HAS_ARG | OPT_VIDEO, {(void*)opt_pad_color}, "set color of pad bands (Hex 000000 thru FFFFFF)", "color" },
3698
    { "intra", OPT_BOOL | OPT_EXPERT | OPT_VIDEO, {(void*)&intra_only}, "use only intra frames"},
3699
    { "vn", OPT_BOOL | OPT_VIDEO, {(void*)&video_disable}, "disable video" },
3700
    { "vdt", OPT_INT | HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)&video_discard}, "discard threshold", "n" },
3701
    { "qscale", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_qscale}, "use fixed video quantizer scale (VBR)", "q" },
3702
    { "qdiff", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_qdiff}, "max difference between the quantizer scale (VBR)", "q" },
3703
    { "rc_override", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_video_rc_override_string}, "rate control override for specific intervals", "override" },
3704
    { "vcodec", HAS_ARG | OPT_VIDEO, {(void*)opt_video_codec}, "force video codec ('copy' to copy stream)", "codec" },
3705
    { "me_threshold", HAS_ARG | OPT_FUNC2 | OPT_EXPERT | OPT_VIDEO, {(void*)opt_me_threshold}, "motion estimaton threshold",  "threshold" },
3706
    { "strict", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_strict}, "how strictly to follow the standards", "strictness" },
3707
    { "sameq", OPT_BOOL | OPT_VIDEO, {(void*)&same_quality},
3708
      "use same video quality as source (implies VBR)" },
3709
    { "pass", HAS_ARG | OPT_VIDEO, {(void*)&opt_pass}, "select the pass number (1 or 2)", "n" },
3710
    { "passlogfile", HAS_ARG | OPT_STRING | OPT_VIDEO, {(void*)&pass_logfilename}, "select two pass log file name", "file" },
3711
    { "deinterlace", OPT_BOOL | OPT_EXPERT | OPT_VIDEO, {(void*)&do_deinterlace},
3712
      "deinterlace pictures" },
3713
    { "psnr", OPT_BOOL | OPT_EXPERT | OPT_VIDEO, {(void*)&do_psnr}, "calculate PSNR of compressed frames" },
3714
    { "vstats", OPT_EXPERT | OPT_VIDEO, {(void*)&opt_vstats}, "dump video coding statistics to file" },
3715
    { "vstats_file", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_vstats_file}, "dump video coding statistics to file", "file" },
3716
#ifdef CONFIG_VHOOK
3717
    { "vhook", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)add_frame_hooker}, "insert video processing module", "module" },
3718
#endif
3719
    { "intra_matrix", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_intra_matrix}, "specify intra matrix coeffs", "matrix" },
3720
    { "inter_matrix", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_inter_matrix}, "specify inter matrix coeffs", "matrix" },
3721
    { "top", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_top_field_first}, "top=1/bottom=0/auto=-1 field first", "" },
3722
    { "dc", OPT_INT | HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)&intra_dc_precision}, "intra_dc_precision", "precision" },
3723
    { "vtag", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_video_tag}, "force video tag/fourcc", "fourcc/tag" },
3724
    { "newvideo", OPT_VIDEO, {(void*)opt_new_video_stream}, "add a new video stream to the current output stream" },
3725
    { "qphist", OPT_BOOL | OPT_EXPERT | OPT_VIDEO, { (void *)&qp_hist }, "show QP histogram" },
3726

    
3727
    /* audio options */
3728
    { "ab", OPT_FUNC2 | HAS_ARG | OPT_AUDIO, {(void*)opt_bitrate}, "set bitrate (in bits/s)", "bitrate" },
3729
    { "aframes", OPT_INT | HAS_ARG | OPT_AUDIO, {(void*)&max_frames[CODEC_TYPE_AUDIO]}, "set the number of audio frames to record", "number" },
3730
    { "aq", OPT_FLOAT | HAS_ARG | OPT_AUDIO, {(void*)&audio_qscale}, "set audio quality (codec-specific)", "quality", },
3731
    { "ar", HAS_ARG | OPT_FUNC2 | OPT_AUDIO, {(void*)opt_audio_rate}, "set audio sampling rate (in Hz)", "rate" },
3732
    { "ac", HAS_ARG | OPT_FUNC2 | OPT_AUDIO, {(void*)opt_audio_channels}, "set number of audio channels", "channels" },
3733
    { "an", OPT_BOOL | OPT_AUDIO, {(void*)&audio_disable}, "disable audio" },
3734
    { "acodec", HAS_ARG | OPT_AUDIO, {(void*)opt_audio_codec}, "force audio codec ('copy' to copy stream)", "codec" },
3735
    { "atag", HAS_ARG | OPT_EXPERT | OPT_AUDIO, {(void*)opt_audio_tag}, "force audio tag/fourcc", "fourcc/tag" },
3736
    { "vol", OPT_INT | HAS_ARG | OPT_AUDIO, {(void*)&audio_volume}, "change audio volume (256=normal)" , "volume" }, //
3737
    { "newaudio", OPT_AUDIO, {(void*)opt_new_audio_stream}, "add a new audio stream to the current output stream" },
3738
    { "alang", HAS_ARG | OPT_STRING | OPT_AUDIO, {(void *)&audio_language}, "set the ISO 639 language code (3 letters) of the current audio stream" , "code" },
3739

    
3740
    /* subtitle options */
3741
    { "sn", OPT_BOOL | OPT_SUBTITLE, {(void*)&subtitle_disable}, "disable subtitle" },
3742
    { "scodec", HAS_ARG | OPT_SUBTITLE, {(void*)opt_subtitle_codec}, "force subtitle codec ('copy' to copy stream)", "codec" },
3743
    { "newsubtitle", OPT_SUBTITLE, {(void*)opt_new_subtitle_stream}, "add a new subtitle stream to the current output stream" },
3744
    { "slang", HAS_ARG | OPT_STRING | OPT_SUBTITLE, {(void *)&subtitle_language}, "set the ISO 639 language code (3 letters) of the current subtitle stream" , "code" },
3745

    
3746
    /* grab options */
3747
    { "vc", HAS_ARG | OPT_EXPERT | OPT_VIDEO | OPT_GRAB, {(void*)opt_video_channel}, "set video grab channel (DV1394 only)", "channel" },
3748
    { "tvstd", HAS_ARG | OPT_EXPERT | OPT_VIDEO | OPT_GRAB, {(void*)opt_video_standard}, "set television standard (NTSC, PAL (SECAM))", "standard" },
3749
    { "isync", OPT_BOOL | OPT_EXPERT | OPT_GRAB, {(void*)&input_sync}, "sync read on input", "" },
3750

    
3751
    /* muxer options */
3752
    { "muxdelay", OPT_FLOAT | HAS_ARG | OPT_EXPERT, {(void*)&mux_max_delay}, "set the maximum demux-decode delay", "seconds" },
3753
    { "muxpreload", OPT_FLOAT | HAS_ARG | OPT_EXPERT, {(void*)&mux_preload}, "set the initial demux-decode delay", "seconds" },
3754

    
3755
    { "absf", OPT_FUNC2 | HAS_ARG | OPT_AUDIO | OPT_EXPERT, {(void*)opt_bsf}, "", "bitstream filter" },
3756
    { "vbsf", OPT_FUNC2 | HAS_ARG | OPT_VIDEO | OPT_EXPERT, {(void*)opt_bsf}, "", "bitstream filter" },
3757
    { "sbsf", OPT_FUNC2 | HAS_ARG | OPT_SUBTITLE | OPT_EXPERT, {(void*)opt_bsf}, "", "bitstream filter" },
3758

    
3759
    { "default", OPT_FUNC2 | HAS_ARG | OPT_AUDIO | OPT_VIDEO | OPT_EXPERT, {(void*)opt_default}, "generic catch all option", "" },
3760
    { NULL, },
3761
};
3762

    
3763
int main(int argc, char **argv)
3764
{
3765
    int i;
3766
    int64_t ti;
3767

    
3768
    avcodec_register_all();
3769
    avdevice_register_all();
3770
    av_register_all();
3771

    
3772
    for(i=0; i<CODEC_TYPE_NB; i++){
3773
        avctx_opts[i]= avcodec_alloc_context2(i);
3774
    }
3775
    avformat_opts = av_alloc_format_context();
3776
    sws_opts = sws_getContext(16,16,0, 16,16,0, sws_flags, NULL,NULL,NULL);
3777

    
3778
    show_banner(program_name, program_birth_year);
3779
    if (argc <= 1) {
3780
        show_help();
3781
        av_exit(1);
3782
    }
3783

    
3784
    /* parse options */
3785
    parse_options(argc, argv, options, opt_output_file);
3786

    
3787
    /* file converter / grab */
3788
    if (nb_output_files <= 0) {
3789
        fprintf(stderr, "Must supply at least one output file\n");
3790
        av_exit(1);
3791
    }
3792

    
3793
    if (nb_input_files == 0) {
3794
        fprintf(stderr, "Must supply at least one input file\n");
3795
        av_exit(1);
3796
    }
3797

    
3798
    ti = getutime();
3799
    av_encode(output_files, nb_output_files, input_files, nb_input_files,
3800
              stream_maps, nb_stream_maps);
3801
    ti = getutime() - ti;
3802
    if (do_benchmark) {
3803
        printf("bench: utime=%0.3fs\n", ti / 1000000.0);
3804
    }
3805

    
3806
    return av_exit(0);
3807
}