Statistics
| Branch: | Revision:

ffmpeg / ffmpeg.c @ 1829e195

History | View | Annotate | Download (155 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 "libavutil/colorspace.h"
41
#include "libavutil/fifo.h"
42
#include "libavutil/intreadwrite.h"
43
#include "libavutil/pixdesc.h"
44
#include "libavutil/avstring.h"
45
#include "libavutil/libm.h"
46
#include "libavformat/os_support.h"
47

    
48
#if CONFIG_AVFILTER
49
# include "libavfilter/avfilter.h"
50
# include "libavfilter/avfiltergraph.h"
51
# include "libavfilter/graphparser.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

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

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

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

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

    
182
static float mux_preload= 0.5;
183
static float mux_max_delay= 0.7;
184

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

    
211
static int rate_emu = 0;
212

    
213
static int  video_channel = 0;
214
static char *video_standard;
215

    
216
static int audio_volume = 256;
217

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

    
233
static float dts_delta_threshold = 10;
234

    
235
static unsigned int sws_flags = SWS_BICUBIC;
236

    
237
static int64_t timer_start;
238

    
239
static uint8_t *audio_buf;
240
static uint8_t *audio_out;
241
unsigned int allocated_audio_out_size, allocated_audio_buf_size;
242

    
243
static short *samples;
244

    
245
static AVBitStreamFilterContext *video_bitstream_filters=NULL;
246
static AVBitStreamFilterContext *audio_bitstream_filters=NULL;
247
static AVBitStreamFilterContext *subtitle_bitstream_filters=NULL;
248

    
249
#define DEFAULT_PASS_LOGFILENAME_PREFIX "ffmpeg2pass"
250

    
251
struct AVInputStream;
252

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

    
274
    /* full frame size of first frame */
275
    int original_height;
276
    int original_width;
277

    
278
    /* forced key frames */
279
    int64_t *forced_kf_pts;
280
    int forced_kf_count;
281
    int forced_kf_index;
282

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

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

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

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

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

    
327
#if HAVE_TERMIOS_H
328

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

    
333
#if CONFIG_AVFILTER
334

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

    
345
    graph = av_mallocz(sizeof(AVFilterGraph));
346

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

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

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

    
364
    last_filter = ist->input_video_filter;
365

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

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

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

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

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

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

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

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

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

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

    
424
static volatile int received_sigterm = 0;
425

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
545
    av_free(video_standard);
546

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

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

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

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

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

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

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

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

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

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

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

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

    
674
        s->nb_streams++;
675

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

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

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

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

    
708
        new_output_stream(s, nb_output_files);
709
    }
710

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

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

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

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

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

    
747
        bsfc= bsfc->next;
748
    }
749

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

    
757
#define MAX_AUDIO_PACKET_SIZE (128 * 1024)
758

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1106
    *frame_size = 0;
1107

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

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

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

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

    
1146
        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));
1147
        if(!ost->video_resample)
1148
            ffmpeg_exit(1);
1149
    }
1150

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1330

    
1331
    oc = output_files[0];
1332

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

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

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

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

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

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

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

    
1411
        fflush(stderr);
1412
    }
1413

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1658
                        av_init_packet(&opkt);
1659

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1848

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
2089
        codec = ost->st->codec;
2090
        icodec = ist->st->codec;
2091

    
2092
        while ((t = av_metadata_get(ist->st->metadata, "", t, AV_METADATA_IGNORE_SUFFIX))) {
2093
            av_metadata_set2(&ost->st->metadata, t->key, t->value, AV_METADATA_DONT_OVERWRITE);
2094
        }
2095

    
2096
        ost->st->disposition = ist->st->disposition;
2097
        codec->bits_per_raw_sample= icodec->bits_per_raw_sample;
2098
        codec->chroma_sample_location = icodec->chroma_sample_location;
