Statistics
| Branch: | Revision:

ffmpeg / ffmpeg.c @ 7b393736

History | View | Annotate | Download (154 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
/* needed for usleep() */
23
#define _XOPEN_SOURCE 600
24

    
25
#include "config.h"
26
#include <ctype.h>
27
#include <string.h>
28
#include <math.h>
29
#include <stdlib.h>
30
#include <errno.h>
31
#include <signal.h>
32
#include <limits.h>
33
#include <unistd.h>
34
#include "libavformat/avformat.h"
35
#include "libavdevice/avdevice.h"
36
#include "libswscale/swscale.h"
37
#include "libavcodec/opt.h"
38
#include "libavcodec/audioconvert.h"
39
#include "libavcore/parseutils.h"
40
#include "libavcore/samplefmt.h"
41
#include "libavutil/colorspace.h"
42
#include "libavutil/fifo.h"
43
#include "libavutil/intreadwrite.h"
44
#include "libavutil/pixdesc.h"
45
#include "libavutil/avstring.h"
46
#include "libavutil/libm.h"
47
#include "libavformat/os_support.h"
48

    
49
#if CONFIG_AVFILTER
50
# include "libavfilter/avfilter.h"
51
# include "libavfilter/avfiltergraph.h"
52
# include "libavfilter/vsrc_buffer.h"
53
#endif
54

    
55
#if HAVE_SYS_RESOURCE_H
56
#include <sys/types.h>
57
#include <sys/time.h>
58
#include <sys/resource.h>
59
#elif HAVE_GETPROCESSTIMES
60
#include <windows.h>
61
#endif
62
#if HAVE_GETPROCESSMEMORYINFO
63
#include <windows.h>
64
#include <psapi.h>
65
#endif
66

    
67
#if HAVE_SYS_SELECT_H
68
#include <sys/select.h>
69
#endif
70

    
71
#if HAVE_TERMIOS_H
72
#include <fcntl.h>
73
#include <sys/ioctl.h>
74
#include <sys/time.h>
75
#include <termios.h>
76
#elif HAVE_CONIO_H
77
#include <conio.h>
78
#endif
79
#include <time.h>
80

    
81
#include "cmdutils.h"
82

    
83
#include "libavutil/avassert.h"
84

    
85
const char program_name[] = "FFmpeg";
86
const int program_birth_year = 2000;
87

    
88
/* select an input stream for an output stream */
89
typedef struct AVStreamMap {
90
    int file_index;
91
    int stream_index;
92
    int sync_file_index;
93
    int sync_stream_index;
94
} AVStreamMap;
95

    
96
/**
97
 * select an input file for an output file
98
 */
99
typedef struct AVMetaDataMap {
100
    int  file;      //< file index
101
    char type;      //< type of metadata to copy -- (g)lobal, (s)tream, (c)hapter or (p)rogram
102
    int  index;     //< stream/chapter/program number
103
} AVMetaDataMap;
104

    
105
static const OptionDef options[];
106

    
107
#define MAX_FILES 100
108
#if !FF_API_MAX_STREAMS
109
#define MAX_STREAMS 1024    /* arbitrary sanity check value */
110
#endif
111

    
112
static const char *last_asked_format = NULL;
113
static AVFormatContext *input_files[MAX_FILES];
114
static int64_t input_files_ts_offset[MAX_FILES];
115
static double *input_files_ts_scale[MAX_FILES] = {NULL};
116
static AVCodec **input_codecs = NULL;
117
static int nb_input_files = 0;
118
static int nb_input_codecs = 0;
119
static int nb_input_files_ts_scale[MAX_FILES] = {0};
120

    
121
static AVFormatContext *output_files[MAX_FILES];
122
static AVCodec **output_codecs = NULL;
123
static int nb_output_files = 0;
124
static int nb_output_codecs = 0;
125

    
126
static AVStreamMap *stream_maps = NULL;
127
static int nb_stream_maps;
128

    
129
/* first item specifies output metadata, second is input */
130
static AVMetaDataMap (*meta_data_maps)[2] = NULL;
131
static int nb_meta_data_maps;
132
static int metadata_streams_autocopy  = 1;
133
static int metadata_chapters_autocopy = 1;
134

    
135
/* indexed by output file stream index */
136
static int *streamid_map = NULL;
137
static int nb_streamid_map = 0;
138

    
139
static int frame_width  = 0;
140
static int frame_height = 0;
141
static float frame_aspect_ratio = 0;
142
static enum PixelFormat frame_pix_fmt = PIX_FMT_NONE;
143
static enum SampleFormat audio_sample_fmt = SAMPLE_FMT_NONE;
144
static int max_frames[4] = {INT_MAX, INT_MAX, INT_MAX, INT_MAX};
145
static AVRational frame_rate;
146
static float video_qscale = 0;
147
static uint16_t *intra_matrix = NULL;
148
static uint16_t *inter_matrix = NULL;
149
static const char *video_rc_override_string=NULL;
150
static int video_disable = 0;
151
static int video_discard = 0;
152
static char *video_codec_name = NULL;
153
static unsigned int video_codec_tag = 0;
154
static char *video_language = NULL;
155
static int same_quality = 0;
156
static int do_deinterlace = 0;
157
static int top_field_first = -1;
158
static int me_threshold = 0;
159
static int intra_dc_precision = 8;
160
static int loop_input = 0;
161
static int loop_output = AVFMT_NOOUTPUTLOOP;
162
static int qp_hist = 0;
163
#if CONFIG_AVFILTER
164
static char *vfilters = NULL;
165
AVFilterGraph *graph = NULL;
166
#endif
167

    
168
static int intra_only = 0;
169
static int audio_sample_rate = 44100;
170
static int64_t channel_layout = 0;
171
#define QSCALE_NONE -99999
172
static float audio_qscale = QSCALE_NONE;
173
static int audio_disable = 0;
174
static int audio_channels = 1;
175
static char  *audio_codec_name = NULL;
176
static unsigned int audio_codec_tag = 0;
177
static char *audio_language = NULL;
178

    
179
static int subtitle_disable = 0;
180
static char *subtitle_codec_name = NULL;
181
static char *subtitle_language = NULL;
182
static unsigned int subtitle_codec_tag = 0;
183

    
184
static float mux_preload= 0.5;
185
static float mux_max_delay= 0.7;
186

    
187
static int64_t recording_time = INT64_MAX;
188
static int64_t start_time = 0;
189
static int64_t recording_timestamp = 0;
190
static int64_t input_ts_offset = 0;
191
static int file_overwrite = 0;
192
static AVMetadata *metadata;
193
static int do_benchmark = 0;
194
static int do_hex_dump = 0;
195
static int do_pkt_dump = 0;
196
static int do_psnr = 0;
197
static int do_pass = 0;
198
static char *pass_logfilename_prefix = NULL;
199
static int audio_stream_copy = 0;
200
static int video_stream_copy = 0;
201
static int subtitle_stream_copy = 0;
202
static int video_sync_method= -1;
203
static int audio_sync_method= 0;
204
static float audio_drift_threshold= 0.1;
205
static int copy_ts= 0;
206
static int opt_shortest = 0;
207
static int video_global_header = 0;
208
static char *vstats_filename;
209
static FILE *vstats_file;
210
static int opt_programid = 0;
211
static int copy_initial_nonkeyframes = 0;
212

    
213
static int rate_emu = 0;
214

    
215
static int  video_channel = 0;
216
static char *video_standard;
217

    
218
static int audio_volume = 256;
219

    
220
static int exit_on_error = 0;
221
static int using_stdin = 0;
222
static int verbose = 1;
223
static int thread_count= 1;
224
static int q_pressed = 0;
225
static int64_t video_size = 0;
226
static int64_t audio_size = 0;
227
static int64_t extra_size = 0;
228
static int nb_frames_dup = 0;
229
static int nb_frames_drop = 0;
230
static int input_sync;
231
static uint64_t limit_filesize = 0;
232
static int force_fps = 0;
233
static char *forced_key_frames = NULL;
234

    
235
static float dts_delta_threshold = 10;
236

    
237
static unsigned int sws_flags = SWS_BICUBIC;
238

    
239
static int64_t timer_start;
240

    
241
static uint8_t *audio_buf;
242
static uint8_t *audio_out;
243
unsigned int allocated_audio_out_size, allocated_audio_buf_size;
244

    
245
static short *samples;
246

    
247
static AVBitStreamFilterContext *video_bitstream_filters=NULL;
248
static AVBitStreamFilterContext *audio_bitstream_filters=NULL;
249
static AVBitStreamFilterContext *subtitle_bitstream_filters=NULL;
250

    
251
#define DEFAULT_PASS_LOGFILENAME_PREFIX "ffmpeg2pass"
252

    
253
struct AVInputStream;
254

    
255
typedef struct AVOutputStream {
256
    int file_index;          /* file index */
257
    int index;               /* stream index in the output file */
258
    int source_index;        /* AVInputStream index */
259
    AVStream *st;            /* stream in the output file */
260
    int encoding_needed;     /* true if encoding needed for this stream */
261
    int frame_number;
262
    /* input pts and corresponding output pts
263
       for A/V sync */
264
    //double sync_ipts;        /* dts from the AVPacket of the demuxer in second units */
265
    struct AVInputStream *sync_ist; /* input stream to sync against */
266
    int64_t sync_opts;       /* output frame counter, could be changed to some true timestamp */ //FIXME look at frame_number
267
    AVBitStreamFilterContext *bitstream_filters;
268
    /* video only */
269
    int video_resample;
270
    AVFrame pict_tmp;      /* temporary image for resampling */
271
    struct SwsContext *img_resample_ctx; /* for image resampling */
272
    int resample_height;
273
    int resample_width;
274
    int resample_pix_fmt;
275

    
276
    /* full frame size of first frame */
277
    int original_height;
278
    int original_width;
279

    
280
    /* forced key frames */
281
    int64_t *forced_kf_pts;
282
    int forced_kf_count;
283
    int forced_kf_index;
284

    
285
    /* audio only */
286
    int audio_resample;
287
    ReSampleContext *resample; /* for audio resampling */
288
    int reformat_pair;
289
    AVAudioConvert *reformat_ctx;
290
    AVFifoBuffer *fifo;     /* for compression: one audio fifo per codec */
291
    FILE *logfile;
292
} AVOutputStream;
293

    
294
static AVOutputStream **output_streams_for_file[MAX_FILES] = { NULL };
295
static int nb_output_streams_for_file[MAX_FILES] = { 0 };
296

    
297
typedef struct AVInputStream {
298
    int file_index;
299
    int index;
300
    AVStream *st;
301
    int discard;             /* true if stream data should be discarded */
302
    int decoding_needed;     /* true if the packets must be decoded in 'raw_fifo' */
303
    int64_t sample_index;      /* current sample */
304

    
305
    int64_t       start;     /* time when read started */
306
    int64_t       next_pts;  /* synthetic pts for cases where pkt.pts
307
                                is not defined */
308
    int64_t       pts;       /* current pts */
309
    PtsCorrectionContext pts_ctx;
310
    int is_start;            /* is 1 at the start and after a discontinuity */
311
    int showed_multi_packet_warning;
312
    int is_past_recording_time;
313
#if CONFIG_AVFILTER
314
    AVFilterContext *output_video_filter;
315
    AVFilterContext *input_video_filter;
316
    AVFrame *filter_frame;
317
    int has_filter_frame;
318
    AVFilterBufferRef *picref;
319
#endif
320
} AVInputStream;
321

    
322
typedef struct AVInputFile {
323
    int eof_reached;      /* true if eof reached */
324
    int ist_index;        /* index of first stream in ist_table */
325
    int buffer_size;      /* current total buffer size */
326
    int nb_streams;       /* nb streams we are aware of */
327
} AVInputFile;
328

    
329
#if HAVE_TERMIOS_H
330

    
331
/* init terminal so that we can grab keys */
332
static struct termios oldtty;
333
#endif
334

    
335
#if CONFIG_AVFILTER
336

    
337
static int configure_filters(AVInputStream *ist, AVOutputStream *ost)
338
{
339
    AVFilterContext *last_filter, *filter;
340
    /** filter graph containing all filters including input & output */
341
    AVCodecContext *codec = ost->st->codec;
342
    AVCodecContext *icodec = ist->st->codec;
343
    FFSinkContext ffsink_ctx = { .pix_fmt = codec->pix_fmt };
344
    char args[255];
345
    int ret;
346

    
347
    graph = avfilter_graph_alloc();
348

    
349
    if ((ret = avfilter_open(&ist->input_video_filter, avfilter_get_by_name("buffer"), "src")) < 0)
350
        return ret;
351
    if ((ret = avfilter_open(&ist->output_video_filter, &ffsink, "out")) < 0)
352
        return ret;
353

    
354
    snprintf(args, 255, "%d:%d:%d:%d:%d", ist->st->codec->width,
355
             ist->st->codec->height, ist->st->codec->pix_fmt, 1, AV_TIME_BASE);
356
    if ((ret = avfilter_init_filter(ist->input_video_filter, args, NULL)) < 0)
357
        return ret;
358
    if ((ret = avfilter_init_filter(ist->output_video_filter, NULL, &ffsink_ctx)) < 0)
359
        return ret;
360

    
361
    /* add input and output filters to the overall graph */
362
    avfilter_graph_add_filter(graph, ist->input_video_filter);
363
    avfilter_graph_add_filter(graph, ist->output_video_filter);
364

    
365
    last_filter = ist->input_video_filter;
366

    
367
    if (codec->width  != icodec->width || codec->height != icodec->height) {
368
        snprintf(args, 255, "%d:%d:flags=0x%X",
369
                 codec->width,
370
                 codec->height,
371
                 (int)av_get_int(sws_opts, "sws_flags", NULL));
372
        if ((ret = avfilter_open(&filter, avfilter_get_by_name("scale"), NULL)) < 0)
373
            return ret;
374
        if ((ret = avfilter_init_filter(filter, args, NULL)) < 0)
375
            return ret;
376
        if ((ret = avfilter_link(last_filter, 0, filter, 0)) < 0)
377
            return ret;
378
        last_filter = filter;
379
        avfilter_graph_add_filter(graph, last_filter);
380
    }
381

    
382
    snprintf(args, sizeof(args), "flags=0x%X", (int)av_get_int(sws_opts, "sws_flags", NULL));
383
    graph->scale_sws_opts = av_strdup(args);
384

    
385
    if (vfilters) {
386
        AVFilterInOut *outputs = av_malloc(sizeof(AVFilterInOut));
387
        AVFilterInOut *inputs  = av_malloc(sizeof(AVFilterInOut));
388

    
389
        outputs->name    = av_strdup("in");
390
        outputs->filter_ctx = last_filter;
391
        outputs->pad_idx = 0;
392
        outputs->next    = NULL;
393

    
394
        inputs->name    = av_strdup("out");
395
        inputs->filter_ctx = ist->output_video_filter;
396
        inputs->pad_idx = 0;
397
        inputs->next    = NULL;
398

    
399
        if ((ret = avfilter_graph_parse(graph, vfilters, inputs, outputs, NULL)) < 0)
400
            return ret;
401
        av_freep(&vfilters);
402
    } else {
403
        if ((ret = avfilter_link(last_filter, 0, ist->output_video_filter, 0)) < 0)
404
            return ret;
405
    }
406

    
407
    if ((ret = avfilter_graph_config(graph, NULL)) < 0)
408
        return ret;
409

    
410
    codec->width  = ist->output_video_filter->inputs[0]->w;
411
    codec->height = ist->output_video_filter->inputs[0]->h;
412

    
413
    return 0;
414
}
415
#endif /* CONFIG_AVFILTER */
416

    
417
static void term_exit(void)
418
{
419
    av_log(NULL, AV_LOG_QUIET, "");
420
#if HAVE_TERMIOS_H
421
    tcsetattr (0, TCSANOW, &oldtty);
422
#endif
423
}
424

    
425
static volatile int received_sigterm = 0;
426

    
427
static void
428
sigterm_handler(int sig)
429
{
430
    received_sigterm = sig;
431
    term_exit();
432
}
433

    
434
static void term_init(void)
435
{
436
#if HAVE_TERMIOS_H
437
    struct termios tty;
438

    
439
    tcgetattr (0, &tty);
440
    oldtty = tty;
441
    atexit(term_exit);
442

    
443
    tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
444
                          |INLCR|IGNCR|ICRNL|IXON);
445
    tty.c_oflag |= OPOST;
446
    tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
447
    tty.c_cflag &= ~(CSIZE|PARENB);
448
    tty.c_cflag |= CS8;
449
    tty.c_cc[VMIN] = 1;
450
    tty.c_cc[VTIME] = 0;
451

    
452
    tcsetattr (0, TCSANOW, &tty);
453
    signal(SIGQUIT, sigterm_handler); /* Quit (POSIX).  */
454
#endif
455

    
456
    signal(SIGINT , sigterm_handler); /* Interrupt (ANSI).  */
457
    signal(SIGTERM, sigterm_handler); /* Termination (ANSI).  */
458
#ifdef SIGXCPU
459
    signal(SIGXCPU, sigterm_handler);
460
#endif
461
}
462

    
463
/* read a key without blocking */
464
static int read_key(void)
465
{
466
#if HAVE_TERMIOS_H
467
    int n = 1;
468
    unsigned char ch;
469
    struct timeval tv;
470
    fd_set rfds;
471

    
472
    FD_ZERO(&rfds);
473
    FD_SET(0, &rfds);
474
    tv.tv_sec = 0;
475
    tv.tv_usec = 0;
476
    n = select(1, &rfds, NULL, NULL, &tv);
477
    if (n > 0) {
478
        n = read(0, &ch, 1);
479
        if (n == 1)
480
            return ch;
481

    
482
        return n;
483
    }
484
#elif HAVE_CONIO_H
485
    if(kbhit())
486
        return(getch());
487
#endif
488
    return -1;
489
}
490

    
491
static int decode_interrupt_cb(void)
492
{
493
    return q_pressed || (q_pressed = read_key() == 'q');
494
}
495

    
496
static int ffmpeg_exit(int ret)
497
{
498
    int i;
499

    
500
    /* close files */
501
    for(i=0;i<nb_output_files;i++) {
502
        /* maybe av_close_output_file ??? */
503
        AVFormatContext *s = output_files[i];
504
        int j;
505
        if (!(s->oformat->flags & AVFMT_NOFILE) && s->pb)
506
            url_fclose(s->pb);
507
        for(j=0;j<s->nb_streams;j++) {
508
            av_metadata_free(&s->streams[j]->metadata);
509
            av_free(s->streams[j]->codec);
510
            av_free(s->streams[j]->info);
511
            av_free(s->streams[j]);
512
        }
513
        for(j=0;j<s->nb_programs;j++) {
514
            av_metadata_free(&s->programs[j]->metadata);
515
        }
516
        for(j=0;j<s->nb_chapters;j++) {
517
            av_metadata_free(&s->chapters[j]->metadata);
518
        }
519
        av_metadata_free(&s->metadata);
520
        av_free(s);
521
        av_free(output_streams_for_file[i]);
522
    }
523
    for(i=0;i<nb_input_files;i++) {
524
        av_close_input_file(input_files[i]);
525
        av_free(input_files_ts_scale[i]);
526
    }
527

    
528
    av_free(intra_matrix);
529
    av_free(inter_matrix);
530

    
531
    if (vstats_file)
532
        fclose(vstats_file);
533
    av_free(vstats_filename);
534

    
535
    av_free(opt_names);
536
    av_free(streamid_map);
537
    av_free(input_codecs);
538
    av_free(output_codecs);
539
    av_free(stream_maps);
540
    av_free(meta_data_maps);
541

    
542
    av_free(video_codec_name);
543
    av_free(audio_codec_name);
544
    av_free(subtitle_codec_name);
545

    
546
    av_free(video_standard);
547

    
548
    uninit_opts();
549
    av_free(audio_buf);
550
    av_free(audio_out);
551
    allocated_audio_buf_size= allocated_audio_out_size= 0;
552
    av_free(samples);
553

    
554
#if CONFIG_AVFILTER
555
    avfilter_uninit();
556
#endif
557

    
558
    if (received_sigterm) {
559
        fprintf(stderr,
560
            "Received signal %d: terminating.\n",
561
            (int) received_sigterm);
562
        exit (255);
563
    }
564

    
565
    exit(ret); /* not all OS-es handle main() return value */
566
    return ret;
567
}
568

    
569
/* similar to ff_dynarray_add() and av_fast_realloc() */
570
static void *grow_array(void *array, int elem_size, int *size, int new_size)
571
{
572
    if (new_size >= INT_MAX / elem_size) {
573
        fprintf(stderr, "Array too big.\n");
574
        ffmpeg_exit(1);
575
    }
576
    if (*size < new_size) {
577
        uint8_t *tmp = av_realloc(array, new_size*elem_size);
578
        if (!tmp) {
579
            fprintf(stderr, "Could not alloc buffer.\n");
580
            ffmpeg_exit(1);
581
        }
582
        memset(tmp + *size*elem_size, 0, (new_size-*size) * elem_size);
583
        *size = new_size;
584
        return tmp;
585
    }
586
    return array;
587
}
588

    
589
static void choose_sample_fmt(AVStream *st, AVCodec *codec)
590
{
591
    if(codec && codec->sample_fmts){
592
        const enum SampleFormat *p= codec->sample_fmts;
593
        for(; *p!=-1; p++){
594
            if(*p == st->codec->sample_fmt)
595
                break;
596
        }
597
        if(*p == -1)
598
            st->codec->sample_fmt = codec->sample_fmts[0];
599
    }
600
}
601

    
602
static void choose_sample_rate(AVStream *st, AVCodec *codec)
603
{
604
    if(codec && codec->supported_samplerates){
605
        const int *p= codec->supported_samplerates;
606
        int best=0;
607
        int best_dist=INT_MAX;
608
        for(; *p; p++){
609
            int dist= abs(st->codec->sample_rate - *p);
610
            if(dist < best_dist){
611
                best_dist= dist;
612
                best= *p;
613
            }
614
        }
615
        if(best_dist){
616
            av_log(st->codec, AV_LOG_WARNING, "Requested sampling rate unsupported using closest supported (%d)\n", best);
617
        }
618
        st->codec->sample_rate= best;
619
    }
620
}
621

    
622
static void choose_pixel_fmt(AVStream *st, AVCodec *codec)
623
{
624
    if(codec && codec->pix_fmts){
625
        const enum PixelFormat *p= codec->pix_fmts;
626
        for(; *p!=-1; p++){
627
            if(*p == st->codec->pix_fmt)
628
                break;
629
        }
630
        if(*p == -1
631
           && !(   st->codec->codec_id==CODEC_ID_MJPEG
632
                && st->codec->strict_std_compliance <= FF_COMPLIANCE_UNOFFICIAL
633
                && (   st->codec->pix_fmt == PIX_FMT_YUV420P
634
                    || st->codec->pix_fmt == PIX_FMT_YUV422P)))
635
            st->codec->pix_fmt = codec->pix_fmts[0];
636
    }
637
}
638

    
639
static AVOutputStream *new_output_stream(AVFormatContext *oc, int file_idx)
640
{
641
    int idx = oc->nb_streams - 1;
642
    AVOutputStream *ost;
643

    
644
    output_streams_for_file[file_idx] =
645
        grow_array(output_streams_for_file[file_idx],
646
                   sizeof(*output_streams_for_file[file_idx]),
647
                   &nb_output_streams_for_file[file_idx],
648
                   oc->nb_streams);
649
    ost = output_streams_for_file[file_idx][idx] =
650
        av_mallocz(sizeof(AVOutputStream));
651
    if (!ost) {
652
        fprintf(stderr, "Could not alloc output stream\n");
653
        ffmpeg_exit(1);
654
    }
655
    ost->file_index = file_idx;
656
    ost->index = idx;
657
    return ost;
658
}
659

    
660
static int read_ffserver_streams(AVFormatContext *s, const char *filename)
661
{
662
    int i, err;
663
    AVFormatContext *ic;
664
    int nopts = 0;
665

    
666
    err = av_open_input_file(&ic, filename, NULL, FFM_PACKET_SIZE, NULL);
667
    if (err < 0)
668
        return err;
669
    /* copy stream format */
670
    s->nb_streams = 0;
671
    for(i=0;i<ic->nb_streams;i++) {
672
        AVStream *st;
673
        AVCodec *codec;
674

    
675
        s->nb_streams++;
676

    
677
        // FIXME: a more elegant solution is needed
678
        st = av_mallocz(sizeof(AVStream));
679
        memcpy(st, ic->streams[i], sizeof(AVStream));
680
        st->codec = avcodec_alloc_context();
681
        if (!st->codec) {
682
            print_error(filename, AVERROR(ENOMEM));
683
            ffmpeg_exit(1);
684
        }
685
        avcodec_copy_context(st->codec, ic->streams[i]->codec);
686
        s->streams[i] = st;
687

    
688
        codec = avcodec_find_encoder(st->codec->codec_id);
689
        if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO) {
690
            if (audio_stream_copy) {
691
                st->stream_copy = 1;
692
            } else
693
                choose_sample_fmt(st, codec);
694
        } else if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
695
            if (video_stream_copy) {
696
                st->stream_copy = 1;
697
            } else
698
                choose_pixel_fmt(st, codec);
699
        }
