Statistics
| Branch: | Revision:

ffmpeg / ffmpeg.c @ 1e80a0ea

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
        METADATA_CHECK_INDEX(out_file_index, nb_output_files, "output file")
2350
        METADATA_CHECK_INDEX(in_file_index, nb_input_files, "input file")
2351

    
2352
        files[0] = output_files[out_file_index];
2353
        files[1] = input_files[in_file_index];
2354

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

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

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

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

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

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

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

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

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

    
2435
    if (want_sdp) {
2436
        print_sdp(output_files, nb_output_files);
2437
    }
2438

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

    
2445
    timer_start = av_gettime();
2446

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

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

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

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

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

    
2524
        no_packet_count=0;
2525
        memset(no_packet, 0, sizeof(no_packet));
2526

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

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

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

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

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

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

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

    
2586
    discard_packet:
2587
        av_free_packet(&pkt);
2588

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

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

    
2601
    term_exit();
2602

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

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

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

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

    
2635
    /* finished ! */
2636
    ret = 0;
2637

    
2638
 fail:
2639
    av_freep(&bit_buffer);
2640
    av_free(file_table);
2641

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

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

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

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

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

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

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

    
2712
    opt_default(opt, arg);
2713

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

    
2717
    return 0;
2718
}
2719

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

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

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

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

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

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

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

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

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

    
2787
    av_metadata_set2(&metadata, arg, mid, 0);
2788

    
2789
    return 0;
2790
}
2791

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
2890
    return 0;
2891
}
2892

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

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

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

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

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

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

    
2944
    meta_data_maps = grow_array(meta_data_maps, sizeof(*meta_data_maps),
2945
                                &nb_meta_data_maps, nb_meta_data_maps + 1);
2946

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

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

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

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

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

    
2974
    if(stream >= MAX_STREAMS)
2975
        ffmpeg_exit(1);
2976

    
2977
    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);
2978
    input_files_ts_scale[nb_input_files][stream]= scale;
2979
}
2980

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

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

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

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

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

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

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

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

    
3055
    if (!strcmp(filename, "-"))
3056
        filename = "pipe:";
3057

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

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

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

    
3081
    set_context_opts(ic, avformat_opts, AV_OPT_FLAG_DECODING_PARAM, NULL);
3082

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

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

    
3124
    ic->loop_input = loop_input;
3125

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

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

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

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

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

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

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

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

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

    
3233
    nb_input_files++;
3234

    
3235
    video_channel = 0;
3236

    
3237
    av_freep(&video_codec_name);
3238
    av_freep(&audio_codec_name);
3239
    av_freep(&subtitle_codec_name);
3240
}
3241

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

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

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

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

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

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

    
3311
    avcodec_thread_init(st->codec, thread_count);
3312

    
3313
    video_enc = st->codec;
3314

    
3315
    if(video_codec_tag)
3316
        video_enc->codec_tag= video_codec_tag;
3317

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

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

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

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

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

    
3352
        choose_pixel_fmt(st, codec);
3353

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

    
3362
        if(intra_matrix)
3363
            video_enc->intra_matrix = intra_matrix;
3364
        if(inter_matrix)
3365
            video_enc->inter_matrix = inter_matrix;
3366

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

    
3397
        if (do_psnr)
3398
            video_enc->flags|= CODEC_FLAG_PSNR;
3399

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

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

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

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

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

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

    
3453
    avcodec_get_context_defaults3(st->codec, codec);
3454

    
3455
    ost->bitstream_filters = audio_bitstream_filters;
3456
    audio_bitstream_filters= NULL;
3457

    
3458
    avcodec_thread_init(st->codec, thread_count);
3459

    
3460
    audio_enc = st->codec;
3461
    audio_enc->codec_type = AVMEDIA_TYPE_AUDIO;
3462

    
3463
    if(audio_codec_tag)
3464
        audio_enc->codec_tag= audio_codec_tag;
3465

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

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

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

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

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

    
3525
    ost->bitstream_filters = subtitle_bitstream_filters;
3526
    subtitle_bitstream_filters= NULL;
3527

    
3528
    subtitle_enc->codec_type = AVMEDIA_TYPE_SUBTITLE;
3529

    
3530
    if(subtitle_codec_tag)
3531
        subtitle_enc->codec_tag= subtitle_codec_tag;
3532

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

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

    
3544
    subtitle_disable = 0;
3545
    av_freep(&subtitle_codec_name);
3546
    subtitle_stream_copy = 0;
3547
}
3548

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

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

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

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

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

    
3598
    if (!strcmp(filename, "-"))
3599
        filename = "pipe:";
3600

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

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

    
3623
    oc->oformat = file_oformat;
3624
    av_strlcpy(oc->filename, filename, sizeof(oc->filename));
3625

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

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

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

    
3658
        if (use_video)    new_video_stream(oc, nb_output_files);
3659
        if (use_audio)    new_audio_stream(oc, nb_output_files);
3660
        if (use_subtitle) new_subtitle_stream(oc, nb_output_files);
3661

    
3662
        oc->timestamp = recording_timestamp;
3663

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

    
3669
    output_files[nb_output_files++] = oc;
3670

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

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

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

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

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

    
3720
    set_context_opts(oc, avformat_opts, AV_OPT_FLAG_ENCODING_PARAM, NULL);
3721

    
3722
    nb_streamid_map = 0;
3723
    av_freep(&forced_key_frames);
3724
}
3725

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

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

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

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

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

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

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

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

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

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

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

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

    
3901
    if(!strcmp(arg, "vcd")) {
3902

    
3903
        opt_video_codec("mpeg1video");
3904
        opt_audio_codec("mp2");
3905
        opt_format("vcd");
3906

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

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

    
3916
        opt_default("ab", "224000");
3917
        audio_sample_rate = 44100;
3918
        audio_channels = 2;
3919

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

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

    
3931
        opt_video_codec("mpeg2video");
3932
        opt_audio_codec("mp2");
3933
        opt_format("svcd");
3934

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

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

    
3945

    
3946
        opt_default("ab", "224000");
3947
        audio_sample_rate = 44100;
3948

    
3949
        opt_default("packetsize", "2324");
3950

    
3951
    } else if(!strcmp(arg, "dvd")) {
3952

    
3953
        opt_video_codec("mpeg2video");
3954
        opt_audio_codec("ac3");
3955
        opt_format("dvd");
3956

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

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

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

    
3969
        opt_default("ab", "448000");
3970
        audio_sample_rate = 48000;
3971

    
3972
    } else if(!strncmp(arg, "dv", 2)) {
3973

    
3974
        opt_format("dv");
3975

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

    
3981
        audio_sample_rate = 48000;
3982
        audio_channels = 2;
3983

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

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

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

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

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

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

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

    
4023
    *bsfp= bsfc;
4024

    
4025
    return 0;
4026
}
4027

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

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

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

    
4062
    fclose(f);
4063

    
4064
    return 0;
4065
}
4066

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

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

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

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

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

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

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

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

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

    
4198
int main(int argc, char **argv)
4199
{
4200
    int64_t ti;
4201

    
4202
    av_log_set_flags(AV_LOG_SKIP_REPEATED);
4203

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

    
4213
#if HAVE_ISATTY
4214
    if(isatty(STDIN_FILENO))
4215
        url_set_interrupt_cb(decode_interrupt_cb);
4216
#endif
4217

    
4218
    init_opts();
4219

    
4220
    show_banner();
4221

    
4222
    /* parse options */
4223
    parse_options(argc, argv, options, opt_output_file);
4224

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

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

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

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

    
4252
    return ffmpeg_exit(0);
4253
}