2099

    
2100
        if (ost->st->stream_copy) {
2101
            uint64_t extra_size = (uint64_t)icodec->extradata_size + FF_INPUT_BUFFER_PADDING_SIZE;
2102

    
2103
            if (extra_size > INT_MAX)
2104
                goto fail;
2105

    
2106
            /* if stream_copy is selected, no need to decode or encode */
2107
            codec->codec_id = icodec->codec_id;
2108
            codec->codec_type = icodec->codec_type;
2109

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

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

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

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

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

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

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

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

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

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

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

    
2344
        int out_file_index = meta_data_maps[i][0].file;
2345
        int in_file_index = meta_data_maps[i][1].file;
2346
        METADATA_CHECK_INDEX(out_file_index, nb_output_files, "output file")
2347
        METADATA_CHECK_INDEX(in_file_index, nb_input_files, "input file")
2348

    
2349
        files[0] = output_files[out_file_index];
2350
        files[1] = input_files[in_file_index];
2351

    
2352
        for (j = 0; j < 2; j++) {
2353
            AVMetaDataMap *map = &meta_data_maps[i][j];
2354

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

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

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

    
2384
        for (j = 0; j < nb_output_files; j++)
2385
            if ((ret = copy_chapters(i, j)) < 0)
2386
                goto dump_format;
2387
    }
2388

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

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

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

    
2427
    if (ret) {
2428
        fprintf(stderr, "%s\n", error);
2429
        goto fail;
2430
    }
2431

    
2432
    if (want_sdp) {
2433
        print_sdp(output_files, nb_output_files);
2434
    }
2435

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

    
2442
    timer_start = av_gettime();
2443

    
2444
    for(; received_sigterm == 0;) {
2445
        int file_index, ist_index;
2446
        AVPacket pkt;
2447
        double ipts_min;
2448
        double opts_min;
2449

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

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

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

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

    
2521
        no_packet_count=0;
2522
        memset(no_packet, 0, sizeof(no_packet));
2523

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

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

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

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

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

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

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

    
2583
    discard_packet:
2584
        av_free_packet(&pkt);
2585

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

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

    
2598
    term_exit();
2599

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

    
2606
    /* dump report by using the first video and audio streams */
2607
    print_report(output_files, ost_table, nb_ostreams, 1);
2608

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

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

    
2632
    /* finished ! */
2633
    ret = 0;
2634

    
2635
 fail:
2636
    av_freep(&bit_buffer);
2637
    av_free(file_table);
2638

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

    
2674
static void opt_format(const char *arg)
2675
{
2676
    last_asked_format = arg;
2677
}
2678

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

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

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

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

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

    
2709
    opt_default(opt, arg);
2710

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

    
2714
    return 0;
2715
}
2716

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

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

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

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

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

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

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

    
2774
static int opt_metadata(const char *opt, const char *arg)
2775
{
2776
    char *mid= strchr(arg, '=');
2777

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

    
2784
    av_metadata_set2(&metadata, arg, mid, 0);
2785

    
2786
    return 0;
2787
}
2788

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

    
2799
static void opt_top_field_first(const char *arg)
2800
{
2801
    top_field_first= atoi(arg);
2802
}
2803

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

    
2814
static void opt_audio_sample_fmt(const char *arg)
2815
{
2816
    if (strcmp(arg, "list"))
2817
        audio_sample_fmt = avcodec_get_sample_fmt(arg);
2818
    else {
2819
        list_fmts(avcodec_sample_fmt_string, SAMPLE_FMT_NB);
2820
        ffmpeg_exit(0);
2821
    }
2822
}
2823

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

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

    
2836
static void opt_video_channel(const char *arg)
2837
{
2838
    video_channel = strtol(arg, NULL, 0);
2839
}
2840

    
2841
static void opt_video_standard(const char *arg)
2842
{
2843
    video_standard = av_strdup(arg);
2844
}
2845

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

    
2857
static void opt_audio_codec(const char *arg)
2858
{
2859
    opt_codec(&audio_stream_copy, &audio_codec_name, AVMEDIA_TYPE_AUDIO, arg);
2860
}
2861

    
2862
static void opt_video_codec(const char *arg)
2863
{
2864
    opt_codec(&video_stream_copy, &video_codec_name, AVMEDIA_TYPE_VIDEO, arg);
2865
}
2866

    
2867
static void opt_subtitle_codec(const char *arg)
2868
{
2869
    opt_codec(&subtitle_stream_copy, &subtitle_codec_name, AVMEDIA_TYPE_SUBTITLE, arg);
2870
}
2871

    
2872
static int opt_codec_tag(const char *opt, const char *arg)
2873
{
2874
    char *tail;
2875
    uint32_t *codec_tag;
2876

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

    
2883
    *codec_tag = strtol(arg, &tail, 0);
2884
    if (!tail || *tail)
2885
        *codec_tag = AV_RL32(arg);
2886

    
2887
    return 0;
2888
}
2889

    
2890
static void opt_map(const char *arg)
2891
{
2892
    AVStreamMap *m;
2893
    char *p;
2894

    
2895
    stream_maps = grow_array(stream_maps, sizeof(*stream_maps), &nb_stream_maps, nb_stream_maps + 1);
2896
    m = &stream_maps[nb_stream_maps-1];
2897

    
2898
    m->file_index = strtol(arg, &p, 0);
2899
    if (*p)
2900
        p++;
2901

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

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

    
2936
static void opt_map_meta_data(const char *arg)
2937
{
2938
    AVMetaDataMap *m, *m1;
2939
    char *p;
2940

    
2941
    meta_data_maps = grow_array(meta_data_maps, sizeof(*meta_data_maps),
2942
                                &nb_meta_data_maps, nb_meta_data_maps + 1);
2943

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

    
2950
    m1 = &meta_data_maps[nb_meta_data_maps - 1][1];
2951
    m1->file = strtol(p, &p, 0);
2952
    parse_meta_type(p, &m1->type, &m1->index, &p);
2953
}
2954

    
2955
static void opt_input_ts_scale(const char *arg)
2956
{
2957
    unsigned int stream;
2958
    double scale;
2959
    char *p;
2960

    
2961
    stream = strtol(arg, &p, 0);
2962
    if (*p)
2963
        p++;
2964
    scale= strtod(p, &p);
2965

    
2966
    if(stream >= MAX_STREAMS)
2967
        ffmpeg_exit(1);
2968

    
2969
    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);
2970
    input_files_ts_scale[nb_input_files][stream]= scale;
2971
}
2972

    
2973
static int opt_recording_time(const char *opt, const char *arg)
2974
{
2975
    recording_time = parse_time_or_die(opt, arg, 1);
2976
    return 0;
2977
}
2978

    
2979
static int opt_start_time(const char *opt, const char *arg)
2980
{
2981
    start_time = parse_time_or_die(opt, arg, 1);
2982
    return 0;
2983
}
2984

    
2985
static int opt_recording_timestamp(const char *opt, const char *arg)
2986
{
2987
    recording_timestamp = parse_time_or_die(opt, arg, 0) / 1000000;
2988
    return 0;
2989
}
2990

    
2991
static int opt_input_ts_offset(const char *opt, const char *arg)
2992
{
2993
    input_ts_offset = parse_time_or_die(opt, arg, 1);
2994
    return 0;
2995
}
2996

    
2997
static enum CodecID find_codec_or_die(const char *name, int type, int encoder, int strict)
2998
{
2999
    const char *codec_string = encoder ? "encoder" : "decoder";
3000
    AVCodec *codec;
3001

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

    
3031
static void opt_input_file(const char *filename)
3032
{
3033
    AVFormatContext *ic;
3034
    AVFormatParameters params, *ap = &params;
3035
    AVInputFormat *file_iformat = NULL;
3036
    int err, i, ret, rfps, rfps_base;
3037
    int64_t timestamp;
3038

    
3039
    if (last_asked_format) {
3040
        if (!(file_iformat = av_find_input_format(last_asked_format))) {
3041
            fprintf(stderr, "Unknown input format: '%s'\n", last_asked_format);
3042
            ffmpeg_exit(1);
3043
        }
3044
        last_asked_format = NULL;
3045
    }
3046

    
3047
    if (!strcmp(filename, "-"))
3048
        filename = "pipe:";
3049

    
3050
    using_stdin |= !strncmp(filename, "pipe:", 5) ||
3051
                    !strcmp(filename, "/dev/stdin");
3052

    
3053
    /* get default parameters from command line */
3054
    ic = avformat_alloc_context();
3055
    if (!ic) {
3056
        print_error(filename, AVERROR(ENOMEM));
3057
        ffmpeg_exit(1);
3058
    }
3059

    
3060
    memset(ap, 0, sizeof(*ap));
3061
    ap->prealloced_context = 1;
3062
    ap->sample_rate = audio_sample_rate;
3063
    ap->channels = audio_channels;
3064
    ap->time_base.den = frame_rate.num;
3065
    ap->time_base.num = frame_rate.den;
3066
    ap->width = frame_width;
3067
    ap->height = frame_height;
3068
    ap->pix_fmt = frame_pix_fmt;
3069
   // ap->sample_fmt = audio_sample_fmt; //FIXME:not implemented in libavformat
3070
    ap->channel = video_channel;
3071
    ap->standard = video_standard;
3072

    
3073
    set_context_opts(ic, avformat_opts, AV_OPT_FLAG_DECODING_PARAM, NULL);
3074

    
3075
    ic->video_codec_id   =
3076
        find_codec_or_die(video_codec_name   , AVMEDIA_TYPE_VIDEO   , 0,
3077
                          avcodec_opts[AVMEDIA_TYPE_VIDEO   ]->strict_std_compliance);
3078
    ic->audio_codec_id   =
3079
        find_codec_or_die(audio_codec_name   , AVMEDIA_TYPE_AUDIO   , 0,
3080
                          avcodec_opts[AVMEDIA_TYPE_AUDIO   ]->strict_std_compliance);
3081
    ic->subtitle_codec_id=
3082
        find_codec_or_die(subtitle_codec_name, AVMEDIA_TYPE_SUBTITLE, 0,
3083
                          avcodec_opts[AVMEDIA_TYPE_SUBTITLE]->strict_std_compliance);
3084
    ic->flags |= AVFMT_FLAG_NONBLOCK;
3085

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

    
3116
    ic->loop_input = loop_input;
3117

    
3118
    /* If not enough info to get the stream parameters, we decode the
3119
       first frames to get it. (used in mpeg case for example) */
3120
    ret = av_find_stream_info(ic);
3121
    if (ret < 0 && verbose >= 0) {
3122
        fprintf(stderr, "%s: could not find codec parameters\n", filename);
3123
        av_close_input_file(ic);
3124
        ffmpeg_exit(1);
3125
    }
3126

    
3127
    timestamp = start_time;
3128
    /* add the stream start time */
3129
    if (ic->start_time != AV_NOPTS_VALUE)
3130
        timestamp += ic->start_time;
3131

    
3132
    /* if seeking requested, we execute it */
3133
    if (start_time != 0) {
3134
        ret = av_seek_frame(ic, -1, timestamp, AVSEEK_FLAG_BACKWARD);
3135
        if (ret < 0) {
3136
            fprintf(stderr, "%s: could not seek to position %0.3f\n",
3137
                    filename, (double)timestamp / AV_TIME_BASE);
3138
        }
3139
        /* reset seek info */
3140
        start_time = 0;
3141
    }
3142

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

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

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

    
3193
                    (float)rfps / rfps_base, rfps, rfps_base);
3194
            }
3195
            /* update the current frame rate to match the stream frame rate */
3196
            frame_rate.num = rfps;
3197
            frame_rate.den = rfps_base;
3198

    
3199
            if(video_disable)
3200
                st->discard= AVDISCARD_ALL;
3201
            else if(video_discard)
3202
                st->discard= video_discard;
3203
            break;
3204
        case AVMEDIA_TYPE_DATA:
3205
            break;
3206
        case AVMEDIA_TYPE_SUBTITLE:
3207
            input_codecs[nb_input_codecs-1] = avcodec_find_decoder_by_name(subtitle_codec_name);
3208
            if(subtitle_disable)
3209
                st->discard = AVDISCARD_ALL;
3210
            break;
3211
        case AVMEDIA_TYPE_ATTACHMENT:
3212
        case AVMEDIA_TYPE_UNKNOWN:
3213
            break;
3214
        default:
3215
            abort();
3216
        }