700

    
701
        if(!st->codec->thread_count)
702
            st->codec->thread_count = 1;
703
        if(st->codec->thread_count>1)
704
            avcodec_thread_init(st->codec, st->codec->thread_count);
705

    
706
        if(st->codec->flags & CODEC_FLAG_BITEXACT)
707
            nopts = 1;
708

    
709
        new_output_stream(s, nb_output_files);
710
    }
711

    
712
    if (!nopts)
713
        s->timestamp = av_gettime();
714

    
715
    av_close_input_file(ic);
716
    return 0;
717
}
718

    
719
static double
720
get_sync_ipts(const AVOutputStream *ost)
721
{
722
    const AVInputStream *ist = ost->sync_ist;
723
    return (double)(ist->pts - start_time)/AV_TIME_BASE;
724
}
725

    
726
static void write_frame(AVFormatContext *s, AVPacket *pkt, AVCodecContext *avctx, AVBitStreamFilterContext *bsfc){
727
    int ret;
728

    
729
    while(bsfc){
730
        AVPacket new_pkt= *pkt;
731
        int a= av_bitstream_filter_filter(bsfc, avctx, NULL,
732
                                          &new_pkt.data, &new_pkt.size,
733
                                          pkt->data, pkt->size,
734
                                          pkt->flags & AV_PKT_FLAG_KEY);
735
        if(a>0){
736
            av_free_packet(pkt);
737
            new_pkt.destruct= av_destruct_packet;
738
        } else if(a<0){
739
            fprintf(stderr, "%s failed for stream %d, codec %s",
740
                    bsfc->filter->name, pkt->stream_index,
741
                    avctx->codec ? avctx->codec->name : "copy");
742
            print_error("", a);
743
            if (exit_on_error)
744
                ffmpeg_exit(1);
745
        }
746
        *pkt= new_pkt;
747

    
748
        bsfc= bsfc->next;
749
    }
750

    
751
    ret= av_interleaved_write_frame(s, pkt);
752
    if(ret < 0){
753
        print_error("av_interleaved_write_frame()", ret);
754
        ffmpeg_exit(1);
755
    }
756
}
757

    
758
#define MAX_AUDIO_PACKET_SIZE (128 * 1024)
759

    
760
static void do_audio_out(AVFormatContext *s,
761
                         AVOutputStream *ost,
762
                         AVInputStream *ist,
763
                         unsigned char *buf, int size)
764
{
765
    uint8_t *buftmp;
766
    int64_t audio_out_size, audio_buf_size;
767
    int64_t allocated_for_size= size;
768

    
769
    int size_out, frame_bytes, ret;
770
    AVCodecContext *enc= ost->st->codec;
771
    AVCodecContext *dec= ist->st->codec;
772
    int osize= av_get_bits_per_sample_fmt(enc->sample_fmt)/8;
773
    int isize= av_get_bits_per_sample_fmt(dec->sample_fmt)/8;
774
    const int coded_bps = av_get_bits_per_sample(enc->codec->id);
775

    
776
need_realloc:
777
    audio_buf_size= (allocated_for_size + isize*dec->channels - 1) / (isize*dec->channels);
778
    audio_buf_size= (audio_buf_size*enc->sample_rate + dec->sample_rate) / dec->sample_rate;
779
    audio_buf_size= audio_buf_size*2 + 10000; //safety factors for the deprecated resampling API
780
    audio_buf_size= FFMAX(audio_buf_size, enc->frame_size);
781
    audio_buf_size*= osize*enc->channels;
782

    
783
    audio_out_size= FFMAX(audio_buf_size, enc->frame_size * osize * enc->channels);
784
    if(coded_bps > 8*osize)
785
        audio_out_size= audio_out_size * coded_bps / (8*osize);
786
    audio_out_size += FF_MIN_BUFFER_SIZE;
787

    
788
    if(audio_out_size > INT_MAX || audio_buf_size > INT_MAX){
789
        fprintf(stderr, "Buffer sizes too large\n");
790
        ffmpeg_exit(1);
791
    }
792

    
793
    av_fast_malloc(&audio_buf, &allocated_audio_buf_size, audio_buf_size);
794
    av_fast_malloc(&audio_out, &allocated_audio_out_size, audio_out_size);
795
    if (!audio_buf || !audio_out){
796
        fprintf(stderr, "Out of memory in do_audio_out\n");
797
        ffmpeg_exit(1);
798
    }
799

    
800
    if (enc->channels != dec->channels)
801
        ost->audio_resample = 1;
802

    
803
    if (ost->audio_resample && !ost->resample) {
804
        if (dec->sample_fmt != SAMPLE_FMT_S16)
805
            fprintf(stderr, "Warning, using s16 intermediate sample format for resampling\n");
806
        ost->resample = av_audio_resample_init(enc->channels,    dec->channels,
807
                                               enc->sample_rate, dec->sample_rate,
808
                                               enc->sample_fmt,  dec->sample_fmt,
809
                                               16, 10, 0, 0.8);
810
        if (!ost->resample) {
811
            fprintf(stderr, "Can not resample %d channels @ %d Hz to %d channels @ %d Hz\n",
812
                    dec->channels, dec->sample_rate,
813
                    enc->channels, enc->sample_rate);
814
            ffmpeg_exit(1);
815
        }
816
    }
817

    
818
#define MAKE_SFMT_PAIR(a,b) ((a)+SAMPLE_FMT_NB*(b))
819
    if (!ost->audio_resample && dec->sample_fmt!=enc->sample_fmt &&
820
        MAKE_SFMT_PAIR(enc->sample_fmt,dec->sample_fmt)!=ost->reformat_pair) {
821
        if (ost->reformat_ctx)
822
            av_audio_convert_free(ost->reformat_ctx);
823
        ost->reformat_ctx = av_audio_convert_alloc(enc->sample_fmt, 1,
824
                                                   dec->sample_fmt, 1, NULL, 0);
825
        if (!ost->reformat_ctx) {
826
            fprintf(stderr, "Cannot convert %s sample format to %s sample format\n",
827
                av_get_sample_fmt_name(dec->sample_fmt),
828
                av_get_sample_fmt_name(enc->sample_fmt));
829
            ffmpeg_exit(1);
830
        }
831
        ost->reformat_pair=MAKE_SFMT_PAIR(enc->sample_fmt,dec->sample_fmt);
832
    }
833

    
834
    if(audio_sync_method){
835
        double delta = get_sync_ipts(ost) * enc->sample_rate - ost->sync_opts
836
                - av_fifo_size(ost->fifo)/(enc->channels * 2);
837
        double idelta= delta*dec->sample_rate / enc->sample_rate;
838
        int byte_delta= ((int)idelta)*2*dec->channels;
839

    
840
        //FIXME resample delay
841
        if(fabs(delta) > 50){
842
            if(ist->is_start || fabs(delta) > audio_drift_threshold*enc->sample_rate){
843
                if(byte_delta < 0){
844
                    byte_delta= FFMAX(byte_delta, -size);
845
                    size += byte_delta;
846
                    buf  -= byte_delta;
847
                    if(verbose > 2)
848
                        fprintf(stderr, "discarding %d audio samples\n", (int)-delta);
849
                    if(!size)
850
                        return;
851
                    ist->is_start=0;
852
                }else{
853
                    static uint8_t *input_tmp= NULL;
854
                    input_tmp= av_realloc(input_tmp, byte_delta + size);
855

    
856
                    if(byte_delta > allocated_for_size - size){
857
                        allocated_for_size= byte_delta + (int64_t)size;
858
                        goto need_realloc;
859
                    }
860
                    ist->is_start=0;
861

    
862
                    memset(input_tmp, 0, byte_delta);
863
                    memcpy(input_tmp + byte_delta, buf, size);
864
                    buf= input_tmp;
865
                    size += byte_delta;
866
                    if(verbose > 2)
867
                        fprintf(stderr, "adding %d audio samples of silence\n", (int)delta);
868
                }
869
            }else if(audio_sync_method>1){
870
                int comp= av_clip(delta, -audio_sync_method, audio_sync_method);
871
                av_assert0(ost->audio_resample);
872
                if(verbose > 2)
873
                    fprintf(stderr, "compensating audio timestamp drift:%f compensation:%d in:%d\n", delta, comp, enc->sample_rate);
874
//                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));
875
                av_resample_compensate(*(struct AVResampleContext**)ost->resample, comp, enc->sample_rate);
876
            }
877
        }
878
    }else
879
        ost->sync_opts= lrintf(get_sync_ipts(ost) * enc->sample_rate)
880
                        - av_fifo_size(ost->fifo)/(enc->channels * 2); //FIXME wrong
881

    
882
    if (ost->audio_resample) {
883
        buftmp = audio_buf;
884
        size_out = audio_resample(ost->resample,
885
                                  (short *)buftmp, (short *)buf,
886
                                  size / (dec->channels * isize));
887
        size_out = size_out * enc->channels * osize;
888
    } else {
889
        buftmp = buf;
890
        size_out = size;
891
    }
892

    
893
    if (!ost->audio_resample && dec->sample_fmt!=enc->sample_fmt) {
894
        const void *ibuf[6]= {buftmp};
895
        void *obuf[6]= {audio_buf};
896
        int istride[6]= {isize};
897
        int ostride[6]= {osize};
898
        int len= size_out/istride[0];
899
        if (av_audio_convert(ost->reformat_ctx, obuf, ostride, ibuf, istride, len)<0) {
900
            printf("av_audio_convert() failed\n");
901
            if (exit_on_error)
902
                ffmpeg_exit(1);
903
            return;
904
        }
905
        buftmp = audio_buf;
906
        size_out = len*osize;
907
    }
908

    
909
    /* now encode as many frames as possible */
910
    if (enc->frame_size > 1) {
911
        /* output resampled raw samples */
912
        if (av_fifo_realloc2(ost->fifo, av_fifo_size(ost->fifo) + size_out) < 0) {
913
            fprintf(stderr, "av_fifo_realloc2() failed\n");
914
            ffmpeg_exit(1);
915
        }
916
        av_fifo_generic_write(ost->fifo, buftmp, size_out, NULL);
917

    
918
        frame_bytes = enc->frame_size * osize * enc->channels;
919

    
920
        while (av_fifo_size(ost->fifo) >= frame_bytes) {
921
            AVPacket pkt;
922
            av_init_packet(&pkt);
923

    
924
            av_fifo_generic_read(ost->fifo, audio_buf, frame_bytes, NULL);
925

    
926
            //FIXME pass ost->sync_opts as AVFrame.pts in avcodec_encode_audio()
927

    
928
            ret = avcodec_encode_audio(enc, audio_out, audio_out_size,
929
                                       (short *)audio_buf);
930
            if (ret < 0) {
931
                fprintf(stderr, "Audio encoding failed\n");
932
                ffmpeg_exit(1);
933
            }
934
            audio_size += ret;
935
            pkt.stream_index= ost->index;
936
            pkt.data= audio_out;
937
            pkt.size= ret;
938
            if(enc->coded_frame && enc->coded_frame->pts != AV_NOPTS_VALUE)
939
                pkt.pts= av_rescale_q(enc->coded_frame->pts, enc->time_base, ost->st->time_base);
940
            pkt.flags |= AV_PKT_FLAG_KEY;
941
            write_frame(s, &pkt, enc, ost->bitstream_filters);
942

    
943
            ost->sync_opts += enc->frame_size;
944
        }
945
    } else {
946
        AVPacket pkt;
947
        av_init_packet(&pkt);
948

    
949
        ost->sync_opts += size_out / (osize * enc->channels);
950

    
951
        /* output a pcm frame */
952
        /* determine the size of the coded buffer */
953
        size_out /= osize;
954
        if (coded_bps)
955
            size_out = size_out*coded_bps/8;
956

    
957
        if(size_out > audio_out_size){
958
            fprintf(stderr, "Internal error, buffer size too small\n");
959
            ffmpeg_exit(1);
960
        }
961

    
962
        //FIXME pass ost->sync_opts as AVFrame.pts in avcodec_encode_audio()
963
        ret = avcodec_encode_audio(enc, audio_out, size_out,
964
                                   (short *)buftmp);
965
        if (ret < 0) {
966
            fprintf(stderr, "Audio encoding failed\n");
967
            ffmpeg_exit(1);
968
        }
969
        audio_size += ret;
970
        pkt.stream_index= ost->index;
971
        pkt.data= audio_out;
972
        pkt.size= ret;
973
        if(enc->coded_frame && enc->coded_frame->pts != AV_NOPTS_VALUE)
974
            pkt.pts= av_rescale_q(enc->coded_frame->pts, enc->time_base, ost->st->time_base);
975
        pkt.flags |= AV_PKT_FLAG_KEY;
976
        write_frame(s, &pkt, enc, ost->bitstream_filters);
977
    }
978
}
979

    
980
static void pre_process_video_frame(AVInputStream *ist, AVPicture *picture, void **bufp)
981
{
982
    AVCodecContext *dec;
983
    AVPicture *picture2;
984
    AVPicture picture_tmp;
985
    uint8_t *buf = 0;
986

    
987
    dec = ist->st->codec;
988

    
989
    /* deinterlace : must be done before any resize */
990
    if (do_deinterlace) {
991
        int size;
992

    
993
        /* create temporary picture */
994
        size = avpicture_get_size(dec->pix_fmt, dec->width, dec->height);
995
        buf = av_malloc(size);
996
        if (!buf)
997
            return;
998

    
999
        picture2 = &picture_tmp;
1000
        avpicture_fill(picture2, buf, dec->pix_fmt, dec->width, dec->height);
1001

    
1002
        if(avpicture_deinterlace(picture2, picture,
1003
                                 dec->pix_fmt, dec->width, dec->height) < 0) {
1004
            /* if error, do not deinterlace */
1005
            fprintf(stderr, "Deinterlacing failed\n");
1006
            av_free(buf);
1007
            buf = NULL;
1008
            picture2 = picture;
1009
        }
1010
    } else {
1011
        picture2 = picture;
1012
    }
1013

    
1014
    if (picture != picture2)
1015
        *picture = *picture2;
1016
    *bufp = buf;
1017
}
1018

    
1019
/* we begin to correct av delay at this threshold */
1020
#define AV_DELAY_MAX 0.100
1021

    
1022
static void do_subtitle_out(AVFormatContext *s,
1023
                            AVOutputStream *ost,
1024
                            AVInputStream *ist,
1025
                            AVSubtitle *sub,
1026
                            int64_t pts)
1027
{
1028
    static uint8_t *subtitle_out = NULL;
1029
    int subtitle_out_max_size = 1024 * 1024;
1030
    int subtitle_out_size, nb, i;
1031
    AVCodecContext *enc;
1032
    AVPacket pkt;
1033

    
1034
    if (pts == AV_NOPTS_VALUE) {
1035
        fprintf(stderr, "Subtitle packets must have a pts\n");
1036
        if (exit_on_error)
1037
            ffmpeg_exit(1);
1038
        return;
1039
    }
1040

    
1041
    enc = ost->st->codec;
1042

    
1043
    if (!subtitle_out) {
1044
        subtitle_out = av_malloc(subtitle_out_max_size);
1045
    }
1046

    
1047
    /* Note: DVB subtitle need one packet to draw them and one other
1048
       packet to clear them */
1049
    /* XXX: signal it in the codec context ? */
1050
    if (enc->codec_id == CODEC_ID_DVB_SUBTITLE)
1051
        nb = 2;
1052
    else
1053
        nb = 1;
1054

    
1055
    for(i = 0; i < nb; i++) {
1056
        sub->pts = av_rescale_q(pts, ist->st->time_base, AV_TIME_BASE_Q);
1057
        // start_display_time is required to be 0
1058
        sub->pts              += av_rescale_q(sub->start_display_time, (AVRational){1, 1000}, AV_TIME_BASE_Q);
1059
        sub->end_display_time -= sub->start_display_time;
1060
        sub->start_display_time = 0;
1061
        subtitle_out_size = avcodec_encode_subtitle(enc, subtitle_out,
1062
                                                    subtitle_out_max_size, sub);
1063
        if (subtitle_out_size < 0) {
1064
            fprintf(stderr, "Subtitle encoding failed\n");
1065
            ffmpeg_exit(1);
1066
        }
1067

    
1068
        av_init_packet(&pkt);
1069
        pkt.stream_index = ost->index;
1070
        pkt.data = subtitle_out;
1071
        pkt.size = subtitle_out_size;
1072
        pkt.pts = av_rescale_q(sub->pts, AV_TIME_BASE_Q, ost->st->time_base);
1073
        if (enc->codec_id == CODEC_ID_DVB_SUBTITLE) {
1074
            /* XXX: the pts correction is handled here. Maybe handling
1075
               it in the codec would be better */
1076
            if (i == 0)
1077
                pkt.pts += 90 * sub->start_display_time;
1078
            else
1079
                pkt.pts += 90 * sub->end_display_time;
1080
        }
1081
        write_frame(s, &pkt, ost->st->codec, ost->bitstream_filters);
1082
    }
1083
}
1084

    
1085
static int bit_buffer_size= 1024*256;
1086
static uint8_t *bit_buffer= NULL;
1087

    
1088
static void do_video_out(AVFormatContext *s,
1089
                         AVOutputStream *ost,
1090
                         AVInputStream *ist,
1091
                         AVFrame *in_picture,
1092
                         int *frame_size)
1093
{
1094
    int nb_frames, i, ret;
1095
    AVFrame *final_picture, *formatted_picture, *resampling_dst, *padding_src;
1096
    AVCodecContext *enc, *dec;
1097
    double sync_ipts;
1098

    
1099
    enc = ost->st->codec;
1100
    dec = ist->st->codec;
1101

    
1102
    sync_ipts = get_sync_ipts(ost) / av_q2d(enc->time_base);
1103

    
1104
    /* by default, we output a single frame */
1105
    nb_frames = 1;
1106

    
1107
    *frame_size = 0;
1108

    
1109
    if(video_sync_method){
1110
        double vdelta = sync_ipts - ost->sync_opts;
1111
        //FIXME set to 0.5 after we fix some dts/pts bugs like in avidec.c
1112
        if (vdelta < -1.1)
1113
            nb_frames = 0;
1114
        else if (video_sync_method == 2 || (video_sync_method<0 && (s->oformat->flags & AVFMT_VARIABLE_FPS))){
1115
            if(vdelta<=-0.6){
1116
                nb_frames=0;
1117
            }else if(vdelta>0.6)
1118
            ost->sync_opts= lrintf(sync_ipts);
1119
        }else if (vdelta > 1.1)
1120
            nb_frames = lrintf(vdelta);
1121
//fprintf(stderr, "vdelta:%f, ost->sync_opts:%"PRId64", ost->sync_ipts:%f nb_frames:%d\n", vdelta, ost->sync_opts, get_sync_ipts(ost), nb_frames);
1122
        if (nb_frames == 0){
1123
            ++nb_frames_drop;
1124
            if (verbose>2)
1125
                fprintf(stderr, "*** drop!\n");
1126
        }else if (nb_frames > 1) {
1127
            nb_frames_dup += nb_frames - 1;
1128
            if (verbose>2)
1129
                fprintf(stderr, "*** %d dup!\n", nb_frames-1);
1130
        }
1131
    }else
1132
        ost->sync_opts= lrintf(sync_ipts);
1133

    
1134
    nb_frames= FFMIN(nb_frames, max_frames[AVMEDIA_TYPE_VIDEO] - ost->frame_number);
1135
    if (nb_frames <= 0)
1136
        return;
1137

    
1138
    formatted_picture = in_picture;
1139
    final_picture = formatted_picture;
1140
    padding_src = formatted_picture;
1141
    resampling_dst = &ost->pict_tmp;
1142

    
1143
    if (   ost->resample_height != ist->st->codec->height
1144
        || ost->resample_width  != ist->st->codec->width
1145
        || (ost->resample_pix_fmt!= ist->st->codec->pix_fmt) ) {
1146

    
1147
        fprintf(stderr,"Input Stream #%d.%d frame size changed to %dx%d, %s\n", ist->file_index, ist->index, ist->st->codec->width,     ist->st->codec->height,avcodec_get_pix_fmt_name(ist->st->codec->pix_fmt));
1148
        if(!ost->video_resample)
1149
            ffmpeg_exit(1);
1150
    }
1151

    
1152
#if !CONFIG_AVFILTER
1153
    if (ost->video_resample) {
1154
        padding_src = NULL;
1155
        final_picture = &ost->pict_tmp;
1156
        if(  ost->resample_height != ist->st->codec->height
1157
          || ost->resample_width  != ist->st->codec->width
1158
          || (ost->resample_pix_fmt!= ist->st->codec->pix_fmt) ) {
1159

    
1160
            /* initialize a new scaler context */
1161
            sws_freeContext(ost->img_resample_ctx);
1162
            sws_flags = av_get_int(sws_opts, "sws_flags", NULL);
1163
            ost->img_resample_ctx = sws_getContext(
1164
                ist->st->codec->width,
1165
                ist->st->codec->height,
1166
                ist->st->codec->pix_fmt,
1167
                ost->st->codec->width,
1168
                ost->st->codec->height,
1169
                ost->st->codec->pix_fmt,
1170
                sws_flags, NULL, NULL, NULL);
1171
            if (ost->img_resample_ctx == NULL) {
1172
                fprintf(stderr, "Cannot get resampling context\n");
1173
                ffmpeg_exit(1);
1174
            }
1175
        }
1176
        sws_scale(ost->img_resample_ctx, formatted_picture->data, formatted_picture->linesize,
1177
              0, ost->resample_height, resampling_dst->data, resampling_dst->linesize);
1178
    }
1179
#endif
1180

    
1181
    /* duplicates frame if needed */
1182
    for(i=0;i<nb_frames;i++) {
1183
        AVPacket pkt;
1184
        av_init_packet(&pkt);
1185
        pkt.stream_index= ost->index;
1186

    
1187
        if (s->oformat->flags & AVFMT_RAWPICTURE) {
1188
            /* raw pictures are written as AVPicture structure to
1189
               avoid any copies. We support temorarily the older
1190
               method. */
1191
            AVFrame* old_frame = enc->coded_frame;
1192
            enc->coded_frame = dec->coded_frame; //FIXME/XXX remove this hack
1193
            pkt.data= (uint8_t *)final_picture;
1194
            pkt.size=  sizeof(AVPicture);
1195
            pkt.pts= av_rescale_q(ost->sync_opts, enc->time_base, ost->st->time_base);
1196
            pkt.flags |= AV_PKT_FLAG_KEY;
1197

    
1198
            write_frame(s, &pkt, ost->st->codec, ost->bitstream_filters);
1199
            enc->coded_frame = old_frame;
1200
        } else {
1201
            AVFrame big_picture;
1202

    
1203
            big_picture= *final_picture;
1204
            /* better than nothing: use input picture interlaced
1205
               settings */
1206
            big_picture.interlaced_frame = in_picture->interlaced_frame;
1207
            if(avcodec_opts[AVMEDIA_TYPE_VIDEO]->flags & (CODEC_FLAG_INTERLACED_DCT|CODEC_FLAG_INTERLACED_ME)){
1208
                if(top_field_first == -1)
1209
                    big_picture.top_field_first = in_picture->top_field_first;
1210
                else
1211
                    big_picture.top_field_first = top_field_first;
1212
            }
1213

    
1214
            /* handles sameq here. This is not correct because it may
1215
               not be a global option */
1216
            big_picture.quality = same_quality ? ist->st->quality : ost->st->quality;
1217
            if(!me_threshold)
1218
                big_picture.pict_type = 0;
1219
//            big_picture.pts = AV_NOPTS_VALUE;
1220
            big_picture.pts= ost->sync_opts;
1221
//            big_picture.pts= av_rescale(ost->sync_opts, AV_TIME_BASE*(int64_t)enc->time_base.num, enc->time_base.den);
1222
//av_log(NULL, AV_LOG_DEBUG, "%"PRId64" -> encoder\n", ost->sync_opts);
1223
            if (ost->forced_kf_index < ost->forced_kf_count &&
1224
                big_picture.pts >= ost->forced_kf_pts[ost->forced_kf_index]) {
1225
                big_picture.pict_type = FF_I_TYPE;
1226
                ost->forced_kf_index++;
1227
            }
1228
            ret = avcodec_encode_video(enc,
1229
                                       bit_buffer, bit_buffer_size,
1230
                                       &big_picture);
1231
            if (ret < 0) {
1232
                fprintf(stderr, "Video encoding failed\n");
1233
                ffmpeg_exit(1);
1234
            }
1235

    
1236
            if(ret>0){
1237
                pkt.data= bit_buffer;
1238
                pkt.size= ret;
1239
                if(enc->coded_frame->pts != AV_NOPTS_VALUE)
1240
                    pkt.pts= av_rescale_q(enc->coded_frame->pts, enc->time_base, ost->st->time_base);
1241
/*av_log(NULL, AV_LOG_DEBUG, "encoder -> %"PRId64"/%"PRId64"\n",
1242
   pkt.pts != AV_NOPTS_VALUE ? av_rescale(pkt.pts, enc->time_base.den, AV_TIME_BASE*(int64_t)enc->time_base.num) : -1,
1243
   pkt.dts != AV_NOPTS_VALUE ? av_rescale(pkt.dts, enc->time_base.den, AV_TIME_BASE*(int64_t)enc->time_base.num) : -1);*/
1244

    
1245
                if(enc->coded_frame->key_frame)
1246
                    pkt.flags |= AV_PKT_FLAG_KEY;
1247
                write_frame(s, &pkt, ost->st->codec, ost->bitstream_filters);
1248
                *frame_size = ret;
1249
                video_size += ret;
1250
                //fprintf(stderr,"\nFrame: %3d size: %5d type: %d",
1251
                //        enc->frame_number-1, ret, enc->pict_type);
1252
                /* if two pass, output log */
1253
                if (ost->logfile && enc->stats_out) {
1254
                    fprintf(ost->logfile, "%s", enc->stats_out);
1255
                }
1256
            }
1257
        }
1258
        ost->sync_opts++;
1259
        ost->frame_number++;
1260
    }
1261
}
1262

    
1263
static double psnr(double d){
1264
    return -10.0*log(d)/log(10.0);
1265
}
1266

    
1267
static void do_video_stats(AVFormatContext *os, AVOutputStream *ost,
1268
                           int frame_size)
