Statistics
| Branch: | Revision:

ffmpeg / ffmpeg.c @ 8af3167b

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

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

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

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

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

    
82
#include "cmdutils.h"
83

    
84
#include "libavutil/avassert.h"
85

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

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

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

    
106
typedef struct AVChapterMap {
107
    int in_file;
108
    int out_file;
109
} AVChapterMap;
110

    
111
static const OptionDef options[];
112

    
113
#define MAX_FILES 100
114
#if !FF_API_MAX_STREAMS
115
#define MAX_STREAMS 1024    /* arbitrary sanity check value */
116
#endif
117

    
118
static const char *last_asked_format = NULL;
119
static AVFormatContext *input_files[MAX_FILES];
120
static int64_t input_files_ts_offset[MAX_FILES];
121
static double *input_files_ts_scale[MAX_FILES] = {NULL};
122
static AVCodec **input_codecs = NULL;
123
static int nb_input_files = 0;
124
static int nb_input_codecs = 0;
125
static int nb_input_files_ts_scale[MAX_FILES] = {0};
126

    
127
static AVFormatContext *output_files[MAX_FILES];
128
static AVCodec **output_codecs = NULL;
129
static int nb_output_files = 0;
130
static int nb_output_codecs = 0;
131

    
132
static AVStreamMap *stream_maps = NULL;
133
static int nb_stream_maps;
134

    
135
/* first item specifies output metadata, second is input */
136
static AVMetaDataMap (*meta_data_maps)[2] = NULL;
137
static int nb_meta_data_maps;
138
static int metadata_global_autocopy   = 1;
139
static int metadata_streams_autocopy  = 1;
140
static int metadata_chapters_autocopy = 1;
141

    
142
static AVChapterMap *chapter_maps = NULL;
143
static int nb_chapter_maps;
144

    
145
/* indexed by output file stream index */
146
static int *streamid_map = NULL;
147
static int nb_streamid_map = 0;
148

    
149
static int frame_width  = 0;
150
static int frame_height = 0;
151
static float frame_aspect_ratio = 0;
152
static int frame_aspect_ratio_override = 0;
153
static enum PixelFormat frame_pix_fmt = PIX_FMT_NONE;
154
static int frame_bits_per_raw_sample = 0;
155
static enum AVSampleFormat audio_sample_fmt = AV_SAMPLE_FMT_NONE;
156
static int max_frames[4] = {INT_MAX, INT_MAX, INT_MAX, INT_MAX};
157
static AVRational frame_rate;
158
static float video_qscale = 0;
159
static uint16_t *intra_matrix = NULL;
160
static uint16_t *inter_matrix = NULL;
161
static const char *video_rc_override_string=NULL;
162
static int video_disable = 0;
163
static int video_discard = 0;
164
static char *video_codec_name = NULL;
165
static unsigned int video_codec_tag = 0;
166
static char *video_language = NULL;
167
static int same_quality = 0;
168
static int do_deinterlace = 0;
169
static int top_field_first = -1;
170
static int me_threshold = 0;
171
static int intra_dc_precision = 8;
172
static int loop_input = 0;
173
static int loop_output = AVFMT_NOOUTPUTLOOP;
174
static int qp_hist = 0;
175
#if CONFIG_AVFILTER
176
static char *vfilters = NULL;
177
#else
178
static unsigned int sws_flags = SWS_BICUBIC;
179
#endif
180

    
181
static int intra_only = 0;
182
static int audio_sample_rate = 44100;
183
static int64_t channel_layout = 0;
184
#define QSCALE_NONE -99999
185
static float audio_qscale = QSCALE_NONE;
186
static int audio_disable = 0;
187
static int audio_channels = 1;
188
static char  *audio_codec_name = NULL;
189
static unsigned int audio_codec_tag = 0;
190
static char *audio_language = NULL;
191

    
192
static int subtitle_disable = 0;
193
static char *subtitle_codec_name = NULL;
194
static char *subtitle_language = NULL;
195
static unsigned int subtitle_codec_tag = 0;
196

    
197
static float mux_preload= 0.5;
198
static float mux_max_delay= 0.7;
199

    
200
static int64_t recording_time = INT64_MAX;
201
static int64_t start_time = 0;
202
static int64_t recording_timestamp = 0;
203
static int64_t input_ts_offset = 0;
204
static int file_overwrite = 0;
205
static AVMetadata *metadata;
206
static int do_benchmark = 0;
207
static int do_hex_dump = 0;
208
static int do_pkt_dump = 0;
209
static int do_psnr = 0;
210
static int do_pass = 0;
211
static char *pass_logfilename_prefix = NULL;
212
static int audio_stream_copy = 0;
213
static int video_stream_copy = 0;
214
static int subtitle_stream_copy = 0;
215
static int video_sync_method= -1;
216
static int audio_sync_method= 0;
217
static float audio_drift_threshold= 0.1;
218
static int copy_ts= 0;
219
static int copy_tb;
220
static int opt_shortest = 0;
221
static int video_global_header = 0;
222
static char *vstats_filename;
223
static FILE *vstats_file;
224
static int opt_programid = 0;
225
static int copy_initial_nonkeyframes = 0;
226

    
227
static int rate_emu = 0;
228

    
229
static int  video_channel = 0;
230
static char *video_standard;
231

    
232
static int audio_volume = 256;
233

    
234
static int exit_on_error = 0;
235
static int using_stdin = 0;
236
static int verbose = 1;
237
static int thread_count= 1;
238
static int q_pressed = 0;
239
static int64_t video_size = 0;
240
static int64_t audio_size = 0;
241
static int64_t extra_size = 0;
242
static int nb_frames_dup = 0;
243
static int nb_frames_drop = 0;
244
static int input_sync;
245
static uint64_t limit_filesize = 0;
246
static int force_fps = 0;
247
static char *forced_key_frames = NULL;
248

    
249
static float dts_delta_threshold = 10;
250

    
251
static int64_t timer_start;
252

    
253
static uint8_t *audio_buf;
254
static uint8_t *audio_out;
255
static unsigned int allocated_audio_out_size, allocated_audio_buf_size;
256

    
257
static short *samples;
258

    
259
static AVBitStreamFilterContext *video_bitstream_filters=NULL;
260
static AVBitStreamFilterContext *audio_bitstream_filters=NULL;
261
static AVBitStreamFilterContext *subtitle_bitstream_filters=NULL;
262

    
263
#define DEFAULT_PASS_LOGFILENAME_PREFIX "ffmpeg2pass"
264

    
265
struct AVInputStream;
266

    
267
typedef struct AVOutputStream {
268
    int file_index;          /* file index */
269
    int index;               /* stream index in the output file */
270
    int source_index;        /* AVInputStream index */
271
    AVStream *st;            /* stream in the output file */
272
    int encoding_needed;     /* true if encoding needed for this stream */
273
    int frame_number;
274
    /* input pts and corresponding output pts
275
       for A/V sync */
276
    //double sync_ipts;        /* dts from the AVPacket of the demuxer in second units */
277
    struct AVInputStream *sync_ist; /* input stream to sync against */
278
    int64_t sync_opts;       /* output frame counter, could be changed to some true timestamp */ //FIXME look at frame_number
279
    AVBitStreamFilterContext *bitstream_filters;
280
    /* video only */
281
    int video_resample;
282
    AVFrame pict_tmp;      /* temporary image for resampling */
283
    struct SwsContext *img_resample_ctx; /* for image resampling */
284
    int resample_height;
285
    int resample_width;
286
    int resample_pix_fmt;
287

    
288
    /* full frame size of first frame */
289
    int original_height;
290
    int original_width;
291

    
292
    /* forced key frames */
293
    int64_t *forced_kf_pts;
294
    int forced_kf_count;
295
    int forced_kf_index;
296

    
297
    /* audio only */
298
    int audio_resample;
299
    ReSampleContext *resample; /* for audio resampling */
300
    int resample_sample_fmt;
301
    int resample_channels;
302
    int resample_sample_rate;
303
    int reformat_pair;
304
    AVAudioConvert *reformat_ctx;
305
    AVFifoBuffer *fifo;     /* for compression: one audio fifo per codec */
306
    FILE *logfile;
307

    
308
#if CONFIG_AVFILTER
309
    AVFilterContext *output_video_filter;
310
    AVFilterContext *input_video_filter;
311
    AVFilterBufferRef *picref;
312
    char *avfilter;
313
    AVFilterGraph *graph;
314
#endif
315
} AVOutputStream;
316

    
317
static AVOutputStream **output_streams_for_file[MAX_FILES] = { NULL };
318
static int nb_output_streams_for_file[MAX_FILES] = { 0 };
319

    
320
typedef struct AVInputStream {
321
    int file_index;
322
    int index;
323
    AVStream *st;
324
    int discard;             /* true if stream data should be discarded */
325
    int decoding_needed;     /* true if the packets must be decoded in 'raw_fifo' */
326
    int64_t sample_index;      /* current sample */
327

    
328
    int64_t       start;     /* time when read started */
329
    int64_t       next_pts;  /* synthetic pts for cases where pkt.pts
330
                                is not defined */
331
    int64_t       pts;       /* current pts */
332
    int is_start;            /* is 1 at the start and after a discontinuity */
333
    int showed_multi_packet_warning;
334
    int is_past_recording_time;
335
#if CONFIG_AVFILTER
336
    AVFrame *filter_frame;
337
    int has_filter_frame;
338
#endif
339
} AVInputStream;
340

    
341
typedef struct AVInputFile {
342
    int eof_reached;      /* true if eof reached */
343
    int ist_index;        /* index of first stream in ist_table */
344
    int buffer_size;      /* current total buffer size */
345
    int nb_streams;       /* nb streams we are aware of */
346
} AVInputFile;
347

    
348
#if HAVE_TERMIOS_H
349

    
350
/* init terminal so that we can grab keys */
351
static struct termios oldtty;
352
#endif
353

    
354
#if CONFIG_AVFILTER
355

    
356
static int configure_filters(AVInputStream *ist, AVOutputStream *ost)
357
{
358
    AVFilterContext *last_filter, *filter;
359
    /** filter graph containing all filters including input & output */
360
    AVCodecContext *codec = ost->st->codec;
361
    AVCodecContext *icodec = ist->st->codec;
362
    FFSinkContext ffsink_ctx = { .pix_fmt = codec->pix_fmt };
363
    AVRational sample_aspect_ratio;
364
    char args[255];
365
    int ret;
366

    
367
    ost->graph = avfilter_graph_alloc();
368

    
369
    if (ist->st->sample_aspect_ratio.num){
370
        sample_aspect_ratio = ist->st->sample_aspect_ratio;
371
    }else
372
        sample_aspect_ratio = ist->st->codec->sample_aspect_ratio;
373

    
374
    snprintf(args, 255, "%d:%d:%d:%d:%d:%d:%d", ist->st->codec->width,
375
             ist->st->codec->height, ist->st->codec->pix_fmt, 1, AV_TIME_BASE,
376
             sample_aspect_ratio.num, sample_aspect_ratio.den);
377

    
378
    ret = avfilter_graph_create_filter(&ost->input_video_filter, avfilter_get_by_name("buffer"),
379
                                       "src", args, NULL, ost->graph);
380
    if (ret < 0)
381
        return ret;
382
    ret = avfilter_graph_create_filter(&ost->output_video_filter, &ffsink,
383
                                       "out", NULL, &ffsink_ctx, ost->graph);
384
    if (ret < 0)
385
        return ret;
386
    last_filter = ost->input_video_filter;
387

    
388
    if (codec->width  != icodec->width || codec->height != icodec->height) {
389
        snprintf(args, 255, "%d:%d:flags=0x%X",
390
                 codec->width,
391
                 codec->height,
392
                 (int)av_get_int(sws_opts, "sws_flags", NULL));
393
        if ((ret = avfilter_graph_create_filter(&filter, avfilter_get_by_name("scale"),
394
                                                NULL, args, NULL, ost->graph)) < 0)
395
            return ret;
396
        if ((ret = avfilter_link(last_filter, 0, filter, 0)) < 0)
397
            return ret;
398
        last_filter = filter;
399
    }
400

    
401
    snprintf(args, sizeof(args), "flags=0x%X", (int)av_get_int(sws_opts, "sws_flags", NULL));
402
    ost->graph->scale_sws_opts = av_strdup(args);
403

    
404
    if (ost->avfilter) {
405
        AVFilterInOut *outputs = av_malloc(sizeof(AVFilterInOut));
406
        AVFilterInOut *inputs  = av_malloc(sizeof(AVFilterInOut));
407

    
408
        outputs->name    = av_strdup("in");
409
        outputs->filter_ctx = last_filter;
410
        outputs->pad_idx = 0;
411
        outputs->next    = NULL;
412

    
413
        inputs->name    = av_strdup("out");
414
        inputs->filter_ctx = ost->output_video_filter;
415
        inputs->pad_idx = 0;
416
        inputs->next    = NULL;
417

    
418
        if ((ret = avfilter_graph_parse(ost->graph, ost->avfilter, inputs, outputs, NULL)) < 0)
419
            return ret;
420
        av_freep(&ost->avfilter);
421
    } else {
422
        if ((ret = avfilter_link(last_filter, 0, ost->output_video_filter, 0)) < 0)
423
            return ret;
424
    }
425

    
426
    if ((ret = avfilter_graph_config(ost->graph, NULL)) < 0)
427
        return ret;
428

    
429
    codec->width  = ost->output_video_filter->inputs[0]->w;
430
    codec->height = ost->output_video_filter->inputs[0]->h;
431
    codec->sample_aspect_ratio = ost->st->sample_aspect_ratio =
432
        ost->output_video_filter->inputs[0]->sample_aspect_ratio;
433

    
434
    return 0;
435
}
436
#endif /* CONFIG_AVFILTER */
437

    
438
static void term_exit(void)
439
{
440
    av_log(NULL, AV_LOG_QUIET, "");
441
#if HAVE_TERMIOS_H
442
    tcsetattr (0, TCSANOW, &oldtty);
443
#endif
444
}
445

    
446
static volatile int received_sigterm = 0;
447

    
448
static void
449
sigterm_handler(int sig)
450
{
451
    received_sigterm = sig;
452
    q_pressed++;
453
    term_exit();
454
}
455

    
456
static void term_init(void)
457
{
458
#if HAVE_TERMIOS_H
459
    struct termios tty;
460

    
461
    tcgetattr (0, &tty);
462
    oldtty = tty;
463
    atexit(term_exit);
464

    
465
    tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
466
                          |INLCR|IGNCR|ICRNL|IXON);
467
    tty.c_oflag |= OPOST;
468
    tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
469
    tty.c_cflag &= ~(CSIZE|PARENB);
470
    tty.c_cflag |= CS8;
471
    tty.c_cc[VMIN] = 1;
472
    tty.c_cc[VTIME] = 0;
473

    
474
    tcsetattr (0, TCSANOW, &tty);
475
    signal(SIGQUIT, sigterm_handler); /* Quit (POSIX).  */
476
#endif
477

    
478
    signal(SIGINT , sigterm_handler); /* Interrupt (ANSI).  */
479
    signal(SIGTERM, sigterm_handler); /* Termination (ANSI).  */
480
#ifdef SIGXCPU
481
    signal(SIGXCPU, sigterm_handler);
482
#endif
483
}
484

    
485
/* read a key without blocking */
486
static int read_key(void)
487
{
488
#if HAVE_TERMIOS_H
489
    int n = 1;
490
    unsigned char ch;
491
    struct timeval tv;
492
    fd_set rfds;
493

    
494
    FD_ZERO(&rfds);
495
    FD_SET(0, &rfds);
496
    tv.tv_sec = 0;
497
    tv.tv_usec = 0;
498
    n = select(1, &rfds, NULL, NULL, &tv);
499
    if (n > 0) {
500
        n = read(0, &ch, 1);
501
        if (n == 1)
502
            return ch;
503

    
504
        return n;
505
    }
506
#elif HAVE_KBHIT
507
    if(kbhit())
508
        return(getch());
509
#endif
510
    return -1;
511
}
512

    
513
static int decode_interrupt_cb(void)
514
{
515
    q_pressed += read_key() == 'q';
516
    return q_pressed > 1;
517
}
518

    
519
static int ffmpeg_exit(int ret)
520
{
521
    int i;
522

    
523
    /* close files */
524
    for(i=0;i<nb_output_files;i++) {
525
        AVFormatContext *s = output_files[i];
526
        if (!(s->oformat->flags & AVFMT_NOFILE) && s->pb)
527
            avio_close(s->pb);
528
        avformat_free_context(s);
529
        av_free(output_streams_for_file[i]);
530
    }
531
    for(i=0;i<nb_input_files;i++) {
532
        av_close_input_file(input_files[i]);
533
        av_free(input_files_ts_scale[i]);
534
    }
535

    
536
    av_free(intra_matrix);
537
    av_free(inter_matrix);
538

    
539
    if (vstats_file)
540
        fclose(vstats_file);
541
    av_free(vstats_filename);
542

    
543
    av_free(streamid_map);
544
    av_free(input_codecs);
545
    av_free(output_codecs);
546
    av_free(stream_maps);
547
    av_free(meta_data_maps);
548

    
549
    av_free(video_codec_name);
550
    av_free(audio_codec_name);
551
    av_free(subtitle_codec_name);
552

    
553
    av_free(video_standard);
554

    
555
    uninit_opts();
556
    av_free(audio_buf);
557
    av_free(audio_out);
558
    allocated_audio_buf_size= allocated_audio_out_size= 0;
559
    av_free(samples);
560

    
561
#if CONFIG_AVFILTER
562
    avfilter_uninit();
563
#endif
564

    
565
    if (received_sigterm) {
566
        fprintf(stderr,
567
            "Received signal %d: terminating.\n",
568
            (int) received_sigterm);
569
        exit (255);
570
    }
571

    
572
    exit(ret); /* not all OS-es handle main() return value */
573
    return ret;
574
}
575

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

    
596
static void choose_sample_fmt(AVStream *st, AVCodec *codec)
597
{
598
    if(codec && codec->sample_fmts){
599
        const enum AVSampleFormat *p= codec->sample_fmts;
600
        for(; *p!=-1; p++){
601
            if(*p == st->codec->sample_fmt)
602
                break;
603
        }
604
        if (*p == -1) {
605
            av_log(NULL, AV_LOG_WARNING,
606
                   "Incompatible sample format '%s' for codec '%s', auto-selecting format '%s'\n",
607
                   av_get_sample_fmt_name(st->codec->sample_fmt),
608
                   codec->name,
609
                   av_get_sample_fmt_name(codec->sample_fmts[0]));
610
            st->codec->sample_fmt = codec->sample_fmts[0];
611
        }
612
    }
613
}
614

    
615
static void choose_sample_rate(AVStream *st, AVCodec *codec)
616
{
617
    if(codec && codec->supported_samplerates){
618
        const int *p= codec->supported_samplerates;
619
        int best=0;
620
        int best_dist=INT_MAX;
621
        for(; *p; p++){
622
            int dist= abs(st->codec->sample_rate - *p);
623
            if(dist < best_dist){
624
                best_dist= dist;
625
                best= *p;
626
            }
627
        }
628
        if(best_dist){
629
            av_log(st->codec, AV_LOG_WARNING, "Requested sampling rate unsupported using closest supported (%d)\n", best);
630
        }
631
        st->codec->sample_rate= best;
632
    }
633
}
634

    
635
static void choose_pixel_fmt(AVStream *st, AVCodec *codec)
636
{
637
    if(codec && codec->pix_fmts){
638
        const enum PixelFormat *p= codec->pix_fmts;
639
        if(st->codec->strict_std_compliance <= FF_COMPLIANCE_UNOFFICIAL){
640
            if(st->codec->codec_id==CODEC_ID_MJPEG){
641
                p= (const enum PixelFormat[]){PIX_FMT_YUVJ420P, PIX_FMT_YUVJ422P, PIX_FMT_YUV420P, PIX_FMT_YUV422P, PIX_FMT_NONE};
642
            }else if(st->codec->codec_id==CODEC_ID_LJPEG){
643
                p= (const enum PixelFormat[]){PIX_FMT_YUVJ420P, PIX_FMT_YUVJ422P, PIX_FMT_YUVJ444P, PIX_FMT_YUV420P, PIX_FMT_YUV422P, PIX_FMT_YUV444P, PIX_FMT_BGRA, PIX_FMT_NONE};
644
            }
645
        }
646
        for(; *p!=-1; p++){
647
            if(*p == st->codec->pix_fmt)
648
                break;
649
        }
650
        if (*p == -1) {
651
            av_log(NULL, AV_LOG_WARNING,
652
                   "Incompatible pixel format '%s' for codec '%s', auto-selecting format '%s'\n",
653
                   av_pix_fmt_descriptors[st->codec->pix_fmt].name,
654
                   codec->name,
655
                   av_pix_fmt_descriptors[codec->pix_fmts[0]].name);
656
            st->codec->pix_fmt = codec->pix_fmts[0];
657
        }
658
    }
659
}
660

    
661
static AVOutputStream *new_output_stream(AVFormatContext *oc, int file_idx)
662
{
663
    int idx = oc->nb_streams - 1;
664
    AVOutputStream *ost;
665

    
666
    output_streams_for_file[file_idx] =
667
        grow_array(output_streams_for_file[file_idx],
668
                   sizeof(*output_streams_for_file[file_idx]),
669
                   &nb_output_streams_for_file[file_idx],
670
                   oc->nb_streams);
671
    ost = output_streams_for_file[file_idx][idx] =
672
        av_mallocz(sizeof(AVOutputStream));
673
    if (!ost) {
674
        fprintf(stderr, "Could not alloc output stream\n");
675
        ffmpeg_exit(1);
676
    }
677
    ost->file_index = file_idx;
678
    ost->index = idx;
679
    return ost;
680
}
681

    
682
static int read_ffserver_streams(AVFormatContext *s, const char *filename)
683
{
684
    int i, err;
685
    AVFormatContext *ic;
686
    int nopts = 0;
687

    
688
    err = av_open_input_file(&ic, filename, NULL, FFM_PACKET_SIZE, NULL);
689
    if (err < 0)
690
        return err;
691
    /* copy stream format */
692
    s->nb_streams = 0;
693
    for(i=0;i<ic->nb_streams;i++) {
694
        AVStream *st;
695
        AVCodec *codec;
696

    
697
        s->nb_streams++;
698

    
699
        // FIXME: a more elegant solution is needed
700
        st = av_mallocz(sizeof(AVStream));
701
        memcpy(st, ic->streams[i], sizeof(AVStream));
702
        st->codec = avcodec_alloc_context();
703
        if (!st->codec) {
704
            print_error(filename, AVERROR(ENOMEM));
705
            ffmpeg_exit(1);
706
        }
707
        avcodec_copy_context(st->codec, ic->streams[i]->codec);
708
        s->streams[i] = st;
709

    
710
        codec = avcodec_find_encoder(st->codec->codec_id);
711
        if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO) {
712
            if (audio_stream_copy) {
713
                st->stream_copy = 1;
714
            } else
715
                choose_sample_fmt(st, codec);
716
        } else if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
717
            if (video_stream_copy) {
718
                st->stream_copy = 1;
719
            } else
720
                choose_pixel_fmt(st, codec);
721
        }
722

    
723
        if(st->codec->flags & CODEC_FLAG_BITEXACT)
724
            nopts = 1;
725

    
726
        new_output_stream(s, nb_output_files);
727
    }
728

    
729
    if (!nopts)
730
        s->timestamp = av_gettime();
731

    
732
    av_close_input_file(ic);
733
    return 0;
734
}
735

    
736
static double
737
get_sync_ipts(const AVOutputStream *ost)
738
{
739
    const AVInputStream *ist = ost->sync_ist;
740
    return (double)(ist->pts - start_time)/AV_TIME_BASE;
741
}
742

    
743
static void write_frame(AVFormatContext *s, AVPacket *pkt, AVCodecContext *avctx, AVBitStreamFilterContext *bsfc){
744
    int ret;
745

    
746
    while(bsfc){
747
        AVPacket new_pkt= *pkt;
748
        int a= av_bitstream_filter_filter(bsfc, avctx, NULL,
749
                                          &new_pkt.data, &new_pkt.size,
750
                                          pkt->data, pkt->size,
751
                                          pkt->flags & AV_PKT_FLAG_KEY);
752
        if(a>0){
753
            av_free_packet(pkt);
754
            new_pkt.destruct= av_destruct_packet;
755
        } else if(a<0){
756
            fprintf(stderr, "%s failed for stream %d, codec %s",
757
                    bsfc->filter->name, pkt->stream_index,
758
                    avctx->codec ? avctx->codec->name : "copy");
759
            print_error("", a);
760
            if (exit_on_error)
761
                ffmpeg_exit(1);
762
        }
763
        *pkt= new_pkt;
764

    
765
        bsfc= bsfc->next;
766
    }
767

    
768
    ret= av_interleaved_write_frame(s, pkt);
769
    if(ret < 0){
770
        print_error("av_interleaved_write_frame()", ret);
771
        ffmpeg_exit(1);
772
    }
773
}
774

    
775
#define MAX_AUDIO_PACKET_SIZE (128 * 1024)
776

    
777
static void do_audio_out(AVFormatContext *s,
778
                         AVOutputStream *ost,
779
                         AVInputStream *ist,
780
                         unsigned char *buf, int size)