3217
    }
3218

    
3219
    input_files[nb_input_files] = ic;
3220
    input_files_ts_offset[nb_input_files] = input_ts_offset - (copy_ts ? 0 : timestamp);
3221
    /* dump the file content */
3222
    if (verbose >= 0)
3223
        dump_format(ic, nb_input_files, filename, 0);
3224

    
3225
    nb_input_files++;
3226

    
3227
    video_channel = 0;
3228

    
3229
    av_freep(&video_codec_name);
3230
    av_freep(&audio_codec_name);
3231
    av_freep(&subtitle_codec_name);
3232
}
3233

    
3234
static void check_audio_video_sub_inputs(int *has_video_ptr, int *has_audio_ptr,
3235
                                         int *has_subtitle_ptr)
3236
{
3237
    int has_video, has_audio, has_subtitle, i, j;
3238
    AVFormatContext *ic;
3239

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

    
3271
static void new_video_stream(AVFormatContext *oc, int file_idx)
3272
{
3273
    AVStream *st;
3274
    AVOutputStream *ost;
3275
    AVCodecContext *video_enc;
3276
    enum CodecID codec_id;
3277
    AVCodec *codec= NULL;
3278

    
3279
    st = av_new_stream(oc, oc->nb_streams < nb_streamid_map ? streamid_map[oc->nb_streams] : 0);
3280
    if (!st) {
3281
        fprintf(stderr, "Could not alloc stream\n");
3282
        ffmpeg_exit(1);
3283
    }
3284
    ost = new_output_stream(oc, file_idx);
3285

    
3286
    output_codecs = grow_array(output_codecs, sizeof(*output_codecs), &nb_output_codecs, nb_output_codecs + 1);
3287
    if(!video_stream_copy){
3288
        if (video_codec_name) {
3289
            codec_id = find_codec_or_die(video_codec_name, AVMEDIA_TYPE_VIDEO, 1,
3290
                                         avcodec_opts[AVMEDIA_TYPE_VIDEO]->strict_std_compliance);
3291
            codec = avcodec_find_encoder_by_name(video_codec_name);
3292
            output_codecs[nb_output_codecs-1] = codec;
3293
        } else {
3294
            codec_id = av_guess_codec(oc->oformat, NULL, oc->filename, NULL, AVMEDIA_TYPE_VIDEO);
3295
            codec = avcodec_find_encoder(codec_id);
3296
        }
3297
    }
3298

    
3299
    avcodec_get_context_defaults3(st->codec, codec);
3300
    ost->bitstream_filters = video_bitstream_filters;
3301
    video_bitstream_filters= NULL;
3302

    
3303
    avcodec_thread_init(st->codec, thread_count);
3304

    
3305
    video_enc = st->codec;
3306

    
3307
    if(video_codec_tag)
3308
        video_enc->codec_tag= video_codec_tag;
3309

    
3310
    if(   (video_global_header&1)
3311
       || (video_global_header==0 && (oc->oformat->flags & AVFMT_GLOBALHEADER))){
3312
        video_enc->flags |= CODEC_FLAG_GLOBAL_HEADER;
3313
        avcodec_opts[AVMEDIA_TYPE_VIDEO]->flags|= CODEC_FLAG_GLOBAL_HEADER;
3314
    }
3315
    if(video_global_header&2){
3316
        video_enc->flags2 |= CODEC_FLAG2_LOCAL_HEADER;
3317
        avcodec_opts[AVMEDIA_TYPE_VIDEO]->flags2|= CODEC_FLAG2_LOCAL_HEADER;
3318
    }
3319

    
3320
    if (video_stream_copy) {
3321
        st->stream_copy = 1;
3322
        video_enc->codec_type = AVMEDIA_TYPE_VIDEO;
3323
        video_enc->sample_aspect_ratio =
3324
        st->sample_aspect_ratio = av_d2q(frame_aspect_ratio*frame_height/frame_width, 255);
3325
    } else {
3326
        const char *p;
3327
        int i;
3328
        AVRational fps= frame_rate.num ? frame_rate : (AVRational){25,1};
3329

    
3330
        video_enc->codec_id = codec_id;
3331
        set_context_opts(video_enc, avcodec_opts[AVMEDIA_TYPE_VIDEO], AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_ENCODING_PARAM, codec);
3332

    
3333
        if (codec && codec->supported_framerates && !force_fps)
3334
            fps = codec->supported_framerates[av_find_nearest_q_idx(fps, codec->supported_framerates)];
3335
        video_enc->time_base.den = fps.num;
3336
        video_enc->time_base.num = fps.den;
3337

    
3338
        video_enc->width = frame_width;
3339
        video_enc->height = frame_height;
3340
        video_enc->sample_aspect_ratio = av_d2q(frame_aspect_ratio*video_enc->height/video_enc->width, 255);
3341
        video_enc->pix_fmt = frame_pix_fmt;
3342
        st->sample_aspect_ratio = video_enc->sample_aspect_ratio;
3343

    
3344
        choose_pixel_fmt(st, codec);
3345

    
3346
        if (intra_only)
3347
            video_enc->gop_size = 0;
3348
        if (video_qscale || same_quality) {
3349
            video_enc->flags |= CODEC_FLAG_QSCALE;
3350
            video_enc->global_quality=
3351
                st->quality = FF_QP2LAMBDA * video_qscale;
3352
        }
3353

    
3354
        if(intra_matrix)
3355
            video_enc->intra_matrix = intra_matrix;
3356
        if(inter_matrix)
3357
            video_enc->inter_matrix = inter_matrix;
3358

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

    
3389
        if (do_psnr)
3390
            video_enc->flags|= CODEC_FLAG_PSNR;
3391

    
3392
        /* two pass mode */
3393
        if (do_pass) {
3394
            if (do_pass == 1) {
3395
                video_enc->flags |= CODEC_FLAG_PASS1;
3396
            } else {
3397
                video_enc->flags |= CODEC_FLAG_PASS2;
3398
            }
3399
        }
3400

    
3401
        if (forced_key_frames)
3402
            parse_forced_key_frames(forced_key_frames, ost, video_enc);
3403
    }
3404
    if (video_language) {
3405
        av_metadata_set2(&st->metadata, "language", video_language, 0);
3406
        av_freep(&video_language);
3407
    }
3408

    
3409
    /* reset some key parameters */
3410
    video_disable = 0;
3411
    av_freep(&video_codec_name);
3412
    av_freep(&forced_key_frames);
3413
    video_stream_copy = 0;
3414
    frame_pix_fmt = PIX_FMT_NONE;
3415
}
3416

    
3417
static void new_audio_stream(AVFormatContext *oc, int file_idx)
3418
{
3419
    AVStream *st;
3420
    AVOutputStream *ost;
3421
    AVCodec *codec= NULL;
3422
    AVCodecContext *audio_enc;
3423
    enum CodecID codec_id;
3424

    
3425
    st = av_new_stream(oc, oc->nb_streams < nb_streamid_map ? streamid_map[oc->nb_streams] : 0);
3426
    if (!st) {
3427
        fprintf(stderr, "Could not alloc stream\n");
3428
        ffmpeg_exit(1);
3429
    }
3430
    ost = new_output_stream(oc, file_idx);
3431

    
3432
    output_codecs = grow_array(output_codecs, sizeof(*output_codecs), &nb_output_codecs, nb_output_codecs + 1);
3433
    if(!audio_stream_copy){
3434
        if (audio_codec_name) {
3435
            codec_id = find_codec_or_die(audio_codec_name, AVMEDIA_TYPE_AUDIO, 1,
3436
                                         avcodec_opts[AVMEDIA_TYPE_AUDIO]->strict_std_compliance);
3437
            codec = avcodec_find_encoder_by_name(audio_codec_name);
3438
            output_codecs[nb_output_codecs-1] = codec;
3439
        } else {
3440
            codec_id = av_guess_codec(oc->oformat, NULL, oc->filename, NULL, AVMEDIA_TYPE_AUDIO);
3441
            codec = avcodec_find_encoder(codec_id);
3442
        }
3443
    }
3444

    
3445
    avcodec_get_context_defaults3(st->codec, codec);
3446

    
3447
    ost->bitstream_filters = audio_bitstream_filters;
3448
    audio_bitstream_filters= NULL;
3449

    
3450
    avcodec_thread_init(st->codec, thread_count);
3451

    
3452
    audio_enc = st->codec;
3453
    audio_enc->codec_type = AVMEDIA_TYPE_AUDIO;
3454

    
3455
    if(audio_codec_tag)
3456
        audio_enc->codec_tag= audio_codec_tag;
3457

    
3458
    if (oc->oformat->flags & AVFMT_GLOBALHEADER) {
3459
        audio_enc->flags |= CODEC_FLAG_GLOBAL_HEADER;
3460
        avcodec_opts[AVMEDIA_TYPE_AUDIO]->flags|= CODEC_FLAG_GLOBAL_HEADER;
3461
    }
3462
    if (audio_stream_copy) {
3463
        st->stream_copy = 1;
3464
        audio_enc->channels = audio_channels;
3465
        audio_enc->sample_rate = audio_sample_rate;
3466
    } else {
3467
        audio_enc->codec_id = codec_id;
3468
        set_context_opts(audio_enc, avcodec_opts[AVMEDIA_TYPE_AUDIO], AV_OPT_FLAG_AUDIO_PARAM | AV_OPT_FLAG_ENCODING_PARAM, codec);
3469

    
3470
        if (audio_qscale > QSCALE_NONE) {
3471
            audio_enc->flags |= CODEC_FLAG_QSCALE;
3472
            audio_enc->global_quality = st->quality = FF_QP2LAMBDA * audio_qscale;
3473
        }
3474
        audio_enc->channels = audio_channels;
3475
        audio_enc->sample_fmt = audio_sample_fmt;
3476
        audio_enc->sample_rate = audio_sample_rate;
3477
        audio_enc->channel_layout = channel_layout;
3478
        if (avcodec_channel_layout_num_channels(channel_layout) != audio_channels)
3479
            audio_enc->channel_layout = 0;
3480
        choose_sample_fmt(st, codec);
3481
        choose_sample_rate(st, codec);
3482
    }
3483
    audio_enc->time_base= (AVRational){1, audio_sample_rate};
3484
    if (audio_language) {
3485
        av_metadata_set2(&st->metadata, "language", audio_language, 0);
3486
        av_freep(&audio_language);
3487
    }
3488

    
3489
    /* reset some key parameters */
3490
    audio_disable = 0;
3491
    av_freep(&audio_codec_name);
3492
    audio_stream_copy = 0;
3493
}
3494

    
3495
static void new_subtitle_stream(AVFormatContext *oc, int file_idx)
3496
{
3497
    AVStream *st;
3498
    AVOutputStream *ost;
3499
    AVCodec *codec=NULL;
3500
    AVCodecContext *subtitle_enc;
3501

    
3502
    st = av_new_stream(oc, oc->nb_streams < nb_streamid_map ? streamid_map[oc->nb_streams] : 0);
3503
    if (!st) {
3504
        fprintf(stderr, "Could not alloc stream\n");
3505
        ffmpeg_exit(1);
3506
    }
3507
    ost = new_output_stream(oc, file_idx);
3508
    subtitle_enc = st->codec;
3509
    output_codecs = grow_array(output_codecs, sizeof(*output_codecs), &nb_output_codecs, nb_output_codecs + 1);
3510
    if(!subtitle_stream_copy){
3511
        subtitle_enc->codec_id = find_codec_or_die(subtitle_codec_name, AVMEDIA_TYPE_SUBTITLE, 1,
3512
                                                   avcodec_opts[AVMEDIA_TYPE_SUBTITLE]->strict_std_compliance);
3513
        codec= output_codecs[nb_output_codecs-1] = avcodec_find_encoder_by_name(subtitle_codec_name);
3514
    }
3515
    avcodec_get_context_defaults3(st->codec, codec);
3516

    
3517
    ost->bitstream_filters = subtitle_bitstream_filters;
3518
    subtitle_bitstream_filters= NULL;
3519

    
3520
    subtitle_enc->codec_type = AVMEDIA_TYPE_SUBTITLE;
3521

    
3522
    if(subtitle_codec_tag)
3523
        subtitle_enc->codec_tag= subtitle_codec_tag;
3524

    
3525
    if (subtitle_stream_copy) {
3526
        st->stream_copy = 1;
3527
    } else {
3528
        set_context_opts(avcodec_opts[AVMEDIA_TYPE_SUBTITLE], subtitle_enc, AV_OPT_FLAG_SUBTITLE_PARAM | AV_OPT_FLAG_ENCODING_PARAM, codec);
3529
    }
3530

    
3531
    if (subtitle_language) {
3532
        av_metadata_set2(&st->metadata, "language", subtitle_language, 0);
3533
        av_freep(&subtitle_language);
3534
    }
3535

    
3536
    subtitle_disable = 0;
3537
    av_freep(&subtitle_codec_name);
3538
    subtitle_stream_copy = 0;
3539
}
3540

    
3541
static int opt_new_stream(const char *opt, const char *arg)
3542
{
3543
    AVFormatContext *oc;
3544
    int file_idx = nb_output_files - 1;
3545
    if (nb_output_files <= 0) {
3546
        fprintf(stderr, "At least one output file must be specified\n");
3547
        ffmpeg_exit(1);
3548
    }
3549
    oc = output_files[file_idx];
3550

    
3551
    if      (!strcmp(opt, "newvideo"   )) new_video_stream   (oc, file_idx);
3552
    else if (!strcmp(opt, "newaudio"   )) new_audio_stream   (oc, file_idx);
3553
    else if (!strcmp(opt, "newsubtitle")) new_subtitle_stream(oc, file_idx);
3554
    else av_assert0(0);
3555
    return 0;
3556
}
3557

    
3558
/* arg format is "output-stream-index:streamid-value". */
3559
static int opt_streamid(const char *opt, const char *arg)
3560
{
3561
    int idx;
3562
    char *p;
3563
    char idx_str[16];
3564

    
3565
    strncpy(idx_str, arg, sizeof(idx_str));
3566
    idx_str[sizeof(idx_str)-1] = '\0';
3567
    p = strchr(idx_str, ':');
3568
    if (!p) {
3569
        fprintf(stderr,
3570
                "Invalid value '%s' for option '%s', required syntax is 'index:value'\n",
3571
                arg, opt);
3572
        ffmpeg_exit(1);
3573
    }
3574
    *p++ = '\0';
3575
    idx = parse_number_or_die(opt, idx_str, OPT_INT, 0, MAX_STREAMS-1);
3576
    streamid_map = grow_array(streamid_map, sizeof(*streamid_map), &nb_streamid_map, idx+1);
3577
    streamid_map[idx] = parse_number_or_die(opt, p, OPT_INT, 0, INT_MAX);
3578
    return 0;
3579
}
3580

    
3581
static void opt_output_file(const char *filename)
3582
{
3583
    AVFormatContext *oc;
3584
    int err, use_video, use_audio, use_subtitle;
3585
    int input_has_video, input_has_audio, input_has_subtitle;
3586
    AVFormatParameters params, *ap = &params;
3587
    AVOutputFormat *file_oformat;
3588
    AVMetadataTag *tag = NULL;
3589

    
3590
    if (!strcmp(filename, "-"))
3591
        filename = "pipe:";
3592

    
3593
    oc = avformat_alloc_context();
3594
    if (!oc) {
3595
        print_error(filename, AVERROR(ENOMEM));
3596
        ffmpeg_exit(1);
3597
    }
3598

    
3599
    if (last_asked_format) {
3600
        file_oformat = av_guess_format(last_asked_format, NULL, NULL);
3601
        if (!file_oformat) {
3602
            fprintf(stderr, "Requested output format '%s' is not a suitable output format\n", last_asked_format);
3603
            ffmpeg_exit(1);
3604
        }
3605
        last_asked_format = NULL;
3606
    } else {
3607
        file_oformat = av_guess_format(NULL, filename, NULL);
3608
        if (!file_oformat) {
3609
            fprintf(stderr, "Unable to find a suitable output format for '%s'\n",
3610
                    filename);
3611
            ffmpeg_exit(1);
3612
        }
3613
    }
3614

    
3615
    oc->oformat = file_oformat;
3616
    av_strlcpy(oc->filename, filename, sizeof(oc->filename));
3617

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

    
3632
        /* disable if no corresponding type found and at least one
3633
           input file */
3634
        if (nb_input_files > 0) {
3635
            check_audio_video_sub_inputs(&input_has_video, &input_has_audio,
3636
                                         &input_has_subtitle);
3637
            if (!input_has_video)
3638
                use_video = 0;
3639
            if (!input_has_audio)
3640
                use_audio = 0;
3641
            if (!input_has_subtitle)
3642
                use_subtitle = 0;
3643
        }
3644

    
3645
        /* manual disable */
3646
        if (audio_disable)    use_audio    = 0;
3647
        if (video_disable)    use_video    = 0;
3648
        if (subtitle_disable) use_subtitle = 0;
3649

    
3650
        if (use_video)    new_video_stream(oc, nb_output_files);
3651
        if (use_audio)    new_audio_stream(oc, nb_output_files);
3652
        if (use_subtitle) new_subtitle_stream(oc, nb_output_files);
3653

    
3654
        oc->timestamp = recording_timestamp;
3655

    
3656
        while ((tag = av_metadata_get(metadata, "", tag, AV_METADATA_IGNORE_SUFFIX)))
3657
            av_metadata_set2(&oc->metadata, tag->key, tag->value, 0);
3658
        av_metadata_free(&metadata);
3659
    }
3660

    
3661
    output_files[nb_output_files++] = oc;
3662

    
3663
    /* check filename in case of an image number is expected */
3664
    if (oc->oformat->flags & AVFMT_NEEDNUMBER) {
3665
        if (!av_filename_number_test(oc->filename)) {
3666
            print_error(oc->filename, AVERROR_NUMEXPECTED);
3667
            ffmpeg_exit(1);
3668
        }
3669
    }
3670

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

    
3693
        /* open the file */
3694
        if ((err = url_fopen(&oc->pb, filename, URL_WRONLY)) < 0) {
3695
            print_error(filename, err);
3696
            ffmpeg_exit(1);
3697
        }
3698
    }