1269
{
1270
    AVCodecContext *enc;
1271
    int frame_number;
1272
    double ti1, bitrate, avg_bitrate;
1273

    
1274
    /* this is executed just the first time do_video_stats is called */
1275
    if (!vstats_file) {
1276
        vstats_file = fopen(vstats_filename, "w");
1277
        if (!vstats_file) {
1278
            perror("fopen");
1279
            ffmpeg_exit(1);
1280
        }
1281
    }
1282

    
1283
    enc = ost->st->codec;
1284
    if (enc->codec_type == AVMEDIA_TYPE_VIDEO) {
1285
        frame_number = ost->frame_number;
1286
        fprintf(vstats_file, "frame= %5d q= %2.1f ", frame_number, enc->coded_frame->quality/(float)FF_QP2LAMBDA);
1287
        if (enc->flags&CODEC_FLAG_PSNR)
1288
            fprintf(vstats_file, "PSNR= %6.2f ", psnr(enc->coded_frame->error[0]/(enc->width*enc->height*255.0*255.0)));
1289

    
1290
        fprintf(vstats_file,"f_size= %6d ", frame_size);
1291
        /* compute pts value */
1292
        ti1 = ost->sync_opts * av_q2d(enc->time_base);
1293
        if (ti1 < 0.01)
1294
            ti1 = 0.01;
1295

    
1296
        bitrate = (frame_size * 8) / av_q2d(enc->time_base) / 1000.0;
1297
        avg_bitrate = (double)(video_size * 8) / ti1 / 1000.0;
1298
        fprintf(vstats_file, "s_size= %8.0fkB time= %0.3f br= %7.1fkbits/s avg_br= %7.1fkbits/s ",
1299
            (double)video_size / 1024, ti1, bitrate, avg_bitrate);
1300
        fprintf(vstats_file,"type= %c\n", av_get_pict_type_char(enc->coded_frame->pict_type));
1301
    }
1302
}
1303

    
1304
static void print_report(AVFormatContext **output_files,
1305
                         AVOutputStream **ost_table, int nb_ostreams,
1306
                         int is_last_report)
1307
{
1308
    char buf[1024];
1309
    AVOutputStream *ost;
1310
    AVFormatContext *oc;
1311
    int64_t total_size;
1312
    AVCodecContext *enc;
1313
    int frame_number, vid, i;
1314
    double bitrate, ti1, pts;
1315
    static int64_t last_time = -1;
1316
    static int qp_histogram[52];
1317

    
1318
    if (!is_last_report) {
1319
        int64_t cur_time;
1320
        /* display the report every 0.5 seconds */
1321
        cur_time = av_gettime();
1322
        if (last_time == -1) {
1323
            last_time = cur_time;
1324
            return;
1325
        }
1326
        if ((cur_time - last_time) < 500000)
1327
            return;
1328
        last_time = cur_time;
1329
    }
1330

    
1331

    
1332
    oc = output_files[0];
1333

    
1334
    total_size = url_fsize(oc->pb);
1335
    if(total_size<0) // FIXME improve url_fsize() so it works with non seekable output too
1336
        total_size= url_ftell(oc->pb);
1337

    
1338
    buf[0] = '\0';
1339
    ti1 = 1e10;
1340
    vid = 0;
1341
    for(i=0;i<nb_ostreams;i++) {
1342
        ost = ost_table[i];
1343
        enc = ost->st->codec;
1344
        if (vid && enc->codec_type == AVMEDIA_TYPE_VIDEO) {
1345
            snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "q=%2.1f ",
1346
                     !ost->st->stream_copy ?
1347
                     enc->coded_frame->quality/(float)FF_QP2LAMBDA : -1);
1348
        }
1349
        if (!vid && enc->codec_type == AVMEDIA_TYPE_VIDEO) {
1350
            float t = (av_gettime()-timer_start) / 1000000.0;
1351

    
1352
            frame_number = ost->frame_number;
1353
            snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "frame=%5d fps=%3d q=%3.1f ",
1354
                     frame_number, (t>1)?(int)(frame_number/t+0.5) : 0,
1355
                     !ost->st->stream_copy ?
1356
                     enc->coded_frame->quality/(float)FF_QP2LAMBDA : -1);
1357
            if(is_last_report)
1358
                snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "L");
1359
            if(qp_hist){
1360
                int j;
1361
                int qp= lrintf(enc->coded_frame->quality/(float)FF_QP2LAMBDA);
1362
                if(qp>=0 && qp<FF_ARRAY_ELEMS(qp_histogram))
1363
                    qp_histogram[qp]++;
1364
                for(j=0; j<32; j++)
1365
                    snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "%X", (int)lrintf(log(qp_histogram[j]+1)/log(2)));
1366
            }
1367
            if (enc->flags&CODEC_FLAG_PSNR){
1368
                int j;
1369
                double error, error_sum=0;
1370
                double scale, scale_sum=0;
1371
                char type[3]= {'Y','U','V'};
1372
                snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "PSNR=");
1373
                for(j=0; j<3; j++){
1374
                    if(is_last_report){
1375
                        error= enc->error[j];
1376
                        scale= enc->width*enc->height*255.0*255.0*frame_number;
1377
                    }else{
1378
                        error= enc->coded_frame->error[j];
1379
                        scale= enc->width*enc->height*255.0*255.0;
1380
                    }
1381
                    if(j) scale/=4;
1382
                    error_sum += error;
1383
                    scale_sum += scale;
1384
                    snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "%c:%2.2f ", type[j], psnr(error/scale));
1385
                }
1386
                snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "*:%2.2f ", psnr(error_sum/scale_sum));
1387
            }
1388
            vid = 1;
1389
        }
1390
        /* compute min output value */
1391
        pts = (double)ost->st->pts.val * av_q2d(ost->st->time_base);
1392
        if ((pts < ti1) && (pts > 0))
1393
            ti1 = pts;
1394
    }
1395
    if (ti1 < 0.01)
1396
        ti1 = 0.01;
1397

    
1398
    if (verbose || is_last_report) {
1399
        bitrate = (double)(total_size * 8) / ti1 / 1000.0;
1400

    
1401
        snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
1402
            "size=%8.0fkB time=%0.2f bitrate=%6.1fkbits/s",
1403
            (double)total_size / 1024, ti1, bitrate);
1404

    
1405
        if (nb_frames_dup || nb_frames_drop)
1406
          snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), " dup=%d drop=%d",
1407
                  nb_frames_dup, nb_frames_drop);
1408

    
1409
        if (verbose >= 0)
1410
            fprintf(stderr, "%s    \r", buf);
1411

    
1412
        fflush(stderr);
1413
    }
1414

    
1415
    if (is_last_report && verbose >= 0){
1416
        int64_t raw= audio_size + video_size + extra_size;
1417
        fprintf(stderr, "\n");
1418
        fprintf(stderr, "video:%1.0fkB audio:%1.0fkB global headers:%1.0fkB muxing overhead %f%%\n",
1419
                video_size/1024.0,
1420
                audio_size/1024.0,
1421
                extra_size/1024.0,
1422
                100.0*(total_size - raw)/raw
1423
        );
1424
    }
1425
}
1426

    
1427
/* pkt = NULL means EOF (needed to flush decoder buffers) */
1428
static int output_packet(AVInputStream *ist, int ist_index,
1429
                         AVOutputStream **ost_table, int nb_ostreams,
1430
                         const AVPacket *pkt)
1431
{
1432
    AVFormatContext *os;
1433
    AVOutputStream *ost;
1434
    int ret, i;
1435
    int got_picture;
1436
    AVFrame picture;
1437
    void *buffer_to_free;
1438
    static unsigned int samples_size= 0;
1439
    AVSubtitle subtitle, *subtitle_to_free;
1440
    int64_t pkt_pts = AV_NOPTS_VALUE;
1441
#if CONFIG_AVFILTER
1442
    int frame_available;
1443
#endif
1444

    
1445
    AVPacket avpkt;
1446
    int bps = av_get_bits_per_sample_fmt(ist->st->codec->sample_fmt)>>3;
1447

    
1448
    if(ist->next_pts == AV_NOPTS_VALUE)
1449
        ist->next_pts= ist->pts;
1450

    
1451
    if (pkt == NULL) {
1452
        /* EOF handling */
1453
        av_init_packet(&avpkt);
1454
        avpkt.data = NULL;
1455
        avpkt.size = 0;
1456
        goto handle_eof;
1457
    } else {
1458
        avpkt = *pkt;
1459
    }
1460

    
1461
    if(pkt->dts != AV_NOPTS_VALUE)
1462
        ist->next_pts = ist->pts = av_rescale_q(pkt->dts, ist->st->time_base, AV_TIME_BASE_Q);
1463
    if(pkt->pts != AV_NOPTS_VALUE)
1464
        pkt_pts = av_rescale_q(pkt->pts, ist->st->time_base, AV_TIME_BASE_Q);
1465

    
1466
    //while we have more to decode or while the decoder did output something on EOF
1467
    while (avpkt.size > 0 || (!pkt && ist->next_pts != ist->pts)) {
1468
        uint8_t *data_buf, *decoded_data_buf;
1469
        int data_size, decoded_data_size;
1470
    handle_eof:
1471
        ist->pts= ist->next_pts;
1472

    
1473
        if(avpkt.size && avpkt.size != pkt->size &&
1474
           ((!ist->showed_multi_packet_warning && verbose>0) || verbose>1)){
1475
            fprintf(stderr, "Multiple frames in a packet from stream %d\n", pkt->stream_index);
1476
            ist->showed_multi_packet_warning=1;
1477
        }
1478

    
1479
        /* decode the packet if needed */
1480
        decoded_data_buf = NULL; /* fail safe */
1481
        decoded_data_size= 0;
1482
        data_buf  = avpkt.data;
1483
        data_size = avpkt.size;
1484
        subtitle_to_free = NULL;
1485
        if (ist->decoding_needed) {
1486
            switch(ist->st->codec->codec_type) {
1487
            case AVMEDIA_TYPE_AUDIO:{
1488
                if(pkt && samples_size < FFMAX(pkt->size*sizeof(*samples), AVCODEC_MAX_AUDIO_FRAME_SIZE)) {
1489
                    samples_size = FFMAX(pkt->size*sizeof(*samples), AVCODEC_MAX_AUDIO_FRAME_SIZE);
1490
                    av_free(samples);
1491
                    samples= av_malloc(samples_size);
1492
                }
1493
                decoded_data_size= samples_size;
1494
                    /* XXX: could avoid copy if PCM 16 bits with same
1495
                       endianness as CPU */
1496
                ret = avcodec_decode_audio3(ist->st->codec, samples, &decoded_data_size,
1497
                                            &avpkt);
1498
                if (ret < 0)
1499
                    goto fail_decode;
1500
                avpkt.data += ret;
1501
                avpkt.size -= ret;
1502
                data_size   = ret;
1503
                /* Some bug in mpeg audio decoder gives */
1504
                /* decoded_data_size < 0, it seems they are overflows */
1505
                if (decoded_data_size <= 0) {
1506
                    /* no audio frame */
1507
                    continue;
1508
                }
1509
                decoded_data_buf = (uint8_t *)samples;
1510
                ist->next_pts += ((int64_t)AV_TIME_BASE/bps * decoded_data_size) /
1511
                    (ist->st->codec->sample_rate * ist->st->codec->channels);
1512
                break;}
1513
            case AVMEDIA_TYPE_VIDEO:
1514
                    decoded_data_size = (ist->st->codec->width * ist->st->codec->height * 3) / 2;
1515
                    /* XXX: allocate picture correctly */
1516
                    avcodec_get_frame_defaults(&picture);
1517
                    ist->st->codec->reordered_opaque = pkt_pts;
1518
                    pkt_pts = AV_NOPTS_VALUE;
1519

    
1520
                    ret = avcodec_decode_video2(ist->st->codec,
1521
                                                &picture, &got_picture, &avpkt);
1522
                    ist->st->quality= picture.quality;
1523
                    if (ret < 0)
1524
                        goto fail_decode;
1525
                    if (!got_picture) {
1526
                        /* no picture yet */
1527
                        goto discard_packet;
1528
                    }
1529
                    ist->next_pts = ist->pts = guess_correct_pts(&ist->pts_ctx, picture.reordered_opaque, ist->pts);
1530
                    if (ist->st->codec->time_base.num != 0) {
1531
                        int ticks= ist->st->parser ? ist->st->parser->repeat_pict+1 : ist->st->codec->ticks_per_frame;
1532
                        ist->next_pts += ((int64_t)AV_TIME_BASE *
1533
                                          ist->st->codec->time_base.num * ticks) /
1534
                            ist->st->codec->time_base.den;
1535
                    }
1536
                    avpkt.size = 0;
1537
                    break;
1538
            case AVMEDIA_TYPE_SUBTITLE:
1539
                ret = avcodec_decode_subtitle2(ist->st->codec,
1540
                                               &subtitle, &got_picture, &avpkt);
1541
                if (ret < 0)
1542
                    goto fail_decode;
1543
                if (!got_picture) {
1544
                    goto discard_packet;
1545
                }
1546
                subtitle_to_free = &subtitle;
1547
                avpkt.size = 0;
1548
                break;
1549
            default:
1550
                goto fail_decode;
1551
            }
1552
        } else {
1553
            switch(ist->st->codec->codec_type) {
1554
            case AVMEDIA_TYPE_AUDIO:
1555
                ist->next_pts += ((int64_t)AV_TIME_BASE * ist->st->codec->frame_size) /
1556
                    ist->st->codec->sample_rate;
1557
                break;
1558
            case AVMEDIA_TYPE_VIDEO:
1559
                if (ist->st->codec->time_base.num != 0) {
1560
                    int ticks= ist->st->parser ? ist->st->parser->repeat_pict+1 : ist->st->codec->ticks_per_frame;
1561
                    ist->next_pts += ((int64_t)AV_TIME_BASE *
1562
                                      ist->st->codec->time_base.num * ticks) /
1563
                        ist->st->codec->time_base.den;
1564
                }
1565
                break;
1566
            }
1567
            ret = avpkt.size;
1568
            avpkt.size = 0;
1569
        }
1570

    
1571
        buffer_to_free = NULL;
1572
        if (ist->st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
1573
            pre_process_video_frame(ist, (AVPicture *)&picture,
1574
                                    &buffer_to_free);
1575
        }
1576

    
1577
#if CONFIG_AVFILTER
1578
        if (ist->st->codec->codec_type == AVMEDIA_TYPE_VIDEO && ist->input_video_filter) {
1579
            // add it to be filtered
1580
            av_vsrc_buffer_add_frame(ist->input_video_filter, &picture,
1581
                                     ist->pts,
1582
                                     ist->st->codec->sample_aspect_ratio);
1583
        }
1584
#endif
1585

    
1586
        // preprocess audio (volume)
1587
        if (ist->st->codec->codec_type == AVMEDIA_TYPE_AUDIO) {
1588
            if (audio_volume != 256) {
1589
                short *volp;
1590
                volp = samples;
1591
                for(i=0;i<(decoded_data_size / sizeof(short));i++) {
1592
                    int v = ((*volp) * audio_volume + 128) >> 8;
1593
                    if (v < -32768) v = -32768;
1594
                    if (v >  32767) v = 32767;
1595
                    *volp++ = v;
1596
                }
1597
            }
1598
        }
1599

    
1600
        /* frame rate emulation */
1601
        if (rate_emu) {
1602
            int64_t pts = av_rescale(ist->pts, 1000000, AV_TIME_BASE);
1603
            int64_t now = av_gettime() - ist->start;
1604
            if (pts > now)
1605
                usleep(pts - now);
1606
        }
1607
#if CONFIG_AVFILTER
1608
        frame_available = ist->st->codec->codec_type != AVMEDIA_TYPE_VIDEO ||
1609
            !ist->output_video_filter || avfilter_poll_frame(ist->output_video_filter->inputs[0]);
1610
#endif
1611
        /* if output time reached then transcode raw format,
1612
           encode packets and output them */
1613
        if (start_time == 0 || ist->pts >= start_time)
1614
#if CONFIG_AVFILTER
1615
        while (frame_available) {
1616
            AVRational ist_pts_tb;
1617
            if (ist->st->codec->codec_type == AVMEDIA_TYPE_VIDEO && ist->output_video_filter)
1618
                get_filtered_video_frame(ist->output_video_filter, &picture, &ist->picref, &ist_pts_tb);
1619
            if (ist->picref)
1620
                ist->pts = av_rescale_q(ist->picref->pts, ist_pts_tb, AV_TIME_BASE_Q);
1621
#endif
1622
            for(i=0;i<nb_ostreams;i++) {
1623
                int frame_size;
1624

    
1625
                ost = ost_table[i];
1626
                if (ost->source_index == ist_index) {
1627
                    os = output_files[ost->file_index];
1628

    
1629
                    /* set the input output pts pairs */
1630
                    //ost->sync_ipts = (double)(ist->pts + input_files_ts_offset[ist->file_index] - start_time)/ AV_TIME_BASE;
1631

    
1632
                    if (ost->encoding_needed) {
1633
                        av_assert0(ist->decoding_needed);
1634
                        switch(ost->st->codec->codec_type) {
1635
                        case AVMEDIA_TYPE_AUDIO:
1636
                            do_audio_out(os, ost, ist, decoded_data_buf, decoded_data_size);
1637
                            break;
1638
                        case AVMEDIA_TYPE_VIDEO:
1639
#if CONFIG_AVFILTER
1640
                            if (ist->picref->video)
1641
                                ost->st->codec->sample_aspect_ratio = ist->picref->video->pixel_aspect;
1642
#endif
1643
                            do_video_out(os, ost, ist, &picture, &frame_size);
1644
                            if (vstats_filename && frame_size)
1645
                                do_video_stats(os, ost, frame_size);
1646
                            break;
1647
                        case AVMEDIA_TYPE_SUBTITLE:
1648
                            do_subtitle_out(os, ost, ist, &subtitle,
1649
                                            pkt->pts);
1650
                            break;
1651
                        default:
1652
                            abort();
1653
                        }
1654
                    } else {
1655
                        AVFrame avframe; //FIXME/XXX remove this
1656
                        AVPacket opkt;
1657
                        int64_t ost_tb_start_time= av_rescale_q(start_time, AV_TIME_BASE_Q, ost->st->time_base);
1658

    
1659
                        av_init_packet(&opkt);
1660

    
1661
                        if ((!ost->frame_number && !(pkt->flags & AV_PKT_FLAG_KEY)) && !copy_initial_nonkeyframes)
1662
                            continue;
1663

    
1664
                        /* no reencoding needed : output the packet directly */
1665
                        /* force the input stream PTS */
1666

    
1667
                        avcodec_get_frame_defaults(&avframe);
1668
                        ost->st->codec->coded_frame= &avframe;
1669
                        avframe.key_frame = pkt->flags & AV_PKT_FLAG_KEY;
1670

    
1671
                        if(ost->st->codec->codec_type == AVMEDIA_TYPE_AUDIO)
1672
                            audio_size += data_size;
1673
                        else if (ost->st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
1674
                            video_size += data_size;
1675
                            ost->sync_opts++;
1676
                        }
1677

    
1678
                        opkt.stream_index= ost->index;
1679
                        if(pkt->pts != AV_NOPTS_VALUE)
1680
                            opkt.pts= av_rescale_q(pkt->pts, ist->st->time_base, ost->st->time_base) - ost_tb_start_time;
1681
                        else
1682
                            opkt.pts= AV_NOPTS_VALUE;
1683

    
1684
                        if (pkt->dts == AV_NOPTS_VALUE)
1685
                            opkt.dts = av_rescale_q(ist->pts, AV_TIME_BASE_Q, ost->st->time_base);
1686
                        else
1687
                            opkt.dts = av_rescale_q(pkt->dts, ist->st->time_base, ost->st->time_base);
1688
                        opkt.dts -= ost_tb_start_time;
1689

    
1690
                        opkt.duration = av_rescale_q(pkt->duration, ist->st->time_base, ost->st->time_base);
1691
                        opkt.flags= pkt->flags;
1692

    
1693
                        //FIXME remove the following 2 lines they shall be replaced by the bitstream filters
1694
                        if(   ost->st->codec->codec_id != CODEC_ID_H264
1695
                           && ost->st->codec->codec_id != CODEC_ID_MPEG1VIDEO
1696
                           && ost->st->codec->codec_id != CODEC_ID_MPEG2VIDEO
1697
                           ) {
1698
                            if(av_parser_change(ist->st->parser, ost->st->codec, &opkt.data, &opkt.size, data_buf, data_size, pkt->flags & AV_PKT_FLAG_KEY))
1699
                                opkt.destruct= av_destruct_packet;
1700
                        } else {
1701
                            opkt.data = data_buf;
1702
                            opkt.size = data_size;
1703
                        }
1704

    
1705
                        write_frame(os, &opkt, ost->st->codec, ost->bitstream_filters);
1706
                        ost->st->codec->frame_number++;
1707
                        ost->frame_number++;
1708
                        av_free_packet(&opkt);
1709
                    }
1710
                }
1711
            }
1712

    
1713
#if CONFIG_AVFILTER
1714
            frame_available = (ist->st->codec->codec_type == AVMEDIA_TYPE_VIDEO) &&
1715
                              ist->output_video_filter && avfilter_poll_frame(ist->output_video_filter->inputs[0]);
1716
            if(ist->picref)
1717
                avfilter_unref_buffer(ist->picref);
1718
        }
1719
#endif
1720
        av_free(buffer_to_free);
1721
        /* XXX: allocate the subtitles in the codec ? */
1722
        if (subtitle_to_free) {
1723
            if (subtitle_to_free->rects != NULL) {
1724
                for (i = 0; i < subtitle_to_free->num_rects; i++) {
1725
                    av_freep(&subtitle_to_free->rects[i]->pict.data[0]);
1726
                    av_freep(&subtitle_to_free->rects[i]->pict.data[1]);
1727
                    av_freep(&subtitle_to_free->rects[i]);
1728
                }
1729
                av_freep(&subtitle_to_free->rects);
1730
            }
1731
            subtitle_to_free->num_rects = 0;
1732
            subtitle_to_free = NULL;
1733
        }
1734
    }
1735
 discard_packet:
1736
    if (pkt == NULL) {
1737
        /* EOF handling */
1738

    
1739
        for(i=0;i<nb_ostreams;i++) {
1740
            ost = ost_table[i];
1741
            if (ost->source_index == ist_index) {
1742
                AVCodecContext *enc= ost->st->codec;
1743
                os = output_files[ost->file_index];
1744

    
1745
                if(ost->st->codec->codec_type == AVMEDIA_TYPE_AUDIO && enc->frame_size <=1)
1746
                    continue;
1747
                if(ost->st->codec->codec_type == AVMEDIA_TYPE_VIDEO && (os->oformat->flags & AVFMT_RAWPICTURE))
1748
                    continue;
1749

    
1750
                if (ost->encoding_needed) {
1751
                    for(;;) {
1752
                        AVPacket pkt;
1753
                        int fifo_bytes;
1754
                        av_init_packet(&pkt);
1755
                        pkt.stream_index= ost->index;
1756

    
1757
                        switch(ost->st->codec->codec_type) {
1758
                        case AVMEDIA_TYPE_AUDIO:
1759
                            fifo_bytes = av_fifo_size(ost->fifo);
1760
                            ret = 0;
1761
                            /* encode any samples remaining in fifo */
1762
                            if (fifo_bytes > 0) {
1763
                                int osize = av_get_bits_per_sample_fmt(enc->sample_fmt) >> 3;
1764
                                int fs_tmp = enc->frame_size;
1765

    
1766
                                av_fifo_generic_read(ost->fifo, audio_buf, fifo_bytes, NULL);
1767
                                if (enc->codec->capabilities & CODEC_CAP_SMALL_LAST_FRAME) {
1768
                                    enc->frame_size = fifo_bytes / (osize * enc->channels);
1769
                                } else { /* pad */
1770
                                    int frame_bytes = enc->frame_size*osize*enc->channels;
1771
                                    if (allocated_audio_buf_size < frame_bytes)
1772
                                        ffmpeg_exit(1);
1773
                                    memset(audio_buf+fifo_bytes, 0, frame_bytes - fifo_bytes);
1774
                                }
1775

    
1776
                                ret = avcodec_encode_audio(enc, bit_buffer, bit_buffer_size, (short *)audio_buf);
1777
                                pkt.duration = av_rescale((int64_t)enc->frame_size*ost->st->time_base.den,
1778
                                                          ost->st->time_base.num, enc->sample_rate);
1779
                                enc->frame_size = fs_tmp;
1780
                            }
1781
                            if(ret <= 0) {
1782
                                ret = avcodec_encode_audio(enc, bit_buffer, bit_buffer_size, NULL);
1783
                            }
1784
                            if (ret < 0) {
1785
                                fprintf(stderr, "Audio encoding failed\n");
1786
                                ffmpeg_exit(1);
1787
                            }
1788
                            audio_size += ret;
1789
                            pkt.flags |= AV_PKT_FLAG_KEY;
1790
                            break;
1791
                        case AVMEDIA_TYPE_VIDEO:
1792
                            ret = avcodec_encode_video(enc, bit_buffer, bit_buffer_size, NULL);
1793
                            if (ret < 0) {
1794
                                fprintf(stderr, "Video encoding failed\n");
1795
                                ffmpeg_exit(1);
1796
                            }
1797
                            video_size += ret;
1798
                            if(enc->coded_frame && enc->coded_frame->key_frame)
1799
                                pkt.flags |= AV_PKT_FLAG_KEY;
1800
                            if (ost->logfile && enc->stats_out) {
1801
                                fprintf(ost->logfile, "%s", enc->stats_out);
1802
                            }
1803
                            break;
1804
                        default:
1805
                            ret=-1;
1806
                        }
1807

    
1808
                        if(ret<=0)
1809
                            break;
1810
                        pkt.data= bit_buffer;
1811
                        pkt.size= ret;
1812
                        if(enc->coded_frame && enc->coded_frame->pts != AV_NOPTS_VALUE)
1813
                            pkt.pts= av_rescale_q(enc->coded_frame->pts, enc->time_base, ost->st->time_base);
1814
                        write_frame(os, &pkt, ost->st->codec, ost->bitstream_filters);
1815
                    }
1816
                }
1817
            }
1818
        }
1819
    }
1820

    
1821
    return 0;
1822
 fail_decode:
1823
    return -1;
1824
}
1825

    
1826
static void print_sdp(AVFormatContext **avc, int n)
1827
{
1828
    char sdp[2048];
1829

    
1830
    avf_sdp_create(avc, n, sdp, sizeof(sdp));
1831
    printf("SDP:\n%s\n", sdp);
1832
    fflush(stdout);
1833
}
1834

    
1835
static int copy_chapters(int infile, int outfile)
1836
{
1837
    AVFormatContext *is = input_files[infile];
1838
    AVFormatContext *os = output_files[outfile];
1839
    int i;
1840

    
1841
    for (i = 0; i < is->nb_chapters; i++) {
1842
        AVChapter *in_ch = is->chapters[i], *out_ch;
1843
        AVMetadataTag *t = NULL;
1844
        int64_t ts_off   = av_rescale_q(start_time - input_files_ts_offset[infile],
1845
                                      AV_TIME_BASE_Q, in_ch->time_base);
1846
        int64_t rt       = (recording_time == INT64_MAX) ? INT64_MAX :
1847
                           av_rescale_q(recording_time, AV_TIME_BASE_Q, in_ch->time_base);
1848

    
1849

    
1850
        if (in_ch->end < ts_off)
1851
            continue;
1852
        if (rt != INT64_MAX && in_ch->start > rt + ts_off)
1853
            break;
1854

    
1855
        out_ch = av_mallocz(sizeof(AVChapter));
1856
        if (!out_ch)
1857
            return AVERROR(ENOMEM);
1858

    
1859
        out_ch->id        = in_ch->id;
1860
        out_ch->time_base = in_ch->time_base;
1861
        out_ch->start     = FFMAX(0,  in_ch->start - ts_off);
1862
        out_ch->end       = FFMIN(rt, in_ch->end   - ts_off);
1863

    
1864
        if (metadata_chapters_autocopy)
1865
            while ((t = av_metadata_get(in_ch->metadata, "", t, AV_METADATA_IGNORE_SUFFIX)))
1866
                av_metadata_set2(&out_ch->metadata, t->key, t->value, 0);
1867

    
1868
        os->nb_chapters++;
1869
        os->chapters = av_realloc(os->chapters, sizeof(AVChapter)*os->nb_chapters);
1870
        if (!os->chapters)
1871
            return AVERROR(ENOMEM);
1872
        os->chapters[os->nb_chapters - 1] = out_ch;
1873
    }
1874
    return 0;
1875
}
1876

    
1877
static void parse_forced_key_frames(char *kf, AVOutputStream *ost,
1878
                                    AVCodecContext *avctx)