781
{
782
    uint8_t *buftmp;
783
    int64_t audio_out_size, audio_buf_size;
784
    int64_t allocated_for_size= size;
785

    
786
    int size_out, frame_bytes, ret, resample_changed;
787
    AVCodecContext *enc= ost->st->codec;
788
    AVCodecContext *dec= ist->st->codec;
789
    int osize= av_get_bits_per_sample_fmt(enc->sample_fmt)/8;
790
    int isize= av_get_bits_per_sample_fmt(dec->sample_fmt)/8;
791
    const int coded_bps = av_get_bits_per_sample(enc->codec->id);
792

    
793
need_realloc:
794
    audio_buf_size= (allocated_for_size + isize*dec->channels - 1) / (isize*dec->channels);
795
    audio_buf_size= (audio_buf_size*enc->sample_rate + dec->sample_rate) / dec->sample_rate;
796
    audio_buf_size= audio_buf_size*2 + 10000; //safety factors for the deprecated resampling API
797
    audio_buf_size= FFMAX(audio_buf_size, enc->frame_size);
798
    audio_buf_size*= osize*enc->channels;
799

    
800
    audio_out_size= FFMAX(audio_buf_size, enc->frame_size * osize * enc->channels);
801
    if(coded_bps > 8*osize)
802
        audio_out_size= audio_out_size * coded_bps / (8*osize);
803
    audio_out_size += FF_MIN_BUFFER_SIZE;
804

    
805
    if(audio_out_size > INT_MAX || audio_buf_size > INT_MAX){
806
        fprintf(stderr, "Buffer sizes too large\n");
807
        ffmpeg_exit(1);
808
    }
809

    
810
    av_fast_malloc(&audio_buf, &allocated_audio_buf_size, audio_buf_size);
811
    av_fast_malloc(&audio_out, &allocated_audio_out_size, audio_out_size);
812
    if (!audio_buf || !audio_out){
813
        fprintf(stderr, "Out of memory in do_audio_out\n");
814
        ffmpeg_exit(1);
815
    }
816

    
817
    if (enc->channels != dec->channels)
818
        ost->audio_resample = 1;
819

    
820
    resample_changed = ost->resample_sample_fmt  != dec->sample_fmt ||
821
                       ost->resample_channels    != dec->channels   ||
822
                       ost->resample_sample_rate != dec->sample_rate;
823

    
824
    if ((ost->audio_resample && !ost->resample) || resample_changed) {
825
        if (resample_changed) {
826
            av_log(NULL, AV_LOG_INFO, "Input stream #%d.%d frame changed from rate:%d fmt:%s ch:%d to rate:%d fmt:%s ch:%d\n",
827
                   ist->file_index, ist->index,
828
                   ost->resample_sample_rate, av_get_sample_fmt_name(ost->resample_sample_fmt), ost->resample_channels,
829
                   dec->sample_rate, av_get_sample_fmt_name(dec->sample_fmt), dec->channels);
830
            ost->resample_sample_fmt  = dec->sample_fmt;
831
            ost->resample_channels    = dec->channels;
832
            ost->resample_sample_rate = dec->sample_rate;
833
            if (ost->resample)
834
                audio_resample_close(ost->resample);
835
        }
836
        /* if audio_sync_method is >1 the resampler is needed for audio drift compensation */
837
        if (audio_sync_method <= 1 &&
838
            ost->resample_sample_fmt  == enc->sample_fmt &&
839
            ost->resample_channels    == enc->channels   &&
840
            ost->resample_sample_rate == enc->sample_rate) {
841
            ost->resample = NULL;
842
            ost->audio_resample = 0;
843
        } else {
844
            if (dec->sample_fmt != AV_SAMPLE_FMT_S16)
845
                fprintf(stderr, "Warning, using s16 intermediate sample format for resampling\n");
846
            ost->resample = av_audio_resample_init(enc->channels,    dec->channels,
847
                                                   enc->sample_rate, dec->sample_rate,
848
                                                   enc->sample_fmt,  dec->sample_fmt,
849
                                                   16, 10, 0, 0.8);
850
            if (!ost->resample) {
851
                fprintf(stderr, "Can not resample %d channels @ %d Hz to %d channels @ %d Hz\n",
852
                        dec->channels, dec->sample_rate,
853
                        enc->channels, enc->sample_rate);
854
                ffmpeg_exit(1);
855
            }
856
        }
857
    }
858

    
859
#define MAKE_SFMT_PAIR(a,b) ((a)+AV_SAMPLE_FMT_NB*(b))
860
    if (!ost->audio_resample && dec->sample_fmt!=enc->sample_fmt &&
861
        MAKE_SFMT_PAIR(enc->sample_fmt,dec->sample_fmt)!=ost->reformat_pair) {
862
        if (ost->reformat_ctx)
863
            av_audio_convert_free(ost->reformat_ctx);
864
        ost->reformat_ctx = av_audio_convert_alloc(enc->sample_fmt, 1,
865
                                                   dec->sample_fmt, 1, NULL, 0);
866
        if (!ost->reformat_ctx) {
867
            fprintf(stderr, "Cannot convert %s sample format to %s sample format\n",
868
                av_get_sample_fmt_name(dec->sample_fmt),
869
                av_get_sample_fmt_name(enc->sample_fmt));
870
            ffmpeg_exit(1);
871
        }
872
        ost->reformat_pair=MAKE_SFMT_PAIR(enc->sample_fmt,dec->sample_fmt);
873
    }
874

    
875
    if(audio_sync_method){
876
        double delta = get_sync_ipts(ost) * enc->sample_rate - ost->sync_opts
877
                - av_fifo_size(ost->fifo)/(enc->channels * 2);
878
        double idelta= delta*dec->sample_rate / enc->sample_rate;
879
        int byte_delta= ((int)idelta)*2*dec->channels;
880

    
881
        //FIXME resample delay
882
        if(fabs(delta) > 50){
883
            if(ist->is_start || fabs(delta) > audio_drift_threshold*enc->sample_rate){
884
                if(byte_delta < 0){
885
                    byte_delta= FFMAX(byte_delta, -size);
886
                    size += byte_delta;
887
                    buf  -= byte_delta;
888
                    if(verbose > 2)
889
                        fprintf(stderr, "discarding %d audio samples\n", (int)-delta);
890
                    if(!size)
891
                        return;
892
                    ist->is_start=0;
893
                }else{
894
                    static uint8_t *input_tmp= NULL;
895
                    input_tmp= av_realloc(input_tmp, byte_delta + size);
896

    
897
                    if(byte_delta > allocated_for_size - size){
898
                        allocated_for_size= byte_delta + (int64_t)size;
899
                        goto need_realloc;
900
                    }
901
                    ist->is_start=0;
902

    
903
                    memset(input_tmp, 0, byte_delta);
904
                    memcpy(input_tmp + byte_delta, buf, size);
905
                    buf= input_tmp;
906
                    size += byte_delta;
907
                    if(verbose > 2)
908
                        fprintf(stderr, "adding %d audio samples of silence\n", (int)delta);
909
                }
910
            }else if(audio_sync_method>1){
911
                int comp= av_clip(delta, -audio_sync_method, audio_sync_method);
912
                av_assert0(ost->audio_resample);
913
                if(verbose > 2)
914
                    fprintf(stderr, "compensating audio timestamp drift:%f compensation:%d in:%d\n", delta, comp, enc->sample_rate);
915
//                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));
916
                av_resample_compensate(*(struct AVResampleContext**)ost->resample, comp, enc->sample_rate);
917
            }
918
        }
919
    }else
920
        ost->sync_opts= lrintf(get_sync_ipts(ost) * enc->sample_rate)
921
                        - av_fifo_size(ost->fifo)/(enc->channels * 2); //FIXME wrong
922

    
923
    if (ost->audio_resample) {
924
        buftmp = audio_buf;
925
        size_out = audio_resample(ost->resample,
926
                                  (short *)buftmp, (short *)buf,
927
                                  size / (dec->channels * isize));
928
        size_out = size_out * enc->channels * osize;
929
    } else {
930
        buftmp = buf;
931
        size_out = size;
932
    }
933

    
934
    if (!ost->audio_resample && dec->sample_fmt!=enc->sample_fmt) {
935
        const void *ibuf[6]= {buftmp};
936
        void *obuf[6]= {audio_buf};
937
        int istride[6]= {isize};
938
        int ostride[6]= {osize};
939
        int len= size_out/istride[0];
940
        if (av_audio_convert(ost->reformat_ctx, obuf, ostride, ibuf, istride, len)<0) {
941
            printf("av_audio_convert() failed\n");
942
            if (exit_on_error)
943
                ffmpeg_exit(1);
944
            return;
945
        }
946
        buftmp = audio_buf;
947
        size_out = len*osize;
948
    }
949

    
950
    /* now encode as many frames as possible */
951
    if (enc->frame_size > 1) {
952
        /* output resampled raw samples */
953
        if (av_fifo_realloc2(ost->fifo, av_fifo_size(ost->fifo) + size_out) < 0) {
954
            fprintf(stderr, "av_fifo_realloc2() failed\n");
955
            ffmpeg_exit(1);
956
        }
957
        av_fifo_generic_write(ost->fifo, buftmp, size_out, NULL);
958

    
959
        frame_bytes = enc->frame_size * osize * enc->channels;
960

    
961
        while (av_fifo_size(ost->fifo) >= frame_bytes) {
962
            AVPacket pkt;
963
            av_init_packet(&pkt);
964

    
965
            av_fifo_generic_read(ost->fifo, audio_buf, frame_bytes, NULL);
966

    
967
            //FIXME pass ost->sync_opts as AVFrame.pts in avcodec_encode_audio()
968

    
969
            ret = avcodec_encode_audio(enc, audio_out, audio_out_size,
970
                                       (short *)audio_buf);
971
            if (ret < 0) {
972
                fprintf(stderr, "Audio encoding failed\n");
973
                ffmpeg_exit(1);
974
            }
975
            audio_size += ret;
976
            pkt.stream_index= ost->index;
977
            pkt.data= audio_out;
978
            pkt.size= ret;
979
            if(enc->coded_frame && enc->coded_frame->pts != AV_NOPTS_VALUE)
980
                pkt.pts= av_rescale_q(enc->coded_frame->pts, enc->time_base, ost->st->time_base);
981
            pkt.flags |= AV_PKT_FLAG_KEY;
982
            write_frame(s, &pkt, enc, ost->bitstream_filters);
983

    
984
            ost->sync_opts += enc->frame_size;
985
        }
986
    } else {
987
        AVPacket pkt;
988
        av_init_packet(&pkt);
989

    
990
        ost->sync_opts += size_out / (osize * enc->channels);
991

    
992
        /* output a pcm frame */
993
        /* determine the size of the coded buffer */
994
        size_out /= osize;
995
        if (coded_bps)
996
            size_out = size_out*coded_bps/8;
997

    
998
        if(size_out > audio_out_size){
999
            fprintf(stderr, "Internal error, buffer size too small\n");
1000
            ffmpeg_exit(1);
1001
        }
1002

    
1003
        //FIXME pass ost->sync_opts as AVFrame.pts in avcodec_encode_audio()
1004
        ret = avcodec_encode_audio(enc, audio_out, size_out,
1005
                                   (short *)buftmp);
1006
        if (ret < 0) {
1007
            fprintf(stderr, "Audio encoding failed\n");
1008
            ffmpeg_exit(1);
1009
        }
1010
        audio_size += ret;
1011
        pkt.stream_index= ost->index;
1012
        pkt.data= audio_out;
1013
        pkt.size= ret;
1014
        if(enc->coded_frame && enc->coded_frame->pts != AV_NOPTS_VALUE)
1015
            pkt.pts= av_rescale_q(enc->coded_frame->pts, enc->time_base, ost->st->time_base);
1016
        pkt.flags |= AV_PKT_FLAG_KEY;
1017
        write_frame(s, &pkt, enc, ost->bitstream_filters);
1018
    }
1019
}
1020

    
1021
static void pre_process_video_frame(AVInputStream *ist, AVPicture *picture, void **bufp)
1022
{
1023
    AVCodecContext *dec;
1024
    AVPicture *picture2;
1025
    AVPicture picture_tmp;
1026
    uint8_t *buf = 0;
1027

    
1028
    dec = ist->st->codec;
1029

    
1030
    /* deinterlace : must be done before any resize */
1031
    if (do_deinterlace) {
1032
        int size;
1033

    
1034
        /* create temporary picture */
1035
        size = avpicture_get_size(dec->pix_fmt, dec->width, dec->height);
1036
        buf = av_malloc(size);
1037
        if (!buf)
1038
            return;
1039

    
1040
        picture2 = &picture_tmp;
1041
        avpicture_fill(picture2, buf, dec->pix_fmt, dec->width, dec->height);
1042

    
1043
        if(avpicture_deinterlace(picture2, picture,
1044
                                 dec->pix_fmt, dec->width, dec->height) < 0) {
1045
            /* if error, do not deinterlace */
1046
            fprintf(stderr, "Deinterlacing failed\n");
1047
            av_free(buf);
1048
            buf = NULL;
1049
            picture2 = picture;
1050
        }
1051
    } else {
1052
        picture2 = picture;
1053
    }
1054

    
1055
    if (picture != picture2)
1056
        *picture = *picture2;
1057
    *bufp = buf;
1058
}
1059

    
1060
/* we begin to correct av delay at this threshold */
1061
#define AV_DELAY_MAX 0.100
1062

    
1063
static void do_subtitle_out(AVFormatContext *s,
1064
                            AVOutputStream *ost,
1065
                            AVInputStream *ist,
1066
                            AVSubtitle *sub,
1067
                            int64_t pts)
1068
{
1069
    static uint8_t *subtitle_out = NULL;
1070
    int subtitle_out_max_size = 1024 * 1024;
1071
    int subtitle_out_size, nb, i;
1072
    AVCodecContext *enc;
1073
    AVPacket pkt;
1074

    
1075
    if (pts == AV_NOPTS_VALUE) {
1076
        fprintf(stderr, "Subtitle packets must have a pts\n");
1077
        if (exit_on_error)
1078
            ffmpeg_exit(1);
1079
        return;
1080
    }
1081

    
1082
    enc = ost->st->codec;
1083

    
1084
    if (!subtitle_out) {
1085
        subtitle_out = av_malloc(subtitle_out_max_size);
1086
    }
1087

    
1088
    /* Note: DVB subtitle need one packet to draw them and one other
1089
       packet to clear them */
1090
    /* XXX: signal it in the codec context ? */
1091
    if (enc->codec_id == CODEC_ID_DVB_SUBTITLE)
1092
        nb = 2;
1093
    else
1094
        nb = 1;
1095

    
1096
    for(i = 0; i < nb; i++) {
1097
        sub->pts = av_rescale_q(pts, ist->st->time_base, AV_TIME_BASE_Q);
1098
        // start_display_time is required to be 0
1099
        sub->pts              += av_rescale_q(sub->start_display_time, (AVRational){1, 1000}, AV_TIME_BASE_Q);
1100
        sub->end_display_time -= sub->start_display_time;
1101
        sub->start_display_time = 0;
1102
        subtitle_out_size = avcodec_encode_subtitle(enc, subtitle_out,
1103
                                                    subtitle_out_max_size, sub);
1104
        if (subtitle_out_size < 0) {
1105
            fprintf(stderr, "Subtitle encoding failed\n");
1106
            ffmpeg_exit(1);
1107
        }
1108

    
1109
        av_init_packet(&pkt);
1110
        pkt.stream_index = ost->index;
1111
        pkt.data = subtitle_out;
1112
        pkt.size = subtitle_out_size;
1113
        pkt.pts = av_rescale_q(sub->pts, AV_TIME_BASE_Q, ost->st->time_base);
1114
        if (enc->codec_id == CODEC_ID_DVB_SUBTITLE) {
1115
            /* XXX: the pts correction is handled here. Maybe handling
1116
               it in the codec would be better */
1117
            if (i == 0)
1118
                pkt.pts += 90 * sub->start_display_time;
1119
            else
1120
                pkt.pts += 90 * sub->end_display_time;
1121
        }
1122
        write_frame(s, &pkt, ost->st->codec, ost->bitstream_filters);
1123
    }
1124
}
1125

    
1126
static int bit_buffer_size= 1024*256;
1127
static uint8_t *bit_buffer= NULL;
1128

    
1129
static void do_video_out(AVFormatContext *s,
1130
                         AVOutputStream *ost,
1131
                         AVInputStream *ist,
1132
                         AVFrame *in_picture,
1133
                         int *frame_size)
1134
{
1135
    int nb_frames, i, ret;
1136
    AVFrame *final_picture, *formatted_picture, *resampling_dst, *padding_src;
1137
    AVCodecContext *enc, *dec;
1138
    double sync_ipts;
1139

    
1140
    enc = ost->st->codec;
1141
    dec = ist->st->codec;
1142

    
1143
    sync_ipts = get_sync_ipts(ost) / av_q2d(enc->time_base);
1144

    
1145
    /* by default, we output a single frame */
1146
    nb_frames = 1;
1147

    
1148
    *frame_size = 0;
1149

    
1150
    if(video_sync_method){
1151
        double vdelta = sync_ipts - ost->sync_opts;
1152
        //FIXME set to 0.5 after we fix some dts/pts bugs like in avidec.c
1153
        if (vdelta < -1.1)
1154
            nb_frames = 0;
1155
        else if (video_sync_method == 2 || (video_sync_method<0 && (s->oformat->flags & AVFMT_VARIABLE_FPS))){
1156
            if(vdelta<=-0.6){
1157
                nb_frames=0;
1158
            }else if(vdelta>0.6)
1159
                ost->sync_opts= lrintf(sync_ipts);
1160
        }else if (vdelta > 1.1)
1161
            nb_frames = lrintf(vdelta);
1162
//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);
1163
        if (nb_frames == 0){
1164
            ++nb_frames_drop;
1165
            if (verbose>2)
1166
                fprintf(stderr, "*** drop!\n");
1167
        }else if (nb_frames > 1) {
1168
            nb_frames_dup += nb_frames - 1;
1169
            if (verbose>2)
1170
                fprintf(stderr, "*** %d dup!\n", nb_frames-1);
1171
        }
1172
    }else
1173
        ost->sync_opts= lrintf(sync_ipts);
1174

    
1175
    nb_frames= FFMIN(nb_frames, max_frames[AVMEDIA_TYPE_VIDEO] - ost->frame_number);
1176
    if (nb_frames <= 0)
1177
        return;
1178

    
1179
    formatted_picture = in_picture;
1180
    final_picture = formatted_picture;
1181
    padding_src = formatted_picture;
1182
    resampling_dst = &ost->pict_tmp;
1183

    
1184
    if (   ost->resample_height != ist->st->codec->height
1185
        || ost->resample_width  != ist->st->codec->width
1186
        || (ost->resample_pix_fmt!= ist->st->codec->pix_fmt) ) {
1187

    
1188
        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));
1189
        if(!ost->video_resample)
1190
            ffmpeg_exit(1);
1191
    }
1192

    
1193
#if !CONFIG_AVFILTER
1194
    if (ost->video_resample) {
1195
        padding_src = NULL;
1196
        final_picture = &ost->pict_tmp;
1197
        if(  ost->resample_height != ist->st->codec->height
1198
          || ost->resample_width  != ist->st->codec->width
1199
          || (ost->resample_pix_fmt!= ist->st->codec->pix_fmt) ) {
1200

    
1201
            /* initialize a new scaler context */
1202
            sws_freeContext(ost->img_resample_ctx);
1203
            sws_flags = av_get_int(sws_opts, "sws_flags", NULL);
1204
            ost->img_resample_ctx = sws_getContext(
1205
                ist->st->codec->width,
1206
                ist->st->codec->height,
1207
                ist->st->codec->pix_fmt,
1208
                ost->st->codec->width,
1209
                ost->st->codec->height,
1210
                ost->st->codec->pix_fmt,
1211
                sws_flags, NULL, NULL, NULL);
1212
            if (ost->img_resample_ctx == NULL) {
1213
                fprintf(stderr, "Cannot get resampling context\n");
1214
                ffmpeg_exit(1);
1215
            }
1216
        }
1217
        sws_scale(ost->img_resample_ctx, formatted_picture->data, formatted_picture->linesize,
1218
              0, ost->resample_height, resampling_dst->data, resampling_dst->linesize);
1219
    }
1220
#endif
1221

    
1222
    /* duplicates frame if needed */
1223
    for(i=0;i<nb_frames;i++) {
1224
        AVPacket pkt;
1225
        av_init_packet(&pkt);
1226
        pkt.stream_index= ost->index;
1227

    
1228
        if (s->oformat->flags & AVFMT_RAWPICTURE) {
1229
            /* raw pictures are written as AVPicture structure to
1230
               avoid any copies. We support temorarily the older
1231
               method. */
1232
            AVFrame* old_frame = enc->coded_frame;
1233
            enc->coded_frame = dec->coded_frame; //FIXME/XXX remove this hack
1234
            pkt.data= (uint8_t *)final_picture;
1235
            pkt.size=  sizeof(AVPicture);
1236
            pkt.pts= av_rescale_q(ost->sync_opts, enc->time_base, ost->st->time_base);
1237
            pkt.flags |= AV_PKT_FLAG_KEY;
1238

    
1239
            write_frame(s, &pkt, ost->st->codec, ost->bitstream_filters);
1240
            enc->coded_frame = old_frame;
1241
        } else {
1242
            AVFrame big_picture;
1243

    
1244
            big_picture= *final_picture;
1245
            /* better than nothing: use input picture interlaced
1246
               settings */
1247
            big_picture.interlaced_frame = in_picture->interlaced_frame;
1248
            if(avcodec_opts[AVMEDIA_TYPE_VIDEO]->flags & (CODEC_FLAG_INTERLACED_DCT|CODEC_FLAG_INTERLACED_ME)){
1249
                if(top_field_first == -1)
1250
                    big_picture.top_field_first = in_picture->top_field_first;
1251
                else
1252
                    big_picture.top_field_first = top_field_first;
1253
            }
1254

    
1255
            /* handles sameq here. This is not correct because it may
1256
               not be a global option */
1257
            big_picture.quality = same_quality ? ist->st->quality : ost->st->quality;
1258
            if(!me_threshold)
1259
                big_picture.pict_type = 0;
1260
//            big_picture.pts = AV_NOPTS_VALUE;
1261
            big_picture.pts= ost->sync_opts;
1262
//            big_picture.pts= av_rescale(ost->sync_opts, AV_TIME_BASE*(int64_t)enc->time_base.num, enc->time_base.den);
1263
//av_log(NULL, AV_LOG_DEBUG, "%"PRId64" -> encoder\n", ost->sync_opts);
1264
            if (ost->forced_kf_index < ost->forced_kf_count &&
1265
                big_picture.pts >= ost->forced_kf_pts[ost->forced_kf_index]) {
1266
                big_picture.pict_type = FF_I_TYPE;
1267
                ost->forced_kf_index++;
1268
            }
1269
            ret = avcodec_encode_video(enc,
1270
                                       bit_buffer, bit_buffer_size,
1271
                                       &big_picture);
1272
            if (ret < 0) {
1273
                fprintf(stderr, "Video encoding failed\n");
1274
                ffmpeg_exit(1);
1275
            }
1276

    
1277
            if(ret>0){
1278
                pkt.data= bit_buffer;
1279
                pkt.size= ret;
1280
                if(enc->coded_frame->pts != AV_NOPTS_VALUE)
1281
                    pkt.pts= av_rescale_q(enc->coded_frame->pts, enc->time_base, ost->st->time_base);
1282
/*av_log(NULL, AV_LOG_DEBUG, "encoder -> %"PRId64"/%"PRId64"\n",
1283
   pkt.pts != AV_NOPTS_VALUE ? av_rescale(pkt.pts, enc->time_base.den, AV_TIME_BASE*(int64_t)enc->time_base.num) : -1,
1284
   pkt.dts != AV_NOPTS_VALUE ? av_rescale(pkt.dts, enc->time_base.den, AV_TIME_BASE*(int64_t)enc->time_base.num) : -1);*/
1285

    
1286
                if(enc->coded_frame->key_frame)
1287
                    pkt.flags |= AV_PKT_FLAG_KEY;
1288
                write_frame(s, &pkt, ost->st->codec, ost->bitstream_filters);
1289
                *frame_size = ret;
1290
                video_size += ret;
1291
                //fprintf(stderr,"\nFrame: %3d size: %5d type: %d",
1292
                //        enc->frame_number-1, ret, enc->pict_type);
1293
                /* if two pass, output log */
1294
                if (ost->logfile && enc->stats_out) {
1295
                    fprintf(ost->logfile, "%s", enc->stats_out);
1296
                }
1297
            }
1298
        }
1299
        ost->sync_opts++;
1300
        ost->frame_number++;
1301
    }