3699

    
3700
    memset(ap, 0, sizeof(*ap));
3701
    if (av_set_parameters(oc, ap) < 0) {
3702
        fprintf(stderr, "%s: Invalid encoding parameters\n",
3703
                oc->filename);
3704
        ffmpeg_exit(1);
3705
    }
3706

    
3707
    oc->preload= (int)(mux_preload*AV_TIME_BASE);
3708
    oc->max_delay= (int)(mux_max_delay*AV_TIME_BASE);
3709
    oc->loop_output = loop_output;
3710
    oc->flags |= AVFMT_FLAG_NONBLOCK;
3711

    
3712
    set_context_opts(oc, avformat_opts, AV_OPT_FLAG_ENCODING_PARAM, NULL);
3713

    
3714
    nb_streamid_map = 0;
3715
    av_freep(&forced_key_frames);
3716
}
3717

    
3718
/* same option as mencoder */
3719
static void opt_pass(const char *pass_str)
3720
{
3721
    int pass;
3722
    pass = atoi(pass_str);
3723
    if (pass != 1 && pass != 2) {
3724
        fprintf(stderr, "pass number can be only 1 or 2\n");
3725
        ffmpeg_exit(1);
3726
    }
3727
    do_pass = pass;
3728
}
3729

    
3730
static int64_t getutime(void)
3731
{
3732
#if HAVE_GETRUSAGE
3733
    struct rusage rusage;
3734

    
3735
    getrusage(RUSAGE_SELF, &rusage);
3736
    return (rusage.ru_utime.tv_sec * 1000000LL) + rusage.ru_utime.tv_usec;
3737
#elif HAVE_GETPROCESSTIMES
3738
    HANDLE proc;
3739
    FILETIME c, e, k, u;
3740
    proc = GetCurrentProcess();
3741
    GetProcessTimes(proc, &c, &e, &k, &u);
3742
    return ((int64_t) u.dwHighDateTime << 32 | u.dwLowDateTime) / 10;
3743
#else
3744
    return av_gettime();
3745
#endif
3746
}
3747

    
3748
static int64_t getmaxrss(void)
3749
{
3750
#if HAVE_GETRUSAGE && HAVE_STRUCT_RUSAGE_RU_MAXRSS
3751
    struct rusage rusage;
3752
    getrusage(RUSAGE_SELF, &rusage);
3753
    return (int64_t)rusage.ru_maxrss * 1024;
3754
#elif HAVE_GETPROCESSMEMORYINFO
3755
    HANDLE proc;
3756
    PROCESS_MEMORY_COUNTERS memcounters;
3757
    proc = GetCurrentProcess();
3758
    memcounters.cb = sizeof(memcounters);
3759
    GetProcessMemoryInfo(proc, &memcounters, sizeof(memcounters));
3760
    return memcounters.PeakPagefileUsage;
3761
#else
3762
    return 0;
3763
#endif
3764
}
3765

    
3766
static void parse_matrix_coeffs(uint16_t *dest, const char *str)
3767
{
3768
    int i;
3769
    const char *p = str;
3770
    for(i = 0;; i++) {
3771
        dest[i] = atoi(p);
3772
        if(i == 63)
3773
            break;
3774
        p = strchr(p, ',');
3775
        if(!p) {
3776
            fprintf(stderr, "Syntax error in matrix \"%s\" at coeff %d\n", str, i);
3777
            ffmpeg_exit(1);
3778
        }
3779
        p++;
3780
    }
3781
}
3782

    
3783
static void opt_inter_matrix(const char *arg)
3784
{
3785
    inter_matrix = av_mallocz(sizeof(uint16_t) * 64);
3786
    parse_matrix_coeffs(inter_matrix, arg);
3787
}
3788

    
3789
static void opt_intra_matrix(const char *arg)
3790
{
3791
    intra_matrix = av_mallocz(sizeof(uint16_t) * 64);
3792
    parse_matrix_coeffs(intra_matrix, arg);
3793
}
3794

    
3795
static void show_usage(void)
3796
{
3797
    printf("Hyper fast Audio and Video encoder\n");
3798
    printf("usage: ffmpeg [options] [[infile options] -i infile]... {[outfile options] outfile}...\n");
3799
    printf("\n");
3800
}
3801

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

    
3837
static void opt_target(const char *arg)
3838
{
3839
    enum { PAL, NTSC, FILM, UNKNOWN } norm = UNKNOWN;
3840
    static const char *const frame_rates[] = {"25", "30000/1001", "24000/1001"};
3841

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

    
3886
    if(norm == UNKNOWN) {
3887
        fprintf(stderr, "Could not determine norm (PAL/NTSC/NTSC-Film) for target.\n");
3888
        fprintf(stderr, "Please prefix target with \"pal-\", \"ntsc-\" or \"film-\",\n");
3889
        fprintf(stderr, "or set a framerate with \"-r xxx\".\n");
3890
        ffmpeg_exit(1);
3891
    }
3892

    
3893
    if(!strcmp(arg, "vcd")) {
3894

    
3895
        opt_video_codec("mpeg1video");
3896
        opt_audio_codec("mp2");
3897
        opt_format("vcd");
3898

    
3899
        opt_frame_size(norm == PAL ? "352x288" : "352x240");
3900
        opt_frame_rate(NULL, frame_rates[norm]);
3901
        opt_default("g", norm == PAL ? "15" : "18");
3902

    
3903
        opt_default("b", "1150000");
3904
        opt_default("maxrate", "1150000");
3905
        opt_default("minrate", "1150000");
3906
        opt_default("bufsize", "327680"); // 40*1024*8;
3907

    
3908
        opt_default("ab", "224000");
3909
        audio_sample_rate = 44100;
3910
        audio_channels = 2;
3911

    
3912
        opt_default("packetsize", "2324");
3913
        opt_default("muxrate", "1411200"); // 2352 * 75 * 8;
3914

    
3915
        /* We have to offset the PTS, so that it is consistent with the SCR.
3916
           SCR starts at 36000, but the first two packs contain only padding
3917
           and the first pack from the other stream, respectively, may also have
3918
           been written before.
3919
           So the real data starts at SCR 36000+3*1200. */
3920
        mux_preload= (36000+3*1200) / 90000.0; //0.44
3921
    } else if(!strcmp(arg, "svcd")) {
3922

    
3923
        opt_video_codec("mpeg2video");
3924
        opt_audio_codec("mp2");
3925
        opt_format("svcd");
3926

    
3927
        opt_frame_size(norm == PAL ? "480x576" : "480x480");
3928
        opt_frame_rate(NULL, frame_rates[norm]);
3929
        opt_default("g", norm == PAL ? "15" : "18");
3930

    
3931
        opt_default("b", "2040000");
3932
        opt_default("maxrate", "2516000");
3933
        opt_default("minrate", "0"); //1145000;
3934
        opt_default("bufsize", "1835008"); //224*1024*8;
3935
        opt_default("flags", "+scan_offset");
3936

    
3937

    
3938
        opt_default("ab", "224000");
3939
        audio_sample_rate = 44100;
3940

    
3941
        opt_default("packetsize", "2324");
3942

    
3943
    } else if(!strcmp(arg, "dvd")) {
3944

    
3945
        opt_video_codec("mpeg2video");
3946
        opt_audio_codec("ac3");
3947
        opt_format("dvd");
3948

    
3949
        opt_frame_size(norm == PAL ? "720x576" : "720x480");
3950
        opt_frame_rate(NULL, frame_rates[norm]);
3951
        opt_default("g", norm == PAL ? "15" : "18");
3952

    
3953
        opt_default("b", "6000000");
3954
        opt_default("maxrate", "9000000");
3955
        opt_default("minrate", "0"); //1500000;
3956
        opt_default("bufsize", "1835008"); //224*1024*8;
3957

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

    
3961
        opt_default("ab", "448000");
3962
        audio_sample_rate = 48000;
3963

    
3964
    } else if(!strncmp(arg, "dv", 2)) {
3965

    
3966
        opt_format("dv");
3967

    
3968
        opt_frame_size(norm == PAL ? "720x576" : "720x480");
3969
        opt_frame_pix_fmt(!strncmp(arg, "dv50", 4) ? "yuv422p" :
3970
                          (norm == PAL ? "yuv420p" : "yuv411p"));
3971
        opt_frame_rate(NULL, frame_rates[norm]);
3972

    
3973
        audio_sample_rate = 48000;
3974
        audio_channels = 2;
3975

    
3976
    } else {
3977
        fprintf(stderr, "Unknown target: %s\n", arg);
3978
        ffmpeg_exit(1);
3979
    }
3980
}
3981

    
3982
static void opt_vstats_file (const char *arg)
3983
{
3984
    av_free (vstats_filename);
3985
    vstats_filename=av_strdup (arg);
3986
}
3987

    
3988
static void opt_vstats (void)
3989
{
3990
    char filename[40];
3991
    time_t today2 = time(NULL);
3992
    struct tm *today = localtime(&today2);
3993

    
3994
    snprintf(filename, sizeof(filename), "vstats_%02d%02d%02d.log", today->tm_hour, today->tm_min,
3995
             today->tm_sec);
3996
    opt_vstats_file(filename);
3997
}
3998

    
3999
static int opt_bsf(const char *opt, const char *arg)
4000
{
4001
    AVBitStreamFilterContext *bsfc= av_bitstream_filter_init(arg); //FIXME split name and args for filter at '='
4002
    AVBitStreamFilterContext **bsfp;
4003

    
4004
    if(!bsfc){
4005
        fprintf(stderr, "Unknown bitstream filter %s\n", arg);
4006
        ffmpeg_exit(1);
4007
    }
4008

    
4009
    bsfp= *opt == 'v' ? &video_bitstream_filters :
4010
          *opt == 'a' ? &audio_bitstream_filters :
4011
                        &subtitle_bitstream_filters;
4012
    while(*bsfp)
4013
        bsfp= &(*bsfp)->next;
4014

    
4015
    *bsfp= bsfc;
4016

    
4017
    return 0;
4018
}
4019

    
4020
static int opt_preset(const char *opt, const char *arg)
4021
{
4022
    FILE *f=NULL;
4023
    char filename[1000], tmp[1000], tmp2[1000], line[1000];
4024
    int i;
4025
    const char *base[3]= { getenv("FFMPEG_DATADIR"),
4026
                           getenv("HOME"),
4027
                           FFMPEG_DATADIR,
4028
                         };
4029

    
4030
    if (*opt != 'f') {
4031
        for(i=0; i<3 && !f; i++){
4032
            if(!base[i])
4033
                continue;
4034
            snprintf(filename, sizeof(filename), "%s%s/%s.ffpreset", base[i], i != 1 ? "" : "/.ffmpeg", arg);
4035
            f= fopen(filename, "r");
4036
            if(!f){
4037
                char *codec_name= *opt == 'v' ? video_codec_name :
4038
                                  *opt == 'a' ? audio_codec_name :
4039
                                                subtitle_codec_name;
4040
                snprintf(filename, sizeof(filename), "%s%s/%s-%s.ffpreset", base[i],  i != 1 ? "" : "/.ffmpeg", codec_name, arg);
4041
                f= fopen(filename, "r");
4042
            }
4043
        }
4044
    } else {
4045
        av_strlcpy(filename, arg, sizeof(filename));
4046
        f= fopen(filename, "r");
4047
    }
4048

    
4049
    if(!f){
4050
        fprintf(stderr, "File for preset '%s' not found\n", arg);
4051
        ffmpeg_exit(1);
4052
    }
4053

    
4054
    while(!feof(f)){
4055
        int e= fscanf(f, "%999[^\n]\n", line) - 1;
4056
        if(line[0] == '#' && !e)
4057
            continue;
4058
        e|= sscanf(line, "%999[^=]=%999[^\n]\n", tmp, tmp2) - 2;
4059
        if(e){
4060
            fprintf(stderr, "%s: Invalid syntax: '%s'\n", filename, line);
4061
            ffmpeg_exit(1);
4062
        }
4063
        if(!strcmp(tmp, "acodec")){
4064
            opt_audio_codec(tmp2);
4065
        }else if(!strcmp(tmp, "vcodec")){
4066
            opt_video_codec(tmp2);
4067
        }else if(!strcmp(tmp, "scodec")){
4068
            opt_subtitle_codec(tmp2);
4069
        }else if(opt_default(tmp, tmp2) < 0){
4070
            fprintf(stderr, "%s: Invalid option or argument: '%s', parsed as '%s' = '%s'\n", filename, line, tmp, tmp2);
4071
            ffmpeg_exit(1);
4072
        }
4073
    }
4074

    
4075
    fclose(f);
4076

    
4077
    return 0;
4078
}
4079

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

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

    
4168
    /* audio options */