1879
{
1880
    char *p;
1881
    int n = 1, i;
1882
    int64_t t;
1883

    
1884
    for (p = kf; *p; p++)
1885
        if (*p == ',')
1886
            n++;
1887
    ost->forced_kf_count = n;
1888
    ost->forced_kf_pts = av_malloc(sizeof(*ost->forced_kf_pts) * n);
1889
    if (!ost->forced_kf_pts) {
1890
        av_log(NULL, AV_LOG_FATAL, "Could not allocate forced key frames array.\n");
1891
        ffmpeg_exit(1);
1892
    }
1893
    for (i = 0; i < n; i++) {
1894
        p = i ? strchr(p, ',') + 1 : kf;
1895
        t = parse_time_or_die("force_key_frames", p, 1);
1896
        ost->forced_kf_pts[i] = av_rescale_q(t, AV_TIME_BASE_Q, avctx->time_base);
1897
    }
1898
}
1899

    
1900
/*
1901
 * The following code is the main loop of the file converter
1902
 */
1903
static int transcode(AVFormatContext **output_files,
1904
                     int nb_output_files,
1905
                     AVFormatContext **input_files,
1906
                     int nb_input_files,
1907
                     AVStreamMap *stream_maps, int nb_stream_maps)
1908
{
1909
    int ret = 0, i, j, k, n, nb_istreams = 0, nb_ostreams = 0;
1910
    AVFormatContext *is, *os;
1911
    AVCodecContext *codec, *icodec;
1912
    AVOutputStream *ost, **ost_table = NULL;
1913
    AVInputStream *ist, **ist_table = NULL;
1914
    AVInputFile *file_table;
1915
    char error[1024];
1916
    int key;
1917
    int want_sdp = 1;
1918
    uint8_t no_packet[MAX_FILES]={0};
1919
    int no_packet_count=0;
1920

    
1921
    file_table= av_mallocz(nb_input_files * sizeof(AVInputFile));
1922
    if (!file_table)
1923
        goto fail;
1924

    
1925
    /* input stream init */
1926
    j = 0;
1927
    for(i=0;i<nb_input_files;i++) {
1928
        is = input_files[i];
1929
        file_table[i].ist_index = j;
1930
        file_table[i].nb_streams = is->nb_streams;
1931
        j += is->nb_streams;
1932
    }
1933
    nb_istreams = j;
1934

    
1935
    ist_table = av_mallocz(nb_istreams * sizeof(AVInputStream *));
1936
    if (!ist_table)
1937
        goto fail;
1938

    
1939
    for(i=0;i<nb_istreams;i++) {
1940
        ist = av_mallocz(sizeof(AVInputStream));
1941
        if (!ist)
1942
            goto fail;
1943
        ist_table[i] = ist;
1944
    }
1945
    j = 0;
1946
    for(i=0;i<nb_input_files;i++) {
1947
        is = input_files[i];
1948
        for(k=0;k<is->nb_streams;k++) {
1949
            ist = ist_table[j++];
1950
            ist->st = is->streams[k];
1951
            ist->file_index = i;
1952
            ist->index = k;
1953
            ist->discard = 1; /* the stream is discarded by default
1954
                                 (changed later) */
1955

    
1956
            if (rate_emu) {
1957
                ist->start = av_gettime();
1958
            }
1959
        }
1960
    }
1961

    
1962
    /* output stream init */
1963
    nb_ostreams = 0;
1964
    for(i=0;i<nb_output_files;i++) {
1965
        os = output_files[i];
1966
        if (!os->nb_streams) {
1967
            dump_format(output_files[i], i, output_files[i]->filename, 1);
1968
            fprintf(stderr, "Output file #%d does not contain any stream\n", i);
1969
            ret = AVERROR(EINVAL);
1970
            goto fail;
1971
        }
1972
        nb_ostreams += os->nb_streams;
1973
    }
1974
    if (nb_stream_maps > 0 && nb_stream_maps != nb_ostreams) {
1975
        fprintf(stderr, "Number of stream maps must match number of output streams\n");
1976
        ret = AVERROR(EINVAL);
1977
        goto fail;
1978
    }
1979

    
1980
    /* Sanity check the mapping args -- do the input files & streams exist? */
1981
    for(i=0;i<nb_stream_maps;i++) {
1982
        int fi = stream_maps[i].file_index;
1983
        int si = stream_maps[i].stream_index;
1984

    
1985
        if (fi < 0 || fi > nb_input_files - 1 ||
1986
            si < 0 || si > file_table[fi].nb_streams - 1) {
1987
            fprintf(stderr,"Could not find input stream #%d.%d\n", fi, si);
1988
            ret = AVERROR(EINVAL);
1989
            goto fail;
1990
        }
1991
        fi = stream_maps[i].sync_file_index;
1992
        si = stream_maps[i].sync_stream_index;
1993
        if (fi < 0 || fi > nb_input_files - 1 ||
1994
            si < 0 || si > file_table[fi].nb_streams - 1) {
1995
            fprintf(stderr,"Could not find sync stream #%d.%d\n", fi, si);
1996
            ret = AVERROR(EINVAL);
1997
            goto fail;
1998
        }
1999
    }
2000

    
2001
    ost_table = av_mallocz(sizeof(AVOutputStream *) * nb_ostreams);
2002
    if (!ost_table)
2003
        goto fail;
2004
    n = 0;
2005
    for(k=0;k<nb_output_files;k++) {
2006
        os = output_files[k];
2007
        for(i=0;i<os->nb_streams;i++,n++) {
2008
            int found;
2009
            ost = ost_table[n] = output_streams_for_file[k][i];
2010
            ost->st = os->streams[i];
2011
            if (nb_stream_maps > 0) {
2012
                ost->source_index = file_table[stream_maps[n].file_index].ist_index +
2013
                    stream_maps[n].stream_index;
2014

    
2015
                /* Sanity check that the stream types match */
2016
                if (ist_table[ost->source_index]->st->codec->codec_type != ost->st->codec->codec_type) {
2017
                    int i= ost->file_index;
2018
                    dump_format(output_files[i], i, output_files[i]->filename, 1);
2019
                    fprintf(stderr, "Codec type mismatch for mapping #%d.%d -> #%d.%d\n",
2020
                        stream_maps[n].file_index, stream_maps[n].stream_index,
2021
                        ost->file_index, ost->index);
2022
                    ffmpeg_exit(1);
2023
                }
2024

    
2025
            } else {
2026
                int best_nb_frames=-1;
2027
                /* get corresponding input stream index : we select the first one with the right type */
2028
                found = 0;
2029
                for(j=0;j<nb_istreams;j++) {
2030
                    int skip=0;
2031
                    ist = ist_table[j];
2032
                    if(opt_programid){
2033
                        int pi,si;
2034
                        AVFormatContext *f= input_files[ ist->file_index ];
2035
                        skip=1;
2036
                        for(pi=0; pi<f->nb_programs; pi++){
2037
                            AVProgram *p= f->programs[pi];
2038
                            if(p->id == opt_programid)
2039
                                for(si=0; si<p->nb_stream_indexes; si++){
2040
                                    if(f->streams[ p->stream_index[si] ] == ist->st)
2041
                                        skip=0;
2042
                                }
2043
                        }
2044
                    }
2045
                    if (ist->discard && ist->st->discard != AVDISCARD_ALL && !skip &&
2046
                        ist->st->codec->codec_type == ost->st->codec->codec_type) {
2047
                        if(best_nb_frames < ist->st->codec_info_nb_frames){
2048
                            best_nb_frames= ist->st->codec_info_nb_frames;
2049
                            ost->source_index = j;
2050
                            found = 1;
2051
                        }
2052
                    }
2053
                }
2054

    
2055
                if (!found) {
2056
                    if(! opt_programid) {
2057
                        /* try again and reuse existing stream */
2058
                        for(j=0;j<nb_istreams;j++) {
2059
                            ist = ist_table[j];
2060
                            if (   ist->st->codec->codec_type == ost->st->codec->codec_type
2061
                                && ist->st->discard != AVDISCARD_ALL) {
2062
                                ost->source_index = j;
2063
                                found = 1;
2064
                            }
2065
                        }
2066
                    }
2067
                    if (!found) {
2068
                        int i= ost->file_index;
2069
                        dump_format(output_files[i], i, output_files[i]->filename, 1);
2070
                        fprintf(stderr, "Could not find input stream matching output stream #%d.%d\n",
2071
                                ost->file_index, ost->index);
2072
                        ffmpeg_exit(1);
2073
                    }
2074
                }
2075
            }
2076
            ist = ist_table[ost->source_index];
2077
            ist->discard = 0;
2078
            ost->sync_ist = (nb_stream_maps > 0) ?
2079
                ist_table[file_table[stream_maps[n].sync_file_index].ist_index +
2080
                         stream_maps[n].sync_stream_index] : ist;
2081
        }
2082
    }
2083

    
2084
    /* for each output stream, we compute the right encoding parameters */
2085
    for(i=0;i<nb_ostreams;i++) {
2086
        AVMetadataTag *t = NULL;
2087
        ost = ost_table[i];
2088
        os = output_files[ost->file_index];
2089
        ist = ist_table[ost->source_index];
2090

    
2091
        codec = ost->st->codec;
2092
        icodec = ist->st->codec;
2093

    
2094
        if (metadata_streams_autocopy)
2095
            while ((t = av_metadata_get(ist->st->metadata, "", t, AV_METADATA_IGNORE_SUFFIX))) {
2096
                av_metadata_set2(&ost->st->metadata, t->key, t->value, AV_METADATA_DONT_OVERWRITE);
2097
            }
2098

    
2099
        ost->st->disposition = ist->st->disposition;
2100
        codec->bits_per_raw_sample= icodec->bits_per_raw_sample;
2101
        codec->chroma_sample_location = icodec->chroma_sample_location;
2102

    
2103
        if (ost->st->stream_copy) {
2104
            uint64_t extra_size = (uint64_t)icodec->extradata_size + FF_INPUT_BUFFER_PADDING_SIZE;
2105

    
2106
            if (extra_size > INT_MAX)
2107
                goto fail;
2108

    
2109
            /* if stream_copy is selected, no need to decode or encode */
2110
            codec->codec_id = icodec->codec_id;
2111
            codec->codec_type = icodec->codec_type;
2112

    
2113
            if(!codec->codec_tag){
2114
                if(   !os->oformat->codec_tag
2115
                   || av_codec_get_id (os->oformat->codec_tag, icodec->codec_tag) == codec->codec_id
2116
                   || av_codec_get_tag(os->oformat->codec_tag, icodec->codec_id) <= 0)
2117
                    codec->codec_tag = icodec->codec_tag;
2118
            }
2119

    
2120
            codec->bit_rate = icodec->bit_rate;
2121
            codec->rc_max_rate    = icodec->rc_max_rate;
2122
            codec->rc_buffer_size = icodec->rc_buffer_size;
2123
            codec->extradata= av_mallocz(extra_size);
2124
            if (!codec->extradata)
2125
                goto fail;
2126
            memcpy(codec->extradata, icodec->extradata, icodec->extradata_size);
2127
            codec->extradata_size= icodec->extradata_size;
2128
            if(av_q2d(icodec->time_base)*icodec->ticks_per_frame > av_q2d(ist->st->time_base) && av_q2d(ist->st->time_base) < 1.0/1000){
2129
                codec->time_base = icodec->time_base;
2130
                codec->time_base.num *= icodec->ticks_per_frame;
2131
                av_reduce(&codec->time_base.num, &codec->time_base.den,
2132
                          codec->time_base.num, codec->time_base.den, INT_MAX);
2133
            }else
2134
                codec->time_base = ist->st->time_base;
2135
            switch(codec->codec_type) {
2136
            case AVMEDIA_TYPE_AUDIO:
2137
                if(audio_volume != 256) {
2138
                    fprintf(stderr,"-acodec copy and -vol are incompatible (frames are not decoded)\n");
2139
                    ffmpeg_exit(1);
2140
                }
2141
                codec->channel_layout = icodec->channel_layout;
2142
                codec->sample_rate = icodec->sample_rate;
2143
                codec->channels = icodec->channels;
2144
                codec->frame_size = icodec->frame_size;
2145
                codec->block_align= icodec->block_align;
2146
                if(codec->block_align == 1 && codec->codec_id == CODEC_ID_MP3)
2147
                    codec->block_align= 0;
2148
                if(codec->codec_id == CODEC_ID_AC3)
2149
                    codec->block_align= 0;
2150
                break;
2151
            case AVMEDIA_TYPE_VIDEO:
2152
                codec->pix_fmt = icodec->pix_fmt;
2153
                codec->width = icodec->width;
2154
                codec->height = icodec->height;
2155
                codec->has_b_frames = icodec->has_b_frames;
2156
                break;
2157
            case AVMEDIA_TYPE_SUBTITLE:
2158
                codec->width = icodec->width;
2159
                codec->height = icodec->height;
2160
                break;
2161
            default:
2162
                abort();
2163
            }
2164
        } else {
2165
            switch(codec->codec_type) {
2166
            case AVMEDIA_TYPE_AUDIO:
2167
                ost->fifo= av_fifo_alloc(1024);
2168
                if(!ost->fifo)
2169
                    goto fail;
2170
                ost->reformat_pair = MAKE_SFMT_PAIR(SAMPLE_FMT_NONE,SAMPLE_FMT_NONE);
2171
                ost->audio_resample = codec->sample_rate != icodec->sample_rate || audio_sync_method > 1;
2172
                icodec->request_channels = codec->channels;
2173
                ist->decoding_needed = 1;
2174
                ost->encoding_needed = 1;
2175
                break;
2176
            case AVMEDIA_TYPE_VIDEO:
2177
                if (ost->st->codec->pix_fmt == PIX_FMT_NONE) {
2178
                    fprintf(stderr, "Video pixel format is unknown, stream cannot be encoded\n");
2179
                    ffmpeg_exit(1);
2180
                }
2181
                ost->video_resample = (codec->width != icodec->width   ||
2182
                                       codec->height != icodec->height ||
2183
                        (codec->pix_fmt != icodec->pix_fmt));
2184
                if (ost->video_resample) {
2185
                    avcodec_get_frame_defaults(&ost->pict_tmp);
2186
                    if(avpicture_alloc((AVPicture*)&ost->pict_tmp, codec->pix_fmt,
2187
                                         codec->width, codec->height)) {
2188
                        fprintf(stderr, "Cannot allocate temp picture, check pix fmt\n");
2189
                        ffmpeg_exit(1);
2190
                    }
2191
                    sws_flags = av_get_int(sws_opts, "sws_flags", NULL);
2192
                    ost->img_resample_ctx = sws_getContext(
2193
                        icodec->width,
2194
                        icodec->height,
2195
                            icodec->pix_fmt,
2196
                            codec->width,
2197
                            codec->height,
2198
                            codec->pix_fmt,
2199
                            sws_flags, NULL, NULL, NULL);
2200
                    if (ost->img_resample_ctx == NULL) {
2201
                        fprintf(stderr, "Cannot get resampling context\n");
2202
                        ffmpeg_exit(1);
2203
                    }
2204

    
2205
#if !CONFIG_AVFILTER
2206
                    ost->original_height = icodec->height;
2207
                    ost->original_width  = icodec->width;
2208
#endif
2209
                    codec->bits_per_raw_sample= 0;
2210
                }
2211
                ost->resample_height = icodec->height;
2212
                ost->resample_width  = icodec->width;
2213
                ost->resample_pix_fmt= icodec->pix_fmt;
2214
                ost->encoding_needed = 1;
2215
                ist->decoding_needed = 1;
2216

    
2217
#if CONFIG_AVFILTER
2218
                if (configure_filters(ist, ost)) {
2219
                    fprintf(stderr, "Error opening filters!\n");
2220
                    exit(1);
2221
                }
2222
#endif
2223
                break;
2224
            case AVMEDIA_TYPE_SUBTITLE:
2225
                ost->encoding_needed = 1;
2226
                ist->decoding_needed = 1;
2227
                break;
2228
            default:
2229
                abort();
2230
                break;
2231
            }
2232
            /* two pass mode */
2233
            if (ost->encoding_needed &&
2234
                (codec->flags & (CODEC_FLAG_PASS1 | CODEC_FLAG_PASS2))) {
2235
                char logfilename[1024];
2236
                FILE *f;
2237

    
2238
                snprintf(logfilename, sizeof(logfilename), "%s-%d.log",
2239
                         pass_logfilename_prefix ? pass_logfilename_prefix : DEFAULT_PASS_LOGFILENAME_PREFIX,
2240
                         i);
2241
                if (codec->flags & CODEC_FLAG_PASS1) {
2242
                    f = fopen(logfilename, "wb");
2243
                    if (!f) {
2244
                        fprintf(stderr, "Cannot write log file '%s' for pass-1 encoding: %s\n", logfilename, strerror(errno));
2245
                        ffmpeg_exit(1);
2246
                    }
2247
                    ost->logfile = f;
2248
                } else {
2249
                    char  *logbuffer;
2250
                    size_t logbuffer_size;
2251
                    if (read_file(logfilename, &logbuffer, &logbuffer_size) < 0) {
2252
                        fprintf(stderr, "Error reading log file '%s' for pass-2 encoding\n", logfilename);
2253
                        ffmpeg_exit(1);
2254
                    }
2255
                    codec->stats_in = logbuffer;
2256
                }
2257
            }
2258
        }
2259
        if(codec->codec_type == AVMEDIA_TYPE_VIDEO){
2260
            int size= codec->width * codec->height;
2261
            bit_buffer_size= FFMAX(bit_buffer_size, 6*size + 200);
2262
        }
2263
    }
2264

    
2265
    if (!bit_buffer)
2266
        bit_buffer = av_malloc(bit_buffer_size);
2267
    if (!bit_buffer) {
2268
        fprintf(stderr, "Cannot allocate %d bytes output buffer\n",
2269
                bit_buffer_size);
2270
        ret = AVERROR(ENOMEM);
2271
        goto fail;
2272
    }
2273

    
2274
    /* open each encoder */
2275
    for(i=0;i<nb_ostreams;i++) {
2276
        ost = ost_table[i];
2277
        if (ost->encoding_needed) {
2278
            AVCodec *codec = i < nb_output_codecs ? output_codecs[i] : NULL;
2279
            if (!codec)
2280
                codec = avcodec_find_encoder(ost->st->codec->codec_id);
2281
            if (!codec) {
2282
                snprintf(error, sizeof(error), "Encoder (codec id %d) not found for output stream #%d.%d",
2283
                         ost->st->codec->codec_id, ost->file_index, ost->index);
2284
                ret = AVERROR(EINVAL);
2285
                goto dump_format;
2286
            }
2287
            if (avcodec_open(ost->st->codec, codec) < 0) {
2288
                snprintf(error, sizeof(error), "Error while opening encoder for output stream #%d.%d - maybe incorrect parameters such as bit_rate, rate, width or height",
2289
                        ost->file_index, ost->index);
2290
                ret = AVERROR(EINVAL);
2291
                goto dump_format;
2292
            }
2293
            extra_size += ost->st->codec->extradata_size;
2294
        }
2295
    }
2296

    
2297
    /* open each decoder */
2298
    for(i=0;i<nb_istreams;i++) {
2299
        ist = ist_table[i];
2300
        if (ist->decoding_needed) {
2301
            AVCodec *codec = i < nb_input_codecs ? input_codecs[i] : NULL;
2302
            if (!codec)
2303
                codec = avcodec_find_decoder(ist->st->codec->codec_id);
2304
            if (!codec) {
2305
                snprintf(error, sizeof(error), "Decoder (codec id %d) not found for input stream #%d.%d",
2306
                        ist->st->codec->codec_id, ist->file_index, ist->index);
2307
                ret = AVERROR(EINVAL);
2308
                goto dump_format;
2309
            }
2310
            if (avcodec_open(ist->st->codec, codec) < 0) {
2311
                snprintf(error, sizeof(error), "Error while opening decoder for input stream #%d.%d",
2312
                        ist->file_index, ist->index);
2313
                ret = AVERROR(EINVAL);
2314
                goto dump_format;
2315
            }
2316
            //if (ist->st->codec->codec_type == AVMEDIA_TYPE_VIDEO)
2317
            //    ist->st->codec->flags |= CODEC_FLAG_REPEAT_FIELD;
2318
        }
2319
    }
2320

    
2321
    /* init pts */
2322
    for(i=0;i<nb_istreams;i++) {
2323
        AVStream *st;
2324
        ist = ist_table[i];
2325
        st= ist->st;
2326
        ist->pts = st->avg_frame_rate.num ? - st->codec->has_b_frames*AV_TIME_BASE / av_q2d(st->avg_frame_rate) : 0;
2327
        ist->next_pts = AV_NOPTS_VALUE;
2328
        init_pts_correction(&ist->pts_ctx);
2329
        ist->is_start = 1;
2330
    }
2331

    
2332
    /* set meta data information from input file if required */
2333
    for (i=0;i<nb_meta_data_maps;i++) {
2334
        AVFormatContext *files[2];
2335
        AVMetadata      **meta[2];
2336
        AVMetadataTag *mtag;
2337
        int j;
2338

    
2339
#define METADATA_CHECK_INDEX(index, nb_elems, desc)\
2340
        if ((index) < 0 || (index) >= (nb_elems)) {\
2341
            snprintf(error, sizeof(error), "Invalid %s index %d while processing metadata maps\n",\
2342
                     (desc), (index));\
2343
            ret = AVERROR(EINVAL);\
2344
            goto dump_format;\
2345
        }
2346

    
2347
        int out_file_index = meta_data_maps[i][0].file;
2348
        int in_file_index = meta_data_maps[i][1].file;
2349
        if (in_file_index < 0 || out_file_index < 0)
2350
            continue;
2351
        METADATA_CHECK_INDEX(out_file_index, nb_output_files, "output file")
2352
        METADATA_CHECK_INDEX(in_file_index, nb_input_files, "input file")
2353

    
2354
        files[0] = output_files[out_file_index];
2355
        files[1] = input_files[in_file_index];
2356

    
2357
        for (j = 0; j < 2; j++) {
2358
            AVMetaDataMap *map = &meta_data_maps[i][j];
2359

    
2360
            switch (map->type) {
2361
            case 'g':
2362
                meta[j] = &files[j]->metadata;
2363
                break;
2364
            case 's':
2365
                METADATA_CHECK_INDEX(map->index, files[j]->nb_streams, "stream")
2366
                meta[j] = &files[j]->streams[map->index]->metadata;
2367
                break;
2368
            case 'c':
2369
                METADATA_CHECK_INDEX(map->index, files[j]->nb_chapters, "chapter")
2370
                meta[j] = &files[j]->chapters[map->index]->metadata;
2371
                break;
2372
            case 'p':
2373
                METADATA_CHECK_INDEX(map->index, files[j]->nb_programs, "program")
2374
                meta[j] = &files[j]->programs[map->index]->metadata;
2375
                break;
2376
            }
2377
        }
2378

    
2379
        mtag=NULL;
2380
        while((mtag=av_metadata_get(*meta[1], "", mtag, AV_METADATA_IGNORE_SUFFIX)))
2381
            av_metadata_set2(meta[0], mtag->key, mtag->value, AV_METADATA_DONT_OVERWRITE);
2382
    }
2383

    
2384
    /* copy chapters from the first input file that has them*/
2385
    for (i = 0; i < nb_input_files; i++) {
2386
        if (!input_files[i]->nb_chapters)
2387
            continue;
2388

    
2389
        for (j = 0; j < nb_output_files; j++)
2390
            if ((ret = copy_chapters(i, j)) < 0)
2391
                goto dump_format;
2392
    }
2393

    
2394
    /* open files and write file headers */
2395
    for(i=0;i<nb_output_files;i++) {
2396
        os = output_files[i];
2397
        if (av_write_header(os) < 0) {
2398
            snprintf(error, sizeof(error), "Could not write header for output file #%d (incorrect codec parameters ?)", i);
2399
            ret = AVERROR(EINVAL);
2400
            goto dump_format;
2401
        }
2402
        if (strcmp(output_files[i]->oformat->name, "rtp")) {
2403
            want_sdp = 0;
2404
        }
2405
    }
2406

    
2407
 dump_format:
2408
    /* dump the file output parameters - cannot be done before in case
2409
       of stream copy */
2410
    for(i=0;i<nb_output_files;i++) {
2411
        dump_format(output_files[i], i, output_files[i]->filename, 1);
2412
    }
2413

    
2414
    /* dump the stream mapping */
2415
    if (verbose >= 0) {
2416
        fprintf(stderr, "Stream mapping:\n");
2417
        for(i=0;i<nb_ostreams;i++) {
2418
            ost = ost_table[i];
2419
            fprintf(stderr, "  Stream #%d.%d -> #%d.%d",
2420
                    ist_table[ost->source_index]->file_index,
2421
                    ist_table[ost->source_index]->index,
2422
                    ost->file_index,
2423
                    ost->index);
2424
            if (ost->sync_ist != ist_table[ost->source_index])
2425
                fprintf(stderr, " [sync #%d.%d]",
2426
                        ost->sync_ist->file_index,
2427
                        ost->sync_ist->index);
2428
            fprintf(stderr, "\n");
2429
        }
2430
    }
2431

    
2432
    if (ret) {
2433
        fprintf(stderr, "%s\n", error);
2434
        goto fail;
2435
    }
2436

    
2437
    if (want_sdp) {
2438
        print_sdp(output_files, nb_output_files);
2439
    }
2440

    
2441
    if (!using_stdin && verbose >= 0) {
2442
        fprintf(stderr, "Press [q] to stop encoding\n");
2443
        url_set_interrupt_cb(decode_interrupt_cb);
2444
    }
2445
    term_init();
2446

    
2447
    timer_start = av_gettime();
2448

    
2449
    for(; received_sigterm == 0;) {
2450
        int file_index, ist_index;
2451
        AVPacket pkt;
2452
        double ipts_min;
2453
        double opts_min;
2454

    
2455
    redo:
2456
        ipts_min= 1e100;
2457
        opts_min= 1e100;
2458
        /* if 'q' pressed, exits */
2459
        if (!using_stdin) {
2460
            if (q_pressed)
2461
                break;
2462
            /* read_key() returns 0 on EOF */
2463
            key = read_key();
2464
            if (key == 'q')
2465
                break;
2466
        }
2467

    
2468
        /* select the stream that we must read now by looking at the
2469
           smallest output pts */
2470
        file_index = -1;
2471
        for(i=0;i<nb_ostreams;i++) {
2472
            double ipts, opts;
2473
            ost = ost_table[i];
2474
            os = output_files[ost->file_index];
2475
            ist = ist_table[ost->source_index];
2476
            if(ist->is_past_recording_time || no_packet[ist->file_index])
2477
                continue;
2478
                opts = ost->st->pts.val * av_q2d(ost->st->time_base);
2479
            ipts = (double)ist->pts;
2480
            if (!file_table[ist->file_index].eof_reached){
2481
                if(ipts < ipts_min) {
2482
                    ipts_min = ipts;
2483
                    if(input_sync ) file_index = ist->file_index;
2484
                }
2485
                if(opts < opts_min) {
2486
                    opts_min = opts;
2487
                    if(!input_sync) file_index = ist->file_index;
2488
                }
2489
            }
2490
            if(ost->frame_number >= max_frames[ost->st->codec->codec_type]){
2491
                file_index= -1;
2492
                break;
2493
            }
2494
        }
2495
        /* if none, if is finished */
2496
        if (file_index < 0) {
2497
            if(no_packet_count){
2498
                no_packet_count=0;
2499
                memset(no_packet, 0, sizeof(no_packet));
2500
                usleep(10000);
2501
                continue;
2502
            }
2503
            break;
2504
        }
2505

    
2506
        /* finish if limit size exhausted */
2507
        if (limit_filesize != 0 && limit_filesize <= url_ftell(output_files[0]->pb))
2508
            break;
2509

    
2510
        /* read a frame from it and output it in the fifo */
2511
        is = input_files[file_index];
2512
        ret= av_read_frame(is, &pkt);
2513
        if(ret == AVERROR(EAGAIN)){
2514
            no_packet[file_index]=1;
2515
            no_packet_count++;
2516
            continue;
2517
        }
2518
        if (ret < 0) {
2519
            file_table[file_index].eof_reached = 1;
2520
            if (opt_shortest)
2521
                break;
2522
            else
2523
                continue;
2524
        }
2525

    
2526
        no_packet_count=0;
2527
        memset(no_packet, 0, sizeof(no_packet));
2528

    
2529
        if (do_pkt_dump) {
2530
            av_pkt_dump_log(NULL, AV_LOG_DEBUG, &pkt, do_hex_dump);
2531
        }
2532
        /* the following test is needed in case new streams appear
2533
           dynamically in stream : we ignore them */
2534
        if (pkt.stream_index >= file_table[file_index].nb_streams)
2535
            goto discard_packet;
2536
        ist_index = file_table[file_index].ist_index + pkt.stream_index;
2537
        ist = ist_table[ist_index];
2538
        if (ist->discard)
2539
            goto discard_packet;
2540

    
2541
        if (pkt.dts != AV_NOPTS_VALUE)
2542
            pkt.dts += av_rescale_q(input_files_ts_offset[ist->file_index], AV_TIME_BASE_Q, ist->st->time_base);
2543
        if (pkt.pts != AV_NOPTS_VALUE)
2544
            pkt.pts += av_rescale_q(input_files_ts_offset[ist->file_index], AV_TIME_BASE_Q, ist->st->time_base);
2545

    
2546
        if (pkt.stream_index < nb_input_files_ts_scale[file_index]
2547
            && input_files_ts_scale[file_index][pkt.stream_index]){
2548
            if(pkt.pts != AV_NOPTS_VALUE)
2549
                pkt.pts *= input_files_ts_scale[file_index][pkt.stream_index];
2550
            if(pkt.dts != AV_NOPTS_VALUE)
2551
                pkt.dts *= input_files_ts_scale[file_index][pkt.stream_index];
2552
        }
2553

    
2554
//        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);
2555
        if (pkt.dts != AV_NOPTS_VALUE && ist->next_pts != AV_NOPTS_VALUE
2556
            && (is->iformat->flags & AVFMT_TS_DISCONT)) {
2557
            int64_t pkt_dts= av_rescale_q(pkt.dts, ist->st->time_base, AV_TIME_BASE_Q);
2558
            int64_t delta= pkt_dts - ist->next_pts;
2559
            if((FFABS(delta) > 1LL*dts_delta_threshold*AV_TIME_BASE || pkt_dts+1<ist->pts)&& !copy_ts){
2560
                input_files_ts_offset[ist->file_index]-= delta;
2561
                if (verbose > 2)
2562
                    fprintf(stderr, "timestamp discontinuity %"PRId64", new offset= %"PRId64"\n", delta, input_files_ts_offset[ist->file_index]);
2563
                pkt.dts-= av_rescale_q(delta, AV_TIME_BASE_Q, ist->st->time_base);
2564
                if(pkt.pts != AV_NOPTS_VALUE)
2565
                    pkt.pts-= av_rescale_q(delta, AV_TIME_BASE_Q, ist->st->time_base);
2566
            }
2567
        }
2568

    
2569
        /* finish if recording time exhausted */
2570
        if (recording_time != INT64_MAX &&
2571
            av_compare_ts(pkt.pts, ist->st->time_base, recording_time + start_time, (AVRational){1, 1000000}) >= 0) {
2572
            ist->is_past_recording_time = 1;
2573
            goto discard_packet;
2574
        }
2575

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

    
2579
            if (verbose >= 0)
2580
                fprintf(stderr, "Error while decoding stream #%d.%d\n",
2581
                        ist->file_index, ist->index);
2582
            if (exit_on_error)
2583
                ffmpeg_exit(1);
2584
            av_free_packet(&pkt);
2585
            goto redo;
2586
        }
2587

    
2588
    discard_packet:
2589
        av_free_packet(&pkt);
2590

    
2591
        /* dump report by using the output first video and audio streams */
2592
        print_report(output_files, ost_table, nb_ostreams, 0);
2593
    }