1302
}
1303

    
1304
static double psnr(double d){
1305
    return -10.0*log(d)/log(10.0);
1306
}
1307

    
1308
static void do_video_stats(AVFormatContext *os, AVOutputStream *ost,
1309
                           int frame_size)
1310
{
1311
    AVCodecContext *enc;
1312
    int frame_number;
1313
    double ti1, bitrate, avg_bitrate;
1314

    
1315
    /* this is executed just the first time do_video_stats is called */
1316
    if (!vstats_file) {
1317
        vstats_file = fopen(vstats_filename, "w");
1318
        if (!vstats_file) {
1319
            perror("fopen");
1320
            ffmpeg_exit(1);
1321
        }
1322
    }
1323

    
1324
    enc = ost->st->codec;
1325
    if (enc->codec_type == AVMEDIA_TYPE_VIDEO) {
1326
        frame_number = ost->frame_number;
1327
        fprintf(vstats_file, "frame= %5d q= %2.1f ", frame_number, enc->coded_frame->quality/(float)FF_QP2LAMBDA);
1328
        if (enc->flags&CODEC_FLAG_PSNR)
1329
            fprintf(vstats_file, "PSNR= %6.2f ", psnr(enc->coded_frame->error[0]/(enc->width*enc->height*255.0*255.0)));
1330

    
1331
        fprintf(vstats_file,"f_size= %6d ", frame_size);
1332
        /* compute pts value */
1333
        ti1 = ost->sync_opts * av_q2d(enc->time_base);
1334
        if (ti1 < 0.01)
1335
            ti1 = 0.01;
1336

    
1337
        bitrate = (frame_size * 8) / av_q2d(enc->time_base) / 1000.0;
1338
        avg_bitrate = (double)(video_size * 8) / ti1 / 1000.0;
1339
        fprintf(vstats_file, "s_size= %8.0fkB time= %0.3f br= %7.1fkbits/s avg_br= %7.1fkbits/s ",
1340
            (double)video_size / 1024, ti1, bitrate, avg_bitrate);
1341
        fprintf(vstats_file,"type= %c\n", av_get_pict_type_char(enc->coded_frame->pict_type));
1342
    }
1343
}
1344

    
1345
static void print_report(AVFormatContext **output_files,
1346
                         AVOutputStream **ost_table, int nb_ostreams,
1347
                         int is_last_report)
1348
{
1349
    char buf[1024];
1350
    AVOutputStream *ost;
1351
    AVFormatContext *oc;
1352
    int64_t total_size;
1353
    AVCodecContext *enc;
1354
    int frame_number, vid, i;
1355
    double bitrate, ti1, pts;
1356
    static int64_t last_time = -1;
1357
    static int qp_histogram[52];
1358

    
1359
    if (!is_last_report) {
1360
        int64_t cur_time;
1361
        /* display the report every 0.5 seconds */
1362
        cur_time = av_gettime();
1363
        if (last_time == -1) {
1364
            last_time = cur_time;
1365
            return;
1366
        }
1367
        if ((cur_time - last_time) < 500000)
1368
            return;
1369
        last_time = cur_time;
1370
    }
1371

    
1372

    
1373
    oc = output_files[0];
1374

    
1375
    total_size = avio_size(oc->pb);
1376
    if(total_size<0) // FIXME improve avio_size() so it works with non seekable output too
1377
        total_size= avio_tell(oc->pb);
1378

    
1379
    buf[0] = '\0';
1380
    ti1 = 1e10;
1381
    vid = 0;
1382
    for(i=0;i<nb_ostreams;i++) {
1383
        ost = ost_table[i];
1384
        enc = ost->st->codec;
1385
        if (vid && enc->codec_type == AVMEDIA_TYPE_VIDEO) {
1386
            snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "q=%2.1f ",
1387
                     !ost->st->stream_copy ?
1388
                     enc->coded_frame->quality/(float)FF_QP2LAMBDA : -1);
1389
        }
1390
        if (!vid && enc->codec_type == AVMEDIA_TYPE_VIDEO) {
1391
            float t = (av_gettime()-timer_start) / 1000000.0;
1392

    
1393
            frame_number = ost->frame_number;
1394
            snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "frame=%5d fps=%3d q=%3.1f ",
1395
                     frame_number, (t>1)?(int)(frame_number/t+0.5) : 0,
1396
                     !ost->st->stream_copy ?
1397
                     enc->coded_frame->quality/(float)FF_QP2LAMBDA : -1);
1398
            if(is_last_report)
1399
                snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "L");
1400
            if(qp_hist){
1401
                int j;
1402
                int qp= lrintf(enc->coded_frame->quality/(float)FF_QP2LAMBDA);
1403
                if(qp>=0 && qp<FF_ARRAY_ELEMS(qp_histogram))
1404
                    qp_histogram[qp]++;
1405
                for(j=0; j<32; j++)
1406
                    snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "%X", (int)lrintf(log(qp_histogram[j]+1)/log(2)));
1407
            }
1408
            if (enc->flags&CODEC_FLAG_PSNR){
1409
                int j;
1410
                double error, error_sum=0;
1411
                double scale, scale_sum=0;
1412
                char type[3]= {'Y','U','V'};
1413
                snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "PSNR=");
1414
                for(j=0; j<3; j++){
1415
                    if(is_last_report){
1416
                        error= enc->error[j];
1417
                        scale= enc->width*enc->height*255.0*255.0*frame_number;
1418
                    }else{
1419
                        error= enc->coded_frame->error[j];
1420
                        scale= enc->width*enc->height*255.0*255.0;
1421
                    }
1422
                    if(j) scale/=4;
1423
                    error_sum += error;
1424
                    scale_sum += scale;
1425
                    snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "%c:%2.2f ", type[j], psnr(error/scale));
1426
                }
1427
                snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "*:%2.2f ", psnr(error_sum/scale_sum));
1428
            }
1429
            vid = 1;
1430
        }
1431
        /* compute min output value */
1432
        pts = (double)ost->st->pts.val * av_q2d(ost->st->time_base);
1433
        if ((pts < ti1) && (pts > 0))
1434
            ti1 = pts;
1435
    }
1436
    if (ti1 < 0.01)
1437
        ti1 = 0.01;
1438

    
1439
    if (verbose || is_last_report) {
1440
        bitrate = (double)(total_size * 8) / ti1 / 1000.0;
1441

    
1442
        snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
1443
            "size=%8.0fkB time=%0.2f bitrate=%6.1fkbits/s",
1444
            (double)total_size / 1024, ti1, bitrate);
1445

    
1446
        if (nb_frames_dup || nb_frames_drop)
1447
          snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), " dup=%d drop=%d",
1448
                  nb_frames_dup, nb_frames_drop);
1449

    
1450
        if (verbose >= 0)
1451
            fprintf(stderr, "%s    \r", buf);
1452

    
1453
        fflush(stderr);
1454
    }
1455

    
1456
    if (is_last_report && verbose >= 0){
1457
        int64_t raw= audio_size + video_size + extra_size;
1458
        fprintf(stderr, "\n");
1459
        fprintf(stderr, "video:%1.0fkB audio:%1.0fkB global headers:%1.0fkB muxing overhead %f%%\n",
1460
                video_size/1024.0,
1461
                audio_size/1024.0,
1462
                extra_size/1024.0,
1463
                100.0*(total_size - raw)/raw
1464
        );
1465
    }
1466
}
1467

    
1468
/* pkt = NULL means EOF (needed to flush decoder buffers) */
1469
static int output_packet(AVInputStream *ist, int ist_index,
1470
                         AVOutputStream **ost_table, int nb_ostreams,
1471
                         const AVPacket *pkt)
1472
{
1473
    AVFormatContext *os;
1474
    AVOutputStream *ost;
1475
    int ret, i;
1476
    int got_picture;
1477
    AVFrame picture;
1478
    void *buffer_to_free;
1479
    static unsigned int samples_size= 0;
1480
    AVSubtitle subtitle, *subtitle_to_free;
1481
    int64_t pkt_pts = AV_NOPTS_VALUE;
1482
#if CONFIG_AVFILTER
1483
    int frame_available;
1484
#endif
1485

    
1486
    AVPacket avpkt;
1487
    int bps = av_get_bits_per_sample_fmt(ist->st->codec->sample_fmt)>>3;
1488

    
1489
    if(ist->next_pts == AV_NOPTS_VALUE)
1490
        ist->next_pts= ist->pts;
1491

    
1492
    if (pkt == NULL) {
1493
        /* EOF handling */
1494
        av_init_packet(&avpkt);
1495
        avpkt.data = NULL;
1496
        avpkt.size = 0;
1497
        goto handle_eof;
1498
    } else {
1499
        avpkt = *pkt;
1500
    }
1501

    
1502
    if(pkt->dts != AV_NOPTS_VALUE)
1503
        ist->next_pts = ist->pts = av_rescale_q(pkt->dts, ist->st->time_base, AV_TIME_BASE_Q);
1504
    if(pkt->pts != AV_NOPTS_VALUE)
1505
        pkt_pts = av_rescale_q(pkt->pts, ist->st->time_base, AV_TIME_BASE_Q);
1506

    
1507
    //while we have more to decode or while the decoder did output something on EOF
1508
    while (avpkt.size > 0 || (!pkt && ist->next_pts != ist->pts)) {
1509
        uint8_t *data_buf, *decoded_data_buf;
1510
        int data_size, decoded_data_size;
1511
    handle_eof:
1512
        ist->pts= ist->next_pts;
1513

    
1514
        if(avpkt.size && avpkt.size != pkt->size &&
1515
           ((!ist->showed_multi_packet_warning && verbose>0) || verbose>1)){
1516
            fprintf(stderr, "Multiple frames in a packet from stream %d\n", pkt->stream_index);
1517
            ist->showed_multi_packet_warning=1;
1518
        }
1519

    
1520
        /* decode the packet if needed */
1521
        decoded_data_buf = NULL; /* fail safe */
1522
        decoded_data_size= 0;
1523
        data_buf  = avpkt.data;
1524
        data_size = avpkt.size;
1525
        subtitle_to_free = NULL;
1526
        if (ist->decoding_needed) {
1527
            switch(ist->st->codec->codec_type) {
1528
            case AVMEDIA_TYPE_AUDIO:{
1529
                if(pkt && samples_size < FFMAX(pkt->size*sizeof(*samples), AVCODEC_MAX_AUDIO_FRAME_SIZE)) {
1530
                    samples_size = FFMAX(pkt->size*sizeof(*samples), AVCODEC_MAX_AUDIO_FRAME_SIZE);
1531
                    av_free(samples);
1532
                    samples= av_malloc(samples_size);
1533
                }
1534
                decoded_data_size= samples_size;
1535
                    /* XXX: could avoid copy if PCM 16 bits with same
1536
                       endianness as CPU */
1537
                ret = avcodec_decode_audio3(ist->st->codec, samples, &decoded_data_size,
1538
                                            &avpkt);
1539
                if (ret < 0)
1540
                    goto fail_decode;
1541
                avpkt.data += ret;
1542
                avpkt.size -= ret;
1543
                data_size   = ret;
1544
                /* Some bug in mpeg audio decoder gives */
1545
                /* decoded_data_size < 0, it seems they are overflows */
1546
                if (decoded_data_size <= 0) {
1547
                    /* no audio frame */
1548
                    continue;
1549
                }
1550
                decoded_data_buf = (uint8_t *)samples;
1551
                ist->next_pts += ((int64_t)AV_TIME_BASE/bps * decoded_data_size) /
1552
                    (ist->st->codec->sample_rate * ist->st->codec->channels);
1553
                break;}
1554
            case AVMEDIA_TYPE_VIDEO:
1555
                    decoded_data_size = (ist->st->codec->width * ist->st->codec->height * 3) / 2;
1556
                    /* XXX: allocate picture correctly */
1557
                    avcodec_get_frame_defaults(&picture);
1558
                    avpkt.pts = pkt_pts;
1559
                    avpkt.dts = ist->pts;
1560
                    pkt_pts = AV_NOPTS_VALUE;
1561

    
1562
                    ret = avcodec_decode_video2(ist->st->codec,
1563
                                                &picture, &got_picture, &avpkt);
1564
                    ist->st->quality= picture.quality;
1565
                    if (ret < 0)
1566
                        goto fail_decode;
1567
                    if (!got_picture) {
1568
                        /* no picture yet */
1569
                        goto discard_packet;
1570
                    }
1571
                    ist->next_pts = ist->pts = picture.best_effort_timestamp;
1572
                    if (ist->st->codec->time_base.num != 0) {
1573
                        int ticks= ist->st->parser ? ist->st->parser->repeat_pict+1 : ist->st->codec->ticks_per_frame;
1574
                        ist->next_pts += ((int64_t)AV_TIME_BASE *
1575
                                          ist->st->codec->time_base.num * ticks) /
1576
                            ist->st->codec->time_base.den;
1577
                    }
1578
                    avpkt.size = 0;
1579
                    break;
1580
            case AVMEDIA_TYPE_SUBTITLE:
1581
                ret = avcodec_decode_subtitle2(ist->st->codec,
1582
                                               &subtitle, &got_picture, &avpkt);
1583
                if (ret < 0)
1584
                    goto fail_decode;
1585
                if (!got_picture) {
1586
                    goto discard_packet;
1587
                }
1588
                subtitle_to_free = &subtitle;
1589
                avpkt.size = 0;
1590
                break;
1591
            default:
1592
                goto fail_decode;
1593
            }
1594
        } else {
1595
            switch(ist->st->codec->codec_type) {
1596
            case AVMEDIA_TYPE_AUDIO:
1597
                ist->next_pts += ((int64_t)AV_TIME_BASE * ist->st->codec->frame_size) /
1598
                    ist->st->codec->sample_rate;
1599
                break;
1600
            case AVMEDIA_TYPE_VIDEO:
1601
                if (ist->st->codec->time_base.num != 0) {
1602
                    int ticks= ist->st->parser ? ist->st->parser->repeat_pict+1 : ist->st->codec->ticks_per_frame;
1603
                    ist->next_pts += ((int64_t)AV_TIME_BASE *
1604
                                      ist->st->codec->time_base.num * ticks) /
1605
                        ist->st->codec->time_base.den;
1606
                }
1607
                break;
1608
            }
1609
            ret = avpkt.size;
1610
            avpkt.size = 0;
1611
        }
1612

    
1613
        buffer_to_free = NULL;
1614
        if (ist->st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
1615
            pre_process_video_frame(ist, (AVPicture *)&picture,
1616
                                    &buffer_to_free);
1617
        }
1618

    
1619
#if CONFIG_AVFILTER
1620
        if(ist->st->codec->codec_type == AVMEDIA_TYPE_VIDEO){
1621
            for(i=0;i<nb_ostreams;i++) {
1622
                ost = ost_table[i];
1623
                if (ost->input_video_filter && ost->source_index == ist_index) {
1624
                    AVRational sar;
1625
                    if (ist->st->sample_aspect_ratio.num) sar = ist->st->sample_aspect_ratio;
1626
                    else                                  sar = ist->st->codec->sample_aspect_ratio;
1627
                    // add it to be filtered
1628
                    av_vsrc_buffer_add_frame2(ost->input_video_filter, &picture,
1629
                                             ist->pts,
1630
                                             sar, ist->st->codec->width, ist->st->codec->height,
1631
                                             ist->st->codec->pix_fmt, "0:0"); //TODO user setable params
1632
                }
1633
            }
1634
        }
1635
#endif
1636

    
1637
        // preprocess audio (volume)
1638
        if (ist->st->codec->codec_type == AVMEDIA_TYPE_AUDIO) {
1639
            if (audio_volume != 256) {
1640
                short *volp;
1641
                volp = samples;
1642
                for(i=0;i<(decoded_data_size / sizeof(short));i++) {
1643
                    int v = ((*volp) * audio_volume + 128) >> 8;
1644
                    if (v < -32768) v = -32768;
1645
                    if (v >  32767) v = 32767;
1646
                    *volp++ = v;
1647
                }
1648
            }
1649
        }
1650

    
1651
        /* frame rate emulation */
1652
        if (rate_emu) {
1653
            int64_t pts = av_rescale(ist->pts, 1000000, AV_TIME_BASE);
1654
            int64_t now = av_gettime() - ist->start;
1655
            if (pts > now)
1656
                usleep(pts - now);
1657
        }
1658
        /* if output time reached then transcode raw format,
1659
           encode packets and output them */
1660
        if (start_time == 0 || ist->pts >= start_time)
1661
            for(i=0;i<nb_ostreams;i++) {
1662
                int frame_size;
1663

    
1664
                ost = ost_table[i];
1665
                if (ost->source_index == ist_index) {
1666
#if CONFIG_AVFILTER
1667
                frame_available = ist->st->codec->codec_type != AVMEDIA_TYPE_VIDEO ||
1668
                    !ost->output_video_filter || avfilter_poll_frame(ost->output_video_filter->inputs[0]);
1669
                while (frame_available) {
1670
                    AVRational ist_pts_tb;
1671
                    if (ist->st->codec->codec_type == AVMEDIA_TYPE_VIDEO && ost->output_video_filter)
1672
                        get_filtered_video_frame(ost->output_video_filter, &picture, &ost->picref, &ist_pts_tb);
1673
                    if (ost->picref)
1674
                        ist->pts = av_rescale_q(ost->picref->pts, ist_pts_tb, AV_TIME_BASE_Q);
1675
#endif
1676
                    os = output_files[ost->file_index];
1677

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

    
1681
                    if (ost->encoding_needed) {
1682
                        av_assert0(ist->decoding_needed);
1683
                        switch(ost->st->codec->codec_type) {
1684
                        case AVMEDIA_TYPE_AUDIO:
1685
                            do_audio_out(os, ost, ist, decoded_data_buf, decoded_data_size);
1686
                            break;
1687
                        case AVMEDIA_TYPE_VIDEO:
1688
#if CONFIG_AVFILTER
1689
                            if (ost->picref->video)
1690
                                ost->st->codec->sample_aspect_ratio = ost->picref->video->pixel_aspect;
1691
#endif
1692
                            do_video_out(os, ost, ist, &picture, &frame_size);
1693
                            if (vstats_filename && frame_size)
1694
                                do_video_stats(os, ost, frame_size);
1695
                            break;
1696
                        case AVMEDIA_TYPE_SUBTITLE:
1697
                            do_subtitle_out(os, ost, ist, &subtitle,
1698
                                            pkt->pts);
1699
                            break;
1700
                        default:
1701
                            abort();
1702
                        }
1703
                    } else {
1704
                        AVFrame avframe; //FIXME/XXX remove this
1705
                        AVPacket opkt;
1706
                        int64_t ost_tb_start_time= av_rescale_q(start_time, AV_TIME_BASE_Q, ost->st->time_base);
1707

    
1708
                        av_init_packet(&opkt);
1709

    
1710
                        if ((!ost->frame_number && !(pkt->flags & AV_PKT_FLAG_KEY)) && !copy_initial_nonkeyframes)
1711
#if !CONFIG_AVFILTER
1712
                            continue;
1713
#else
1714
                            goto cont;
1715
#endif
1716

    
1717
                        /* no reencoding needed : output the packet directly */
1718
                        /* force the input stream PTS */
1719

    
1720
                        avcodec_get_frame_defaults(&avframe);
1721
                        ost->st->codec->coded_frame= &avframe;
1722
                        avframe.key_frame = pkt->flags & AV_PKT_FLAG_KEY;
1723

    
1724
                        if(ost->st->codec->codec_type == AVMEDIA_TYPE_AUDIO)
1725
                            audio_size += data_size;
1726
                        else if (ost->st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
1727
                            video_size += data_size;
1728
                            ost->sync_opts++;
1729
                        }
1730

    
1731
                        opkt.stream_index= ost->index;
1732
                        if(pkt->pts != AV_NOPTS_VALUE)
1733
                            opkt.pts= av_rescale_q(pkt->pts, ist->st->time_base, ost->st->time_base) - ost_tb_start_time;
1734
                        else
1735
                            opkt.pts= AV_NOPTS_VALUE;
1736

    
1737
                        if (pkt->dts == AV_NOPTS_VALUE)
1738
                            opkt.dts = av_rescale_q(ist->pts, AV_TIME_BASE_Q, ost->st->time_base);
1739
                        else
1740
                            opkt.dts = av_rescale_q(pkt->dts, ist->st->time_base, ost->st->time_base);
1741
                        opkt.dts -= ost_tb_start_time;
1742

    
1743
                        opkt.duration = av_rescale_q(pkt->duration, ist->st->time_base, ost->st->time_base);
1744
                        opkt.flags= pkt->flags;
1745

    
1746
                        //FIXME remove the following 2 lines they shall be replaced by the bitstream filters
1747
                        if(   ost->st->codec->codec_id != CODEC_ID_H264
1748
                           && ost->st->codec->codec_id != CODEC_ID_MPEG1VIDEO
1749
                           && ost->st->codec->codec_id != CODEC_ID_MPEG2VIDEO
1750
                           ) {
1751
                            if(av_parser_change(ist->st->parser, ost->st->codec, &opkt.data, &opkt.size, data_buf, data_size, pkt->flags & AV_PKT_FLAG_KEY))
1752
                                opkt.destruct= av_destruct_packet;
1753
                        } else {
1754
                            opkt.data = data_buf;
1755
                            opkt.size = data_size;
1756
                        }
1757

    
1758
                        write_frame(os, &opkt, ost->st->codec, ost->bitstream_filters);
1759
                        ost->st->codec->frame_number++;
1760
                        ost->frame_number++;
1761
                        av_free_packet(&opkt);
1762
                    }
1763
#if CONFIG_AVFILTER
1764
                    cont:
1765
                    frame_available = (ist->st->codec->codec_type == AVMEDIA_TYPE_VIDEO) &&
1766
                                       ost->output_video_filter && avfilter_poll_frame(ost->output_video_filter->inputs[0]);
1767
                    if(ost->picref)
1768
                        avfilter_unref_buffer(ost->picref);
1769
                }
1770
#endif
1771
                }
1772
            }
1773

    
1774
        av_free(buffer_to_free);
1775
        /* XXX: allocate the subtitles in the codec ? */
1776
        if (subtitle_to_free) {
1777
            avsubtitle_free(subtitle_to_free);
1778
            subtitle_to_free = NULL;
1779
        }
1780
    }
1781
 discard_packet:
1782
    if (pkt == NULL) {
1783
        /* EOF handling */
1784

    
1785
        for(i=0;i<nb_ostreams;i++) {
1786
            ost = ost_table[i];
1787
            if (ost->source_index == ist_index) {
1788
                AVCodecContext *enc= ost->st->codec;
1789
                os = output_files[ost->file_index];
1790

    
1791
                if(ost->st->codec->codec_type == AVMEDIA_TYPE_AUDIO && enc->frame_size <=1)
1792
                    continue;
1793
                if(ost->st->codec->codec_type == AVMEDIA_TYPE_VIDEO && (os->oformat->flags & AVFMT_RAWPICTURE))
1794
                    continue;
1795

    
1796
                if (ost->encoding_needed) {
1797
                    for(;;) {
1798
                        AVPacket pkt;
1799
                        int fifo_bytes;
1800
                        av_init_packet(&pkt);
1801
                        pkt.stream_index= ost->index;
1802

    
1803
                        switch(ost->st->codec->codec_type) {
1804
                        case AVMEDIA_TYPE_AUDIO:
1805
                            fifo_bytes = av_fifo_size(ost->fifo);
1806
                            ret = 0;
1807
                            /* encode any samples remaining in fifo */
1808
                            if (fifo_bytes > 0) {
1809
                                int osize = av_get_bits_per_sample_fmt(enc->sample_fmt) >> 3;
1810
                                int fs_tmp = enc->frame_size;
1811

    
1812
                                av_fifo_generic_read(ost->fifo, audio_buf, fifo_bytes, NULL);
1813
                                if (enc->codec->capabilities & CODEC_CAP_SMALL_LAST_FRAME) {
1814
                                    enc->frame_size = fifo_bytes / (osize * enc->channels);
1815
                                } else { /* pad */
1816
                                    int frame_bytes = enc->frame_size*osize*enc->channels;
1817
                                    if (allocated_audio_buf_size < frame_bytes)
1818
                                        ffmpeg_exit(1);
1819
                                    memset(audio_buf+fifo_bytes, 0, frame_bytes - fifo_bytes);
1820
                                }
1821

    
1822
                                ret = avcodec_encode_audio(enc, bit_buffer, bit_buffer_size, (short *)audio_buf);
1823
                                pkt.duration = av_rescale((int64_t)enc->frame_size*ost->st->time_base.den,
1824
                                                          ost->st->time_base.num, enc->sample_rate);
1825
                                enc->frame_size = fs_tmp;
1826
                            }
1827
                            if(ret <= 0) {
1828
                                ret = avcodec_encode_audio(enc, bit_buffer, bit_buffer_size, NULL);
1829
                            }
1830
                            if (ret < 0) {
1831
                                fprintf(stderr, "Audio encoding failed\n");
1832
                                ffmpeg_exit(1);
1833
                            }
1834
                            audio_size += ret;
1835
                            pkt.flags |= AV_PKT_FLAG_KEY;
1836
                            break;
1837
                        case AVMEDIA_TYPE_VIDEO:
1838
                            ret = avcodec_encode_video(enc, bit_buffer, bit_buffer_size, NULL);
1839
                            if (ret < 0) {
1840
                                fprintf(stderr, "Video encoding failed\n");
1841
                                ffmpeg_exit(1);
1842
                            }
1843
                            video_size += ret;
1844
                            if(enc->coded_frame && enc->coded_frame->key_frame)
1845
                                pkt.flags |= AV_PKT_FLAG_KEY;
1846
                            if (ost->logfile && enc->stats_out) {
1847
                                fprintf(ost->logfile, "%s", enc->stats_out);
1848
                            }
1849
                            break;
1850
                        default:
1851
                            ret=-1;
1852
                        }
1853

    
1854
                        if(ret<=0)
1855
                            break;
1856
                        pkt.data= bit_buffer;
1857
                        pkt.size= ret;
1858
                        if(enc->coded_frame && enc->coded_frame->pts != AV_NOPTS_VALUE)
1859
                            pkt.pts= av_rescale_q(enc->coded_frame->pts, enc->time_base, ost->st->time_base);
1860
                        write_frame(os, &pkt, ost->st->codec, ost->bitstream_filters);
1861
                    }
1862
                }
1863
            }
1864
        }
1865
    }
1866

    
1867
    return 0;
1868
 fail_decode:
1869
    return -1;
1870
}
1871

    
1872
static void print_sdp(AVFormatContext **avc, int n)
1873
{
1874
    char sdp[2048];
1875

    
1876
    avf_sdp_create(avc, n, sdp, sizeof(sdp));
1877
    printf("SDP:\n%s\n", sdp);
1878
    fflush(stdout);
1879
}
1880

    
1881
static int copy_chapters(int infile, int outfile)
1882
{
1883
    AVFormatContext *is = input_files[infile];
1884
    AVFormatContext *os = output_files[outfile];
1885
    int i;
1886

    
1887
    for (i = 0; i < is->nb_chapters; i++) {
1888
        AVChapter *in_ch = is->chapters[i], *out_ch;
1889
        int64_t ts_off   = av_rescale_q(start_time - input_files_ts_offset[infile],
1890
                                      AV_TIME_BASE_Q, in_ch->time_base);
1891
        int64_t rt       = (recording_time == INT64_MAX) ? INT64_MAX :
1892
                           av_rescale_q(recording_time, AV_TIME_BASE_Q, in_ch->time_base);
1893

    
1894

    
1895
        if (in_ch->end < ts_off)
1896
            continue;
1897
        if (rt != INT64_MAX && in_ch->start > rt + ts_off)
1898
            break;
1899

    
1900
        out_ch = av_mallocz(sizeof(AVChapter));
1901
        if (!out_ch)
1902
            return AVERROR(ENOMEM);
1903

    
1904
        out_ch->id        = in_ch->id;
1905
        out_ch->time_base = in_ch->time_base;
1906
        out_ch->start     = FFMAX(0,  in_ch->start - ts_off);
1907
        out_ch->end       = FFMIN(rt, in_ch->end   - ts_off);
1908

    
1909
        if (metadata_chapters_autocopy)
1910
            av_metadata_copy(&out_ch->metadata, in_ch->metadata, 0);
1911

    
1912
        os->nb_chapters++;
1913
        os->chapters = av_realloc(os->chapters, sizeof(AVChapter)*os->nb_chapters);
1914
        if (!os->chapters)
1915
            return AVERROR(ENOMEM);
1916
        os->chapters[os->nb_chapters - 1] = out_ch;
1917
    }
1918
    return 0;
1919
}
1920

    
1921
static void parse_forced_key_frames(char *kf, AVOutputStream *ost,
1922
                                    AVCodecContext *avctx)