4169
    { "ab", OPT_FUNC2 | HAS_ARG | OPT_AUDIO, {(void*)opt_bitrate}, "set bitrate (in bits/s)", "bitrate" },
4170
    { "aframes", OPT_INT | HAS_ARG | OPT_AUDIO, {(void*)&max_frames[AVMEDIA_TYPE_AUDIO]}, "set the number of audio frames to record", "number" },
4171
    { "aq", OPT_FLOAT | HAS_ARG | OPT_AUDIO, {(void*)&audio_qscale}, "set audio quality (codec-specific)", "quality", },
4172
    { "ar", HAS_ARG | OPT_FUNC2 | OPT_AUDIO, {(void*)opt_audio_rate}, "set audio sampling rate (in Hz)", "rate" },
4173
    { "ac", HAS_ARG | OPT_FUNC2 | OPT_AUDIO, {(void*)opt_audio_channels}, "set number of audio channels", "channels" },
4174
    { "an", OPT_BOOL | OPT_AUDIO, {(void*)&audio_disable}, "disable audio" },
4175
    { "acodec", HAS_ARG | OPT_AUDIO, {(void*)opt_audio_codec}, "force audio codec ('copy' to copy stream)", "codec" },
4176
    { "atag", OPT_FUNC2 | HAS_ARG | OPT_EXPERT | OPT_AUDIO, {(void*)opt_codec_tag}, "force audio tag/fourcc", "fourcc/tag" },