2594

    
2595
    /* at the end of stream, we must flush the decoder buffers */
2596
    for(i=0;i<nb_istreams;i++) {
2597
        ist = ist_table[i];
2598
        if (ist->decoding_needed) {
2599
            output_packet(ist, i, ost_table, nb_ostreams, NULL);
2600
        }
2601
    }
2602

    
2603
    term_exit();
2604

    
2605
    /* write the trailer if needed and close file */
2606
    for(i=0;i<nb_output_files;i++) {
2607
        os = output_files[i];
2608
        av_write_trailer(os);
2609
    }
2610

    
2611
    /* dump report by using the first video and audio streams */
2612
    print_report(output_files, ost_table, nb_ostreams, 1);
2613

    
2614
    /* close each encoder */
2615
    for(i=0;i<nb_ostreams;i++) {
2616
        ost = ost_table[i];
2617
        if (ost->encoding_needed) {
2618
            av_freep(&ost->st->codec->stats_in);
2619
            avcodec_close(ost->st->codec);
2620
        }
2621
    }
2622

    
2623
    /* close each decoder */
2624
    for(i=0;i<nb_istreams;i++) {
2625
        ist = ist_table[i];
2626
        if (ist->decoding_needed) {
2627
            avcodec_close(ist->st->codec);
2628
        }
2629
    }
2630
#if CONFIG_AVFILTER
2631
    if (graph) {
2632
        avfilter_graph_free(graph);
2633
        av_freep(&graph);
2634
    }
2635
#endif
2636

    
2637
    /* finished ! */
2638
    ret = 0;
2639

    
2640
 fail:
2641
    av_freep(&bit_buffer);
2642
    av_free(file_table);
2643

    
2644
    if (ist_table) {
2645
        for(i=0;i<nb_istreams;i++) {
2646
            ist = ist_table[i];
2647
            av_free(ist);
2648
        }
2649
        av_free(ist_table);
2650
    }
2651
    if (ost_table) {
2652
        for(i=0;i<nb_ostreams;i++) {
2653
            ost = ost_table[i];
2654
            if (ost) {
2655
                if (ost->st->stream_copy)
2656
                    av_freep(&ost->st->codec->extradata);
2657
                if (ost->logfile) {
2658
                    fclose(ost->logfile);
2659
                    ost->logfile = NULL;
2660
                }
2661
                av_fifo_free(ost->fifo); /* works even if fifo is not
2662
                                             initialized but set to zero */
2663
                av_free(ost->pict_tmp.data[0]);
2664
                av_free(ost->forced_kf_pts);
2665
                if (ost->video_resample)
2666
                    sws_freeContext(ost->img_resample_ctx);
2667
                if (ost->resample)
2668
                    audio_resample_close(ost->resample);
2669
                if (ost->reformat_ctx)
2670
                    av_audio_convert_free(ost->reformat_ctx);
2671
                av_free(ost);
2672
            }
2673
        }
2674
        av_free(ost_table);
2675
    }
2676
    return ret;
2677
}
2678

    
2679
static void opt_format(const char *arg)
2680
{
2681
    last_asked_format = arg;
2682
}
2683

    
2684
static void opt_video_rc_override_string(const char *arg)
2685
{
2686
    video_rc_override_string = arg;
2687
}
2688

    
2689
static int opt_me_threshold(const char *opt, const char *arg)
2690
{
2691
    me_threshold = parse_number_or_die(opt, arg, OPT_INT64, INT_MIN, INT_MAX);
2692
    return 0;
2693
}
2694

    
2695
static int opt_verbose(const char *opt, const char *arg)
2696
{
2697
    verbose = parse_number_or_die(opt, arg, OPT_INT64, -10, 10);
2698
    return 0;
2699
}
2700

    
2701
static int opt_frame_rate(const char *opt, const char *arg)
2702
{
2703
    if (av_parse_video_rate(&frame_rate, arg) < 0) {
2704
        fprintf(stderr, "Incorrect value for %s: %s\n", opt, arg);
2705
        ffmpeg_exit(1);
2706
    }
2707
    return 0;
2708
}
2709

    
2710
static int opt_bitrate(const char *opt, const char *arg)
2711
{
2712
    int codec_type = opt[0]=='a' ? AVMEDIA_TYPE_AUDIO : AVMEDIA_TYPE_VIDEO;
2713

    
2714
    opt_default(opt, arg);
2715

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

    
2719
    return 0;
2720
}
2721

    
2722
static int opt_frame_crop(const char *opt, const char *arg)
2723
{
2724
    fprintf(stderr, "Option '%s' has been removed, use the crop filter instead\n", opt);
2725
    return AVERROR(EINVAL);
2726
}
2727

    
2728
static void opt_frame_size(const char *arg)
2729
{
2730
    if (av_parse_video_size(&frame_width, &frame_height, arg) < 0) {
2731
        fprintf(stderr, "Incorrect frame size\n");
2732
        ffmpeg_exit(1);
2733
    }
2734
}
2735

    
2736
static int opt_pad(const char *opt, const char *arg) {
2737
    fprintf(stderr, "Option '%s' has been removed, use the pad filter instead\n", opt);
2738
    return -1;
2739
}
2740

    
2741
static void opt_frame_pix_fmt(const char *arg)
2742
{
2743
    if (strcmp(arg, "list")) {
2744
        frame_pix_fmt = av_get_pix_fmt(arg);
2745
        if (frame_pix_fmt == PIX_FMT_NONE) {
2746
            fprintf(stderr, "Unknown pixel format requested: %s\n", arg);
2747
            ffmpeg_exit(1);
2748
        }
2749
    } else {
2750
        show_pix_fmts();
2751
        ffmpeg_exit(0);
2752
    }
2753
}
2754

    
2755
static void opt_frame_aspect_ratio(const char *arg)
2756
{
2757
    int x = 0, y = 0;
2758
    double ar = 0;
2759
    const char *p;
2760
    char *end;
2761

    
2762
    p = strchr(arg, ':');
2763
    if (p) {
2764
        x = strtol(arg, &end, 10);
2765
        if (end == p)
2766
            y = strtol(end+1, &end, 10);
2767
        if (x > 0 && y > 0)
2768
            ar = (double)x / (double)y;
2769
    } else
2770
        ar = strtod(arg, NULL);
2771

    
2772
    if (!ar) {
2773
        fprintf(stderr, "Incorrect aspect ratio specification.\n");
2774
        ffmpeg_exit(1);
2775
    }
2776
    frame_aspect_ratio = ar;
2777
}
2778

    
2779
static int opt_metadata(const char *opt, const char *arg)
2780
{
2781
    char *mid= strchr(arg, '=');
2782

    
2783
    if(!mid){
2784
        fprintf(stderr, "Missing =\n");
2785
        ffmpeg_exit(1);
2786
    }
2787
    *mid++= 0;
2788

    
2789
    av_metadata_set2(&metadata, arg, mid, 0);
2790

    
2791
    return 0;
2792
}
2793

    
2794
static void opt_qscale(const char *arg)
2795
{
2796
    video_qscale = atof(arg);
2797
    if (video_qscale <= 0 ||
2798
        video_qscale > 255) {
2799
        fprintf(stderr, "qscale must be > 0.0 and <= 255\n");
2800
        ffmpeg_exit(1);
2801
    }
2802
}
2803

    
2804
static void opt_top_field_first(const char *arg)
2805
{
2806
    top_field_first= atoi(arg);
2807
}
2808

    
2809
static int opt_thread_count(const char *opt, const char *arg)
2810
{
2811
    thread_count= parse_number_or_die(opt, arg, OPT_INT64, 0, INT_MAX);
2812
#if !HAVE_THREADS
2813
    if (verbose >= 0)
2814
        fprintf(stderr, "Warning: not compiled with thread support, using thread emulation\n");
2815
#endif
2816
    return 0;
2817
}
2818

    
2819
static void opt_audio_sample_fmt(const char *arg)
2820
{
2821
    if (strcmp(arg, "list"))
2822
        audio_sample_fmt = av_get_sample_fmt(arg);
2823
    else {
2824
        list_fmts(av_get_sample_fmt_string, SAMPLE_FMT_NB);
2825
        ffmpeg_exit(0);
2826
    }
2827
}
2828

    
2829
static int opt_audio_rate(const char *opt, const char *arg)
2830
{
2831
    audio_sample_rate = parse_number_or_die(opt, arg, OPT_INT64, 0, INT_MAX);
2832
    return 0;
2833
}
2834

    
2835
static int opt_audio_channels(const char *opt, const char *arg)
2836
{
2837
    audio_channels = parse_number_or_die(opt, arg, OPT_INT64, 0, INT_MAX);
2838
    return 0;
2839
}
2840

    
2841
static void opt_video_channel(const char *arg)
2842
{
2843
    video_channel = strtol(arg, NULL, 0);
2844
}
2845

    
2846
static void opt_video_standard(const char *arg)
2847
{
2848
    video_standard = av_strdup(arg);
2849
}
2850

    
2851
static void opt_codec(int *pstream_copy, char **pcodec_name,
2852
                      int codec_type, const char *arg)