1923
{
1924
    char *p;
1925
    int n = 1, i;
1926
    int64_t t;
1927

    
1928
    for (p = kf; *p; p++)
1929
        if (*p == ',')
1930
            n++;
1931
    ost->forced_kf_count = n;
1932
    ost->forced_kf_pts = av_malloc(sizeof(*ost->forced_kf_pts) * n);
1933
    if (!ost->forced_kf_pts) {
1934
        av_log(NULL, AV_LOG_FATAL, "Could not allocate forced key frames array.\n");
1935
        ffmpeg_exit(1);
1936
    }
1937
    for (i = 0; i < n; i++) {
1938
        p = i ? strchr(p, ',') + 1 : kf;
1939
        t = parse_time_or_die("force_key_frames", p, 1);
1940
        ost->forced_kf_pts[i] = av_rescale_q(t, AV_TIME_BASE_Q, avctx->time_base);
1941
    }
1942
}
1943

    
1944
/*
1945
 * The following code is the main loop of the file converter
1946
 */
1947
static int transcode(AVFormatContext **output_files,
1948
                     int nb_output_files,
1949
                     AVFormatContext **input_files,
1950
                     int nb_input_files,
1951
                     AVStreamMap *stream_maps, int nb_stream_maps)
1952
{
1953
    int ret = 0, i, j, k, n, nb_istreams = 0, nb_ostreams = 0, step;
1954
    AVFormatContext *is, *os;
1955
    AVCodecContext *codec, *icodec;
1956
    AVOutputStream *ost, **ost_table = NULL;
1957
    AVInputStream *ist, **ist_table = NULL;
1958
    AVInputFile *file_table;
1959
    char error[1024];
1960
    int key;
1961
    int want_sdp = 1;
1962
    uint8_t no_packet[MAX_FILES]={0};
1963
    int no_packet_count=0;
1964
    int nb_frame_threshold[AVMEDIA_TYPE_NB]={0};
1965
    int nb_streams[AVMEDIA_TYPE_NB]={0};
1966

    
1967
    file_table= av_mallocz(nb_input_files * sizeof(AVInputFile));
1968
    if (!file_table)
1969
        goto fail;
1970

    
1971
    /* input stream init */
1972
    j = 0;
1973
    for(i=0;i<nb_input_files;i++) {
1974
        is = input_files[i];
1975
        file_table[i].ist_index = j;
1976
        file_table[i].nb_streams = is->nb_streams;
1977
        j += is->nb_streams;
1978
    }
1979
    nb_istreams = j;
1980

    
1981
    ist_table = av_mallocz(nb_istreams * sizeof(AVInputStream *));
1982
    if (!ist_table)
1983
        goto fail;
1984

    
1985
    for(i=0;i<nb_istreams;i++) {
1986
        ist = av_mallocz(sizeof(AVInputStream));
1987
        if (!ist)
1988
            goto fail;
1989
        ist_table[i] = ist;
1990
    }
1991
    j = 0;
1992
    for(i=0;i<nb_input_files;i++) {
1993
        is = input_files[i];
1994
        for(k=0;k<is->nb_streams;k++) {
1995
            ist = ist_table[j++];
1996
            ist->st = is->streams[k];
1997
            ist->file_index = i;
1998
            ist->index = k;
1999
            ist->discard = 1; /* the stream is discarded by default
2000
                                 (changed later) */
2001

    
2002
            if (rate_emu) {
2003
                ist->start = av_gettime();
2004
            }
2005
        }
2006
    }
2007

    
2008
    /* output stream init */
2009
    nb_ostreams = 0;
2010
    for(i=0;i<nb_output_files;i++) {
2011
        os = output_files[i];
2012
        if (!os->nb_streams && !(os->oformat->flags & AVFMT_NOSTREAMS)) {
2013
            av_dump_format(output_files[i], i, output_files[i]->filename, 1);
2014
            fprintf(stderr, "Output file #%d does not contain any stream\n", i);
2015
            ret = AVERROR(EINVAL);
2016
            goto fail;
2017
        }
2018
        nb_ostreams += os->nb_streams;
2019
    }
2020
    if (nb_stream_maps > 0 && nb_stream_maps != nb_ostreams) {
2021
        fprintf(stderr, "Number of stream maps must match number of output streams\n");
2022
        ret = AVERROR(EINVAL);
2023
        goto fail;
2024
    }
2025

    
2026
    /* Sanity check the mapping args -- do the input files & streams exist? */
2027
    for(i=0;i<nb_stream_maps;i++) {
2028
        int fi = stream_maps[i].file_index;
2029
        int si = stream_maps[i].stream_index;
2030

    
2031
        if (fi < 0 || fi > nb_input_files - 1 ||
2032
            si < 0 || si > file_table[fi].nb_streams - 1) {
2033
            fprintf(stderr,"Could not find input stream #%d.%d\n", fi, si);
2034
            ret = AVERROR(EINVAL);
2035
            goto fail;
2036
        }
2037
        fi = stream_maps[i].sync_file_index;
2038
        si = stream_maps[i].sync_stream_index;
2039
        if (fi < 0 || fi > nb_input_files - 1 ||
2040
            si < 0 || si > file_table[fi].nb_streams - 1) {
2041
            fprintf(stderr,"Could not find sync stream #%d.%d\n", fi, si);
2042
            ret = AVERROR(EINVAL);
2043
            goto fail;
2044
        }
2045
    }
2046

    
2047
    ost_table = av_mallocz(sizeof(AVOutputStream *) * nb_ostreams);
2048
    if (!ost_table)
2049
        goto fail;
2050

    
2051
    for(k=0;k<nb_output_files;k++) {
2052
        os = output_files[k];
2053
        for(i=0;i<os->nb_streams;i++,n++) {
2054
            nb_streams[os->streams[i]->codec->codec_type]++;
2055
        }
2056
    }
2057
    for(step=1<<30; step; step>>=1){
2058
        int found_streams[AVMEDIA_TYPE_NB]={0};
2059
        for(j=0; j<AVMEDIA_TYPE_NB; j++)
2060
            nb_frame_threshold[j] += step;
2061

    
2062
        for(j=0; j<nb_istreams; j++) {
2063
            int skip=0;
2064
            ist = ist_table[j];
2065
            if(opt_programid){
2066
                int pi,si;
2067
                AVFormatContext *f= input_files[ ist->file_index ];
2068
                skip=1;
2069
                for(pi=0; pi<f->nb_programs; pi++){
2070
                    AVProgram *p= f->programs[pi];
2071
                    if(p->id == opt_programid)
2072
                        for(si=0; si<p->nb_stream_indexes; si++){
2073
                            if(f->streams[ p->stream_index[si] ] == ist->st)
2074
                                skip=0;
2075
                        }
2076
                }
2077
            }
2078
            if (ist->discard && ist->st->discard != AVDISCARD_ALL && !skip
2079
                && nb_frame_threshold[ist->st->codec->codec_type] <= ist->st->codec_info_nb_frames){
2080
                found_streams[ist->st->codec->codec_type]++;
2081
            }
2082
        }
2083
        for(j=0; j<AVMEDIA_TYPE_NB; j++)
2084
            if(found_streams[j] < nb_streams[j])
2085
                nb_frame_threshold[j] -= step;
2086
    }
2087
    n = 0;
2088
    for(k=0;k<nb_output_files;k++) {
2089
        os = output_files[k];
2090
        for(i=0;i<os->nb_streams;i++,n++) {
2091
            int found;
2092
            ost = ost_table[n] = output_streams_for_file[k][i];
2093
            ost->st = os->streams[i];
2094
            if (nb_stream_maps > 0) {
2095
                ost->source_index = file_table[stream_maps[n].file_index].ist_index +
2096
                    stream_maps[n].stream_index;
2097

    
2098
                /* Sanity check that the stream types match */
2099
                if (ist_table[ost->source_index]->st->codec->codec_type != ost->st->codec->codec_type) {
2100
                    int i= ost->file_index;
2101
                    av_dump_format(output_files[i], i, output_files[i]->filename, 1);
2102
                    fprintf(stderr, "Codec type mismatch for mapping #%d.%d -> #%d.%d\n",
2103
                        stream_maps[n].file_index, stream_maps[n].stream_index,
2104
                        ost->file_index, ost->index);
2105
                    ffmpeg_exit(1);
2106
                }
2107

    
2108
            } else {
2109
                /* get corresponding input stream index : we select the first one with the right type */
2110
                found = 0;
2111
                for(j=0;j<nb_istreams;j++) {
2112
                    int skip=0;
2113
                    ist = ist_table[j];
2114
                    if(opt_programid){
2115
                        int pi,si;
2116
                        AVFormatContext *f= input_files[ ist->file_index ];
2117
                        skip=1;
2118
                        for(pi=0; pi<f->nb_programs; pi++){
2119
                            AVProgram *p= f->programs[pi];
2120
                            if(p->id == opt_programid)
2121
                                for(si=0; si<p->nb_stream_indexes; si++){
2122
                                    if(f->streams[ p->stream_index[si] ] == ist->st)
2123
                                        skip=0;
2124
                                }
2125
                        }
2126
                    }
2127
                    if (ist->discard && ist->st->discard != AVDISCARD_ALL && !skip &&
2128
                        ist->st->codec->codec_type == ost->st->codec->codec_type &&
2129
                        nb_frame_threshold[ist->st->codec->codec_type] <= ist->st->codec_info_nb_frames) {
2130
                            ost->source_index = j;
2131
                            found = 1;
2132
                            break;
2133
                    }
2134
                }
2135

    
2136
                if (!found) {
2137
                    if(! opt_programid) {
2138
                        /* try again and reuse existing stream */
2139
                        for(j=0;j<nb_istreams;j++) {
2140
                            ist = ist_table[j];
2141
                            if (   ist->st->codec->codec_type == ost->st->codec->codec_type
2142
                                && ist->st->discard != AVDISCARD_ALL) {
2143
                                ost->source_index = j;
2144
                                found = 1;
2145
                            }
2146
                        }
2147
                    }
2148
                    if (!found) {
2149
                        int i= ost->file_index;
2150
                        av_dump_format(output_files[i], i, output_files[i]->filename, 1);
2151
                        fprintf(stderr, "Could not find input stream matching output stream #%d.%d\n",
2152
                                ost->file_index, ost->index);
2153
                        ffmpeg_exit(1);
2154
                    }
2155
                }
2156
            }
2157
            ist = ist_table[ost->source_index];
2158
            ist->discard = 0;
2159
            ost->sync_ist = (nb_stream_maps > 0) ?
2160
                ist_table[file_table[stream_maps[n].sync_file_index].ist_index +
2161
                         stream_maps[n].sync_stream_index] : ist;
2162
        }
2163
    }
2164

    
2165
    /* for each output stream, we compute the right encoding parameters */
2166
    for(i=0;i<nb_ostreams;i++) {
2167
        ost = ost_table[i];
2168
        os = output_files[ost->file_index];
2169
        ist = ist_table[ost->source_index];
2170

    
2171
        codec = ost->st->codec;
2172
        icodec = ist->st->codec;
2173

    
2174
        if (metadata_streams_autocopy)
2175
            av_metadata_copy(&ost->st->metadata, ist->st->metadata,
2176
                             AV_METADATA_DONT_OVERWRITE);
2177

    
2178
        ost->st->disposition = ist->st->disposition;
2179
        codec->bits_per_raw_sample= icodec->bits_per_raw_sample;
2180
        codec->chroma_sample_location = icodec->chroma_sample_location;
2181

    
2182
        if (ost->st->stream_copy) {
2183
            uint64_t extra_size = (uint64_t)icodec->extradata_size + FF_INPUT_BUFFER_PADDING_SIZE;
2184

    
2185
            if (extra_size > INT_MAX)
2186
                goto fail;
2187

    
2188
            /* if stream_copy is selected, no need to decode or encode */
2189
            codec->codec_id = icodec->codec_id;
2190
            codec->codec_type = icodec->codec_type;
2191

    
2192
            if(!codec->codec_tag){
2193
                if(   !os->oformat->codec_tag
2194
                   || av_codec_get_id (os->oformat->codec_tag, icodec->codec_tag) == codec->codec_id
2195
                   || av_codec_get_tag(os->oformat->codec_tag, icodec->codec_id) <= 0)
2196
                    codec->codec_tag = icodec->codec_tag;
2197
            }
2198

    
2199
            codec->bit_rate = icodec->bit_rate;
2200
            codec->rc_max_rate    = icodec->rc_max_rate;
2201
            codec->rc_buffer_size = icodec->rc_buffer_size;
2202
            codec->extradata= av_mallocz(extra_size);
2203
            if (!codec->extradata)
2204
                goto fail;
2205
            memcpy(codec->extradata, icodec->extradata, icodec->extradata_size);
2206
            codec->extradata_size= icodec->extradata_size;
2207
            if(!copy_tb && av_q2d(icodec->time_base)*icodec->ticks_per_frame > av_q2d(ist->st->time_base) && av_q2d(ist->st->time_base) < 1.0/500){
2208
                codec->time_base = icodec->time_base;
2209
                codec->time_base.num *= icodec->ticks_per_frame;
2210
                av_reduce(&codec->time_base.num, &codec->time_base.den,
2211
                          codec->time_base.num, codec->time_base.den, INT_MAX);
2212
            }else
2213
                codec->time_base = ist->st->time_base;
2214
            switch(codec->codec_type) {
2215
            case AVMEDIA_TYPE_AUDIO:
2216
                if(audio_volume != 256) {
2217
                    fprintf(stderr,"-acodec copy and -vol are incompatible (frames are not decoded)\n");
2218
                    ffmpeg_exit(1);
2219
                }
2220
                codec->channel_layout = icodec->channel_layout;
2221
                codec->sample_rate = icodec->sample_rate;
2222
                codec->channels = icodec->channels;
2223
                codec->frame_size = icodec->frame_size;
2224
                codec->audio_service_type = icodec->audio_service_type;
2225
                codec->block_align= icodec->block_align;
2226
                if(codec->block_align == 1 && codec->codec_id == CODEC_ID_MP3)
2227
                    codec->block_align= 0;
2228
                if(codec->codec_id == CODEC_ID_AC3)
2229
                    codec->block_align= 0;
2230
                break;
2231
            case AVMEDIA_TYPE_VIDEO:
2232
                codec->pix_fmt = icodec->pix_fmt;
2233
                codec->width = icodec->width;
2234
                codec->height = icodec->height;
2235
                codec->has_b_frames = icodec->has_b_frames;
2236
                break;
2237
            case AVMEDIA_TYPE_SUBTITLE:
2238
                codec->width = icodec->width;
2239
                codec->height = icodec->height;
2240
                break;
2241
            default:
2242
                abort();
2243
            }
2244
        } else {
2245
            switch(codec->codec_type) {
2246
            case AVMEDIA_TYPE_AUDIO:
2247
                ost->fifo= av_fifo_alloc(1024);
2248
                if(!ost->fifo)
2249
                    goto fail;
2250
                ost->reformat_pair = MAKE_SFMT_PAIR(AV_SAMPLE_FMT_NONE,AV_SAMPLE_FMT_NONE);
2251
                ost->audio_resample = codec->sample_rate != icodec->sample_rate || audio_sync_method > 1;
2252
                icodec->request_channels = codec->channels;
2253
                ist->decoding_needed = 1;
2254
                ost->encoding_needed = 1;
2255
                ost->resample_sample_fmt  = icodec->sample_fmt;
2256
                ost->resample_sample_rate = icodec->sample_rate;
2257
                ost->resample_channels    = icodec->channels;
2258
                break;
2259
            case AVMEDIA_TYPE_VIDEO:
2260
                if (ost->st->codec->pix_fmt == PIX_FMT_NONE) {
2261
                    fprintf(stderr, "Video pixel format is unknown, stream cannot be encoded\n");
2262
                    ffmpeg_exit(1);
2263
                }
2264
                ost->video_resample = (codec->width != icodec->width   ||
2265
                                       codec->height != icodec->height ||
2266
                        (codec->pix_fmt != icodec->pix_fmt));
2267
                if (ost->video_resample) {
2268
#if !CONFIG_AVFILTER
2269
                    avcodec_get_frame_defaults(&ost->pict_tmp);
2270
                    if(avpicture_alloc((AVPicture*)&ost->pict_tmp, codec->pix_fmt,
2271
                                         codec->width, codec->height)) {
2272
                        fprintf(stderr, "Cannot allocate temp picture, check pix fmt\n");
2273
                        ffmpeg_exit(1);
2274
                    }
2275
                    sws_flags = av_get_int(sws_opts, "sws_flags", NULL);
2276
                    ost->img_resample_ctx = sws_getContext(
2277
                        icodec->width,
2278
                        icodec->height,
2279
                            icodec->pix_fmt,
2280
                            codec->width,
2281
                            codec->height,
2282
                            codec->pix_fmt,
2283
                            sws_flags, NULL, NULL, NULL);
2284
                    if (ost->img_resample_ctx == NULL) {
2285
                        fprintf(stderr, "Cannot get resampling context\n");
2286
                        ffmpeg_exit(1);
2287
                    }
2288

    
2289
                    ost->original_height = icodec->height;
2290
                    ost->original_width  = icodec->width;
2291
#endif
2292
                    codec->bits_per_raw_sample= frame_bits_per_raw_sample;
2293
                }
2294
                ost->resample_height = icodec->height;
2295
                ost->resample_width  = icodec->width;
2296
                ost->resample_pix_fmt= icodec->pix_fmt;
2297
                ost->encoding_needed = 1;
2298
                ist->decoding_needed = 1;
2299

    
2300
#if CONFIG_AVFILTER
2301
                if (configure_filters(ist, ost)) {
2302
                    fprintf(stderr, "Error opening filters!\n");
2303
                    exit(1);
2304
                }
2305
#endif
2306
                break;
2307
            case AVMEDIA_TYPE_SUBTITLE:
2308
                ost->encoding_needed = 1;
2309
                ist->decoding_needed = 1;
2310
                break;
2311
            default:
2312
                abort();
2313
                break;
2314
            }
2315
            /* two pass mode */
2316
            if (ost->encoding_needed &&
2317
                (codec->flags & (CODEC_FLAG_PASS1 | CODEC_FLAG_PASS2))) {
2318
                char logfilename[1024];
2319
                FILE *f;
2320

    
2321
                snprintf(logfilename, sizeof(logfilename), "%s-%d.log",
2322
                         pass_logfilename_prefix ? pass_logfilename_prefix : DEFAULT_PASS_LOGFILENAME_PREFIX,
2323
                         i);
2324
                if (codec->flags & CODEC_FLAG_PASS1) {
2325
                    f = fopen(logfilename, "wb");
2326
                    if (!f) {
2327
                        fprintf(stderr, "Cannot write log file '%s' for pass-1 encoding: %s\n", logfilename, strerror(errno));
2328
                        ffmpeg_exit(1);
2329
                    }
2330
                    ost->logfile = f;
2331
                } else {
2332
                    char  *logbuffer;
2333
                    size_t logbuffer_size;
2334
                    if (read_file(logfilename, &logbuffer, &logbuffer_size) < 0) {
2335
                        fprintf(stderr, "Error reading log file '%s' for pass-2 encoding\n", logfilename);
2336
                        ffmpeg_exit(1);
2337
                    }
2338
                    codec->stats_in = logbuffer;
2339
                }
2340
            }
2341
        }
2342
        if(codec->codec_type == AVMEDIA_TYPE_VIDEO){
2343
            /* maximum video buffer size is 6-bytes per pixel, plus DPX header size */
2344
            int size= codec->width * codec->height;
2345
            bit_buffer_size= FFMAX(bit_buffer_size, 6*size + 1664);
2346
        }
2347
    }
2348

    
2349
    if (!bit_buffer)
2350
        bit_buffer = av_malloc(bit_buffer_size);
2351
    if (!bit_buffer) {
2352
        fprintf(stderr, "Cannot allocate %d bytes output buffer\n",
2353
                bit_buffer_size);
2354
        ret = AVERROR(ENOMEM);
2355
        goto fail;
2356
    }
2357

    
2358
    /* open each encoder */
2359
    for(i=0;i<nb_ostreams;i++) {
2360
        ost = ost_table[i];
2361
        if (ost->encoding_needed) {
2362
            AVCodec *codec = i < nb_output_codecs ? output_codecs[i] : NULL;
2363
            AVCodecContext *dec = ist_table[ost->source_index]->st->codec;
2364
            if (!codec)
2365
                codec = avcodec_find_encoder(ost->st->codec->codec_id);
2366
            if (!codec) {
2367
                snprintf(error, sizeof(error), "Encoder (codec id %d) not found for output stream #%d.%d",
2368
                         ost->st->codec->codec_id, ost->file_index, ost->index);
2369
                ret = AVERROR(EINVAL);
2370
                goto dump_format;
2371
            }
2372
            if (dec->subtitle_header) {
2373
                ost->st->codec->subtitle_header = av_malloc(dec->subtitle_header_size);
2374
                if (!ost->st->codec->subtitle_header) {
2375
                    ret = AVERROR(ENOMEM);
2376
                    goto dump_format;
2377
                }
2378
                memcpy(ost->st->codec->subtitle_header, dec->subtitle_header, dec->subtitle_header_size);
2379
                ost->st->codec->subtitle_header_size = dec->subtitle_header_size;
2380
            }
2381
            if (avcodec_open(ost->st->codec, codec) < 0) {
2382
                snprintf(error, sizeof(error), "Error while opening encoder for output stream #%d.%d - maybe incorrect parameters such as bit_rate, rate, width or height",
2383
                        ost->file_index, ost->index);
2384
                ret = AVERROR(EINVAL);
2385
                goto dump_format;
2386
            }
2387
            extra_size += ost->st->codec->extradata_size;
2388
        }
2389
    }
2390

    
2391
    /* open each decoder */
2392
    for(i=0;i<nb_istreams;i++) {
2393
        ist = ist_table[i];
2394
        if (ist->decoding_needed) {
2395
            AVCodec *codec = i < nb_input_codecs ? input_codecs[i] : NULL;
2396
            if (!codec)
2397
                codec = avcodec_find_decoder(ist->st->codec->codec_id);
2398
            if (!codec) {
2399
                snprintf(error, sizeof(error), "Decoder (codec id %d) not found for input stream #%d.%d",
2400
                        ist->st->codec->codec_id, ist->file_index, ist->index);
2401
                ret = AVERROR(EINVAL);
2402
                goto dump_format;
2403
            }
2404
            if (avcodec_open(ist->st->codec, codec) < 0) {
2405
                snprintf(error, sizeof(error), "Error while opening decoder for input stream #%d.%d",
2406
                        ist->file_index, ist->index);
2407
                ret = AVERROR(EINVAL);
2408
                goto dump_format;
2409
            }
2410
            //if (ist->st->codec->codec_type == AVMEDIA_TYPE_VIDEO)
2411
            //    ist->st->codec->flags |= CODEC_FLAG_REPEAT_FIELD;
2412
        }
2413
    }
2414

    
2415
    /* init pts */
2416
    for(i=0;i<nb_istreams;i++) {
2417
        AVStream *st;
2418
        ist = ist_table[i];
2419
        st= ist->st;
2420
        ist->pts = st->avg_frame_rate.num ? - st->codec->has_b_frames*AV_TIME_BASE / av_q2d(st->avg_frame_rate) : 0;
2421
        ist->next_pts = AV_NOPTS_VALUE;
2422
        ist->is_start = 1;
2423
    }
2424

    
2425
    /* set meta data information from input file if required */
2426
    for (i=0;i<nb_meta_data_maps;i++) {
2427
        AVFormatContext *files[2];
2428
        AVMetadata      **meta[2];
2429
        int j;
2430

    
2431
#define METADATA_CHECK_INDEX(index, nb_elems, desc)\
2432
        if ((index) < 0 || (index) >= (nb_elems)) {\
2433
            snprintf(error, sizeof(error), "Invalid %s index %d while processing metadata maps\n",\
2434
                     (desc), (index));\
2435
            ret = AVERROR(EINVAL);\
2436
            goto dump_format;\
2437
        }
2438

    
2439
        int out_file_index = meta_data_maps[i][0].file;
2440
        int in_file_index = meta_data_maps[i][1].file;
2441
        if (in_file_index < 0 || out_file_index < 0)
2442
            continue;
2443
        METADATA_CHECK_INDEX(out_file_index, nb_output_files, "output file")
2444
        METADATA_CHECK_INDEX(in_file_index, nb_input_files, "input file")
2445

    
2446
        files[0] = output_files[out_file_index];
2447
        files[1] = input_files[in_file_index];
2448

    
2449
        for (j = 0; j < 2; j++) {
2450
            AVMetaDataMap *map = &meta_data_maps[i][j];
2451

    
2452
            switch (map->type) {
2453
            case 'g':
2454
                meta[j] = &files[j]->metadata;
2455
                break;
2456
            case 's':
2457
                METADATA_CHECK_INDEX(map->index, files[j]->nb_streams, "stream")
2458
                meta[j] = &files[j]->streams[map->index]->metadata;
2459
                break;
2460
            case 'c':
2461
                METADATA_CHECK_INDEX(map->index, files[j]->nb_chapters, "chapter")
2462
                meta[j] = &files[j]->chapters[map->index]->metadata;
2463
                break;
2464
            case 'p':
2465
                METADATA_CHECK_INDEX(map->index, files[j]->nb_programs, "program")
2466
                meta[j] = &files[j]->programs[map->index]->metadata;
2467
                break;
2468
            }
2469
        }
2470

    
2471
        av_metadata_copy(meta[0], *meta[1], AV_METADATA_DONT_OVERWRITE);
2472
    }
2473

    
2474
    /* copy global metadata by default */
2475
    if (metadata_global_autocopy) {
2476

    
2477
        for (i = 0; i < nb_output_files; i++)
2478
            av_metadata_copy(&output_files[i]->metadata, input_files[0]->metadata,
2479
                             AV_METADATA_DONT_OVERWRITE);
2480
    }
2481

    
2482
    /* copy chapters according to chapter maps */
2483
    for (i = 0; i < nb_chapter_maps; i++) {
2484
        int infile  = chapter_maps[i].in_file;
2485
        int outfile = chapter_maps[i].out_file;
2486

    
2487
        if (infile < 0 || outfile < 0)
2488
            continue;
2489
        if (infile >= nb_input_files) {
2490
            snprintf(error, sizeof(error), "Invalid input file index %d in chapter mapping.\n", infile);
2491
            ret = AVERROR(EINVAL);
2492
            goto dump_format;
2493
        }
2494
        if (outfile >= nb_output_files) {
2495
            snprintf(error, sizeof(error), "Invalid output file index %d in chapter mapping.\n",outfile);
2496
            ret = AVERROR(EINVAL);
2497
            goto dump_format;
2498
        }
2499
        copy_chapters(infile, outfile);
2500
    }
2501

    
2502
    /* copy chapters from the first input file that has them*/
2503
    if (!nb_chapter_maps)
2504
        for (i = 0; i < nb_input_files; i++) {
2505
            if (!input_files[i]->nb_chapters)
2506
                continue;
2507

    
2508
            for (j = 0; j < nb_output_files; j++)
2509
                if ((ret = copy_chapters(i, j)) < 0)
2510
                    goto dump_format;
2511
            break;
2512
        }
2513

    
2514
    /* open files and write file headers */
2515
    for(i=0;i<nb_output_files;i++) {
2516
        os = output_files[i];
2517
        if (av_write_header(os) < 0) {
2518
            snprintf(error, sizeof(error), "Could not write header for output file #%d (incorrect codec parameters ?)", i);
2519
            ret = AVERROR(EINVAL);
2520
            goto dump_format;
2521
        }
2522
        if (strcmp(output_files[i]->oformat->name, "rtp")) {
2523
            want_sdp = 0;
2524
        }
2525
    }
2526

    
2527
 dump_format:
2528
    /* dump the file output parameters - cannot be done before in case
2529
       of stream copy */
2530
    for(i=0;i<nb_output_files;i++) {
2531
        av_dump_format(output_files[i], i, output_files[i]->filename, 1);
2532
    }
2533

    
2534
    /* dump the stream mapping */
2535
    if (verbose >= 0) {
2536
        fprintf(stderr, "Stream mapping:\n");
2537
        for(i=0;i<nb_ostreams;i++) {
2538
            ost = ost_table[i];
2539
            fprintf(stderr, "  Stream #%d.%d -> #%d.%d",
2540
                    ist_table[ost->source_index]->file_index,
2541
                    ist_table[ost->source_index]->index,
2542
                    ost->file_index,
2543
                    ost->index);
2544
            if (ost->sync_ist != ist_table[ost->source_index])
2545
                fprintf(stderr, " [sync #%d.%d]",
2546
                        ost->sync_ist->file_index,
2547
                        ost->sync_ist->index);
2548
            fprintf(stderr, "\n");
2549
        }
2550
    }
2551

    
2552
    if (ret) {
2553
        fprintf(stderr, "%s\n", error);
2554
        goto fail;
2555
    }
2556

    
2557
    if (want_sdp) {
2558
        print_sdp(output_files, nb_output_files);
2559
    }
2560

    
2561
    if (!using_stdin) {
2562
        if(verbose >= 0)
2563
            fprintf(stderr, "Press [q] to stop encoding\n");
2564
        url_set_interrupt_cb(decode_interrupt_cb);
2565
    }
2566
    term_init();
2567

    
2568
    timer_start = av_gettime();
2569

    
2570
    for(; received_sigterm == 0;) {
2571
        int file_index, ist_index;
2572
        AVPacket pkt;
2573
        double ipts_min;
2574
        double opts_min;
2575

    
2576
    redo:
2577
        ipts_min= 1e100;
2578
        opts_min= 1e100;
2579
        /* if 'q' pressed, exits */
2580
        if (!using_stdin) {
2581
            if (q_pressed)
2582
                break;
2583
            /* read_key() returns 0 on EOF */
2584
            key = read_key();
2585
            if (key == 'q')
2586
                break;
2587
        }
2588

    
2589
        /* select the stream that we must read now by looking at the
2590
           smallest output pts */
2591
        file_index = -1;
2592
        for(i=0;i<nb_ostreams;i++) {
2593
            double ipts, opts;
2594
            ost = ost_table[i];
2595
            os = output_files[ost->file_index];
2596
            ist = ist_table[ost->source_index];
2597
            if(ist->is_past_recording_time || no_packet[ist->file_index])
2598
                continue;
2599
                opts = ost->st->pts.val * av_q2d(ost->st->time_base);
2600
            ipts = (double)ist->pts;
2601
            if (!file_table[ist->file_index].eof_reached){
2602
                if(ipts < ipts_min) {
2603
                    ipts_min = ipts;
2604
                    if(input_sync ) file_index = ist->file_index;
2605
                }
2606
                if(opts < opts_min) {
2607
                    opts_min = opts;
2608
                    if(!input_sync) file_index = ist->file_index;
2609
                }
2610
            }
2611
            if(ost->frame_number >= max_frames[ost->st->codec->codec_type]){
2612
                file_index= -1;
2613
                break;
2614
            }
2615
        }
2616
        /* if none, if is finished */
2617
        if (file_index < 0) {
2618
            if(no_packet_count){
2619
                no_packet_count=0;
2620
                memset(no_packet, 0, sizeof(no_packet));
2621
                usleep(10000);
2622
                continue;
2623
            }
2624
            break;
2625
        }
2626

    
2627
        /* finish if limit size exhausted */
2628
        if (limit_filesize != 0 && limit_filesize <= avio_tell(output_files[0]->pb))
2629
            break;
2630

    
2631
        /* read a frame from it and output it in the fifo */
2632
        is = input_files[file_index];
2633
        ret= av_read_frame(is, &pkt);
2634
        if(ret == AVERROR(EAGAIN)){
2635
            no_packet[file_index]=1;
2636
            no_packet_count++;
2637
            continue;
2638
        }
2639
        if (ret < 0) {
2640
            file_table[file_index].eof_reached = 1;
2641
            if (opt_shortest)
2642
                break;
2643
            else
2644
                continue;
2645
        }
2646

    
2647
        no_packet_count=0;
2648
        memset(no_packet, 0, sizeof(no_packet));
2649

    
2650
        if (do_pkt_dump) {
2651
            av_pkt_dump_log2(NULL, AV_LOG_DEBUG, &pkt, do_hex_dump,
2652
                             is->streams[pkt.stream_index]);
2653
        }
2654
        /* the following test is needed in case new streams appear
2655
           dynamically in stream : we ignore them */
2656
        if (pkt.stream_index >= file_table[file_index].nb_streams)
2657
            goto discard_packet;
2658
        ist_index = file_table[file_index].ist_index + pkt.stream_index;
2659
        ist = ist_table[ist_index];
2660
        if (ist->discard)
2661
            goto discard_packet;
2662

    
2663
        if (pkt.dts != AV_NOPTS_VALUE)
2664
            pkt.dts += av_rescale_q(input_files_ts_offset[ist->file_index], AV_TIME_BASE_Q, ist->st->time_base);
2665
        if (pkt.pts != AV_NOPTS_VALUE)
2666
            pkt.pts += av_rescale_q(input_files_ts_offset[ist->file_index], AV_TIME_BASE_Q, ist->st->time_base);
2667

    
2668
        if (pkt.stream_index < nb_input_files_ts_scale[file_index]
2669
            && input_files_ts_scale[file_index][pkt.stream_index]){
2670
            if(pkt.pts != AV_NOPTS_VALUE)
2671
                pkt.pts *= input_files_ts_scale[file_index][pkt.stream_index];
2672
            if(pkt.dts != AV_NOPTS_VALUE)
2673
                pkt.dts *= input_files_ts_scale[file_index][pkt.stream_index];
2674
        }
2675

    
2676
//        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);
2677
        if (pkt.dts != AV_NOPTS_VALUE && ist->next_pts != AV_NOPTS_VALUE
2678
            && (is->iformat->flags & AVFMT_TS_DISCONT)) {
2679
            int64_t pkt_dts= av_rescale_q(pkt.dts, ist->st->time_base, AV_TIME_BASE_Q);
2680
            int64_t delta= pkt_dts - ist->next_pts;
2681
            if((FFABS(delta) > 1LL*dts_delta_threshold*AV_TIME_BASE || pkt_dts+1<ist->pts)&& !copy_ts){
2682
                input_files_ts_offset[ist->file_index]-= delta;
2683
                if (verbose > 2)
2684
                    fprintf(stderr, "timestamp discontinuity %"PRId64", new offset= %"PRId64"\n", delta, input_files_ts_offset[ist->file_index]);
2685
                pkt.dts-= av_rescale_q(delta, AV_TIME_BASE_Q, ist->st->time_base);
2686
                if(pkt.pts != AV_NOPTS_VALUE)
2687
                    pkt.pts-= av_rescale_q(delta, AV_TIME_BASE_Q, ist->st->time_base);
2688
            }
2689
        }
2690

    
2691
        /* finish if recording time exhausted */
2692
        if (recording_time != INT64_MAX &&
2693
            av_compare_ts(pkt.pts, ist->st->time_base, recording_time + start_time, (AVRational){1, 1000000}) >= 0) {
2694
            ist->is_past_recording_time = 1;
2695
            goto discard_packet;
2696
        }
2697

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

    
2701
            if (verbose >= 0)
2702
                fprintf(stderr, "Error while decoding stream #%d.%d\n",
2703
                        ist->file_index, ist->index);
2704
            if (exit_on_error)
2705
                ffmpeg_exit(1);
2706
            av_free_packet(&pkt);
2707
            goto redo;
2708
        }
2709

    
2710
    discard_packet:
2711
        av_free_packet(&pkt);
2712

    
2713
        /* dump report by using the output first video and audio streams */
2714
        print_report(output_files, ost_table, nb_ostreams, 0);
2715
    }