4177
    { "vol", OPT_INT | HAS_ARG | OPT_AUDIO, {(void*)&audio_volume}, "change audio volume (256=normal)" , "volume" }, //
4178
    { "newaudio", OPT_AUDIO | OPT_FUNC2, {(void*)opt_new_stream}, "add a new audio stream to the current output stream" },
4179
    { "alang", HAS_ARG | OPT_STRING | OPT_AUDIO, {(void *)&audio_language}, "set the ISO 639 language code (3 letters) of the current audio stream" , "code" },
4180
    { "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" },
4181

    
4182
    /* subtitle options */
4183
    { "sn", OPT_BOOL | OPT_SUBTITLE, {(void*)&subtitle_disable}, "disable subtitle" },
4184
    { "scodec", HAS_ARG | OPT_SUBTITLE, {(void*)opt_subtitle_codec}, "force subtitle codec ('copy' to copy stream)", "codec" },
4185
    { "newsubtitle", OPT_SUBTITLE | OPT_FUNC2, {(void*)opt_new_stream}, "add a new subtitle stream to the current output stream" },
4186
    { "slang", HAS_ARG | OPT_STRING | OPT_SUBTITLE, {(void *)&subtitle_language}, "set the ISO 639 language code (3 letters) of the current subtitle stream" , "code" },