2853
{
2854
    av_freep(pcodec_name);
2855
    if (!strcmp(arg, "copy")) {
2856
        *pstream_copy = 1;
2857
    } else {
2858
        *pcodec_name = av_strdup(arg);
2859
    }
2860
}
2861

    
2862
static void opt_audio_codec(const char *arg)
2863
{
2864
    opt_codec(&audio_stream_copy, &audio_codec_name, AVMEDIA_TYPE_AUDIO, arg);
2865
}
2866

    
2867
static void opt_video_codec(const char *arg)
2868
{
2869
    opt_codec(&video_stream_copy, &video_codec_name, AVMEDIA_TYPE_VIDEO, arg);
2870
}
2871

    
2872
static void opt_subtitle_codec(const char *arg)
2873
{
2874
    opt_codec(&subtitle_stream_copy, &subtitle_codec_name, AVMEDIA_TYPE_SUBTITLE, arg);
2875
}
2876

    
2877
static int opt_codec_tag(const char *opt, const char *arg)
2878
{
2879
    char *tail;
2880
    uint32_t *codec_tag;
2881

    
2882
    codec_tag = !strcmp(opt, "atag") ? &audio_codec_tag :
2883
                !strcmp(opt, "vtag") ? &video_codec_tag :
2884
                !strcmp(opt, "stag") ? &subtitle_codec_tag : NULL;
2885
    if (!codec_tag)
2886
        return -1;
2887

    
2888
    *codec_tag = strtol(arg, &tail, 0);
2889
    if (!tail || *tail)
2890
        *codec_tag = AV_RL32(arg);
2891

    
2892
    return 0;
2893
}
2894

    
2895
static void opt_map(const char *arg)
2896
{
2897
    AVStreamMap *m;
2898
    char *p;
2899

    
2900
    stream_maps = grow_array(stream_maps, sizeof(*stream_maps), &nb_stream_maps, nb_stream_maps + 1);
2901
    m = &stream_maps[nb_stream_maps-1];
2902

    
2903
    m->file_index = strtol(arg, &p, 0);
2904
    if (*p)
2905
        p++;
2906

    
2907
    m->stream_index = strtol(p, &p, 0);
2908
    if (*p) {
2909
        p++;
2910
        m->sync_file_index = strtol(p, &p, 0);
2911
        if (*p)
2912
            p++;
2913
        m->sync_stream_index = strtol(p, &p, 0);
2914
    } else {
2915
        m->sync_file_index = m->file_index;
2916
        m->sync_stream_index = m->stream_index;
2917
    }
2918
}
2919

    
2920
static void parse_meta_type(const char *arg, char *type, int *index, char **endptr)
2921
{
2922
    *endptr = arg;
2923
    if (*arg == ',') {
2924
        *type = *(++arg);
2925
        switch (*arg) {
2926
        case 'g':
2927
            break;
2928
        case 's':
2929
        case 'c':
2930
        case 'p':
2931
            *index = strtol(++arg, endptr, 0);
2932
            break;
2933
        default:
2934
            fprintf(stderr, "Invalid metadata type %c.\n", *arg);
2935
            ffmpeg_exit(1);
2936
        }
2937
    } else
2938
        *type = 'g';
2939
}
2940

    
2941
static void opt_map_meta_data(const char *arg)
2942
{
2943
    AVMetaDataMap *m, *m1;
2944
    char *p;
2945

    
2946
    meta_data_maps = grow_array(meta_data_maps, sizeof(*meta_data_maps),
2947
                                &nb_meta_data_maps, nb_meta_data_maps + 1);
2948

    
2949
    m = &meta_data_maps[nb_meta_data_maps - 1][0];
2950
    m->file = strtol(arg, &p, 0);
2951
    parse_meta_type(p, &m->type, &m->index, &p);
2952
    if (*p)
2953
        p++;
2954

    
2955
    m1 = &meta_data_maps[nb_meta_data_maps - 1][1];
2956
    m1->file = strtol(p, &p, 0);
2957
    parse_meta_type(p, &m1->type, &m1->index, &p);
2958

    
2959
    if (m->type == 's' || m1->type == 's')
2960
        metadata_streams_autocopy = 0;
2961
    if (m->type == 'c' || m1->type == 'c')
2962
        metadata_chapters_autocopy = 0;
2963
}
2964

    
2965
static void opt_input_ts_scale(const char *arg)
2966
{
2967
    unsigned int stream;
2968
    double scale;
2969
    char *p;
2970

    
2971
    stream = strtol(arg, &p, 0);
2972
    if (*p)
2973
        p++;
2974
    scale= strtod(p, &p);
2975

    
2976
    if(stream >= MAX_STREAMS)
2977
        ffmpeg_exit(1);
2978

    
2979
    input_files_ts_scale[nb_input_files] = grow_array(input_files_ts_scale[nb_input_files], sizeof(*input_files_ts_scale[nb_input_files]), &nb_input_files_ts_scale[nb_input_files], stream + 1);
2980
    input_files_ts_scale[nb_input_files][stream]= scale;
2981
}
2982

    
2983
static int opt_recording_time(const char *opt, const char *arg)
2984
{
2985
    recording_time = parse_time_or_die(opt, arg, 1);
2986
    return 0;
2987
}
2988

    
2989
static int opt_start_time(const char *opt, const char *arg)
2990
{
2991
    start_time = parse_time_or_die(opt, arg, 1);
2992
    return 0;
2993
}
2994

    
2995
static int opt_recording_timestamp(const char *opt, const char *arg)
2996
{
2997
    recording_timestamp = parse_time_or_die(opt, arg, 0) / 1000000;
2998
    return 0;
2999
}
3000

    
3001
static int opt_input_ts_offset(const char *opt, const char *arg)
3002
{
3003
    input_ts_offset = parse_time_or_die(opt, arg, 1);
3004
    return 0;
3005
}
3006

    
3007
static enum CodecID find_codec_or_die(const char *name, int type, int encoder, int strict)
3008
{
3009
    const char *codec_string = encoder ? "encoder" : "decoder";
3010
    AVCodec *codec;
3011

    
3012
    if(!name)
3013
        return CODEC_ID_NONE;
3014
    codec = encoder ?
3015
        avcodec_find_encoder_by_name(name) :
3016
        avcodec_find_decoder_by_name(name);
3017
    if(!codec) {
3018
        fprintf(stderr, "Unknown %s '%s'\n", codec_string, name);
3019
        ffmpeg_exit(1);
3020
    }
3021
    if(codec->type != type) {
3022
        fprintf(stderr, "Invalid %s type '%s'\n", codec_string, name);
3023
        ffmpeg_exit(1);
3024
    }
3025
    if(codec->capabilities & CODEC_CAP_EXPERIMENTAL &&
3026
       strict > FF_COMPLIANCE_EXPERIMENTAL) {
3027
        fprintf(stderr, "%s '%s' is experimental and might produce bad "
3028
                "results.\nAdd '-strict experimental' if you want to use it.\n",
3029
                codec_string, codec->name);
3030
        codec = encoder ?
3031
            avcodec_find_encoder(codec->id) :
3032
            avcodec_find_decoder(codec->id);
3033
        if (!(codec->capabilities & CODEC_CAP_EXPERIMENTAL))
3034
            fprintf(stderr, "Or use the non experimental %s '%s'.\n",
3035
                    codec_string, codec->name);
3036
        ffmpeg_exit(1);
3037
    }
3038
    return codec->id;
3039
}
3040

    
3041
static void opt_input_file(const char *filename)
3042
{
3043
    AVFormatContext *ic;
3044
    AVFormatParameters params, *ap = &params;
3045
    AVInputFormat *file_iformat = NULL;
3046
    int err, i, ret, rfps, rfps_base;
3047
    int64_t timestamp;
3048

    
3049
    if (last_asked_format) {
3050
        if (!(file_iformat = av_find_input_format(last_asked_format))) {
3051
            fprintf(stderr, "Unknown input format: '%s'\n", last_asked_format);
3052
            ffmpeg_exit(1);
3053
        }
3054
        last_asked_format = NULL;
3055
    }
3056

    
3057
    if (!strcmp(filename, "-"))
3058
        filename = "pipe:";
3059

    
3060
    using_stdin |= !strncmp(filename, "pipe:", 5) ||
3061
                    !strcmp(filename, "/dev/stdin");
3062

    
3063
    /* get default parameters from command line */
3064
    ic = avformat_alloc_context();
3065
    if (!ic) {
3066
        print_error(filename, AVERROR(ENOMEM));
3067
        ffmpeg_exit(1);
3068
    }
3069

    
3070
    memset(ap, 0, sizeof(*ap));
3071
    ap->prealloced_context = 1;
3072
    ap->sample_rate = audio_sample_rate;
3073
    ap->channels = audio_channels;
3074
    ap->time_base.den = frame_rate.num;
3075
    ap->time_base.num = frame_rate.den;
3076
    ap->width = frame_width;
3077
    ap->height = frame_height;
3078
    ap->pix_fmt = frame_pix_fmt;
3079
   // ap->sample_fmt = audio_sample_fmt; //FIXME:not implemented in libavformat
3080
    ap->channel = video_channel;
3081
    ap->standard = video_standard;
3082

    
3083
    set_context_opts(ic, avformat_opts, AV_OPT_FLAG_DECODING_PARAM, NULL);
3084

    
3085
    ic->video_codec_id   =
3086
        find_codec_or_die(video_codec_name   , AVMEDIA_TYPE_VIDEO   , 0,
3087
                          avcodec_opts[AVMEDIA_TYPE_VIDEO   ]->strict_std_compliance);
3088
    ic->audio_codec_id   =
3089
        find_codec_or_die(audio_codec_name   , AVMEDIA_TYPE_AUDIO   , 0,
3090
                          avcodec_opts[AVMEDIA_TYPE_AUDIO   ]->strict_std_compliance);
3091
    ic->subtitle_codec_id=
3092
        find_codec_or_die(subtitle_codec_name, AVMEDIA_TYPE_SUBTITLE, 0,
3093
                          avcodec_opts[AVMEDIA_TYPE_SUBTITLE]->strict_std_compliance);
3094
    ic->flags |= AVFMT_FLAG_NONBLOCK;
3095

    
3096
    /* open the input file with generic libav function */
3097
    err = av_open_input_file(&ic, filename, file_iformat, 0, ap);
3098
    if (err < 0) {
3099
        print_error(filename, err);
3100
        ffmpeg_exit(1);
3101
    }
3102
    if(opt_programid) {
3103
        int i, j;
3104
        int found=0;
3105
        for(i=0; i<ic->nb_streams; i++){
3106
            ic->streams[i]->discard= AVDISCARD_ALL;
3107
        }
3108
        for(i=0; i<ic->nb_programs; i++){
3109
            AVProgram *p= ic->programs[i];
3110
            if(p->id != opt_programid){
3111
                p->discard = AVDISCARD_ALL;
3112
            }else{
3113
                found=1;
3114
                for(j=0; j<p->nb_stream_indexes; j++){
3115
                    ic->streams[p->stream_index[j]]->discard= AVDISCARD_DEFAULT;
3116
                }
3117
            }
3118
        }
3119
        if(!found){
3120
            fprintf(stderr, "Specified program id not found\n");
3121
            ffmpeg_exit(1);
3122
        }
3123
        opt_programid=0;
3124
    }
3125

    
3126
    ic->loop_input = loop_input;
3127

    
3128
    /* If not enough info to get the stream parameters, we decode the
3129
       first frames to get it. (used in mpeg case for example) */
3130
    ret = av_find_stream_info(ic);
3131
    if (ret < 0 && verbose >= 0) {
3132
        fprintf(stderr, "%s: could not find codec parameters\n", filename);
3133
        av_close_input_file(ic);
3134
        ffmpeg_exit(1);
3135
    }
3136

    
3137
    timestamp = start_time;
3138
    /* add the stream start time */
3139
    if (ic->start_time != AV_NOPTS_VALUE)
3140
        timestamp += ic->start_time;
3141

    
3142
    /* if seeking requested, we execute it */
3143
    if (start_time != 0) {
3144
        ret = av_seek_frame(ic, -1, timestamp, AVSEEK_FLAG_BACKWARD);
3145
        if (ret < 0) {
3146
            fprintf(stderr, "%s: could not seek to position %0.3f\n",
3147
                    filename, (double)timestamp / AV_TIME_BASE);
3148
        }
3149
        /* reset seek info */
3150
        start_time = 0;
3151
    }
3152

    
3153
    /* update the current parameters so that they match the one of the input stream */
3154
    for(i=0;i<ic->nb_streams;i++) {
3155
        AVStream *st = ic->streams[i];
3156
        AVCodecContext *dec = st->codec;
3157
        avcodec_thread_init(dec, thread_count);
3158
        input_codecs = grow_array(input_codecs, sizeof(*input_codecs), &nb_input_codecs, nb_input_codecs + 1);
3159
        switch (dec->codec_type) {
3160
        case AVMEDIA_TYPE_AUDIO:
3161
            input_codecs[nb_input_codecs-1] = avcodec_find_decoder_by_name(audio_codec_name);
3162
            set_context_opts(dec, avcodec_opts[AVMEDIA_TYPE_AUDIO], AV_OPT_FLAG_AUDIO_PARAM | AV_OPT_FLAG_DECODING_PARAM, input_codecs[nb_input_codecs-1]);
3163
            //fprintf(stderr, "\nInput Audio channels: %d", dec->channels);
3164
            channel_layout    = dec->channel_layout;
3165
            audio_channels    = dec->channels;
3166
            audio_sample_rate = dec->sample_rate;
3167
            audio_sample_fmt  = dec->sample_fmt;
3168
            if(audio_disable)
3169
                st->discard= AVDISCARD_ALL;
3170
            /* Note that av_find_stream_info can add more streams, and we
3171
             * currently have no chance of setting up lowres decoding
3172
             * early enough for them. */
3173
            if (dec->lowres)
3174
                audio_sample_rate >>= dec->lowres;
3175
            break;
3176
        case AVMEDIA_TYPE_VIDEO:
3177
            input_codecs[nb_input_codecs-1] = avcodec_find_decoder_by_name(video_codec_name);
3178
            set_context_opts(dec, avcodec_opts[AVMEDIA_TYPE_VIDEO], AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_DECODING_PARAM, input_codecs[nb_input_codecs-1]);
3179
            frame_height = dec->height;
3180
            frame_width  = dec->width;
3181
            if(ic->streams[i]->sample_aspect_ratio.num)
3182
                frame_aspect_ratio=av_q2d(ic->streams[i]->sample_aspect_ratio);
3183
            else
3184
                frame_aspect_ratio=av_q2d(dec->sample_aspect_ratio);
3185
            frame_aspect_ratio *= (float) dec->width / dec->height;
3186
            frame_pix_fmt = dec->pix_fmt;
3187
            rfps      = ic->streams[i]->r_frame_rate.num;
3188
            rfps_base = ic->streams[i]->r_frame_rate.den;
3189
            if (dec->lowres) {
3190
                dec->flags |= CODEC_FLAG_EMU_EDGE;
3191
                frame_height >>= dec->lowres;
3192
                frame_width  >>= dec->lowres;
3193
            }
3194
            if(me_threshold)
3195
                dec->debug |= FF_DEBUG_MV;
3196

    
3197
            if (dec->time_base.den != rfps*dec->ticks_per_frame || dec->time_base.num != rfps_base) {
3198

    
3199
                if (verbose >= 0)
3200
                    fprintf(stderr,"\nSeems stream %d codec frame rate differs from container frame rate: %2.2f (%d/%d) -> %2.2f (%d/%d)\n",
3201
                            i, (float)dec->time_base.den / dec->time_base.num, dec->time_base.den, dec->time_base.num,
3202

    
3203
                    (float)rfps / rfps_base, rfps, rfps_base);
3204
            }
3205
            /* update the current frame rate to match the stream frame rate */
3206
            frame_rate.num = rfps;
3207
            frame_rate.den = rfps_base;
3208

    
3209
            if(video_disable)
3210
                st->discard= AVDISCARD_ALL;
3211
            else if(video_discard)
3212
                st->discard= video_discard;
3213
            break;
3214
        case AVMEDIA_TYPE_DATA:
3215
            break;
3216
        case AVMEDIA_TYPE_SUBTITLE:
3217
            input_codecs[nb_input_codecs-1] = avcodec_find_decoder_by_name(subtitle_codec_name);
3218
            if(subtitle_disable)
3219
                st->discard = AVDISCARD_ALL;
3220
            break;
3221
        case AVMEDIA_TYPE_ATTACHMENT:
3222
        case AVMEDIA_TYPE_UNKNOWN:
3223
            break;
3224
        default:
3225
            abort();
3226
        }
3227
    }
3228

    
3229
    input_files[nb_input_files] = ic;
3230
    input_files_ts_offset[nb_input_files] = input_ts_offset - (copy_ts ? 0 : timestamp);
3231
    /* dump the file content */
3232
    if (verbose >= 0)
3233
        dump_format(ic, nb_input_files, filename, 0);
3234

    
3235
    nb_input_files++;
3236

    
3237
    video_channel = 0;
3238

    
3239
    av_freep(&video_codec_name);
3240
    av_freep(&audio_codec_name);
3241
    av_freep(&subtitle_codec_name);
3242
}
3243

    
3244
static void check_audio_video_sub_inputs(int *has_video_ptr, int *has_audio_ptr,
3245
                                         int *has_subtitle_ptr)