2716

    
2717
    /* at the end of stream, we must flush the decoder buffers */
2718
    for(i=0;i<nb_istreams;i++) {
2719
        ist = ist_table[i];
2720
        if (ist->decoding_needed) {
2721
            output_packet(ist, i, ost_table, nb_ostreams, NULL);
2722
        }
2723
    }
2724

    
2725
    term_exit();
2726

    
2727
    /* write the trailer if needed and close file */
2728
    for(i=0;i<nb_output_files;i++) {
2729
        os = output_files[i];
2730
        av_write_trailer(os);
2731
    }
2732

    
2733
    /* dump report by using the first video and audio streams */
2734
    print_report(output_files, ost_table, nb_ostreams, 1);
2735

    
2736
    /* close each encoder */
2737
    for(i=0;i<nb_ostreams;i++) {
2738
        ost = ost_table[i];
2739
        if (ost->encoding_needed) {
2740
            av_freep(&ost->st->codec->stats_in);
2741
            avcodec_close(ost->st->codec);
2742
        }
2743
#if CONFIG_AVFILTER
2744
        avfilter_graph_free(&ost->graph);
2745
#endif
2746
    }
2747

    
2748
    /* close each decoder */
2749
    for(i=0;i<nb_istreams;i++) {
2750
        ist = ist_table[i];
2751
        if (ist->decoding_needed) {
2752
            avcodec_close(ist->st->codec);
2753
        }
2754
    }
2755

    
2756
    /* finished ! */
2757
    ret = 0;
2758

    
2759
 fail:
2760
    av_freep(&bit_buffer);
2761
    av_free(file_table);
2762

    
2763
    if (ist_table) {
2764
        for(i=0;i<nb_istreams;i++) {
2765
            ist = ist_table[i];
2766
            av_free(ist);
2767
        }
2768
        av_free(ist_table);
2769
    }
2770
    if (ost_table) {
2771
        for(i=0;i<nb_ostreams;i++) {
2772
            ost = ost_table[i];
2773
            if (ost) {
2774
                if (ost->st->stream_copy)
2775
                    av_freep(&ost->st->codec->extradata);
2776
                if (ost->logfile) {
2777
                    fclose(ost->logfile);
2778
                    ost->logfile = NULL;
2779
                }
2780
                av_fifo_free(ost->fifo); /* works even if fifo is not
2781
                                             initialized but set to zero */
2782
                av_freep(&ost->st->codec->subtitle_header);
2783
                av_free(ost->pict_tmp.data[0]);
2784
                av_free(ost->forced_kf_pts);
2785
                if (ost->video_resample)
2786
                    sws_freeContext(ost->img_resample_ctx);
2787
                if (ost->resample)
2788
                    audio_resample_close(ost->resample);
2789
                if (ost->reformat_ctx)
2790
                    av_audio_convert_free(ost->reformat_ctx);
2791
                av_free(ost);
2792
            }
2793
        }
2794
        av_free(ost_table);
2795
    }
2796
    return ret;
2797
}
2798

    
2799
static void opt_format(const char *arg)
2800
{
2801
    last_asked_format = arg;
2802
}
2803

    
2804
static void opt_video_rc_override_string(const char *arg)
2805
{
2806
    video_rc_override_string = arg;
2807
}
2808

    
2809
static int opt_me_threshold(const char *opt, const char *arg)
2810
{
2811
    me_threshold = parse_number_or_die(opt, arg, OPT_INT64, INT_MIN, INT_MAX);
2812
    return 0;
2813
}
2814

    
2815
static int opt_verbose(const char *opt, const char *arg)
2816
{
2817
    verbose = parse_number_or_die(opt, arg, OPT_INT64, -10, 10);
2818
    return 0;
2819
}
2820

    
2821
static int opt_frame_rate(const char *opt, const char *arg)
2822
{
2823
    if (av_parse_video_rate(&frame_rate, arg) < 0) {
2824
        fprintf(stderr, "Incorrect value for %s: %s\n", opt, arg);
2825
        ffmpeg_exit(1);
2826
    }
2827
    return 0;
2828
}
2829

    
2830
static int opt_bitrate(const char *opt, const char *arg)
2831
{
2832
    int codec_type = opt[0]=='a' ? AVMEDIA_TYPE_AUDIO : AVMEDIA_TYPE_VIDEO;
2833

    
2834
    opt_default(opt, arg);
2835

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

    
2839
    return 0;
2840
}
2841

    
2842
static int opt_frame_crop(const char *opt, const char *arg)
2843
{
2844
    fprintf(stderr, "Option '%s' has been removed, use the crop filter instead\n", opt);
2845
    return AVERROR(EINVAL);
2846
}
2847

    
2848
static void opt_frame_size(const char *arg)
2849
{
2850
    if (av_parse_video_size(&frame_width, &frame_height, arg) < 0) {
2851
        fprintf(stderr, "Incorrect frame size\n");
2852
        ffmpeg_exit(1);
2853
    }
2854
}
2855

    
2856
static int opt_pad(const char *opt, const char *arg) {
2857
    fprintf(stderr, "Option '%s' has been removed, use the pad filter instead\n", opt);
2858
    return -1;
2859
}
2860

    
2861
static void opt_frame_pix_fmt(const char *arg)
2862
{
2863
    if (strcmp(arg, "list")) {
2864
        frame_pix_fmt = av_get_pix_fmt(arg);
2865
        if (frame_pix_fmt == PIX_FMT_NONE) {
2866
            fprintf(stderr, "Unknown pixel format requested: %s\n", arg);
2867
            ffmpeg_exit(1);
2868
        }
2869
    } else {
2870
        show_pix_fmts();
2871
        ffmpeg_exit(0);
2872
    }
2873
}
2874

    
2875
static void opt_frame_aspect_ratio(const char *arg)
2876
{
2877
    int x = 0, y = 0;
2878
    double ar = 0;
2879
    const char *p;
2880
    char *end;
2881

    
2882
    p = strchr(arg, ':');
2883
    if (p) {
2884
        x = strtol(arg, &end, 10);
2885
        if (end == p)
2886
            y = strtol(end+1, &end, 10);
2887
        if (x > 0 && y > 0)
2888
            ar = (double)x / (double)y;
2889
    } else
2890
        ar = strtod(arg, NULL);
2891

    
2892
    if (!ar) {
2893
        fprintf(stderr, "Incorrect aspect ratio specification.\n");
2894
        ffmpeg_exit(1);
2895
    }
2896
    frame_aspect_ratio = ar;
2897
    frame_aspect_ratio_override = 1;
2898
}
2899

    
2900
static int opt_metadata(const char *opt, const char *arg)
2901
{
2902
    char *mid= strchr(arg, '=');
2903

    
2904
    if(!mid){
2905
        fprintf(stderr, "Missing =\n");
2906
        ffmpeg_exit(1);
2907
    }
2908
    *mid++= 0;
2909

    
2910
    av_metadata_set2(&metadata, arg, mid, 0);
2911

    
2912
    return 0;
2913
}
2914

    
2915
static void opt_qscale(const char *arg)
2916
{
2917
    video_qscale = atof(arg);
2918
    if (video_qscale <= 0 ||
2919
        video_qscale > 255) {
2920
        fprintf(stderr, "qscale must be > 0.0 and <= 255\n");
2921
        ffmpeg_exit(1);
2922
    }
2923
}
2924

    
2925
static void opt_top_field_first(const char *arg)
2926
{
2927
    top_field_first= atoi(arg);
2928
}
2929

    
2930
static int opt_thread_count(const char *opt, const char *arg)
2931
{
2932
    thread_count= parse_number_or_die(opt, arg, OPT_INT64, 0, INT_MAX);
2933
#if !HAVE_THREADS
2934
    if (verbose >= 0)
2935
        fprintf(stderr, "Warning: not compiled with thread support, using thread emulation\n");
2936
#endif
2937
    return 0;
2938
}
2939

    
2940
static void opt_audio_sample_fmt(const char *arg)
2941
{
2942
    if (strcmp(arg, "list")) {
2943
        audio_sample_fmt = av_get_sample_fmt(arg);
2944
        if (audio_sample_fmt == AV_SAMPLE_FMT_NONE) {
2945
            av_log(NULL, AV_LOG_ERROR, "Invalid sample format '%s'\n", arg);
2946
            ffmpeg_exit(1);
2947
        }
2948
    } else {
2949
        int i;
2950
        char fmt_str[128];
2951
        for (i = -1; i < AV_SAMPLE_FMT_NB; i++)
2952
            printf("%s\n", av_get_sample_fmt_string(fmt_str, sizeof(fmt_str), i));
2953
        ffmpeg_exit(0);
2954
    }
2955
}
2956

    
2957
static int opt_audio_rate(const char *opt, const char *arg)
2958
{
2959
    audio_sample_rate = parse_number_or_die(opt, arg, OPT_INT64, 0, INT_MAX);
2960
    return 0;
2961
}
2962

    
2963
static int opt_audio_channels(const char *opt, const char *arg)
2964
{
2965
    audio_channels = parse_number_or_die(opt, arg, OPT_INT64, 0, INT_MAX);
2966
    return 0;
2967
}
2968

    
2969
static void opt_video_channel(const char *arg)
2970
{
2971
    video_channel = strtol(arg, NULL, 0);
2972
}
2973

    
2974
static void opt_video_standard(const char *arg)
2975
{
2976
    video_standard = av_strdup(arg);
2977
}
2978

    
2979
static void opt_codec(int *pstream_copy, char **pcodec_name,
2980
                      int codec_type, const char *arg)