4187
    { "stag", OPT_FUNC2 | HAS_ARG | OPT_EXPERT | OPT_SUBTITLE, {(void*)opt_codec_tag}, "force subtitle tag/fourcc", "fourcc/tag" },
4188

    
4189
    /* grab options */
4190
    { "vc", HAS_ARG | OPT_EXPERT | OPT_VIDEO | OPT_GRAB, {(void*)opt_video_channel}, "set video grab channel (DV1394 only)", "channel" },
4191
    { "tvstd", HAS_ARG | OPT_EXPERT | OPT_VIDEO | OPT_GRAB, {(void*)opt_video_standard}, "set television standard (NTSC, PAL (SECAM))", "standard" },
4192
    { "isync", OPT_BOOL | OPT_EXPERT | OPT_GRAB, {(void*)&input_sync}, "sync read on input", "" },
4193

    
4194
    /* muxer options */
4195
    { "muxdelay", OPT_FLOAT | HAS_ARG | OPT_EXPERT, {(void*)&mux_max_delay}, "set the maximum demux-decode delay", "seconds" },
4196
    { "muxpreload", OPT_FLOAT | HAS_ARG | OPT_EXPERT, {(void*)&mux_preload}, "set the initial demux-decode delay", "seconds" },
4197

    
4198
    { "absf", OPT_FUNC2 | HAS_ARG | OPT_AUDIO | OPT_EXPERT, {(void*)opt_bsf}, "", "bitstream_filter" },