3246
{
3247
    int has_video, has_audio, has_subtitle, i, j;
3248
    AVFormatContext *ic;
3249

    
3250
    has_video = 0;
3251
    has_audio = 0;
3252
    has_subtitle = 0;
3253
    for(j=0;j<nb_input_files;j++) {
3254
        ic = input_files[j];
3255
        for(i=0;i<ic->nb_streams;i++) {
3256
            AVCodecContext *enc = ic->streams[i]->codec;
3257
            switch(enc->codec_type) {
3258
            case AVMEDIA_TYPE_AUDIO:
3259
                has_audio = 1;
3260
                break;
3261
            case AVMEDIA_TYPE_VIDEO:
3262
                has_video = 1;
3263
                break;
3264
            case AVMEDIA_TYPE_SUBTITLE:
3265
                has_subtitle = 1;
3266
                break;
3267
            case AVMEDIA_TYPE_DATA:
3268
            case AVMEDIA_TYPE_ATTACHMENT:
3269
            case AVMEDIA_TYPE_UNKNOWN:
3270
                break;
3271
            default:
3272
                abort();
3273
            }
3274
        }
3275
    }
3276
    *has_video_ptr = has_video;
3277
    *has_audio_ptr = has_audio;
3278
    *has_subtitle_ptr = has_subtitle;
3279
}
3280

    
3281
static void new_video_stream(AVFormatContext *oc, int file_idx)
3282
{
3283
    AVStream *st;
3284
    AVOutputStream *ost;
3285
    AVCodecContext *video_enc;
3286
    enum CodecID codec_id;
3287
    AVCodec *codec= NULL;
3288

    
3289
    st = av_new_stream(oc, oc->nb_streams < nb_streamid_map ? streamid_map[oc->nb_streams] : 0);
3290
    if (!st) {
3291
        fprintf(stderr, "Could not alloc stream\n");
3292
        ffmpeg_exit(1);
3293
    }
3294
    ost = new_output_stream(oc, file_idx);
3295

    
3296
    output_codecs = grow_array(output_codecs, sizeof(*output_codecs), &nb_output_codecs, nb_output_codecs + 1);
3297
    if(!video_stream_copy){
3298
        if (video_codec_name) {
3299
            codec_id = find_codec_or_die(video_codec_name, AVMEDIA_TYPE_VIDEO, 1,
3300
                                         avcodec_opts[AVMEDIA_TYPE_VIDEO]->strict_std_compliance);
3301
            codec = avcodec_find_encoder_by_name(video_codec_name);
3302
            output_codecs[nb_output_codecs-1] = codec;
3303
        } else {
3304
            codec_id = av_guess_codec(oc->oformat, NULL, oc->filename, NULL, AVMEDIA_TYPE_VIDEO);
3305
            codec = avcodec_find_encoder(codec_id);
3306
        }
3307
    }
3308

    
3309
    avcodec_get_context_defaults3(st->codec, codec);
3310
    ost->bitstream_filters = video_bitstream_filters;
3311
    video_bitstream_filters= NULL;
3312

    
3313
    avcodec_thread_init(st->codec, thread_count);
3314

    
3315
    video_enc = st->codec;
3316

    
3317
    if(video_codec_tag)
3318
        video_enc->codec_tag= video_codec_tag;
3319

    
3320
    if(   (video_global_header&1)
3321
       || (video_global_header==0 && (oc->oformat->flags & AVFMT_GLOBALHEADER))){
3322
        video_enc->flags |= CODEC_FLAG_GLOBAL_HEADER;
3323
        avcodec_opts[AVMEDIA_TYPE_VIDEO]->flags|= CODEC_FLAG_GLOBAL_HEADER;
3324
    }
3325
    if(video_global_header&2){
3326
        video_enc->flags2 |= CODEC_FLAG2_LOCAL_HEADER;
3327
        avcodec_opts[AVMEDIA_TYPE_VIDEO]->flags2|= CODEC_FLAG2_LOCAL_HEADER;
3328
    }
3329

    
3330
    if (video_stream_copy) {
3331
        st->stream_copy = 1;
3332
        video_enc->codec_type = AVMEDIA_TYPE_VIDEO;
3333
        video_enc->sample_aspect_ratio =
3334
        st->sample_aspect_ratio = av_d2q(frame_aspect_ratio*frame_height/frame_width, 255);
3335
    } else {
3336
        const char *p;
3337
        int i;
3338
        AVRational fps= frame_rate.num ? frame_rate : (AVRational){25,1};
3339

    
3340
        video_enc->codec_id = codec_id;
3341
        set_context_opts(video_enc, avcodec_opts[AVMEDIA_TYPE_VIDEO], AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_ENCODING_PARAM, codec);
3342

    
3343
        if (codec && codec->supported_framerates && !force_fps)
3344
            fps = codec->supported_framerates[av_find_nearest_q_idx(fps, codec->supported_framerates)];
3345
        video_enc->time_base.den = fps.num;
3346
        video_enc->time_base.num = fps.den;
3347

    
3348
        video_enc->width = frame_width;
3349
        video_enc->height = frame_height;
3350
        video_enc->sample_aspect_ratio = av_d2q(frame_aspect_ratio*video_enc->height/video_enc->width, 255);
3351
        video_enc->pix_fmt = frame_pix_fmt;
3352
        st->sample_aspect_ratio = video_enc->sample_aspect_ratio;
3353

    
3354
        choose_pixel_fmt(st, codec);
3355

    
3356
        if (intra_only)
3357
            video_enc->gop_size = 0;
3358
        if (video_qscale || same_quality) {
3359
            video_enc->flags |= CODEC_FLAG_QSCALE;
3360
            video_enc->global_quality=
3361
                st->quality = FF_QP2LAMBDA * video_qscale;
3362
        }
3363

    
3364
        if(intra_matrix)
3365
            video_enc->intra_matrix = intra_matrix;
3366
        if(inter_matrix)
3367
            video_enc->inter_matrix = inter_matrix;
3368

    
3369
        p= video_rc_override_string;
3370
        for(i=0; p; i++){
3371
            int start, end, q;
3372
            int e=sscanf(p, "%d,%d,%d", &start, &end, &q);
3373
            if(e!=3){
3374
                fprintf(stderr, "error parsing rc_override\n");
3375
                ffmpeg_exit(1);
3376
            }
3377
            video_enc->rc_override=
3378
                av_realloc(video_enc->rc_override,
3379
                           sizeof(RcOverride)*(i+1));
3380
            video_enc->rc_override[i].start_frame= start;
3381
            video_enc->rc_override[i].end_frame  = end;
3382
            if(q>0){
3383
                video_enc->rc_override[i].qscale= q;
3384
                video_enc->rc_override[i].quality_factor= 1.0;
3385
            }
3386
            else{
3387
                video_enc->rc_override[i].qscale= 0;
3388
                video_enc->rc_override[i].quality_factor= -q/100.0;
3389
            }
3390
            p= strchr(p, '/');
3391
            if(p) p++;
3392
        }
3393
        video_enc->rc_override_count=i;
3394
        if (!video_enc->rc_initial_buffer_occupancy)
3395
            video_enc->rc_initial_buffer_occupancy = video_enc->rc_buffer_size*3/4;
3396
        video_enc->me_threshold= me_threshold;
3397
        video_enc->intra_dc_precision= intra_dc_precision - 8;
3398

    
3399
        if (do_psnr)
3400
            video_enc->flags|= CODEC_FLAG_PSNR;
3401

    
3402
        /* two pass mode */
3403
        if (do_pass) {
3404
            if (do_pass == 1) {
3405
                video_enc->flags |= CODEC_FLAG_PASS1;
3406
            } else {
3407
                video_enc->flags |= CODEC_FLAG_PASS2;
3408
            }
3409
        }
3410

    
3411
        if (forced_key_frames)
3412
            parse_forced_key_frames(forced_key_frames, ost, video_enc);
3413
    }
3414
    if (video_language) {
3415
        av_metadata_set2(&st->metadata, "language", video_language, 0);
3416
        av_freep(&video_language);
3417
    }
3418

    
3419
    /* reset some key parameters */
3420
    video_disable = 0;
3421
    av_freep(&video_codec_name);
3422
    av_freep(&forced_key_frames);
3423
    video_stream_copy = 0;
3424
    frame_pix_fmt = PIX_FMT_NONE;
3425
}
3426

    
3427
static void new_audio_stream(AVFormatContext *oc, int file_idx)
3428
{
3429
    AVStream *st;
3430
    AVOutputStream *ost;
3431
    AVCodec *codec= NULL;
3432
    AVCodecContext *audio_enc;
3433
    enum CodecID codec_id;
3434

    
3435
    st = av_new_stream(oc, oc->nb_streams < nb_streamid_map ? streamid_map[oc->nb_streams] : 0);
3436
    if (!st) {
3437
        fprintf(stderr, "Could not alloc stream\n");
3438
        ffmpeg_exit(1);
3439
    }
3440
    ost = new_output_stream(oc, file_idx);
3441

    
3442
    output_codecs = grow_array(output_codecs, sizeof(*output_codecs), &nb_output_codecs, nb_output_codecs + 1);
3443
    if(!audio_stream_copy){
3444
        if (audio_codec_name) {
3445
            codec_id = find_codec_or_die(audio_codec_name, AVMEDIA_TYPE_AUDIO, 1,
3446
                                         avcodec_opts[AVMEDIA_TYPE_AUDIO]->strict_std_compliance);
3447
            codec = avcodec_find_encoder_by_name(audio_codec_name);
3448
            output_codecs[nb_output_codecs-1] = codec;
3449
        } else {
3450
            codec_id = av_guess_codec(oc->oformat, NULL, oc->filename, NULL, AVMEDIA_TYPE_AUDIO);
3451
            codec = avcodec_find_encoder(codec_id);
3452
        }
3453
    }
3454

    
3455
    avcodec_get_context_defaults3(st->codec, codec);
3456

    
3457
    ost->bitstream_filters = audio_bitstream_filters;
3458
    audio_bitstream_filters= NULL;
3459

    
3460
    avcodec_thread_init(st->codec, thread_count);
3461

    
3462
    audio_enc = st->codec;
3463
    audio_enc->codec_type = AVMEDIA_TYPE_AUDIO;
3464

    
3465
    if(audio_codec_tag)
3466
        audio_enc->codec_tag= audio_codec_tag;
3467

    
3468
    if (oc->oformat->flags & AVFMT_GLOBALHEADER) {
3469
        audio_enc->flags |= CODEC_FLAG_GLOBAL_HEADER;
3470
        avcodec_opts[AVMEDIA_TYPE_AUDIO]->flags|= CODEC_FLAG_GLOBAL_HEADER;
3471
    }
3472
    if (audio_stream_copy) {
3473
        st->stream_copy = 1;
3474
        audio_enc->channels = audio_channels;
3475
        audio_enc->sample_rate = audio_sample_rate;
3476
    } else {
3477
        audio_enc->codec_id = codec_id;
3478
        set_context_opts(audio_enc, avcodec_opts[AVMEDIA_TYPE_AUDIO], AV_OPT_FLAG_AUDIO_PARAM | AV_OPT_FLAG_ENCODING_PARAM, codec);
3479

    
3480
        if (audio_qscale > QSCALE_NONE) {
3481
            audio_enc->flags |= CODEC_FLAG_QSCALE;
3482
            audio_enc->global_quality = st->quality = FF_QP2LAMBDA * audio_qscale;
3483
        }
3484
        audio_enc->channels = audio_channels;
3485
        audio_enc->sample_fmt = audio_sample_fmt;
3486
        audio_enc->sample_rate = audio_sample_rate;
3487
        audio_enc->channel_layout = channel_layout;
3488
        if (avcodec_channel_layout_num_channels(channel_layout) != audio_channels)
3489
            audio_enc->channel_layout = 0;
3490
        choose_sample_fmt(st, codec);
3491
        choose_sample_rate(st, codec);
3492
    }
3493
    audio_enc->time_base= (AVRational){1, audio_sample_rate};
3494
    if (audio_language) {
3495
        av_metadata_set2(&st->metadata, "language", audio_language, 0);
3496
        av_freep(&audio_language);
3497
    }
3498

    
3499
    /* reset some key parameters */
3500
    audio_disable = 0;
3501
    av_freep(&audio_codec_name);
3502
    audio_stream_copy = 0;
3503
}
3504

    
3505
static void new_subtitle_stream(AVFormatContext *oc, int file_idx)
3506
{
3507
    AVStream *st;
3508
    AVOutputStream *ost;
3509
    AVCodec *codec=NULL;
3510
    AVCodecContext *subtitle_enc;
3511

    
3512
    st = av_new_stream(oc, oc->nb_streams < nb_streamid_map ? streamid_map[oc->nb_streams] : 0);
3513
    if (!st) {
3514
        fprintf(stderr, "Could not alloc stream\n");
3515
        ffmpeg_exit(1);
3516
    }
3517
    ost = new_output_stream(oc, file_idx);
3518
    subtitle_enc = st->codec;
3519
    output_codecs = grow_array(output_codecs, sizeof(*output_codecs), &nb_output_codecs, nb_output_codecs + 1);
3520
    if(!subtitle_stream_copy){
3521
        subtitle_enc->codec_id = find_codec_or_die(subtitle_codec_name, AVMEDIA_TYPE_SUBTITLE, 1,
3522
                                                   avcodec_opts[AVMEDIA_TYPE_SUBTITLE]->strict_std_compliance);
3523
        codec= output_codecs[nb_output_codecs-1] = avcodec_find_encoder_by_name(subtitle_codec_name);
3524
    }
3525
    avcodec_get_context_defaults3(st->codec, codec);
3526

    
3527
    ost->bitstream_filters = subtitle_bitstream_filters;
3528
    subtitle_bitstream_filters= NULL;
3529

    
3530
    subtitle_enc->codec_type = AVMEDIA_TYPE_SUBTITLE;
3531

    
3532
    if(subtitle_codec_tag)
3533
        subtitle_enc->codec_tag= subtitle_codec_tag;
3534

    
3535
    if (subtitle_stream_copy) {
3536
        st->stream_copy = 1;
3537
    } else {
3538
        set_context_opts(avcodec_opts[AVMEDIA_TYPE_SUBTITLE], subtitle_enc, AV_OPT_FLAG_SUBTITLE_PARAM | AV_OPT_FLAG_ENCODING_PARAM, codec);
3539
    }
3540

    
3541
    if (subtitle_language) {
3542
        av_metadata_set2(&st->metadata, "language", subtitle_language, 0);
3543
        av_freep(&subtitle_language);
3544
    }
3545

    
3546
    subtitle_disable = 0;
3547
    av_freep(&subtitle_codec_name);
3548
    subtitle_stream_copy = 0;
3549
}
3550

    
3551
static int opt_new_stream(const char *opt, const char *arg)
3552
{
3553
    AVFormatContext *oc;
3554
    int file_idx = nb_output_files - 1;
3555
    if (nb_output_files <= 0) {
3556
        fprintf(stderr, "At least one output file must be specified\n");
3557
        ffmpeg_exit(1);
3558
    }
3559
    oc = output_files[file_idx];
3560

    
3561
    if      (!strcmp(opt, "newvideo"   )) new_video_stream   (oc, file_idx);
3562
    else if (!strcmp(opt, "newaudio"   )) new_audio_stream   (oc, file_idx);
3563
    else if (!strcmp(opt, "newsubtitle")) new_subtitle_stream(oc, file_idx);
3564
    else av_assert0(0);
3565
    return 0;
3566
}
3567

    
3568
/* arg format is "output-stream-index:streamid-value". */
3569
static int opt_streamid(const char *opt, const char *arg)
3570
{
3571
    int idx;
3572
    char *p;
3573
    char idx_str[16];
3574

    
3575
    strncpy(idx_str, arg, sizeof(idx_str));
3576
    idx_str[sizeof(idx_str)-1] = '\0';
3577
    p = strchr(idx_str, ':');
3578
    if (!p) {
3579
        fprintf(stderr,
3580
                "Invalid value '%s' for option '%s', required syntax is 'index:value'\n",
3581
                arg, opt);
3582
        ffmpeg_exit(1);
3583
    }
3584
    *p++ = '\0';
3585
    idx = parse_number_or_die(opt, idx_str, OPT_INT, 0, MAX_STREAMS-1);
3586
    streamid_map = grow_array(streamid_map, sizeof(*streamid_map), &nb_streamid_map, idx+1);
3587
    streamid_map[idx] = parse_number_or_die(opt, p, OPT_INT, 0, INT_MAX);
3588
    return 0;
3589
}
3590

    
3591
static void opt_output_file(const char *filename)
3592
{
3593
    AVFormatContext *oc;
3594
    int err, use_video, use_audio, use_subtitle;
3595
    int input_has_video, input_has_audio, input_has_subtitle;
3596
    AVFormatParameters params, *ap = &params;
3597
    AVOutputFormat *file_oformat;
3598
    AVMetadataTag *tag = NULL;
3599

    
3600
    if (!strcmp(filename, "-"))
3601
        filename = "pipe:";
3602

    
3603
    oc = avformat_alloc_context();
3604
    if (!oc) {
3605
        print_error(filename, AVERROR(ENOMEM));
3606
        ffmpeg_exit(1);
3607
    }
3608

    
3609
    if (last_asked_format) {
3610
        file_oformat = av_guess_format(last_asked_format, NULL, NULL);
3611
        if (!file_oformat) {
3612
            fprintf(stderr, "Requested output format '%s' is not a suitable output format\n", last_asked_format);
3613
            ffmpeg_exit(1);
3614
        }
3615
        last_asked_format = NULL;
3616
    } else {
3617
        file_oformat = av_guess_format(NULL, filename, NULL);
3618
        if (!file_oformat) {
3619
            fprintf(stderr, "Unable to find a suitable output format for '%s'\n",
3620
                    filename);
3621
            ffmpeg_exit(1);
3622
        }
3623
    }
3624

    
3625
    oc->oformat = file_oformat;
3626
    av_strlcpy(oc->filename, filename, sizeof(oc->filename));
3627

    
3628
    if (!strcmp(file_oformat->name, "ffm") &&
3629
        av_strstart(filename, "http:", NULL)) {
3630
        /* special case for files sent to ffserver: we get the stream
3631
           parameters from ffserver */
3632
        int err = read_ffserver_streams(oc, filename);
3633
        if (err < 0) {
3634
            print_error(filename, err);
3635
            ffmpeg_exit(1);
3636
        }
3637
    } else {
3638
        use_video = file_oformat->video_codec != CODEC_ID_NONE || video_stream_copy || video_codec_name;
3639
        use_audio = file_oformat->audio_codec != CODEC_ID_NONE || audio_stream_copy || audio_codec_name;
3640
        use_subtitle = file_oformat->subtitle_codec != CODEC_ID_NONE || subtitle_stream_copy || subtitle_codec_name;
3641

    
3642
        /* disable if no corresponding type found and at least one
3643
           input file */
3644
        if (nb_input_files > 0) {
3645
            check_audio_video_sub_inputs(&input_has_video, &input_has_audio,
3646
                                         &input_has_subtitle);
3647
            if (!input_has_video)
3648
                use_video = 0;
3649
            if (!input_has_audio)
3650
                use_audio = 0;
3651
            if (!input_has_subtitle)
3652
                use_subtitle = 0;
3653
        }
3654

    
3655
        /* manual disable */
3656
        if (audio_disable)    use_audio    = 0;
3657
        if (video_disable)    use_video    = 0;
3658
        if (subtitle_disable) use_subtitle = 0;
3659

    
3660
        if (use_video)    new_video_stream(oc, nb_output_files);
3661
        if (use_audio)    new_audio_stream(oc, nb_output_files);
3662
        if (use_subtitle) new_subtitle_stream(oc, nb_output_files);
3663

    
3664
        oc->timestamp = recording_timestamp;
3665

    
3666
        while ((tag = av_metadata_get(metadata, "", tag, AV_METADATA_IGNORE_SUFFIX)))
3667
            av_metadata_set2(&oc->metadata, tag->key, tag->value, 0);
3668
        av_metadata_free(&metadata);
3669
    }
3670

    
3671
    output_files[nb_output_files++] = oc;
3672

    
3673
    /* check filename in case of an image number is expected */
3674
    if (oc->oformat->flags & AVFMT_NEEDNUMBER) {
3675
        if (!av_filename_number_test(oc->filename)) {
3676
            print_error(oc->filename, AVERROR_NUMEXPECTED);
3677
            ffmpeg_exit(1);
3678
        }
3679
    }
3680

    
3681
    if (!(oc->oformat->flags & AVFMT_NOFILE)) {
3682
        /* test if it already exists to avoid loosing precious files */
3683
        if (!file_overwrite &&
3684
            (strchr(filename, ':') == NULL ||
3685
             filename[1] == ':' ||
3686
             av_strstart(filename, "file:", NULL))) {
3687
            if (url_exist(filename)) {
3688
                if (!using_stdin) {
3689
                    fprintf(stderr,"File '%s' already exists. Overwrite ? [y/N] ", filename);
3690
                    fflush(stderr);
3691
                    if (!read_yesno()) {
3692
                        fprintf(stderr, "Not overwriting - exiting\n");
3693
                        ffmpeg_exit(1);
3694
                    }
3695
                }
3696
                else {
3697
                    fprintf(stderr,"File '%s' already exists. Exiting.\n", filename);
3698
                    ffmpeg_exit(1);
3699
                }
3700
            }
3701
        }
3702

    
3703
        /* open the file */
3704
        if ((err = url_fopen(&oc->pb, filename, URL_WRONLY)) < 0) {
3705
            print_error(filename, err);
3706
            ffmpeg_exit(1);
3707
        }
3708
    }
3709

    
3710
    memset(ap, 0, sizeof(*ap));
3711
    if (av_set_parameters(oc, ap) < 0) {
3712
        fprintf(stderr, "%s: Invalid encoding parameters\n",
3713
                oc->filename);
3714
        ffmpeg_exit(1);
3715
    }
3716

    
3717
    oc->preload= (int)(mux_preload*AV_TIME_BASE);
3718
    oc->max_delay= (int)(mux_max_delay*AV_TIME_BASE);
3719
    oc->loop_output = loop_output;
3720
    oc->flags |= AVFMT_FLAG_NONBLOCK;
3721

    
3722
    set_context_opts(oc, avformat_opts, AV_OPT_FLAG_ENCODING_PARAM, NULL);
3723

    
3724
    nb_streamid_map = 0;
3725
    av_freep(&forced_key_frames);
3726
}
3727

    
3728
/* same option as mencoder */
3729
static void opt_pass(const char *pass_str)
3730
{
3731
    int pass;
3732
    pass = atoi(pass_str);
3733
    if (pass != 1 && pass != 2) {
3734
        fprintf(stderr, "pass number can be only 1 or 2\n");
3735
        ffmpeg_exit(1);
3736
    }
3737
    do_pass = pass;
3738
}
3739

    
3740
static int64_t getutime(void)
3741
{
3742
#if HAVE_GETRUSAGE
3743
    struct rusage rusage;
3744

    
3745
    getrusage(RUSAGE_SELF, &rusage);
3746
    return (rusage.ru_utime.tv_sec * 1000000LL) + rusage.ru_utime.tv_usec;
3747
#elif HAVE_GETPROCESSTIMES
3748
    HANDLE proc;
3749
    FILETIME c, e, k, u;
3750
    proc = GetCurrentProcess();
3751
    GetProcessTimes(proc, &c, &e, &k, &u);
3752
    return ((int64_t) u.dwHighDateTime << 32 | u.dwLowDateTime) / 10;
3753
#else
3754
    return av_gettime();
3755
#endif
3756
}
3757

    
3758
static int64_t getmaxrss(void)
3759
{
3760
#if HAVE_GETRUSAGE && HAVE_STRUCT_RUSAGE_RU_MAXRSS
3761
    struct rusage rusage;
3762
    getrusage(RUSAGE_SELF, &rusage);
3763
    return (int64_t)rusage.ru_maxrss * 1024;
3764
#elif HAVE_GETPROCESSMEMORYINFO
3765
    HANDLE proc;
3766
    PROCESS_MEMORY_COUNTERS memcounters;
3767
    proc = GetCurrentProcess();
3768
    memcounters.cb = sizeof(memcounters);
3769
    GetProcessMemoryInfo(proc, &memcounters, sizeof(memcounters));
3770
    return memcounters.PeakPagefileUsage;
3771
#else
3772
    return 0;
3773
#endif
3774
}
3775

    
3776
static void parse_matrix_coeffs(uint16_t *dest, const char *str)
3777
{
3778
    int i;
3779
    const char *p = str;
3780
    for(i = 0;; i++) {
3781
        dest[i] = atoi(p);
3782
        if(i == 63)
3783
            break;
3784
        p = strchr(p, ',');
3785
        if(!p) {
3786
            fprintf(stderr, "Syntax error in matrix \"%s\" at coeff %d\n", str, i);
3787
            ffmpeg_exit(1);
3788
        }
3789
        p++;
3790
    }
3791
}
3792

    
3793
static void opt_inter_matrix(const char *arg)
3794
{
3795
    inter_matrix = av_mallocz(sizeof(uint16_t) * 64);
3796
    parse_matrix_coeffs(inter_matrix, arg);
3797
}
3798

    
3799
static void opt_intra_matrix(const char *arg)
3800
{
3801
    intra_matrix = av_mallocz(sizeof(uint16_t) * 64);
3802
    parse_matrix_coeffs(intra_matrix, arg);
3803
}
3804

    
3805
static void show_usage(void)
3806
{
3807
    printf("Hyper fast Audio and Video encoder\n");
3808
    printf("usage: ffmpeg [options] [[infile options] -i infile]... {[outfile options] outfile}...\n");
3809
    printf("\n");
3810
}
3811

    
3812
static void show_help(void)
3813
{
3814
    av_log_set_callback(log_callback_help);
3815
    show_usage();
3816
    show_help_options(options, "Main options:\n",
3817
                      OPT_EXPERT | OPT_AUDIO | OPT_VIDEO | OPT_SUBTITLE | OPT_GRAB, 0);
3818
    show_help_options(options, "\nAdvanced options:\n",
3819
                      OPT_EXPERT | OPT_AUDIO | OPT_VIDEO | OPT_SUBTITLE | OPT_GRAB,
3820
                      OPT_EXPERT);
3821
    show_help_options(options, "\nVideo options:\n",
3822
                      OPT_EXPERT | OPT_AUDIO | OPT_VIDEO | OPT_GRAB,
3823
                      OPT_VIDEO);
3824
    show_help_options(options, "\nAdvanced Video options:\n",
3825
                      OPT_EXPERT | OPT_AUDIO | OPT_VIDEO | OPT_GRAB,
3826
                      OPT_VIDEO | OPT_EXPERT);
3827
    show_help_options(options, "\nAudio options:\n",
3828
                      OPT_EXPERT | OPT_AUDIO | OPT_VIDEO | OPT_GRAB,
3829
                      OPT_AUDIO);
3830
    show_help_options(options, "\nAdvanced Audio options:\n",
3831
                      OPT_EXPERT | OPT_AUDIO | OPT_VIDEO | OPT_GRAB,
3832
                      OPT_AUDIO | OPT_EXPERT);
3833
    show_help_options(options, "\nSubtitle options:\n",
3834
                      OPT_SUBTITLE | OPT_GRAB,
3835
                      OPT_SUBTITLE);
3836
    show_help_options(options, "\nAudio/Video grab options:\n",
3837
                      OPT_GRAB,
3838
                      OPT_GRAB);
3839
    printf("\n");
3840
    av_opt_show2(avcodec_opts[0], NULL, AV_OPT_FLAG_ENCODING_PARAM|AV_OPT_FLAG_DECODING_PARAM, 0);
3841
    printf("\n");
3842
    av_opt_show2(avformat_opts, NULL, AV_OPT_FLAG_ENCODING_PARAM|AV_OPT_FLAG_DECODING_PARAM, 0);
3843
    printf("\n");
3844
    av_opt_show2(sws_opts, NULL, AV_OPT_FLAG_ENCODING_PARAM|AV_OPT_FLAG_DECODING_PARAM, 0);
3845
}
3846

    
3847
static void opt_target(const char *arg)
3848
{
3849
    enum { PAL, NTSC, FILM, UNKNOWN } norm = UNKNOWN;
3850
    static const char *const frame_rates[] = {"25", "30000/1001", "24000/1001"};
3851

    
3852
    if(!strncmp(arg, "pal-", 4)) {
3853
        norm = PAL;
3854
        arg += 4;
3855
    } else if(!strncmp(arg, "ntsc-", 5)) {
3856
        norm = NTSC;
3857
        arg += 5;
3858
    } else if(!strncmp(arg, "film-", 5)) {
3859
        norm = FILM;
3860
        arg += 5;
3861
    } else {
3862
        int fr;
3863
        /* Calculate FR via float to avoid int overflow */
3864
        fr = (int)(frame_rate.num * 1000.0 / frame_rate.den);
3865
        if(fr == 25000) {
3866
            norm = PAL;
3867
        } else if((fr == 29970) || (fr == 23976)) {
3868
            norm = NTSC;
3869
        } else {
3870
            /* Try to determine PAL/NTSC by peeking in the input files */
3871
            if(nb_input_files) {
3872
                int i, j;
3873
                for(j = 0; j < nb_input_files; j++) {
3874
                    for(i = 0; i < input_files[j]->nb_streams; i++) {
3875
                        AVCodecContext *c = input_files[j]->streams[i]->codec;
3876
                        if(c->codec_type != AVMEDIA_TYPE_VIDEO)
3877
                            continue;
3878
                        fr = c->time_base.den * 1000 / c->time_base.num;
3879
                        if(fr == 25000) {
3880
                            norm = PAL;
3881
                            break;
3882
                        } else if((fr == 29970) || (fr == 23976)) {
3883
                            norm = NTSC;
3884
                            break;
3885
                        }
3886
                    }
3887
                    if(norm != UNKNOWN)
3888
                        break;
3889
                }
3890
            }
3891
        }
3892
        if(verbose && norm != UNKNOWN)
3893
            fprintf(stderr, "Assuming %s for target.\n", norm == PAL ? "PAL" : "NTSC");
3894
    }
3895

    
3896
    if(norm == UNKNOWN) {
3897
        fprintf(stderr, "Could not determine norm (PAL/NTSC/NTSC-Film) for target.\n");
3898
        fprintf(stderr, "Please prefix target with \"pal-\", \"ntsc-\" or \"film-\",\n");
3899
        fprintf(stderr, "or set a framerate with \"-r xxx\".\n");
3900
        ffmpeg_exit(1);
3901
    }
3902

    
3903
    if(!strcmp(arg, "vcd")) {
3904

    
3905
        opt_video_codec("mpeg1video");
3906
        opt_audio_codec("mp2");
3907
        opt_format("vcd");
3908

    
3909
        opt_frame_size(norm == PAL ? "352x288" : "352x240");
3910
        opt_frame_rate(NULL, frame_rates[norm]);
3911
        opt_default("g", norm == PAL ? "15" : "18");
3912

    
3913
        opt_default("b", "1150000");
3914
        opt_default("maxrate", "1150000");
3915
        opt_default("minrate", "1150000");
3916
        opt_default("bufsize", "327680"); // 40*1024*8;
3917

    
3918
        opt_default("ab", "224000");
3919
        audio_sample_rate = 44100;
3920
        audio_channels = 2;
3921

    
3922
        opt_default("packetsize", "2324");
3923
        opt_default("muxrate", "1411200"); // 2352 * 75 * 8;
3924

    
3925
        /* We have to offset the PTS, so that it is consistent with the SCR.
3926
           SCR starts at 36000, but the first two packs contain only padding
3927
           and the first pack from the other stream, respectively, may also have
3928
           been written before.
3929
           So the real data starts at SCR 36000+3*1200. */
3930
        mux_preload= (36000+3*1200) / 90000.0; //0.44
3931
    } else if(!strcmp(arg, "svcd")) {
3932

    
3933
        opt_video_codec("mpeg2video");
3934
        opt_audio_codec("mp2");
3935
        opt_format("svcd");
3936

    
3937
        opt_frame_size(norm == PAL ? "480x576" : "480x480");
3938
        opt_frame_rate(NULL, frame_rates[norm]);
3939
        opt_default("g", norm == PAL ? "15" : "18");
3940

    
3941
        opt_default("b", "2040000");
3942
        opt_default("maxrate", "2516000");
3943
        opt_default("minrate", "0"); //1145000;
3944
        opt_default("bufsize", "1835008"); //224*1024*8;
3945
        opt_default("flags", "+scan_offset");
3946

    
3947

    
3948
        opt_default("ab", "224000");
3949
        audio_sample_rate = 44100;
3950

    
3951
        opt_default("packetsize", "2324");
3952

    
3953
    } else if(!strcmp(arg, "dvd")) {
3954

    
3955
        opt_video_codec("mpeg2video");
3956
        opt_audio_codec("ac3");
3957
        opt_format("dvd");
3958

    
3959
        opt_frame_size(norm == PAL ? "720x576" : "720x480");
3960
        opt_frame_rate(NULL, frame_rates[norm]);
3961
        opt_default("g", norm == PAL ? "15" : "18");
3962

    
3963
        opt_default("b", "6000000");
3964
        opt_default("maxrate", "9000000");
3965
        opt_default("minrate", "0"); //1500000;
3966
        opt_default("bufsize", "1835008"); //224*1024*8;
3967

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

    
3971
        opt_default("ab", "448000");
3972
        audio_sample_rate = 48000;
3973

    
3974
    } else if(!strncmp(arg, "dv", 2)) {
3975

    
3976
        opt_format("dv");
3977

    
3978
        opt_frame_size(norm == PAL ? "720x576" : "720x480");
3979
        opt_frame_pix_fmt(!strncmp(arg, "dv50", 4) ? "yuv422p" :
3980
                          (norm == PAL ? "yuv420p" : "yuv411p"));
3981
        opt_frame_rate(NULL, frame_rates[norm]);
3982

    
3983
        audio_sample_rate = 48000;
3984
        audio_channels = 2;
3985

    
3986
    } else {
3987
        fprintf(stderr, "Unknown target: %s\n", arg);
3988
        ffmpeg_exit(1);
3989
    }
3990
}
3991

    
3992
static void opt_vstats_file (const char *arg)
3993
{
3994
    av_free (vstats_filename);
3995
    vstats_filename=av_strdup (arg);
3996
}
3997

    
3998
static void opt_vstats (void)
3999
{
4000
    char filename[40];
4001
    time_t today2 = time(NULL);
4002
    struct tm *today = localtime(&today2);
4003

    
4004
    snprintf(filename, sizeof(filename), "vstats_%02d%02d%02d.log", today->tm_hour, today->tm_min,
4005
             today->tm_sec);
4006
    opt_vstats_file(filename);
4007
}
4008

    
4009
static int opt_bsf(const char *opt, const char *arg)
4010
{
4011
    AVBitStreamFilterContext *bsfc= av_bitstream_filter_init(arg); //FIXME split name and args for filter at '='
4012
    AVBitStreamFilterContext **bsfp;
4013

    
4014
    if(!bsfc){
4015
        fprintf(stderr, "Unknown bitstream filter %s\n", arg);
4016
        ffmpeg_exit(1);
4017
    }
4018

    
4019
    bsfp= *opt == 'v' ? &video_bitstream_filters :
4020
          *opt == 'a' ? &audio_bitstream_filters :
4021
                        &subtitle_bitstream_filters;
4022
    while(*bsfp)
4023
        bsfp= &(*bsfp)->next;
4024

    
4025
    *bsfp= bsfc;
4026

    
4027
    return 0;
4028
}
4029

    
4030
static int opt_preset(const char *opt, const char *arg)
4031
{
4032
    FILE *f=NULL;
4033
    char filename[1000], tmp[1000], tmp2[1000], line[1000];
4034
    char *codec_name = *opt == 'v' ? video_codec_name :
4035
                       *opt == 'a' ? audio_codec_name :
4036
                                     subtitle_codec_name;
4037

    
4038
    if (!(f = get_preset_file(filename, sizeof(filename), arg, *opt == 'f', codec_name))) {
4039
        fprintf(stderr, "File for preset '%s' not found\n", arg);
4040
        ffmpeg_exit(1);
4041
    }
4042

    
4043
    while(!feof(f)){
4044
        int e= fscanf(f, "%999[^\n]\n", line) - 1;
4045
        if(line[0] == '#' && !e)
4046
            continue;
4047
        e|= sscanf(line, "%999[^=]=%999[^\n]\n", tmp, tmp2) - 2;
4048
        if(e){
4049
            fprintf(stderr, "%s: Invalid syntax: '%s'\n", filename, line);
4050
            ffmpeg_exit(1);
4051
        }
4052
        if(!strcmp(tmp, "acodec")){
4053
            opt_audio_codec(tmp2);
4054
        }else if(!strcmp(tmp, "vcodec")){
4055
            opt_video_codec(tmp2);
4056
        }else if(!strcmp(tmp, "scodec")){
4057
            opt_subtitle_codec(tmp2);
4058
        }else if(opt_default(tmp, tmp2) < 0){
4059
            fprintf(stderr, "%s: Invalid option or argument: '%s', parsed as '%s' = '%s'\n", filename, line, tmp, tmp2);
4060
            ffmpeg_exit(1);
4061
        }
4062
    }
4063

    
4064
    fclose(f);
4065

    
4066
    return 0;
4067
}
4068

    
4069
static const OptionDef options[] = {
4070
    /* main options */
4071
#include "cmdutils_common_opts.h"
4072
    { "f", HAS_ARG, {(void*)opt_format}, "force format", "fmt" },
4073
    { "i", HAS_ARG, {(void*)opt_input_file}, "input file name", "filename" },
4074
    { "y", OPT_BOOL, {(void*)&file_overwrite}, "overwrite output files" },
4075
    { "map", HAS_ARG | OPT_EXPERT, {(void*)opt_map}, "set input stream mapping", "file:stream[:syncfile:syncstream]" },
4076
    { "map_meta_data", HAS_ARG | OPT_EXPERT, {(void*)opt_map_meta_data}, "set meta data information of outfile from infile", "outfile[,metadata]:infile[,metadata]" },
4077
    { "t", OPT_FUNC2 | HAS_ARG, {(void*)opt_recording_time}, "record or transcode \"duration\" seconds of audio/video", "duration" },
4078
    { "fs", HAS_ARG | OPT_INT64, {(void*)&limit_filesize}, "set the limit file size in bytes", "limit_size" }, //
4079
    { "ss", OPT_FUNC2 | HAS_ARG, {(void*)opt_start_time}, "set the start time offset", "time_off" },
4080
    { "itsoffset", OPT_FUNC2 | HAS_ARG, {(void*)opt_input_ts_offset}, "set the input ts offset", "time_off" },
4081
    { "itsscale", HAS_ARG, {(void*)opt_input_ts_scale}, "set the input ts scale", "stream:scale" },
4082
    { "timestamp", OPT_FUNC2 | HAS_ARG, {(void*)opt_recording_timestamp}, "set the recording timestamp ('now' to set the current time)", "time" },
4083
    { "metadata", OPT_FUNC2 | HAS_ARG, {(void*)opt_metadata}, "add metadata", "string=string" },
4084
    { "dframes", OPT_INT | HAS_ARG, {(void*)&max_frames[AVMEDIA_TYPE_DATA]}, "set the number of data frames to record", "number" },
4085
    { "benchmark", OPT_BOOL | OPT_EXPERT, {(void*)&do_benchmark},
4086
      "add timings for benchmarking" },
4087
    { "timelimit", OPT_FUNC2 | HAS_ARG, {(void*)opt_timelimit}, "set max runtime in seconds", "limit" },
4088
    { "dump", OPT_BOOL | OPT_EXPERT, {(void*)&do_pkt_dump},
4089
      "dump each input packet" },
4090
    { "hex", OPT_BOOL | OPT_EXPERT, {(void*)&do_hex_dump},
4091
      "when dumping packets, also dump the payload" },
4092
    { "re", OPT_BOOL | OPT_EXPERT, {(void*)&rate_emu}, "read input at native frame rate", "" },
4093
    { "loop_input", OPT_BOOL | OPT_EXPERT, {(void*)&loop_input}, "loop (current only works with images)" },
4094
    { "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)", "" },
4095
    { "v", HAS_ARG | OPT_FUNC2, {(void*)opt_verbose}, "set ffmpeg verbosity level", "number" },
4096
    { "target", HAS_ARG, {(void*)opt_target}, "specify target file type (\"vcd\", \"svcd\", \"dvd\", \"dv\", \"dv50\", \"pal-vcd\", \"ntsc-svcd\", ...)", "type" },
4097
    { "threads", OPT_FUNC2 | HAS_ARG | OPT_EXPERT, {(void*)opt_thread_count}, "thread count", "count" },
4098
    { "vsync", HAS_ARG | OPT_INT | OPT_EXPERT, {(void*)&video_sync_method}, "video sync method", "" },
4099
    { "async", HAS_ARG | OPT_INT | OPT_EXPERT, {(void*)&audio_sync_method}, "audio sync method", "" },
4100
    { "adrift_threshold", HAS_ARG | OPT_FLOAT | OPT_EXPERT, {(void*)&audio_drift_threshold}, "audio drift threshold", "threshold" },
4101
    { "vglobal", HAS_ARG | OPT_INT | OPT_EXPERT, {(void*)&video_global_header}, "video global header storage type", "" },
4102
    { "copyts", OPT_BOOL | OPT_EXPERT, {(void*)&copy_ts}, "copy timestamps" },
4103
    { "shortest", OPT_BOOL | OPT_EXPERT, {(void*)&opt_shortest}, "finish encoding within shortest input" }, //
4104
    { "dts_delta_threshold", HAS_ARG | OPT_FLOAT | OPT_EXPERT, {(void*)&dts_delta_threshold}, "timestamp discontinuity delta threshold", "threshold" },
4105
    { "programid", HAS_ARG | OPT_INT | OPT_EXPERT, {(void*)&opt_programid}, "desired program number", "" },
4106
    { "xerror", OPT_BOOL, {(void*)&exit_on_error}, "exit on error", "error" },
4107
    { "copyinkf", OPT_BOOL | OPT_EXPERT, {(void*)&copy_initial_nonkeyframes}, "copy initial non-keyframes" },
4108

    
4109
    /* video options */
4110
    { "b", OPT_FUNC2 | HAS_ARG | OPT_VIDEO, {(void*)opt_bitrate}, "set bitrate (in bits/s)", "bitrate" },
4111
    { "vb", OPT_FUNC2 | HAS_ARG | OPT_VIDEO, {(void*)opt_bitrate}, "set bitrate (in bits/s)", "bitrate" },
4112
    { "vframes", OPT_INT | HAS_ARG | OPT_VIDEO, {(void*)&max_frames[AVMEDIA_TYPE_VIDEO]}, "set the number of video frames to record", "number" },
4113
    { "r", OPT_FUNC2 | HAS_ARG | OPT_VIDEO, {(void*)opt_frame_rate}, "set frame rate (Hz value, fraction or abbreviation)", "rate" },
4114
    { "s", HAS_ARG | OPT_VIDEO, {(void*)opt_frame_size}, "set frame size (WxH or abbreviation)", "size" },
4115
    { "aspect", HAS_ARG | OPT_VIDEO, {(void*)opt_frame_aspect_ratio}, "set aspect ratio (4:3, 16:9 or 1.3333, 1.7777)", "aspect" },
4116
    { "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" },
4117
    { "croptop", OPT_FUNC2 | HAS_ARG | OPT_VIDEO, {(void*)opt_frame_crop}, "Removed, use the crop filter instead", "size" },
4118
    { "cropbottom", OPT_FUNC2 | HAS_ARG | OPT_VIDEO, {(void*)opt_frame_crop}, "Removed, use the crop filter instead", "size" },
4119
    { "cropleft", OPT_FUNC2 | HAS_ARG | OPT_VIDEO, {(void*)opt_frame_crop}, "Removed, use the crop filter instead", "size" },
4120
    { "cropright", OPT_FUNC2 | HAS_ARG | OPT_VIDEO, {(void*)opt_frame_crop}, "Removed, use the crop filter instead", "size" },
4121
    { "padtop", OPT_FUNC2 | HAS_ARG | OPT_VIDEO, {(void*)opt_pad}, "Removed, use the pad filter instead", "size" },
4122
    { "padbottom", OPT_FUNC2 | HAS_ARG | OPT_VIDEO, {(void*)opt_pad}, "Removed, use the pad filter instead", "size" },
4123
    { "padleft", OPT_FUNC2 | HAS_ARG | OPT_VIDEO, {(void*)opt_pad}, "Removed, use the pad filter instead", "size" },
4124
    { "padright", OPT_FUNC2 | HAS_ARG | OPT_VIDEO, {(void*)opt_pad}, "Removed, use the pad filter instead", "size" },
4125
    { "padcolor", OPT_FUNC2 | HAS_ARG | OPT_VIDEO, {(void*)opt_pad}, "Removed, use the pad filter instead", "color" },
4126
    { "intra", OPT_BOOL | OPT_EXPERT | OPT_VIDEO, {(void*)&intra_only}, "use only intra frames"},
4127
    { "vn", OPT_BOOL | OPT_VIDEO, {(void*)&video_disable}, "disable video" },
4128
    { "vdt", OPT_INT | HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)&video_discard}, "discard threshold", "n" },