2981
{
2982
    av_freep(pcodec_name);
2983
    if (!strcmp(arg, "copy")) {
2984
        *pstream_copy = 1;
2985
    } else {
2986
        *pcodec_name = av_strdup(arg);
2987
    }
2988
}
2989

    
2990
static void opt_audio_codec(const char *arg)
2991
{
2992
    opt_codec(&audio_stream_copy, &audio_codec_name, AVMEDIA_TYPE_AUDIO, arg);
2993
}
2994

    
2995
static void opt_video_codec(const char *arg)
2996
{
2997
    opt_codec(&video_stream_copy, &video_codec_name, AVMEDIA_TYPE_VIDEO, arg);
2998
}
2999

    
3000
static void opt_subtitle_codec(const char *arg)
3001
{
3002
    opt_codec(&subtitle_stream_copy, &subtitle_codec_name, AVMEDIA_TYPE_SUBTITLE, arg);
3003
}
3004

    
3005
static int opt_codec_tag(const char *opt, const char *arg)
3006
{
3007
    char *tail;
3008
    uint32_t *codec_tag;
3009

    
3010
    codec_tag = !strcmp(opt, "atag") ? &audio_codec_tag :
3011
                !strcmp(opt, "vtag") ? &video_codec_tag :
3012
                !strcmp(opt, "stag") ? &subtitle_codec_tag : NULL;
3013
    if (!codec_tag)
3014
        return -1;
3015

    
3016
    *codec_tag = strtol(arg, &tail, 0);
3017
    if (!tail || *tail)
3018
        *codec_tag = AV_RL32(arg);
3019

    
3020
    return 0;
3021
}
3022

    
3023
static void opt_map(const char *arg)
3024
{
3025
    AVStreamMap *m;
3026
    char *p;
3027

    
3028
    stream_maps = grow_array(stream_maps, sizeof(*stream_maps), &nb_stream_maps, nb_stream_maps + 1);
3029
    m = &stream_maps[nb_stream_maps-1];
3030

    
3031
    m->file_index = strtol(arg, &p, 0);
3032
    if (*p)
3033
        p++;
3034

    
3035
    m->stream_index = strtol(p, &p, 0);
3036
    if (*p) {
3037
        p++;
3038
        m->sync_file_index = strtol(p, &p, 0);
3039
        if (*p)
3040
            p++;
3041
        m->sync_stream_index = strtol(p, &p, 0);
3042
    } else {
3043
        m->sync_file_index = m->file_index;
3044
        m->sync_stream_index = m->stream_index;
3045
    }
3046
}
3047

    
3048
static void parse_meta_type(char *arg, char *type, int *index, char **endptr)
3049
{
3050
    *endptr = arg;
3051
    if (*arg == ',') {
3052
        *type = *(++arg);
3053
        switch (*arg) {
3054
        case 'g':
3055
            break;
3056
        case 's':
3057
        case 'c':
3058
        case 'p':
3059
            *index = strtol(++arg, endptr, 0);
3060
            break;
3061
        default:
3062
            fprintf(stderr, "Invalid metadata type %c.\n", *arg);
3063
            ffmpeg_exit(1);
3064
        }
3065
    } else
3066
        *type = 'g';
3067
}
3068

    
3069
static void opt_map_metadata(const char *arg)
3070
{
3071
    AVMetaDataMap *m, *m1;
3072
    char *p;
3073

    
3074
    meta_data_maps = grow_array(meta_data_maps, sizeof(*meta_data_maps),
3075
                                &nb_meta_data_maps, nb_meta_data_maps + 1);
3076

    
3077
    m = &meta_data_maps[nb_meta_data_maps - 1][0];
3078
    m->file = strtol(arg, &p, 0);
3079
    parse_meta_type(p, &m->type, &m->index, &p);
3080
    if (*p)
3081
        p++;
3082

    
3083
    m1 = &meta_data_maps[nb_meta_data_maps - 1][1];
3084
    m1->file = strtol(p, &p, 0);
3085
    parse_meta_type(p, &m1->type, &m1->index, &p);
3086

    
3087
    if (m->type == 'g' || m1->type == 'g')
3088
        metadata_global_autocopy = 0;
3089
    if (m->type == 's' || m1->type == 's')
3090
        metadata_streams_autocopy = 0;
3091
    if (m->type == 'c' || m1->type == 'c')
3092
        metadata_chapters_autocopy = 0;
3093
}
3094

    
3095
static void opt_map_meta_data(const char *arg)
3096
{
3097
    fprintf(stderr, "-map_meta_data is deprecated and will be removed soon. "
3098
                    "Use -map_metadata instead.\n");
3099
    opt_map_metadata(arg);
3100
}
3101

    
3102
static void opt_map_chapters(const char *arg)
3103
{
3104
    AVChapterMap *c;
3105
    char *p;
3106

    
3107
    chapter_maps = grow_array(chapter_maps, sizeof(*chapter_maps), &nb_chapter_maps,
3108
                              nb_chapter_maps + 1);
3109
    c = &chapter_maps[nb_chapter_maps - 1];
3110
    c->out_file = strtol(arg, &p, 0);
3111
    if (*p)
3112
        p++;
3113

    
3114
    c->in_file = strtol(p, &p, 0);
3115
}
3116

    
3117
static void opt_input_ts_scale(const char *arg)
3118
{
3119
    unsigned int stream;
3120
    double scale;
3121
    char *p;
3122

    
3123
    stream = strtol(arg, &p, 0);
3124
    if (*p)
3125
        p++;
3126
    scale= strtod(p, &p);
3127

    
3128
    if(stream >= MAX_STREAMS)
3129
        ffmpeg_exit(1);
3130

    
3131
    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);
3132
    input_files_ts_scale[nb_input_files][stream]= scale;
3133
}
3134

    
3135
static int opt_recording_time(const char *opt, const char *arg)
3136
{
3137
    recording_time = parse_time_or_die(opt, arg, 1);
3138
    return 0;
3139
}
3140

    
3141
static int opt_start_time(const char *opt, const char *arg)
3142
{
3143
    start_time = parse_time_or_die(opt, arg, 1);
3144
    return 0;
3145
}
3146

    
3147
static int opt_recording_timestamp(const char *opt, const char *arg)
3148
{
3149
    recording_timestamp = parse_time_or_die(opt, arg, 0) / 1000000;
3150
    return 0;
3151
}
3152

    
3153
static int opt_input_ts_offset(const char *opt, const char *arg)
3154
{
3155
    input_ts_offset = parse_time_or_die(opt, arg, 1);
3156
    return 0;
3157
}
3158

    
3159
static enum CodecID find_codec_or_die(const char *name, int type, int encoder, int strict)
3160
{
3161
    const char *codec_string = encoder ? "encoder" : "decoder";
3162
    AVCodec *codec;
3163

    
3164
    if(!name)
3165
        return CODEC_ID_NONE;
3166
    codec = encoder ?
3167
        avcodec_find_encoder_by_name(name) :
3168
        avcodec_find_decoder_by_name(name);
3169
    if(!codec) {
3170
        fprintf(stderr, "Unknown %s '%s'\n", codec_string, name);
3171
        ffmpeg_exit(1);
3172
    }
3173
    if(codec->type != type) {
3174
        fprintf(stderr, "Invalid %s type '%s'\n", codec_string, name);
3175
        ffmpeg_exit(1);
3176
    }
3177
    if(codec->capabilities & CODEC_CAP_EXPERIMENTAL &&
3178
       strict > FF_COMPLIANCE_EXPERIMENTAL) {
3179
        fprintf(stderr, "%s '%s' is experimental and might produce bad "
3180
                "results.\nAdd '-strict experimental' if you want to use it.\n",
3181
                codec_string, codec->name);
3182
        codec = encoder ?
3183
            avcodec_find_encoder(codec->id) :
3184
            avcodec_find_decoder(codec->id);
3185
        if (!(codec->capabilities & CODEC_CAP_EXPERIMENTAL))
3186
            fprintf(stderr, "Or use the non experimental %s '%s'.\n",
3187
                    codec_string, codec->name);
3188
        ffmpeg_exit(1);
3189
    }
3190
    return codec->id;
3191
}
3192

    
3193
static void opt_input_file(const char *filename)
3194
{
3195
    AVFormatContext *ic;
3196
    AVFormatParameters params, *ap = &params;
3197
    AVInputFormat *file_iformat = NULL;
3198
    int err, i, ret, rfps, rfps_base;
3199
    int64_t timestamp;
3200

    
3201
    if (last_asked_format) {
3202
        if (!(file_iformat = av_find_input_format(last_asked_format))) {
3203
            fprintf(stderr, "Unknown input format: '%s'\n", last_asked_format);
3204
            ffmpeg_exit(1);
3205
        }
3206
        last_asked_format = NULL;
3207
    }
3208

    
3209
    if (!strcmp(filename, "-"))
3210
        filename = "pipe:";
3211

    
3212
    using_stdin |= !strncmp(filename, "pipe:", 5) ||
3213
                    !strcmp(filename, "/dev/stdin");
3214

    
3215
    /* get default parameters from command line */
3216
    ic = avformat_alloc_context();
3217
    if (!ic) {
3218
        print_error(filename, AVERROR(ENOMEM));
3219
        ffmpeg_exit(1);
3220
    }
3221

    
3222
    memset(ap, 0, sizeof(*ap));
3223
    ap->prealloced_context = 1;
3224
    ap->sample_rate = audio_sample_rate;
3225
    ap->channels = audio_channels;
3226
    ap->time_base.den = frame_rate.num;
3227
    ap->time_base.num = frame_rate.den;
3228
    ap->width = frame_width;
3229
    ap->height = frame_height;
3230
    ap->pix_fmt = frame_pix_fmt;
3231
   // ap->sample_fmt = audio_sample_fmt; //FIXME:not implemented in libavformat
3232
    ap->channel = video_channel;
3233
    ap->standard = video_standard;
3234

    
3235
    set_context_opts(ic, avformat_opts, AV_OPT_FLAG_DECODING_PARAM, NULL);
3236

    
3237
    ic->video_codec_id   =
3238
        find_codec_or_die(video_codec_name   , AVMEDIA_TYPE_VIDEO   , 0,
3239
                          avcodec_opts[AVMEDIA_TYPE_VIDEO   ]->strict_std_compliance);
3240
    ic->audio_codec_id   =
3241
        find_codec_or_die(audio_codec_name   , AVMEDIA_TYPE_AUDIO   , 0,
3242
                          avcodec_opts[AVMEDIA_TYPE_AUDIO   ]->strict_std_compliance);
3243
    ic->subtitle_codec_id=
3244
        find_codec_or_die(subtitle_codec_name, AVMEDIA_TYPE_SUBTITLE, 0,
3245
                          avcodec_opts[AVMEDIA_TYPE_SUBTITLE]->strict_std_compliance);
3246
    ic->flags |= AVFMT_FLAG_NONBLOCK;
3247

    
3248
    /* open the input file with generic libav function */
3249
    err = av_open_input_file(&ic, filename, file_iformat, 0, ap);
3250
    if (err < 0) {
3251
        print_error(filename, err);
3252
        ffmpeg_exit(1);
3253
    }
3254
    if(opt_programid) {
3255
        int i, j;
3256
        int found=0;
3257
        for(i=0; i<ic->nb_streams; i++){
3258
            ic->streams[i]->discard= AVDISCARD_ALL;
3259
        }
3260
        for(i=0; i<ic->nb_programs; i++){
3261
            AVProgram *p= ic->programs[i];
3262
            if(p->id != opt_programid){
3263
                p->discard = AVDISCARD_ALL;
3264
            }else{
3265
                found=1;
3266
                for(j=0; j<p->nb_stream_indexes; j++){
3267
                    ic->streams[p->stream_index[j]]->discard= AVDISCARD_DEFAULT;
3268
                }
3269
            }
3270
        }
3271
        if(!found){
3272
            fprintf(stderr, "Specified program id not found\n");
3273
            ffmpeg_exit(1);
3274
        }
3275
        opt_programid=0;
3276
    }
3277

    
3278
    ic->loop_input = loop_input;
3279

    
3280
    /* If not enough info to get the stream parameters, we decode the
3281
       first frames to get it. (used in mpeg case for example) */
3282
    ret = av_find_stream_info(ic);
3283
    if (ret < 0 && verbose >= 0) {
3284
        fprintf(stderr, "%s: could not find codec parameters\n", filename);
3285
        av_close_input_file(ic);
3286
        ffmpeg_exit(1);
3287
    }
3288

    
3289
    timestamp = start_time;
3290
    /* add the stream start time */
3291
    if (ic->start_time != AV_NOPTS_VALUE)
3292
        timestamp += ic->start_time;
3293

    
3294
    /* if seeking requested, we execute it */
3295
    if (start_time != 0) {
3296
        ret = av_seek_frame(ic, -1, timestamp, AVSEEK_FLAG_BACKWARD);
3297
        if (ret < 0) {
3298
            fprintf(stderr, "%s: could not seek to position %0.3f\n",
3299
                    filename, (double)timestamp / AV_TIME_BASE);
3300
        }
3301
        /* reset seek info */
3302
        start_time = 0;
3303
    }
3304

    
3305
    /* update the current parameters so that they match the one of the input stream */
3306
    for(i=0;i<ic->nb_streams;i++) {
3307
        AVStream *st = ic->streams[i];
3308
        AVCodecContext *dec = st->codec;
3309
        dec->thread_count = thread_count;
3310
        input_codecs = grow_array(input_codecs, sizeof(*input_codecs), &nb_input_codecs, nb_input_codecs + 1);
3311
        switch (dec->codec_type) {
3312
        case AVMEDIA_TYPE_AUDIO:
3313
            input_codecs[nb_input_codecs-1] = avcodec_find_decoder_by_name(audio_codec_name);
3314
            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]);
3315
            //fprintf(stderr, "\nInput Audio channels: %d", dec->channels);
3316
            channel_layout    = dec->channel_layout;
3317
            audio_channels    = dec->channels;
3318
            audio_sample_rate = dec->sample_rate;
3319
            audio_sample_fmt  = dec->sample_fmt;
3320
            if(audio_disable)
3321
                st->discard= AVDISCARD_ALL;
3322
            /* Note that av_find_stream_info can add more streams, and we
3323
             * currently have no chance of setting up lowres decoding
3324
             * early enough for them. */
3325
            if (dec->lowres)
3326
                audio_sample_rate >>= dec->lowres;
3327
            break;
3328
        case AVMEDIA_TYPE_VIDEO:
3329
            input_codecs[nb_input_codecs-1] = avcodec_find_decoder_by_name(video_codec_name);
3330
            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]);
3331
            frame_height = dec->height;
3332
            frame_width  = dec->width;
3333
            if(ic->streams[i]->sample_aspect_ratio.num)
3334
                frame_aspect_ratio=av_q2d(ic->streams[i]->sample_aspect_ratio);
3335
            else
3336
                frame_aspect_ratio=av_q2d(dec->sample_aspect_ratio);
3337
            frame_aspect_ratio *= (float) dec->width / dec->height;
3338
            frame_aspect_ratio_override = 0;
3339
            frame_pix_fmt = dec->pix_fmt;
3340
            rfps      = ic->streams[i]->r_frame_rate.num;
3341
            rfps_base = ic->streams[i]->r_frame_rate.den;
3342
            if (dec->lowres) {
3343
                dec->flags |= CODEC_FLAG_EMU_EDGE;
3344
                frame_height >>= dec->lowres;
3345
                frame_width  >>= dec->lowres;
3346
                dec->height = frame_height;
3347
                dec->width  = frame_width;
3348
            }
3349
            if(me_threshold)
3350
                dec->debug |= FF_DEBUG_MV;
3351

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

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

    
3358
                    (float)rfps / rfps_base, rfps, rfps_base);
3359
            }
3360
            /* update the current frame rate to match the stream frame rate */
3361
            frame_rate.num = rfps;
3362
            frame_rate.den = rfps_base;
3363

    
3364
            if(video_disable)
3365
                st->discard= AVDISCARD_ALL;
3366
            else if(video_discard)
3367
                st->discard= video_discard;
3368
            break;
3369
        case AVMEDIA_TYPE_DATA:
3370
            break;
3371
        case AVMEDIA_TYPE_SUBTITLE:
3372
            input_codecs[nb_input_codecs-1] = avcodec_find_decoder_by_name(subtitle_codec_name);
3373
            if(subtitle_disable)
3374
                st->discard = AVDISCARD_ALL;
3375
            break;
3376
        case AVMEDIA_TYPE_ATTACHMENT:
3377
        case AVMEDIA_TYPE_UNKNOWN:
3378
            break;
3379
        default:
3380
            abort();
3381
        }
3382
    }
3383

    
3384
    input_files[nb_input_files] = ic;
3385
    input_files_ts_offset[nb_input_files] = input_ts_offset - (copy_ts ? 0 : timestamp);
3386
    /* dump the file content */
3387
    if (verbose >= 0)
3388
        av_dump_format(ic, nb_input_files, filename, 0);
3389

    
3390
    nb_input_files++;
3391

    
3392
    video_channel = 0;
3393

    
3394
    av_freep(&video_codec_name);
3395
    av_freep(&audio_codec_name);
3396
    av_freep(&subtitle_codec_name);
3397
}
3398

    
3399
static void check_audio_video_sub_inputs(int *has_video_ptr, int *has_audio_ptr,
3400
                                         int *has_subtitle_ptr)