4199
    { "vbsf", OPT_FUNC2 | HAS_ARG | OPT_VIDEO | OPT_EXPERT, {(void*)opt_bsf}, "", "bitstream_filter" },
4200
    { "sbsf", OPT_FUNC2 | HAS_ARG | OPT_SUBTITLE | OPT_EXPERT, {(void*)opt_bsf}, "", "bitstream_filter" },
4201

    
4202
    { "apre", OPT_FUNC2 | HAS_ARG | OPT_AUDIO | OPT_EXPERT, {(void*)opt_preset}, "set the audio options to the indicated preset", "preset" },
4203
    { "vpre", OPT_FUNC2 | HAS_ARG | OPT_VIDEO | OPT_EXPERT, {(void*)opt_preset}, "set the video options to the indicated preset", "preset" },
4204
    { "spre", OPT_FUNC2 | HAS_ARG | OPT_SUBTITLE | OPT_EXPERT, {(void*)opt_preset}, "set the subtitle options to the indicated preset", "preset" },
4205
    { "fpre", OPT_FUNC2 | HAS_ARG | OPT_EXPERT, {(void*)opt_preset}, "set options from indicated preset file", "filename" },
4206

    
4207
    { "default", OPT_FUNC2 | HAS_ARG | OPT_AUDIO | OPT_VIDEO | OPT_EXPERT, {(void*)opt_default}, "generic catch all option", "" },
4208
    { NULL, },
4209
};
4210

    
4211
int main(int argc, char **argv)
4212
{
4213
    int64_t ti;
4214

    
4215
    av_log_set_flags(AV_LOG_SKIP_REPEATED);
4216

    
4217
    avcodec_register_all();
4218
#if CONFIG_AVDEVICE
4219
    avdevice_register_all();
4220
#endif
4221
#if CONFIG_AVFILTER
4222
    avfilter_register_all();
4223
#endif
4224
    av_register_all();
4225

    
4226
#if HAVE_ISATTY
4227
    if(isatty(STDIN_FILENO))
4228
        url_set_interrupt_cb(decode_interrupt_cb);
4229
#endif
4230

    
4231
    init_opts();
4232

    
4233
    show_banner();
4234

    
4235
    /* parse options */
4236
    parse_options(argc, argv, options, opt_output_file);
4237

    
4238
    if(nb_output_files <= 0 && nb_input_files == 0) {
4239
        show_usage();
4240
        fprintf(stderr, "Use -h to get full help or, even better, run 'man ffmpeg'\n");
4241
        ffmpeg_exit(1);
4242
    }
4243

    
4244
    /* file converter / grab */
4245
    if (nb_output_files <= 0) {
4246
        fprintf(stderr, "At least one output file must be specified\n");
4247
        ffmpeg_exit(1);
4248
    }
4249

    
4250
    if (nb_input_files == 0) {
4251
        fprintf(stderr, "At least one input file must be specified\n");
4252
        ffmpeg_exit(1);
4253
    }
4254

    
4255
    ti = getutime();
4256
    if (transcode(output_files, nb_output_files, input_files, nb_input_files,
4257
                  stream_maps, nb_stream_maps) < 0)
4258
        ffmpeg_exit(1);
4259
    ti = getutime() - ti;
4260
    if (do_benchmark) {
4261
        int maxrss = getmaxrss() / 1024;
4262
        printf("bench: utime=%0.3fs maxrss=%ikB\n", ti / 1000000.0, maxrss);
4263
    }
4264

    
4265
    return ffmpeg_exit(0);
4266
}