4129
    { "qscale", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_qscale}, "use fixed video quantizer scale (VBR)", "q" },
4130
    { "rc_override", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_video_rc_override_string}, "rate control override for specific intervals", "override" },
4131
    { "vcodec", HAS_ARG | OPT_VIDEO, {(void*)opt_video_codec}, "force video codec ('copy' to copy stream)", "codec" },
4132
    { "me_threshold", HAS_ARG | OPT_FUNC2 | OPT_EXPERT | OPT_VIDEO, {(void*)opt_me_threshold}, "motion estimaton threshold",  "threshold" },
4133
    { "sameq", OPT_BOOL | OPT_VIDEO, {(void*)&same_quality},
4134
      "use same video quality as source (implies VBR)" },
4135
    { "pass", HAS_ARG | OPT_VIDEO, {(void*)&opt_pass}, "select the pass number (1 or 2)", "n" },
4136
    { "passlogfile", HAS_ARG | OPT_STRING | OPT_VIDEO, {(void*)&pass_logfilename_prefix}, "select two pass log file name prefix", "prefix" },
4137
    { "deinterlace", OPT_BOOL | OPT_EXPERT | OPT_VIDEO, {(void*)&do_deinterlace},
4138
      "deinterlace pictures" },
4139
    { "psnr", OPT_BOOL | OPT_EXPERT | OPT_VIDEO, {(void*)&do_psnr}, "calculate PSNR of compressed frames" },
4140
    { "vstats", OPT_EXPERT | OPT_VIDEO, {(void*)&opt_vstats}, "dump video coding statistics to file" },
4141
    { "vstats_file", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_vstats_file}, "dump video coding statistics to file", "file" },
4142
#if CONFIG_AVFILTER
4143
    { "vf", OPT_STRING | HAS_ARG, {(void*)&vfilters}, "video filters", "filter list" },
4144
#endif
4145
    { "intra_matrix", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_intra_matrix}, "specify intra matrix coeffs", "matrix" },
4146
    { "inter_matrix", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_inter_matrix}, "specify inter matrix coeffs", "matrix" },
4147
    { "top", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_top_field_first}, "top=1/bottom=0/auto=-1 field first", "" },
4148
    { "dc", OPT_INT | HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)&intra_dc_precision}, "intra_dc_precision", "precision" },
4149
    { "vtag", OPT_FUNC2 | HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_codec_tag}, "force video tag/fourcc", "fourcc/tag" },
4150
    { "newvideo", OPT_VIDEO | OPT_FUNC2, {(void*)opt_new_stream}, "add a new video stream to the current output stream" },
4151
    { "vlang", HAS_ARG | OPT_STRING | OPT_VIDEO, {(void *)&video_language}, "set the ISO 639 language code (3 letters) of the current video stream" , "code" },
4152
    { "qphist", OPT_BOOL | OPT_EXPERT | OPT_VIDEO, { (void *)&qp_hist }, "show QP histogram" },
4153
    { "force_fps", OPT_BOOL | OPT_EXPERT | OPT_VIDEO, {(void*)&force_fps}, "force the selected framerate, disable the best supported framerate selection" },
4154
    { "streamid", OPT_FUNC2 | HAS_ARG | OPT_EXPERT, {(void*)opt_streamid}, "set the value of an outfile streamid", "streamIndex:value" },
4155
    { "force_key_frames", OPT_STRING | HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void *)&forced_key_frames}, "force key frames at specified timestamps", "timestamps" },
4156

    
4157
    /* audio options */
4158
    { "ab", OPT_FUNC2 | HAS_ARG | OPT_AUDIO, {(void*)opt_bitrate}, "set bitrate (in bits/s)", "bitrate" },
4159
    { "aframes", OPT_INT | HAS_ARG | OPT_AUDIO, {(void*)&max_frames[AVMEDIA_TYPE_AUDIO]}, "set the number of audio frames to record", "number" },
4160
    { "aq", OPT_FLOAT | HAS_ARG | OPT_AUDIO, {(void*)&audio_qscale}, "set audio quality (codec-specific)", "quality", },
4161
    { "ar", HAS_ARG | OPT_FUNC2 | OPT_AUDIO, {(void*)opt_audio_rate}, "set audio sampling rate (in Hz)", "rate" },
4162
    { "ac", HAS_ARG | OPT_FUNC2 | OPT_AUDIO, {(void*)opt_audio_channels}, "set number of audio channels", "channels" },
4163
    { "an", OPT_BOOL | OPT_AUDIO, {(void*)&audio_disable}, "disable audio" },
4164
    { "acodec", HAS_ARG | OPT_AUDIO, {(void*)opt_audio_codec}, "force audio codec ('copy' to copy stream)", "codec" },
4165
    { "atag", OPT_FUNC2 | HAS_ARG | OPT_EXPERT | OPT_AUDIO, {(void*)opt_codec_tag}, "force audio tag/fourcc", "fourcc/tag" },
4166
    { "vol", OPT_INT | HAS_ARG | OPT_AUDIO, {(void*)&audio_volume}, "change audio volume (256=normal)" , "volume" }, //
4167
    { "newaudio", OPT_AUDIO | OPT_FUNC2, {(void*)opt_new_stream}, "add a new audio stream to the current output stream" },
4168
    { "alang", HAS_ARG | OPT_STRING | OPT_AUDIO, {(void *)&audio_language}, "set the ISO 639 language code (3 letters) of the current audio stream" , "code" },
4169
    { "sample_fmt", HAS_ARG | OPT_EXPERT | OPT_AUDIO, {(void*)opt_audio_sample_fmt}, "set sample format, 'list' as argument shows all the sample formats supported", "format" },
4170

    
4171
    /* subtitle options */
4172
    { "sn", OPT_BOOL | OPT_SUBTITLE, {(void*)&subtitle_disable}, "disable subtitle" },
4173
    { "scodec", HAS_ARG | OPT_SUBTITLE, {(void*)opt_subtitle_codec}, "force subtitle codec ('copy' to copy stream)", "codec" },
4174
    { "newsubtitle", OPT_SUBTITLE | OPT_FUNC2, {(void*)opt_new_stream}, "add a new subtitle stream to the current output stream" },
4175
    { "slang", HAS_ARG | OPT_STRING | OPT_SUBTITLE, {(void *)&subtitle_language}, "set the ISO 639 language code (3 letters) of the current subtitle stream" , "code" },
4176
    { "stag", OPT_FUNC2 | HAS_ARG | OPT_EXPERT | OPT_SUBTITLE, {(void*)opt_codec_tag}, "force subtitle tag/fourcc", "fourcc/tag" },
4177

    
4178
    /* grab options */
4179
    { "vc", HAS_ARG | OPT_EXPERT | OPT_VIDEO | OPT_GRAB, {(void*)opt_video_channel}, "set video grab channel (DV1394 only)", "channel" },
4180
    { "tvstd", HAS_ARG | OPT_EXPERT | OPT_VIDEO | OPT_GRAB, {(void*)opt_video_standard}, "set television standard (NTSC, PAL (SECAM))", "standard" },
4181
    { "isync", OPT_BOOL | OPT_EXPERT | OPT_GRAB, {(void*)&input_sync}, "sync read on input", "" },
4182

    
4183
    /* muxer options */
4184
    { "muxdelay", OPT_FLOAT | HAS_ARG | OPT_EXPERT, {(void*)&mux_max_delay}, "set the maximum demux-decode delay", "seconds" },
4185
    { "muxpreload", OPT_FLOAT | HAS_ARG | OPT_EXPERT, {(void*)&mux_preload}, "set the initial demux-decode delay", "seconds" },
4186

    
4187
    { "absf", OPT_FUNC2 | HAS_ARG | OPT_AUDIO | OPT_EXPERT, {(void*)opt_bsf}, "", "bitstream_filter" },
4188
    { "vbsf", OPT_FUNC2 | HAS_ARG | OPT_VIDEO | OPT_EXPERT, {(void*)opt_bsf}, "", "bitstream_filter" },
4189
    { "sbsf", OPT_FUNC2 | HAS_ARG | OPT_SUBTITLE | OPT_EXPERT, {(void*)opt_bsf}, "", "bitstream_filter" },
4190

    
4191
    { "apre", OPT_FUNC2 | HAS_ARG | OPT_AUDIO | OPT_EXPERT, {(void*)opt_preset}, "set the audio options to the indicated preset", "preset" },
4192
    { "vpre", OPT_FUNC2 | HAS_ARG | OPT_VIDEO | OPT_EXPERT, {(void*)opt_preset}, "set the video options to the indicated preset", "preset" },
4193
    { "spre", OPT_FUNC2 | HAS_ARG | OPT_SUBTITLE | OPT_EXPERT, {(void*)opt_preset}, "set the subtitle options to the indicated preset", "preset" },
4194
    { "fpre", OPT_FUNC2 | HAS_ARG | OPT_EXPERT, {(void*)opt_preset}, "set options from indicated preset file", "filename" },
4195

    
4196
    { "default", OPT_FUNC2 | HAS_ARG | OPT_AUDIO | OPT_VIDEO | OPT_EXPERT, {(void*)opt_default}, "generic catch all option", "" },
4197
    { NULL, },
4198
};
4199

    
4200
int main(int argc, char **argv)
4201
{
4202
    int64_t ti;
4203

    
4204
    av_log_set_flags(AV_LOG_SKIP_REPEATED);
4205

    
4206
    avcodec_register_all();
4207
#if CONFIG_AVDEVICE
4208
    avdevice_register_all();
4209
#endif
4210
#if CONFIG_AVFILTER
4211
    avfilter_register_all();
4212
#endif
4213
    av_register_all();
4214

    
4215
#if HAVE_ISATTY
4216
    if(isatty(STDIN_FILENO))
4217
        url_set_interrupt_cb(decode_interrupt_cb);
4218
#endif
4219

    
4220
    init_opts();
4221

    
4222
    show_banner();
4223

    
4224
    /* parse options */
4225
    parse_options(argc, argv, options, opt_output_file);
4226

    
4227
    if(nb_output_files <= 0 && nb_input_files == 0) {
4228
        show_usage();
4229
        fprintf(stderr, "Use -h to get full help or, even better, run 'man ffmpeg'\n");
4230
        ffmpeg_exit(1);
4231
    }
4232

    
4233
    /* file converter / grab */
4234
    if (nb_output_files <= 0) {
4235
        fprintf(stderr, "At least one output file must be specified\n");
4236
        ffmpeg_exit(1);
4237
    }
4238

    
4239
    if (nb_input_files == 0) {
4240
        fprintf(stderr, "At least one input file must be specified\n");
4241
        ffmpeg_exit(1);
4242
    }
4243

    
4244
    ti = getutime();
4245
    if (transcode(output_files, nb_output_files, input_files, nb_input_files,
4246
                  stream_maps, nb_stream_maps) < 0)
4247
        ffmpeg_exit(1);
4248
    ti = getutime() - ti;
4249
    if (do_benchmark) {
4250
        int maxrss = getmaxrss() / 1024;
4251
        printf("bench: utime=%0.3fs maxrss=%ikB\n", ti / 1000000.0, maxrss);
4252
    }
4253

    
4254
    return ffmpeg_exit(0);
4255
}