3401
{
3402
    int has_video, has_audio, has_subtitle, i, j;
3403
    AVFormatContext *ic;
3404

    
3405
    has_video = 0;
3406
    has_audio = 0;
3407
    has_subtitle = 0;
3408
    for(j=0;j<nb_input_files;j++) {
3409
        ic = input_files[j];
3410
        for(i=0;i<ic->nb_streams;i++) {
3411
            AVCodecContext *enc = ic->streams[i]->codec;
3412
            switch(enc->codec_type) {
3413
            case AVMEDIA_TYPE_AUDIO:
3414
                has_audio = 1;
3415
                break;
3416
            case AVMEDIA_TYPE_VIDEO:
3417
                has_video = 1;
3418
                break;
3419
            case AVMEDIA_TYPE_SUBTITLE:
3420
                has_subtitle = 1;
3421
                break;
3422
            case AVMEDIA_TYPE_DATA:
3423
            case AVMEDIA_TYPE_ATTACHMENT:
3424
            case AVMEDIA_TYPE_UNKNOWN:
3425
                break;
3426
            default:
3427
                abort();
3428
            }
3429
        }
3430
    }
3431
    *has_video_ptr = has_video;
3432
    *has_audio_ptr = has_audio;
3433
    *has_subtitle_ptr = has_subtitle;
3434
}
3435

    
3436
static void new_video_stream(AVFormatContext *oc, int file_idx)
3437
{
3438
    AVStream *st;
3439
    AVOutputStream *ost;
3440
    AVCodecContext *video_enc;
3441
    enum CodecID codec_id = CODEC_ID_NONE;
3442
    AVCodec *codec= NULL;
3443
    int i;
3444

    
3445
    st = av_new_stream(oc, oc->nb_streams < nb_streamid_map ? streamid_map[oc->nb_streams] : 0);
3446
    if (!st) {
3447
        fprintf(stderr, "Could not alloc stream\n");
3448
        ffmpeg_exit(1);
3449
    }
3450
    ost = new_output_stream(oc, file_idx);
3451

    
3452
    output_codecs = grow_array(output_codecs, sizeof(*output_codecs), &nb_output_codecs, nb_output_codecs + 1);
3453
    if(!video_stream_copy){
3454
        if (video_codec_name) {
3455
            codec_id = find_codec_or_die(video_codec_name, AVMEDIA_TYPE_VIDEO, 1,
3456
                                         avcodec_opts[AVMEDIA_TYPE_VIDEO]->strict_std_compliance);
3457
            codec = avcodec_find_encoder_by_name(video_codec_name);
3458
            output_codecs[nb_output_codecs-1] = codec;
3459
        } else {
3460
            codec_id = av_guess_codec(oc->oformat, NULL, oc->filename, NULL, AVMEDIA_TYPE_VIDEO);
3461
            codec = avcodec_find_encoder(codec_id);
3462
        }
3463
#if CONFIG_AVFILTER
3464
        if(frame_aspect_ratio_override){
3465
            i = vfilters ? strlen(vfilters) : 0;
3466
            vfilters = av_realloc(vfilters, i+100);
3467
            snprintf(vfilters+i, 100, "%csetdar=%f\n", i?',':' ', frame_aspect_ratio);
3468
            frame_aspect_ratio=0;
3469
            frame_aspect_ratio_override=0;
3470
        }
3471

    
3472
        ost->avfilter= vfilters;
3473
        vfilters= NULL;
3474
#endif
3475
    }
3476

    
3477
    avcodec_get_context_defaults3(st->codec, codec);
3478
    ost->bitstream_filters = video_bitstream_filters;
3479
    video_bitstream_filters= NULL;
3480

    
3481
    st->codec->thread_count= thread_count;
3482

    
3483
    video_enc = st->codec;
3484

    
3485
    if(video_codec_tag)
3486
        video_enc->codec_tag= video_codec_tag;
3487

    
3488
    if(   (video_global_header&1)
3489
       || (video_global_header==0 && (oc->oformat->flags & AVFMT_GLOBALHEADER))){
3490
        video_enc->flags |= CODEC_FLAG_GLOBAL_HEADER;
3491
        avcodec_opts[AVMEDIA_TYPE_VIDEO]->flags|= CODEC_FLAG_GLOBAL_HEADER;
3492
    }
3493
    if(video_global_header&2){
3494
        video_enc->flags2 |= CODEC_FLAG2_LOCAL_HEADER;
3495
        avcodec_opts[AVMEDIA_TYPE_VIDEO]->flags2|= CODEC_FLAG2_LOCAL_HEADER;
3496
    }
3497

    
3498
    if (video_stream_copy) {
3499
        st->stream_copy = 1;
3500
        video_enc->codec_type = AVMEDIA_TYPE_VIDEO;
3501
        video_enc->sample_aspect_ratio =
3502
        st->sample_aspect_ratio = av_d2q(frame_aspect_ratio*frame_height/frame_width, 255);
3503
    } else {
3504
        const char *p;
3505
        int i;
3506
        AVRational fps= frame_rate.num ? frame_rate : (AVRational){25,1};
3507

    
3508
        video_enc->codec_id = codec_id;
3509
        set_context_opts(video_enc, avcodec_opts[AVMEDIA_TYPE_VIDEO], AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_ENCODING_PARAM, codec);
3510

    
3511
        if (codec && codec->supported_framerates && !force_fps)
3512
            fps = codec->supported_framerates[av_find_nearest_q_idx(fps, codec->supported_framerates)];
3513
        video_enc->time_base.den = fps.num;
3514
        video_enc->time_base.num = fps.den;
3515

    
3516
        video_enc->width = frame_width;
3517
        video_enc->height = frame_height;
3518
        video_enc->sample_aspect_ratio = av_d2q(frame_aspect_ratio*video_enc->height/video_enc->width, 255);
3519
        video_enc->pix_fmt = frame_pix_fmt;
3520
        video_enc->bits_per_raw_sample = frame_bits_per_raw_sample;
3521
        st->sample_aspect_ratio = video_enc->sample_aspect_ratio;
3522

    
3523
        choose_pixel_fmt(st, codec);
3524

    
3525
        if (intra_only)
3526
            video_enc->gop_size = 0;
3527
        if (video_qscale || same_quality) {
3528
            video_enc->flags |= CODEC_FLAG_QSCALE;
3529
            video_enc->global_quality=
3530
                st->quality = FF_QP2LAMBDA * video_qscale;
3531
        }
3532

    
3533
        if(intra_matrix)
3534
            video_enc->intra_matrix = intra_matrix;
3535
        if(inter_matrix)
3536
            video_enc->inter_matrix = inter_matrix;
3537

    
3538
        p= video_rc_override_string;
3539
        for(i=0; p; i++){
3540
            int start, end, q;
3541
            int e=sscanf(p, "%d,%d,%d", &start, &end, &q);
3542
            if(e!=3){
3543
                fprintf(stderr, "error parsing rc_override\n");
3544
                ffmpeg_exit(1);
3545
            }
3546
            video_enc->rc_override=
3547
                av_realloc(video_enc->rc_override,
3548
                           sizeof(RcOverride)*(i+1));
3549
            video_enc->rc_override[i].start_frame= start;
3550
            video_enc->rc_override[i].end_frame  = end;
3551
            if(q>0){
3552
                video_enc->rc_override[i].qscale= q;
3553
                video_enc->rc_override[i].quality_factor= 1.0;
3554
            }
3555
            else{
3556
                video_enc->rc_override[i].qscale= 0;
3557
                video_enc->rc_override[i].quality_factor= -q/100.0;
3558
            }
3559
            p= strchr(p, '/');
3560
            if(p) p++;
3561
        }
3562
        video_enc->rc_override_count=i;
3563
        if (!video_enc->rc_initial_buffer_occupancy)
3564
            video_enc->rc_initial_buffer_occupancy = video_enc->rc_buffer_size*3/4;
3565
        video_enc->me_threshold= me_threshold;
3566
        video_enc->intra_dc_precision= intra_dc_precision - 8;
3567

    
3568
        if (do_psnr)
3569
            video_enc->flags|= CODEC_FLAG_PSNR;
3570

    
3571
        /* two pass mode */
3572
        if (do_pass) {
3573
            if (do_pass == 1) {
3574
                video_enc->flags |= CODEC_FLAG_PASS1;
3575
            } else {
3576
                video_enc->flags |= CODEC_FLAG_PASS2;
3577
            }
3578
        }
3579

    
3580
        if (forced_key_frames)
3581
            parse_forced_key_frames(forced_key_frames, ost, video_enc);
3582
    }
3583
    if (video_language) {
3584
        av_metadata_set2(&st->metadata, "language", video_language, 0);
3585
        av_freep(&video_language);
3586
    }
3587

    
3588
    /* reset some key parameters */
3589
    video_disable = 0;
3590
    av_freep(&video_codec_name);
3591
    av_freep(&forced_key_frames);
3592
    video_stream_copy = 0;
3593
    frame_pix_fmt = PIX_FMT_NONE;
3594
}
3595

    
3596
static void new_audio_stream(AVFormatContext *oc, int file_idx)
3597
{
3598
    AVStream *st;
3599
    AVOutputStream *ost;
3600
    AVCodec *codec= NULL;
3601
    AVCodecContext *audio_enc;
3602
    enum CodecID codec_id = CODEC_ID_NONE;
3603

    
3604
    st = av_new_stream(oc, oc->nb_streams < nb_streamid_map ? streamid_map[oc->nb_streams] : 0);
3605
    if (!st) {
3606
        fprintf(stderr, "Could not alloc stream\n");
3607
        ffmpeg_exit(1);
3608
    }
3609
    ost = new_output_stream(oc, file_idx);
3610

    
3611
    output_codecs = grow_array(output_codecs, sizeof(*output_codecs), &nb_output_codecs, nb_output_codecs + 1);
3612
    if(!audio_stream_copy){
3613
        if (audio_codec_name) {
3614
            codec_id = find_codec_or_die(audio_codec_name, AVMEDIA_TYPE_AUDIO, 1,
3615
                                         avcodec_opts[AVMEDIA_TYPE_AUDIO]->strict_std_compliance);
3616
            codec = avcodec_find_encoder_by_name(audio_codec_name);
3617
            output_codecs[nb_output_codecs-1] = codec;
3618
        } else {
3619
            codec_id = av_guess_codec(oc->oformat, NULL, oc->filename, NULL, AVMEDIA_TYPE_AUDIO);
3620
            codec = avcodec_find_encoder(codec_id);
3621
        }
3622
    }
3623

    
3624
    avcodec_get_context_defaults3(st->codec, codec);
3625

    
3626
    ost->bitstream_filters = audio_bitstream_filters;
3627
    audio_bitstream_filters= NULL;
3628

    
3629
    st->codec->thread_count= thread_count;
3630

    
3631
    audio_enc = st->codec;
3632
    audio_enc->codec_type = AVMEDIA_TYPE_AUDIO;
3633

    
3634
    if(audio_codec_tag)
3635
        audio_enc->codec_tag= audio_codec_tag;
3636

    
3637
    if (oc->oformat->flags & AVFMT_GLOBALHEADER) {
3638
        audio_enc->flags |= CODEC_FLAG_GLOBAL_HEADER;
3639
        avcodec_opts[AVMEDIA_TYPE_AUDIO]->flags|= CODEC_FLAG_GLOBAL_HEADER;
3640
    }
3641
    if (audio_stream_copy) {
3642
        st->stream_copy = 1;
3643
        audio_enc->channels = audio_channels;
3644
        audio_enc->sample_rate = audio_sample_rate;
3645
    } else {
3646
        audio_enc->codec_id = codec_id;
3647
        set_context_opts(audio_enc, avcodec_opts[AVMEDIA_TYPE_AUDIO], AV_OPT_FLAG_AUDIO_PARAM | AV_OPT_FLAG_ENCODING_PARAM, codec);
3648

    
3649
        if (audio_qscale > QSCALE_NONE) {
3650
            audio_enc->flags |= CODEC_FLAG_QSCALE;
3651
            audio_enc->global_quality = st->quality = FF_QP2LAMBDA * audio_qscale;
3652
        }
3653
        audio_enc->channels = audio_channels;
3654
        audio_enc->sample_fmt = audio_sample_fmt;
3655
        audio_enc->sample_rate = audio_sample_rate;
3656
        audio_enc->channel_layout = channel_layout;
3657
        if (av_get_channel_layout_nb_channels(channel_layout) != audio_channels)
3658
            audio_enc->channel_layout = 0;
3659
        choose_sample_fmt(st, codec);
3660
        choose_sample_rate(st, codec);
3661
    }
3662
    audio_enc->time_base= (AVRational){1, audio_sample_rate};
3663
    if (audio_language) {
3664
        av_metadata_set2(&st->metadata, "language", audio_language, 0);
3665
        av_freep(&audio_language);
3666
    }
3667

    
3668
    /* reset some key parameters */
3669
    audio_disable = 0;
3670
    av_freep(&audio_codec_name);
3671
    audio_stream_copy = 0;
3672
}
3673

    
3674
static void new_subtitle_stream(AVFormatContext *oc, int file_idx)
3675
{
3676
    AVStream *st;
3677
    AVOutputStream *ost;
3678
    AVCodec *codec=NULL;
3679
    AVCodecContext *subtitle_enc;
3680
    enum CodecID codec_id = CODEC_ID_NONE;
3681

    
3682
    st = av_new_stream(oc, oc->nb_streams < nb_streamid_map ? streamid_map[oc->nb_streams] : 0);
3683
    if (!st) {
3684
        fprintf(stderr, "Could not alloc stream\n");
3685
        ffmpeg_exit(1);
3686
    }
3687
    ost = new_output_stream(oc, file_idx);
3688
    subtitle_enc = st->codec;
3689
    output_codecs = grow_array(output_codecs, sizeof(*output_codecs), &nb_output_codecs, nb_output_codecs + 1);
3690
    if(!subtitle_stream_copy){
3691
        if (subtitle_codec_name) {
3692
            codec_id = find_codec_or_die(subtitle_codec_name, AVMEDIA_TYPE_SUBTITLE, 1,
3693
                                         avcodec_opts[AVMEDIA_TYPE_SUBTITLE]->strict_std_compliance);
3694
            codec= output_codecs[nb_output_codecs-1] = avcodec_find_encoder_by_name(subtitle_codec_name);
3695
        } else {
3696
            codec_id = av_guess_codec(oc->oformat, NULL, oc->filename, NULL, AVMEDIA_TYPE_SUBTITLE);
3697
            codec = avcodec_find_encoder(codec_id);
3698
        }
3699
    }
3700
    avcodec_get_context_defaults3(st->codec, codec);
3701

    
3702
    ost->bitstream_filters = subtitle_bitstream_filters;
3703
    subtitle_bitstream_filters= NULL;
3704

    
3705
    subtitle_enc->codec_type = AVMEDIA_TYPE_SUBTITLE;
3706

    
3707
    if(subtitle_codec_tag)
3708
        subtitle_enc->codec_tag= subtitle_codec_tag;
3709

    
3710
    if (oc->oformat->flags & AVFMT_GLOBALHEADER) {
3711
        subtitle_enc->flags |= CODEC_FLAG_GLOBAL_HEADER;
3712
        avcodec_opts[AVMEDIA_TYPE_SUBTITLE]->flags |= CODEC_FLAG_GLOBAL_HEADER;
3713
    }
3714
    if (subtitle_stream_copy) {
3715
        st->stream_copy = 1;
3716
    } else {
3717
        subtitle_enc->codec_id = codec_id;
3718
        set_context_opts(avcodec_opts[AVMEDIA_TYPE_SUBTITLE], subtitle_enc, AV_OPT_FLAG_SUBTITLE_PARAM | AV_OPT_FLAG_ENCODING_PARAM, codec);
3719
    }
3720

    
3721
    if (subtitle_language) {
3722
        av_metadata_set2(&st->metadata, "language", subtitle_language, 0);
3723
        av_freep(&subtitle_language);
3724
    }
3725

    
3726
    subtitle_disable = 0;
3727
    av_freep(&subtitle_codec_name);
3728
    subtitle_stream_copy = 0;
3729
}
3730

    
3731
static int opt_new_stream(const char *opt, const char *arg)
3732
{
3733
    AVFormatContext *oc;
3734
    int file_idx = nb_output_files - 1;
3735
    if (nb_output_files <= 0) {
3736
        fprintf(stderr, "At least one output file must be specified\n");
3737
        ffmpeg_exit(1);
3738
    }
3739
    oc = output_files[file_idx];
3740

    
3741
    if      (!strcmp(opt, "newvideo"   )) new_video_stream   (oc, file_idx);
3742
    else if (!strcmp(opt, "newaudio"   )) new_audio_stream   (oc, file_idx);
3743
    else if (!strcmp(opt, "newsubtitle")) new_subtitle_stream(oc, file_idx);
3744
    else av_assert0(0);
3745
    return 0;
3746
}
3747

    
3748
/* arg format is "output-stream-index:streamid-value". */
3749
static int opt_streamid(const char *opt, const char *arg)
3750
{
3751
    int idx;
3752
    char *p;
3753
    char idx_str[16];
3754

    
3755
    strncpy(idx_str, arg, sizeof(idx_str));
3756
    idx_str[sizeof(idx_str)-1] = '\0';
3757
    p = strchr(idx_str, ':');
3758
    if (!p) {
3759
        fprintf(stderr,
3760
                "Invalid value '%s' for option '%s', required syntax is 'index:value'\n",
3761
                arg, opt);
3762
        ffmpeg_exit(1);
3763
    }
3764
    *p++ = '\0';
3765
    idx = parse_number_or_die(opt, idx_str, OPT_INT, 0, MAX_STREAMS-1);
3766
    streamid_map = grow_array(streamid_map, sizeof(*streamid_map), &nb_streamid_map, idx+1);
3767
    streamid_map[idx] = parse_number_or_die(opt, p, OPT_INT, 0, INT_MAX);
3768
    return 0;
3769
}
3770

    
3771
static void opt_output_file(const char *filename)
3772
{
3773
    AVFormatContext *oc;
3774
    int err, use_video, use_audio, use_subtitle;
3775
    int input_has_video, input_has_audio, input_has_subtitle;
3776
    AVFormatParameters params, *ap = &params;
3777
    AVOutputFormat *file_oformat;
3778

    
3779
    if (!strcmp(filename, "-"))
3780
        filename = "pipe:";
3781

    
3782
    oc = avformat_alloc_context();
3783
    if (!oc) {
3784
        print_error(filename, AVERROR(ENOMEM));
3785
        ffmpeg_exit(1);
3786
    }
3787

    
3788
    if (last_asked_format) {
3789
        file_oformat = av_guess_format(last_asked_format, NULL, NULL);
3790
        if (!file_oformat) {
3791
            fprintf(stderr, "Requested output format '%s' is not a suitable output format\n", last_asked_format);
3792
            ffmpeg_exit(1);
3793
        }
3794
        last_asked_format = NULL;
3795
    } else {
3796
        file_oformat = av_guess_format(NULL, filename, NULL);
3797
        if (!file_oformat) {
3798
            fprintf(stderr, "Unable to find a suitable output format for '%s'\n",
3799
                    filename);
3800
            ffmpeg_exit(1);
3801
        }
3802
    }
3803

    
3804
    oc->oformat = file_oformat;
3805
    av_strlcpy(oc->filename, filename, sizeof(oc->filename));
3806

    
3807
    if (!strcmp(file_oformat->name, "ffm") &&
3808
        av_strstart(filename, "http:", NULL)) {
3809
        /* special case for files sent to ffserver: we get the stream
3810
           parameters from ffserver */
3811
        int err = read_ffserver_streams(oc, filename);
3812
        if (err < 0) {
3813
            print_error(filename, err);
3814
            ffmpeg_exit(1);
3815
        }
3816
    } else {
3817
        use_video = file_oformat->video_codec != CODEC_ID_NONE || video_stream_copy || video_codec_name;
3818
        use_audio = file_oformat->audio_codec != CODEC_ID_NONE || audio_stream_copy || audio_codec_name;
3819
        use_subtitle = file_oformat->subtitle_codec != CODEC_ID_NONE || subtitle_stream_copy || subtitle_codec_name;
3820

    
3821
        /* disable if no corresponding type found and at least one
3822
           input file */
3823
        if (nb_input_files > 0) {
3824
            check_audio_video_sub_inputs(&input_has_video, &input_has_audio,
3825
                                         &input_has_subtitle);
3826
            if (!input_has_video)
3827
                use_video = 0;
3828
            if (!input_has_audio)
3829
                use_audio = 0;
3830
            if (!input_has_subtitle)
3831
                use_subtitle = 0;
3832
        }
3833

    
3834
        /* manual disable */
3835
        if (audio_disable)    use_audio    = 0;
3836
        if (video_disable)    use_video    = 0;
3837
        if (subtitle_disable) use_subtitle = 0;
3838

    
3839
        if (use_video)    new_video_stream(oc, nb_output_files);
3840
        if (use_audio)    new_audio_stream(oc, nb_output_files);
3841
        if (use_subtitle) new_subtitle_stream(oc, nb_output_files);
3842

    
3843
        oc->timestamp = recording_timestamp;
3844

    
3845
        av_metadata_copy(&oc->metadata, metadata, 0);
3846
        av_metadata_free(&metadata);
3847
    }
3848

    
3849
    output_files[nb_output_files++] = oc;
3850

    
3851
    /* check filename in case of an image number is expected */
3852
    if (oc->oformat->flags & AVFMT_NEEDNUMBER) {
3853
        if (!av_filename_number_test(oc->filename)) {
3854
            print_error(oc->filename, AVERROR_NUMEXPECTED);
3855
            ffmpeg_exit(1);
3856
        }
3857
    }
3858

    
3859
    if (!(oc->oformat->flags & AVFMT_NOFILE)) {
3860
        /* test if it already exists to avoid loosing precious files */
3861
        if (!file_overwrite &&
3862
            (strchr(filename, ':') == NULL ||
3863
             filename[1] == ':' ||
3864
             av_strstart(filename, "file:", NULL))) {
3865
            if (url_exist(filename)) {
3866
                if (!using_stdin) {
3867
                    fprintf(stderr,"File '%s' already exists. Overwrite ? [y/N] ", filename);
3868
                    fflush(stderr);
3869
                    if (!read_yesno()) {
3870
                        fprintf(stderr, "Not overwriting - exiting\n");
3871
                        ffmpeg_exit(1);
3872
                    }
3873
                }
3874
                else {
3875
                    fprintf(stderr,"File '%s' already exists. Exiting.\n", filename);
3876
                    ffmpeg_exit(1);
3877
                }
3878
            }
3879
        }
3880

    
3881
        /* open the file */
3882
        if ((err = avio_open(&oc->pb, filename, URL_WRONLY)) < 0) {
3883
            print_error(filename, err);
3884
            ffmpeg_exit(1);
3885
        }
3886
    }
3887

    
3888
    memset(ap, 0, sizeof(*ap));
3889
    if (av_set_parameters(oc, ap) < 0) {
3890
        fprintf(stderr, "%s: Invalid encoding parameters\n",
3891
                oc->filename);
3892
        ffmpeg_exit(1);
3893
    }
3894

    
3895
    oc->preload= (int)(mux_preload*AV_TIME_BASE);
3896
    oc->max_delay= (int)(mux_max_delay*AV_TIME_BASE);
3897
    oc->loop_output = loop_output;
3898

    
3899
    set_context_opts(oc, avformat_opts, AV_OPT_FLAG_ENCODING_PARAM, NULL);
3900

    
3901
    av_freep(&forced_key_frames);
3902
}
3903

    
3904
/* same option as mencoder */
3905
static void opt_pass(const char *pass_str)
3906
{
3907
    int pass;
3908
    pass = atoi(pass_str);
3909
    if (pass != 1 && pass != 2) {
3910
        fprintf(stderr, "pass number can be only 1 or 2\n");
3911
        ffmpeg_exit(1);
3912
    }
3913
    do_pass = pass;
3914
}
3915

    
3916
static int64_t getutime(void)
3917
{
3918
#if HAVE_GETRUSAGE
3919
    struct rusage rusage;
3920

    
3921
    getrusage(RUSAGE_SELF, &rusage);
3922
    return (rusage.ru_utime.tv_sec * 1000000LL) + rusage.ru_utime.tv_usec;
3923
#elif HAVE_GETPROCESSTIMES
3924
    HANDLE proc;
3925
    FILETIME c, e, k, u;
3926
    proc = GetCurrentProcess();
3927
    GetProcessTimes(proc, &c, &e, &k, &u);
3928
    return ((int64_t) u.dwHighDateTime << 32 | u.dwLowDateTime) / 10;
3929
#else
3930
    return av_gettime();
3931
#endif
3932
}
3933

    
3934
static int64_t getmaxrss(void)
3935
{
3936
#if HAVE_GETRUSAGE && HAVE_STRUCT_RUSAGE_RU_MAXRSS
3937
    struct rusage rusage;
3938
    getrusage(RUSAGE_SELF, &rusage);
3939
    return (int64_t)rusage.ru_maxrss * 1024;
3940
#elif HAVE_GETPROCESSMEMORYINFO
3941
    HANDLE proc;
3942
    PROCESS_MEMORY_COUNTERS memcounters;
3943
    proc = GetCurrentProcess();
3944
    memcounters.cb = sizeof(memcounters);
3945
    GetProcessMemoryInfo(proc, &memcounters, sizeof(memcounters));
3946
    return memcounters.PeakPagefileUsage;
3947
#else
3948
    return 0;
3949
#endif
3950
}
3951

    
3952
static void parse_matrix_coeffs(uint16_t *dest, const char *str)
3953
{
3954
    int i;
3955
    const char *p = str;
3956
    for(i = 0;; i++) {
3957
        dest[i] = atoi(p);
3958
        if(i == 63)
3959
            break;
3960
        p = strchr(p, ',');
3961
        if(!p) {
3962
            fprintf(stderr, "Syntax error in matrix \"%s\" at coeff %d\n", str, i);
3963
            ffmpeg_exit(1);
3964
        }
3965
        p++;
3966
    }
3967
}
3968

    
3969
static void opt_inter_matrix(const char *arg)
3970
{
3971
    inter_matrix = av_mallocz(sizeof(uint16_t) * 64);
3972
    parse_matrix_coeffs(inter_matrix, arg);
3973
}
3974

    
3975
static void opt_intra_matrix(const char *arg)
3976
{
3977
    intra_matrix = av_mallocz(sizeof(uint16_t) * 64);
3978
    parse_matrix_coeffs(intra_matrix, arg);
3979
}
3980

    
3981
static void show_usage(void)
3982
{
3983
    printf("Hyper fast Audio and Video encoder\n");
3984
    printf("usage: ffmpeg [options] [[infile options] -i infile]... {[outfile options] outfile}...\n");
3985
    printf("\n");
3986
}
3987

    
3988
static void show_help(void)
3989
{
3990
    AVCodec *c;
3991
    AVOutputFormat *oformat = NULL;
3992

    
3993
    av_log_set_callback(log_callback_help);
3994
    show_usage();
3995
    show_help_options(options, "Main options:\n",
3996
                      OPT_EXPERT | OPT_AUDIO | OPT_VIDEO | OPT_SUBTITLE | OPT_GRAB, 0);
3997
    show_help_options(options, "\nAdvanced options:\n",
3998
                      OPT_EXPERT | OPT_AUDIO | OPT_VIDEO | OPT_SUBTITLE | OPT_GRAB,
3999
                      OPT_EXPERT);
4000
    show_help_options(options, "\nVideo options:\n",
4001
                      OPT_EXPERT | OPT_AUDIO | OPT_VIDEO | OPT_GRAB,
4002
                      OPT_VIDEO);
4003
    show_help_options(options, "\nAdvanced Video options:\n",
4004
                      OPT_EXPERT | OPT_AUDIO | OPT_VIDEO | OPT_GRAB,
4005
                      OPT_VIDEO | OPT_EXPERT);
4006
    show_help_options(options, "\nAudio options:\n",
4007
                      OPT_EXPERT | OPT_AUDIO | OPT_VIDEO | OPT_GRAB,
4008
                      OPT_AUDIO);
4009
    show_help_options(options, "\nAdvanced Audio options:\n",
4010
                      OPT_EXPERT | OPT_AUDIO | OPT_VIDEO | OPT_GRAB,
4011
                      OPT_AUDIO | OPT_EXPERT);
4012
    show_help_options(options, "\nSubtitle options:\n",
4013
                      OPT_SUBTITLE | OPT_GRAB,
4014
                      OPT_SUBTITLE);
4015
    show_help_options(options, "\nAudio/Video grab options:\n",
4016
                      OPT_GRAB,
4017
                      OPT_GRAB);
4018
    printf("\n");
4019
    av_opt_show2(avcodec_opts[0], NULL, AV_OPT_FLAG_ENCODING_PARAM|AV_OPT_FLAG_DECODING_PARAM, 0);
4020
    printf("\n");
4021

    
4022
    /* individual codec options */
4023
    c = NULL;
4024
    while ((c = av_codec_next(c))) {
4025
        if (c->priv_class) {
4026
            av_opt_show2(&c->priv_class, NULL, AV_OPT_FLAG_ENCODING_PARAM|AV_OPT_FLAG_DECODING_PARAM, 0);
4027
            printf("\n");
4028
        }
4029
    }
4030

    
4031
    av_opt_show2(avformat_opts, NULL, AV_OPT_FLAG_ENCODING_PARAM|AV_OPT_FLAG_DECODING_PARAM, 0);
4032
    printf("\n");
4033

    
4034
    /* individual muxer options */
4035
    while ((oformat = av_oformat_next(oformat))) {
4036
        if (oformat->priv_class) {
4037
            av_opt_show2(&oformat->priv_class, NULL, AV_OPT_FLAG_ENCODING_PARAM, 0);
4038
            printf("\n");
4039
        }
4040
    }
4041

    
4042
    av_opt_show2(sws_opts, NULL, AV_OPT_FLAG_ENCODING_PARAM|AV_OPT_FLAG_DECODING_PARAM, 0);
4043
}
4044

    
4045
static void opt_target(const char *arg)
4046
{
4047
    enum { PAL, NTSC, FILM, UNKNOWN } norm = UNKNOWN;
4048
    static const char *const frame_rates[] = {"25", "30000/1001", "24000/1001"};
4049

    
4050
    if(!strncmp(arg, "pal-", 4)) {
4051
        norm = PAL;
4052
        arg += 4;
4053
    } else if(!strncmp(arg, "ntsc-", 5)) {
4054
        norm = NTSC;
4055
        arg += 5;
4056
    } else if(!strncmp(arg, "film-", 5)) {
4057
        norm = FILM;
4058
        arg += 5;
4059
    } else {
4060
        int fr;
4061
        /* Calculate FR via float to avoid int overflow */
4062
        fr = (int)(frame_rate.num * 1000.0 / frame_rate.den);
4063
        if(fr == 25000) {
4064
            norm = PAL;
4065
        } else if((fr == 29970) || (fr == 23976)) {
4066
            norm = NTSC;
4067
        } else {
4068
            /* Try to determine PAL/NTSC by peeking in the input files */
4069
            if(nb_input_files) {
4070
                int i, j;
4071
                for(j = 0; j < nb_input_files; j++) {
4072
                    for(i = 0; i < input_files[j]->nb_streams; i++) {
4073
                        AVCodecContext *c = input_files[j]->streams[i]->codec;
4074
                        if(c->codec_type != AVMEDIA_TYPE_VIDEO)
4075
                            continue;
4076
                        fr = c->time_base.den * 1000 / c->time_base.num;
4077
                        if(fr == 25000) {
4078
                            norm = PAL;
4079
                            break;
4080
                        } else if((fr == 29970) || (fr == 23976)) {
4081
                            norm = NTSC;
4082
                            break;
4083
                        }
4084
                    }
4085
                    if(norm != UNKNOWN)
4086
                        break;
4087
                }
4088
            }
4089
        }
4090
        if(verbose && norm != UNKNOWN)
4091
            fprintf(stderr, "Assuming %s for target.\n", norm == PAL ? "PAL" : "NTSC");
4092
    }
4093

    
4094
    if(norm == UNKNOWN) {
4095
        fprintf(stderr, "Could not determine norm (PAL/NTSC/NTSC-Film) for target.\n");
4096
        fprintf(stderr, "Please prefix target with \"pal-\", \"ntsc-\" or \"film-\",\n");
4097
        fprintf(stderr, "or set a framerate with \"-r xxx\".\n");
4098
        ffmpeg_exit(1);
4099
    }
4100

    
4101
    if(!strcmp(arg, "vcd")) {
4102

    
4103
        opt_video_codec("mpeg1video");
4104
        opt_audio_codec("mp2");
4105
        opt_format("vcd");
4106

    
4107
        opt_frame_size(norm == PAL ? "352x288" : "352x240");
4108
        opt_frame_rate(NULL, frame_rates[norm]);
4109
        opt_default("g", norm == PAL ? "15" : "18");
4110

    
4111
        opt_default("b", "1150000");
4112
        opt_default("maxrate", "1150000");
4113
        opt_default("minrate", "1150000");
4114
        opt_default("bufsize", "327680"); // 40*1024*8;
4115

    
4116
        opt_default("ab", "224000");
4117
        audio_sample_rate = 44100;
4118
        audio_channels = 2;
4119

    
4120
        opt_default("packetsize", "2324");
4121
        opt_default("muxrate", "1411200"); // 2352 * 75 * 8;
4122

    
4123
        /* We have to offset the PTS, so that it is consistent with the SCR.
4124
           SCR starts at 36000, but the first two packs contain only padding
4125
           and the first pack from the other stream, respectively, may also have
4126
           been written before.
4127
           So the real data starts at SCR 36000+3*1200. */
4128
        mux_preload= (36000+3*1200) / 90000.0; //0.44
4129
    } else if(!strcmp(arg, "svcd")) {
4130

    
4131
        opt_video_codec("mpeg2video");
4132
        opt_audio_codec("mp2");
4133
        opt_format("svcd");
4134

    
4135
        opt_frame_size(norm == PAL ? "480x576" : "480x480");
4136
        opt_frame_rate(NULL, frame_rates[norm]);
4137
        opt_default("g", norm == PAL ? "15" : "18");
4138

    
4139
        opt_default("b", "2040000");
4140
        opt_default("maxrate", "2516000");
4141
        opt_default("minrate", "0"); //1145000;
4142
        opt_default("bufsize", "1835008"); //224*1024*8;
4143
        opt_default("flags", "+scan_offset");
4144

    
4145

    
4146
        opt_default("ab", "224000");
4147
        audio_sample_rate = 44100;
4148

    
4149
        opt_default("packetsize", "2324");
4150

    
4151
    } else if(!strcmp(arg, "dvd")) {
4152

    
4153
        opt_video_codec("mpeg2video");
4154
        opt_audio_codec("ac3");
4155
        opt_format("dvd");
4156

    
4157
        opt_frame_size(norm == PAL ? "720x576" : "720x480");
4158
        opt_frame_rate(NULL, frame_rates[norm]);
4159
        opt_default("g", norm == PAL ? "15" : "18");
4160

    
4161
        opt_default("b", "6000000");
4162
        opt_default("maxrate", "9000000");
4163
        opt_default("minrate", "0"); //1500000;
4164
        opt_default("bufsize", "1835008"); //224*1024*8;
4165

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

    
4169
        opt_default("ab", "448000");
4170
        audio_sample_rate = 48000;
4171

    
4172
    } else if(!strncmp(arg, "dv", 2)) {
4173

    
4174
        opt_format("dv");
4175

    
4176
        opt_frame_size(norm == PAL ? "720x576" : "720x480");
4177
        opt_frame_pix_fmt(!strncmp(arg, "dv50", 4) ? "yuv422p" :
4178
                          (norm == PAL ? "yuv420p" : "yuv411p"));
4179
        opt_frame_rate(NULL, frame_rates[norm]);
4180

    
4181
        audio_sample_rate = 48000;
4182
        audio_channels = 2;
4183

    
4184
    } else {
4185
        fprintf(stderr, "Unknown target: %s\n", arg);
4186
        ffmpeg_exit(1);
4187
    }
4188
}
4189

    
4190
static void opt_vstats_file (const char *arg)
4191
{
4192
    av_free (vstats_filename);
4193
    vstats_filename=av_strdup (arg);
4194
}
4195

    
4196
static void opt_vstats (void)
4197
{
4198
    char filename[40];
4199
    time_t today2 = time(NULL);
4200
    struct tm *today = localtime(&today2);
4201

    
4202
    snprintf(filename, sizeof(filename), "vstats_%02d%02d%02d.log", today->tm_hour, today->tm_min,
4203
             today->tm_sec);
4204
    opt_vstats_file(filename);
4205
}
4206

    
4207
static int opt_bsf(const char *opt, const char *arg)
4208
{
4209
    AVBitStreamFilterContext *bsfc= av_bitstream_filter_init(arg); //FIXME split name and args for filter at '='
4210
    AVBitStreamFilterContext **bsfp;
4211

    
4212
    if(!bsfc){
4213
        fprintf(stderr, "Unknown bitstream filter %s\n", arg);
4214
        ffmpeg_exit(1);
4215
    }
4216

    
4217
    bsfp= *opt == 'v' ? &video_bitstream_filters :
4218
          *opt == 'a' ? &audio_bitstream_filters :
4219
                        &subtitle_bitstream_filters;
4220
    while(*bsfp)
4221
        bsfp= &(*bsfp)->next;
4222

    
4223
    *bsfp= bsfc;
4224

    
4225
    return 0;
4226
}
4227

    
4228
static int opt_preset(const char *opt, const char *arg)
4229
{
4230
    FILE *f=NULL;
4231
    char filename[1000], tmp[1000], tmp2[1000], line[1000];
4232
    char *codec_name = *opt == 'v' ? video_codec_name :
4233
                       *opt == 'a' ? audio_codec_name :
4234
                                     subtitle_codec_name;
4235

    
4236
    if (!(f = get_preset_file(filename, sizeof(filename), arg, *opt == 'f', codec_name))) {
4237
        fprintf(stderr, "File for preset '%s' not found\n", arg);
4238
        ffmpeg_exit(1);
4239
    }
4240

    
4241
    while(!feof(f)){
4242
        int e= fscanf(f, "%999[^\n]\n", line) - 1;
4243
        if(line[0] == '#' && !e)
4244
            continue;
4245
        e|= sscanf(line, "%999[^=]=%999[^\n]\n", tmp, tmp2) - 2;
4246
        if(e){
4247
            fprintf(stderr, "%s: Invalid syntax: '%s'\n", filename, line);
4248
            ffmpeg_exit(1);
4249
        }
4250
        if(!strcmp(tmp, "acodec")){
4251
            opt_audio_codec(tmp2);
4252
        }else if(!strcmp(tmp, "vcodec")){
4253
            opt_video_codec(tmp2);
4254
        }else if(!strcmp(tmp, "scodec")){
4255
            opt_subtitle_codec(tmp2);
4256
        }else if(opt_default(tmp, tmp2) < 0){
4257
            fprintf(stderr, "%s: Invalid option or argument: '%s', parsed as '%s' = '%s'\n", filename, line, tmp, tmp2);
4258
            ffmpeg_exit(1);
4259
        }
4260
    }
4261

    
4262
    fclose(f);
4263

    
4264
    return 0;
4265
}
4266

    
4267
static const OptionDef options[] = {
4268
    /* main options */
4269
#include "cmdutils_common_opts.h"
4270
    { "f", HAS_ARG, {(void*)opt_format}, "force format", "fmt" },
4271
    { "i", HAS_ARG, {(void*)opt_input_file}, "input file name", "filename" },
4272
    { "y", OPT_BOOL, {(void*)&file_overwrite}, "overwrite output files" },
4273
    { "map", HAS_ARG | OPT_EXPERT, {(void*)opt_map}, "set input stream mapping", "file.stream[:syncfile.syncstream]" },
4274
    { "map_meta_data", HAS_ARG | OPT_EXPERT, {(void*)opt_map_meta_data}, "DEPRECATED set meta data information of outfile from infile",
4275
      "outfile[,metadata]:infile[,metadata]" },
4276
    { "map_metadata", HAS_ARG | OPT_EXPERT, {(void*)opt_map_metadata}, "set metadata information of outfile from infile",
4277
      "outfile[,metadata]:infile[,metadata]" },
4278
    { "map_chapters",  HAS_ARG | OPT_EXPERT, {(void*)opt_map_chapters},  "set chapters mapping", "outfile:infile" },
4279
    { "t", OPT_FUNC2 | HAS_ARG, {(void*)opt_recording_time}, "record or transcode \"duration\" seconds of audio/video", "duration" },
4280
    { "fs", HAS_ARG | OPT_INT64, {(void*)&limit_filesize}, "set the limit file size in bytes", "limit_size" }, //
4281
    { "ss", OPT_FUNC2 | HAS_ARG, {(void*)opt_start_time}, "set the start time offset", "time_off" },
4282
    { "itsoffset", OPT_FUNC2 | HAS_ARG, {(void*)opt_input_ts_offset}, "set the input ts offset", "time_off" },
4283
    { "itsscale", HAS_ARG, {(void*)opt_input_ts_scale}, "set the input ts scale", "stream:scale" },
4284
    { "timestamp", OPT_FUNC2 | HAS_ARG, {(void*)opt_recording_timestamp}, "set the recording timestamp ('now' to set the current time)", "time" },
4285
    { "metadata", OPT_FUNC2 | HAS_ARG, {(void*)opt_metadata}, "add metadata", "string=string" },
4286
    { "dframes", OPT_INT | HAS_ARG, {(void*)&max_frames[AVMEDIA_TYPE_DATA]}, "set the number of data frames to record", "number" },
4287
    { "benchmark", OPT_BOOL | OPT_EXPERT, {(void*)&do_benchmark},
4288
      "add timings for benchmarking" },
4289
    { "timelimit", OPT_FUNC2 | HAS_ARG, {(void*)opt_timelimit}, "set max runtime in seconds", "limit" },
4290
    { "dump", OPT_BOOL | OPT_EXPERT, {(void*)&do_pkt_dump},
4291
      "dump each input packet" },
4292
    { "hex", OPT_BOOL | OPT_EXPERT, {(void*)&do_hex_dump},
4293
      "when dumping packets, also dump the payload" },
4294
    { "re", OPT_BOOL | OPT_EXPERT, {(void*)&rate_emu}, "read input at native frame rate", "" },
4295
    { "loop_input", OPT_BOOL | OPT_EXPERT, {(void*)&loop_input}, "loop (current only works with images)" },
4296
    { "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)", "" },
4297
    { "v", HAS_ARG | OPT_FUNC2, {(void*)opt_verbose}, "set ffmpeg verbosity level", "number" },
4298
    { "target", HAS_ARG, {(void*)opt_target}, "specify target file type (\"vcd\", \"svcd\", \"dvd\", \"dv\", \"dv50\", \"pal-vcd\", \"ntsc-svcd\", ...)", "type" },
4299
    { "threads", OPT_FUNC2 | HAS_ARG | OPT_EXPERT, {(void*)opt_thread_count}, "thread count", "count" },
4300
    { "vsync", HAS_ARG | OPT_INT | OPT_EXPERT, {(void*)&video_sync_method}, "video sync method", "" },
4301
    { "async", HAS_ARG | OPT_INT | OPT_EXPERT, {(void*)&audio_sync_method}, "audio sync method", "" },
4302
    { "adrift_threshold", HAS_ARG | OPT_FLOAT | OPT_EXPERT, {(void*)&audio_drift_threshold}, "audio drift threshold", "threshold" },
4303
    { "vglobal", HAS_ARG | OPT_INT | OPT_EXPERT, {(void*)&video_global_header}, "video global header storage type", "" },
4304
    { "copyts", OPT_BOOL | OPT_EXPERT, {(void*)&copy_ts}, "copy timestamps" },
4305
    { "copytb", OPT_BOOL | OPT_EXPERT, {(void*)&copy_tb}, "copy input stream time base when stream copying" },
4306
    { "shortest", OPT_BOOL | OPT_EXPERT, {(void*)&opt_shortest}, "finish encoding within shortest input" }, //
4307
    { "dts_delta_threshold", HAS_ARG | OPT_FLOAT | OPT_EXPERT, {(void*)&dts_delta_threshold}, "timestamp discontinuity delta threshold", "threshold" },
4308
    { "programid", HAS_ARG | OPT_INT | OPT_EXPERT, {(void*)&opt_programid}, "desired program number", "" },
4309
    { "xerror", OPT_BOOL, {(void*)&exit_on_error}, "exit on error", "error" },
4310
    { "copyinkf", OPT_BOOL | OPT_EXPERT, {(void*)&copy_initial_nonkeyframes}, "copy initial non-keyframes" },
4311

    
4312
    /* video options */
4313
    { "b", OPT_FUNC2 | HAS_ARG | OPT_VIDEO, {(void*)opt_bitrate}, "set bitrate (in bits/s)", "bitrate" },
4314
    { "vb", OPT_FUNC2 | HAS_ARG | OPT_VIDEO, {(void*)opt_bitrate}, "set bitrate (in bits/s)", "bitrate" },
4315
    { "vframes", OPT_INT | HAS_ARG | OPT_VIDEO, {(void*)&max_frames[AVMEDIA_TYPE_VIDEO]}, "set the number of video frames to record", "number" },
4316
    { "r", OPT_FUNC2 | HAS_ARG | OPT_VIDEO, {(void*)opt_frame_rate}, "set frame rate (Hz value, fraction or abbreviation)", "rate" },
4317
    { "s", HAS_ARG | OPT_VIDEO, {(void*)opt_frame_size}, "set frame size (WxH or abbreviation)", "size" },
4318
    { "aspect", HAS_ARG | OPT_VIDEO, {(void*)opt_frame_aspect_ratio}, "set aspect ratio (4:3, 16:9 or 1.3333, 1.7777)", "aspect" },
4319
    { "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" },
4320
    { "bits_per_raw_sample", OPT_INT | HAS_ARG | OPT_VIDEO, {(void*)&frame_bits_per_raw_sample}, "set the number of bits per raw sample", "number" },
4321
    { "croptop", OPT_FUNC2 | HAS_ARG | OPT_VIDEO, {(void*)opt_frame_crop}, "Removed, use the crop filter instead", "size" },
4322
    { "cropbottom", OPT_FUNC2 | HAS_ARG | OPT_VIDEO, {(void*)opt_frame_crop}, "Removed, use the crop filter instead", "size" },
4323
    { "cropleft", OPT_FUNC2 | HAS_ARG | OPT_VIDEO, {(void*)opt_frame_crop}, "Removed, use the crop filter instead", "size" },
4324
    { "cropright", OPT_FUNC2 | HAS_ARG | OPT_VIDEO, {(void*)opt_frame_crop}, "Removed, use the crop filter instead", "size" },
4325
    { "padtop", OPT_FUNC2 | HAS_ARG | OPT_VIDEO, {(void*)opt_pad}, "Removed, use the pad filter instead", "size" },
4326
    { "padbottom", OPT_FUNC2 | HAS_ARG | OPT_VIDEO, {(void*)opt_pad}, "Removed, use the pad filter instead", "size" },
4327
    { "padleft", OPT_FUNC2 | HAS_ARG | OPT_VIDEO, {(void*)opt_pad}, "Removed, use the pad filter instead", "size" },
4328
    { "padright", OPT_FUNC2 | HAS_ARG | OPT_VIDEO, {(void*)opt_pad}, "Removed, use the pad filter instead", "size" },
4329
    { "padcolor", OPT_FUNC2 | HAS_ARG | OPT_VIDEO, {(void*)opt_pad}, "Removed, use the pad filter instead", "color" },
4330
    { "intra", OPT_BOOL | OPT_EXPERT | OPT_VIDEO, {(void*)&intra_only}, "use only intra frames"},
4331
    { "vn", OPT_BOOL | OPT_VIDEO, {(void*)&video_disable}, "disable video" },
4332
    { "vdt", OPT_INT | HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)&video_discard}, "discard threshold", "n" },
4333
    { "qscale", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_qscale}, "use fixed video quantizer scale (VBR)", "q" },
4334
    { "rc_override", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_video_rc_override_string}, "rate control override for specific intervals", "override" },
4335
    { "vcodec", HAS_ARG | OPT_VIDEO, {(void*)opt_video_codec}, "force video codec ('copy' to copy stream)", "codec" },
4336
    { "me_threshold", HAS_ARG | OPT_FUNC2 | OPT_EXPERT | OPT_VIDEO, {(void*)opt_me_threshold}, "motion estimaton threshold",  "threshold" },
4337
    { "sameq", OPT_BOOL | OPT_VIDEO, {(void*)&same_quality},
4338
      "use same quantizer as source (implies VBR)" },
4339
    { "pass", HAS_ARG | OPT_VIDEO, {(void*)&opt_pass}, "select the pass number (1 or 2)", "n" },
4340
    { "passlogfile", HAS_ARG | OPT_STRING | OPT_VIDEO, {(void*)&pass_logfilename_prefix}, "select two pass log file name prefix", "prefix" },
4341
    { "deinterlace", OPT_BOOL | OPT_EXPERT | OPT_VIDEO, {(void*)&do_deinterlace},
4342
      "deinterlace pictures" },
4343
    { "psnr", OPT_BOOL | OPT_EXPERT | OPT_VIDEO, {(void*)&do_psnr}, "calculate PSNR of compressed frames" },
4344
    { "vstats", OPT_EXPERT | OPT_VIDEO, {(void*)&opt_vstats}, "dump video coding statistics to file" },
4345
    { "vstats_file", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_vstats_file}, "dump video coding statistics to file", "file" },
4346
#if CONFIG_AVFILTER
4347
    { "vf", OPT_STRING | HAS_ARG, {(void*)&vfilters}, "video filters", "filter list" },
4348
#endif
4349
    { "intra_matrix", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_intra_matrix}, "specify intra matrix coeffs", "matrix" },
4350
    { "inter_matrix", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_inter_matrix}, "specify inter matrix coeffs", "matrix" },
4351
    { "top", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_top_field_first}, "top=1/bottom=0/auto=-1 field first", "" },
4352
    { "dc", OPT_INT | HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)&intra_dc_precision}, "intra_dc_precision", "precision" },
4353
    { "vtag", OPT_FUNC2 | HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_codec_tag}, "force video tag/fourcc", "fourcc/tag" },
4354
    { "newvideo", OPT_VIDEO | OPT_FUNC2, {(void*)opt_new_stream}, "add a new video stream to the current output stream" },
4355
    { "vlang", HAS_ARG | OPT_STRING | OPT_VIDEO, {(void *)&video_language}, "set the ISO 639 language code (3 letters) of the current video stream" , "code" },
4356
    { "qphist", OPT_BOOL | OPT_EXPERT | OPT_VIDEO, { (void *)&qp_hist }, "show QP histogram" },
4357
    { "force_fps", OPT_BOOL | OPT_EXPERT | OPT_VIDEO, {(void*)&force_fps}, "force the selected framerate, disable the best supported framerate selection" },
4358
    { "streamid", OPT_FUNC2 | HAS_ARG | OPT_EXPERT, {(void*)opt_streamid}, "set the value of an outfile streamid", "streamIndex:value" },
4359
    { "force_key_frames", OPT_STRING | HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void *)&forced_key_frames}, "force key frames at specified timestamps", "timestamps" },
4360

    
4361
    /* audio options */
4362
    { "ab", OPT_FUNC2 | HAS_ARG | OPT_AUDIO, {(void*)opt_bitrate}, "set bitrate (in bits/s)", "bitrate" },
4363
    { "aframes", OPT_INT | HAS_ARG | OPT_AUDIO, {(void*)&max_frames[AVMEDIA_TYPE_AUDIO]}, "set the number of audio frames to record", "number" },
4364
    { "aq", OPT_FLOAT | HAS_ARG | OPT_AUDIO, {(void*)&audio_qscale}, "set audio quality (codec-specific)", "quality", },
4365
    { "ar", HAS_ARG | OPT_FUNC2 | OPT_AUDIO, {(void*)opt_audio_rate}, "set audio sampling rate (in Hz)", "rate" },
4366
    { "ac", HAS_ARG | OPT_FUNC2 | OPT_AUDIO, {(void*)opt_audio_channels}, "set number of audio channels", "channels" },
4367
    { "an", OPT_BOOL | OPT_AUDIO, {(void*)&audio_disable}, "disable audio" },
4368
    { "acodec", HAS_ARG | OPT_AUDIO, {(void*)opt_audio_codec}, "force audio codec ('copy' to copy stream)", "codec" },
4369
    { "atag", OPT_FUNC2 | HAS_ARG | OPT_EXPERT | OPT_AUDIO, {(void*)opt_codec_tag}, "force audio tag/fourcc", "fourcc/tag" },
4370
    { "vol", OPT_INT | HAS_ARG | OPT_AUDIO, {(void*)&audio_volume}, "change audio volume (256=normal)" , "volume" }, //
4371
    { "newaudio", OPT_AUDIO | OPT_FUNC2, {(void*)opt_new_stream}, "add a new audio stream to the current output stream" },
4372
    { "alang", HAS_ARG | OPT_STRING | OPT_AUDIO, {(void *)&audio_language}, "set the ISO 639 language code (3 letters) of the current audio stream" , "code" },
4373
    { "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" },
4374

    
4375
    /* subtitle options */
4376
    { "sn", OPT_BOOL | OPT_SUBTITLE, {(void*)&subtitle_disable}, "disable subtitle" },
4377
    { "scodec", HAS_ARG | OPT_SUBTITLE, {(void*)opt_subtitle_codec}, "force subtitle codec ('copy' to copy stream)", "codec" },
4378
    { "newsubtitle", OPT_SUBTITLE | OPT_FUNC2, {(void*)opt_new_stream}, "add a new subtitle stream to the current output stream" },
4379
    { "slang", HAS_ARG | OPT_STRING | OPT_SUBTITLE, {(void *)&subtitle_language}, "set the ISO 639 language code (3 letters) of the current subtitle stream" , "code" },
4380
    { "stag", OPT_FUNC2 | HAS_ARG | OPT_EXPERT | OPT_SUBTITLE, {(void*)opt_codec_tag}, "force subtitle tag/fourcc", "fourcc/tag" },
4381

    
4382
    /* grab options */
4383
    { "vc", HAS_ARG | OPT_EXPERT | OPT_VIDEO | OPT_GRAB, {(void*)opt_video_channel}, "set video grab channel (DV1394 only)", "channel" },
4384
    { "tvstd", HAS_ARG | OPT_EXPERT | OPT_VIDEO | OPT_GRAB, {(void*)opt_video_standard}, "set television standard (NTSC, PAL (SECAM))", "standard" },
4385
    { "isync", OPT_BOOL | OPT_EXPERT | OPT_GRAB, {(void*)&input_sync}, "sync read on input", "" },
4386

    
4387
    /* muxer options */
4388
    { "muxdelay", OPT_FLOAT | HAS_ARG | OPT_EXPERT, {(void*)&mux_max_delay}, "set the maximum demux-decode delay", "seconds" },
4389
    { "muxpreload", OPT_FLOAT | HAS_ARG | OPT_EXPERT, {(void*)&mux_preload}, "set the initial demux-decode delay", "seconds" },
4390

    
4391
    { "absf", OPT_FUNC2 | HAS_ARG | OPT_AUDIO | OPT_EXPERT, {(void*)opt_bsf}, "", "bitstream_filter" },
4392
    { "vbsf", OPT_FUNC2 | HAS_ARG | OPT_VIDEO | OPT_EXPERT, {(void*)opt_bsf}, "", "bitstream_filter" },
4393
    { "sbsf", OPT_FUNC2 | HAS_ARG | OPT_SUBTITLE | OPT_EXPERT, {(void*)opt_bsf}, "", "bitstream_filter" },
4394

    
4395
    { "apre", OPT_FUNC2 | HAS_ARG | OPT_AUDIO | OPT_EXPERT, {(void*)opt_preset}, "set the audio options to the indicated preset", "preset" },
4396
    { "vpre", OPT_FUNC2 | HAS_ARG | OPT_VIDEO | OPT_EXPERT, {(void*)opt_preset}, "set the video options to the indicated preset", "preset" },
4397
    { "spre", OPT_FUNC2 | HAS_ARG | OPT_SUBTITLE | OPT_EXPERT, {(void*)opt_preset}, "set the subtitle options to the indicated preset", "preset" },
4398
    { "fpre", OPT_FUNC2 | HAS_ARG | OPT_EXPERT, {(void*)opt_preset}, "set options from indicated preset file", "filename" },
4399

    
4400
    { "default", OPT_FUNC2 | HAS_ARG | OPT_AUDIO | OPT_VIDEO | OPT_EXPERT, {(void*)opt_default}, "generic catch all option", "" },
4401
    { NULL, },
4402
};
4403

    
4404
int main(int argc, char **argv)
4405
{
4406
    int64_t ti;
4407

    
4408
    av_log_set_flags(AV_LOG_SKIP_REPEATED);
4409

    
4410
    avcodec_register_all();
4411
#if CONFIG_AVDEVICE
4412
    avdevice_register_all();
4413
#endif
4414
#if CONFIG_AVFILTER
4415
    avfilter_register_all();
4416
#endif
4417
    av_register_all();
4418

    
4419
#if HAVE_ISATTY
4420
    if(isatty(STDIN_FILENO))
4421
        url_set_interrupt_cb(decode_interrupt_cb);
4422
#endif
4423

    
4424
    init_opts();
4425

    
4426
    show_banner();
4427

    
4428
    /* parse options */
4429
    parse_options(argc, argv, options, opt_output_file);
4430

    
4431
    if(nb_output_files <= 0 && nb_input_files == 0) {
4432
        show_usage();
4433
        fprintf(stderr, "Use -h to get full help or, even better, run 'man ffmpeg'\n");
4434
        ffmpeg_exit(1);
4435
    }
4436

    
4437
    /* file converter / grab */
4438
    if (nb_output_files <= 0) {
4439
        fprintf(stderr, "At least one output file must be specified\n");
4440
        ffmpeg_exit(1);
4441
    }
4442

    
4443
    if (nb_input_files == 0) {
4444
        fprintf(stderr, "At least one input file must be specified\n");
4445
        ffmpeg_exit(1);
4446
    }
4447

    
4448
    ti = getutime();
4449
    if (transcode(output_files, nb_output_files, input_files, nb_input_files,
4450
                  stream_maps, nb_stream_maps) < 0)
4451
        ffmpeg_exit(1);
4452
    ti = getutime() - ti;
4453
    if (do_benchmark) {
4454
        int maxrss = getmaxrss() / 1024;
4455
        printf("bench: utime=%0.3fs maxrss=%ikB\n", ti / 1000000.0, maxrss);
4456
    }
4457

    
4458
    return ffmpeg_exit(0);
4459
}