Statistics
| Branch: | Revision:

ffmpeg / ffmpeg.c @ 4a908866

History | View | Annotate | Download (160 KB)

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

    
22
/* needed for usleep() */
23
#define _XOPEN_SOURCE 600
24

    
25
#include "config.h"
26
#include <ctype.h>
27
#include <string.h>
28
#include <math.h>
29
#include <stdlib.h>
30
#include <errno.h>
31
#include <signal.h>
32
#include <limits.h>
33
#include <unistd.h>
34
#include "libavformat/avformat.h"
35
#include "libavdevice/avdevice.h"
36
#include "libswscale/swscale.h"
37
#include "libavcodec/opt.h"
38
#include "libavcodec/audioconvert.h"
39
#include "libavcore/audioconvert.h"
40
#include "libavcore/parseutils.h"
41
#include "libavcore/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_CONIO_H
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 enum PixelFormat frame_pix_fmt = PIX_FMT_NONE;
153
static enum AVSampleFormat audio_sample_fmt = AV_SAMPLE_FMT_NONE;
154
static int max_frames[4] = {INT_MAX, INT_MAX, INT_MAX, INT_MAX};
155
static AVRational frame_rate;
156
static float video_qscale = 0;
157
static uint16_t *intra_matrix = NULL;
158
static uint16_t *inter_matrix = NULL;
159
static const char *video_rc_override_string=NULL;
160
static int video_disable = 0;
161
static int video_discard = 0;
162
static char *video_codec_name = NULL;
163
static unsigned int video_codec_tag = 0;
164
static char *video_language = NULL;
165
static int same_quality = 0;
166
static int do_deinterlace = 0;
167
static int top_field_first = -1;
168
static int me_threshold = 0;
169
static int intra_dc_precision = 8;
170
static int loop_input = 0;
171
static int loop_output = AVFMT_NOOUTPUTLOOP;
172
static int qp_hist = 0;
173
#if CONFIG_AVFILTER
174
static char *vfilters = NULL;
175
static AVFilterGraph *graph = NULL;
176
#endif
177

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

    
189
static int subtitle_disable = 0;
190
static char *subtitle_codec_name = NULL;
191
static char *subtitle_language = NULL;
192
static unsigned int subtitle_codec_tag = 0;
193

    
194
static float mux_preload= 0.5;
195
static float mux_max_delay= 0.7;
196

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

    
224
static int rate_emu = 0;
225

    
226
static int  video_channel = 0;
227
static char *video_standard;
228

    
229
static int audio_volume = 256;
230

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

    
246
static float dts_delta_threshold = 10;
247

    
248
static unsigned int sws_flags = SWS_BICUBIC;
249

    
250
static int64_t timer_start;
251

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

    
256
static short *samples;
257

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

    
262
#define DEFAULT_PASS_LOGFILENAME_PREFIX "ffmpeg2pass"
263

    
264
struct AVInputStream;
265

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

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

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

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

    
308
static AVOutputStream **output_streams_for_file[MAX_FILES] = { NULL };
309
static int nb_output_streams_for_file[MAX_FILES] = { 0 };
310

    
311
typedef struct AVInputStream {
312
    int file_index;
313
    int index;
314
    AVStream *st;
315
    int discard;             /* true if stream data should be discarded */
316
    int decoding_needed;     /* true if the packets must be decoded in 'raw_fifo' */
317
    int64_t sample_index;      /* current sample */
318

    
319
    int64_t       start;     /* time when read started */
320
    int64_t       next_pts;  /* synthetic pts for cases where pkt.pts
321
                                is not defined */
322
    int64_t       pts;       /* current pts */
323
    PtsCorrectionContext pts_ctx;
324
    int is_start;            /* is 1 at the start and after a discontinuity */
325
    int showed_multi_packet_warning;
326
    int is_past_recording_time;
327
#if CONFIG_AVFILTER
328
    AVFilterContext *output_video_filter;
329
    AVFilterContext *input_video_filter;
330
    AVFrame *filter_frame;
331
    int has_filter_frame;
332
    AVFilterBufferRef *picref;
333
#endif
334
} AVInputStream;
335

    
336
typedef struct AVInputFile {
337
    int eof_reached;      /* true if eof reached */
338
    int ist_index;        /* index of first stream in ist_table */
339
    int buffer_size;      /* current total buffer size */
340
    int nb_streams;       /* nb streams we are aware of */
341
} AVInputFile;
342

    
343
#if HAVE_TERMIOS_H
344

    
345
/* init terminal so that we can grab keys */
346
static struct termios oldtty;
347
#endif
348

    
349
#if CONFIG_AVFILTER
350

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

    
362
    graph = avfilter_graph_alloc();
363

    
364
    if (ist->st->sample_aspect_ratio.num){
365
        sample_aspect_ratio = ist->st->sample_aspect_ratio;
366
    }else
367
        sample_aspect_ratio = ist->st->codec->sample_aspect_ratio;
368

    
369
    snprintf(args, 255, "%d:%d:%d:%d:%d:%d:%d", ist->st->codec->width,
370
             ist->st->codec->height, ist->st->codec->pix_fmt, 1, AV_TIME_BASE,
371
             sample_aspect_ratio.num, sample_aspect_ratio.den);
372

    
373
    ret = avfilter_graph_create_filter(&ist->input_video_filter, avfilter_get_by_name("buffer"),
374
                                       "src", args, NULL, graph);
375
    if (ret < 0)
376
        return ret;
377
    ret = avfilter_graph_create_filter(&ist->output_video_filter, &ffsink,
378
                                       "out", NULL, &ffsink_ctx, graph);
379
    if (ret < 0)
380
        return ret;
381
    last_filter = ist->input_video_filter;
382

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

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

    
399
    if (vfilters) {
400
        AVFilterInOut *outputs = av_malloc(sizeof(AVFilterInOut));
401
        AVFilterInOut *inputs  = av_malloc(sizeof(AVFilterInOut));
402

    
403
        outputs->name    = av_strdup("in");
404
        outputs->filter_ctx = last_filter;
405
        outputs->pad_idx = 0;
406
        outputs->next    = NULL;
407

    
408
        inputs->name    = av_strdup("out");
409
        inputs->filter_ctx = ist->output_video_filter;
410
        inputs->pad_idx = 0;
411
        inputs->next    = NULL;
412

    
413
        if ((ret = avfilter_graph_parse(graph, vfilters, inputs, outputs, NULL)) < 0)
414
            return ret;
415
        av_freep(&vfilters);
416
    } else {
417
        if ((ret = avfilter_link(last_filter, 0, ist->output_video_filter, 0)) < 0)
418
            return ret;
419
    }
420

    
421
    if ((ret = avfilter_graph_config(graph, NULL)) < 0)
422
        return ret;
423

    
424
    codec->width  = ist->output_video_filter->inputs[0]->w;
425
    codec->height = ist->output_video_filter->inputs[0]->h;
426
    codec->sample_aspect_ratio = ost->st->sample_aspect_ratio =
427
        ist->output_video_filter->inputs[0]->sample_aspect_ratio;
428

    
429
    return 0;
430
}
431
#endif /* CONFIG_AVFILTER */
432

    
433
static void term_exit(void)
434
{
435
    av_log(NULL, AV_LOG_QUIET, "");
436
#if HAVE_TERMIOS_H
437
    tcsetattr (0, TCSANOW, &oldtty);
438
#endif
439
}
440

    
441
static volatile int received_sigterm = 0;
442

    
443
static void
444
sigterm_handler(int sig)
445
{
446
    received_sigterm = sig;
447
    term_exit();
448
}
449

    
450
static void term_init(void)
451
{
452
#if HAVE_TERMIOS_H
453
    struct termios tty;
454

    
455
    tcgetattr (0, &tty);
456
    oldtty = tty;
457
    atexit(term_exit);
458

    
459
    tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
460
                          |INLCR|IGNCR|ICRNL|IXON);
461
    tty.c_oflag |= OPOST;
462
    tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
463
    tty.c_cflag &= ~(CSIZE|PARENB);
464
    tty.c_cflag |= CS8;
465
    tty.c_cc[VMIN] = 1;
466
    tty.c_cc[VTIME] = 0;
467

    
468
    tcsetattr (0, TCSANOW, &tty);
469
    signal(SIGQUIT, sigterm_handler); /* Quit (POSIX).  */
470
#endif
471

    
472
    signal(SIGINT , sigterm_handler); /* Interrupt (ANSI).  */
473
    signal(SIGTERM, sigterm_handler); /* Termination (ANSI).  */
474
#ifdef SIGXCPU
475
    signal(SIGXCPU, sigterm_handler);
476
#endif
477
}
478

    
479
/* read a key without blocking */
480
static int read_key(void)
481
{
482
#if HAVE_TERMIOS_H
483
    int n = 1;
484
    unsigned char ch;
485
    struct timeval tv;
486
    fd_set rfds;
487

    
488
    FD_ZERO(&rfds);
489
    FD_SET(0, &rfds);
490
    tv.tv_sec = 0;
491
    tv.tv_usec = 0;
492
    n = select(1, &rfds, NULL, NULL, &tv);
493
    if (n > 0) {
494
        n = read(0, &ch, 1);
495
        if (n == 1)
496
            return ch;
497

    
498
        return n;
499
    }
500
#elif HAVE_CONIO_H
501
    if(kbhit())
502
        return(getch());
503
#endif
504
    return -1;
505
}
506

    
507
static int decode_interrupt_cb(void)
508
{
509
    return q_pressed || (q_pressed = read_key() == 'q');
510
}
511

    
512
static int ffmpeg_exit(int ret)
513
{
514
    int i;
515

    
516
    /* close files */
517
    for(i=0;i<nb_output_files;i++) {
518
        /* maybe av_close_output_file ??? */
519
        AVFormatContext *s = output_files[i];
520
        int j;
521
        if (!(s->oformat->flags & AVFMT_NOFILE) && s->pb)
522
            url_fclose(s->pb);
523
        for(j=0;j<s->nb_streams;j++) {
524
            av_metadata_free(&s->streams[j]->metadata);
525
            av_free(s->streams[j]->codec);
526
            av_free(s->streams[j]->info);
527
            av_free(s->streams[j]);
528
        }
529
        for(j=0;j<s->nb_programs;j++) {
530
            av_metadata_free(&s->programs[j]->metadata);
531
        }
532
        for(j=0;j<s->nb_chapters;j++) {
533
            av_metadata_free(&s->chapters[j]->metadata);
534
        }
535
        av_metadata_free(&s->metadata);
536
        av_free(s);
537
        av_free(output_streams_for_file[i]);
538
    }
539
    for(i=0;i<nb_input_files;i++) {
540
        av_close_input_file(input_files[i]);
541
        av_free(input_files_ts_scale[i]);
542
    }
543

    
544
    av_free(intra_matrix);
545
    av_free(inter_matrix);
546

    
547
    if (vstats_file)
548
        fclose(vstats_file);
549
    av_free(vstats_filename);
550

    
551
    av_free(opt_names);
552
    av_free(streamid_map);
553
    av_free(input_codecs);
554
    av_free(output_codecs);
555
    av_free(stream_maps);
556
    av_free(meta_data_maps);
557

    
558
    av_free(video_codec_name);
559
    av_free(audio_codec_name);
560
    av_free(subtitle_codec_name);
561

    
562
    av_free(video_standard);
563

    
564
    uninit_opts();
565
    av_free(audio_buf);
566
    av_free(audio_out);
567
    allocated_audio_buf_size= allocated_audio_out_size= 0;
568
    av_free(samples);
569

    
570
#if CONFIG_AVFILTER
571
    avfilter_uninit();
572
#endif
573

    
574
    if (received_sigterm) {
575
        fprintf(stderr,
576
            "Received signal %d: terminating.\n",
577
            (int) received_sigterm);
578
        exit (255);
579
    }
580

    
581
    exit(ret); /* not all OS-es handle main() return value */
582
    return ret;
583
}
584

    
585
/* similar to ff_dynarray_add() and av_fast_realloc() */
586
static void *grow_array(void *array, int elem_size, int *size, int new_size)
587
{
588
    if (new_size >= INT_MAX / elem_size) {
589
        fprintf(stderr, "Array too big.\n");
590
        ffmpeg_exit(1);
591
    }
592
    if (*size < new_size) {
593
        uint8_t *tmp = av_realloc(array, new_size*elem_size);
594
        if (!tmp) {
595
            fprintf(stderr, "Could not alloc buffer.\n");
596
            ffmpeg_exit(1);
597
        }
598
        memset(tmp + *size*elem_size, 0, (new_size-*size) * elem_size);
599
        *size = new_size;
600
        return tmp;
601
    }
602
    return array;
603
}
604

    
605
static void choose_sample_fmt(AVStream *st, AVCodec *codec)
606
{
607
    if(codec && codec->sample_fmts){
608
        const enum AVSampleFormat *p= codec->sample_fmts;
609
        for(; *p!=-1; p++){
610
            if(*p == st->codec->sample_fmt)
611
                break;
612
        }
613
        if (*p == -1) {
614
            av_log(NULL, AV_LOG_WARNING,
615
                   "Incompatible sample format '%s' for codec '%s', auto-selecting format '%s'\n",
616
                   av_get_sample_fmt_name(st->codec->sample_fmt),
617
                   codec->name,
618
                   av_get_sample_fmt_name(codec->sample_fmts[0]));
619
            st->codec->sample_fmt = codec->sample_fmts[0];
620
        }
621
    }
622
}
623

    
624
static void choose_sample_rate(AVStream *st, AVCodec *codec)
625
{
626
    if(codec && codec->supported_samplerates){
627
        const int *p= codec->supported_samplerates;
628
        int best=0;
629
        int best_dist=INT_MAX;
630
        for(; *p; p++){
631
            int dist= abs(st->codec->sample_rate - *p);
632
            if(dist < best_dist){
633
                best_dist= dist;
634
                best= *p;
635
            }
636
        }
637
        if(best_dist){
638
            av_log(st->codec, AV_LOG_WARNING, "Requested sampling rate unsupported using closest supported (%d)\n", best);
639
        }
640
        st->codec->sample_rate= best;
641
    }
642
}
643

    
644
static void choose_pixel_fmt(AVStream *st, AVCodec *codec)
645
{
646
    if(codec && codec->pix_fmts){
647
        const enum PixelFormat *p= codec->pix_fmts;
648
        if(st->codec->strict_std_compliance <= FF_COMPLIANCE_UNOFFICIAL){
649
            if(st->codec->codec_id==CODEC_ID_MJPEG){
650
                p= (const enum PixelFormat[]){PIX_FMT_YUVJ420P, PIX_FMT_YUVJ422P, PIX_FMT_YUV420P, PIX_FMT_YUV422P, PIX_FMT_NONE};
651
            }else if(st->codec->codec_id==CODEC_ID_LJPEG){
652
                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};
653
            }
654
        }
655
        for(; *p!=-1; p++){
656
            if(*p == st->codec->pix_fmt)
657
                break;
658
        }
659
        if(*p == -1)
660
            st->codec->pix_fmt = codec->pix_fmts[0];
661
    }
662
}
663

    
664
static AVOutputStream *new_output_stream(AVFormatContext *oc, int file_idx)
665
{
666
    int idx = oc->nb_streams - 1;
667
    AVOutputStream *ost;
668

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

    
685
static int read_ffserver_streams(AVFormatContext *s, const char *filename)
686
{
687
    int i, err;
688
    AVFormatContext *ic;
689
    int nopts = 0;
690

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

    
700
        s->nb_streams++;
701

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

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

    
726
        if(!st->codec->thread_count)
727
            st->codec->thread_count = 1;
728
        if(st->codec->thread_count>1)
729
            avcodec_thread_init(st->codec, st->codec->thread_count);
730

    
731
        if(st->codec->flags & CODEC_FLAG_BITEXACT)
732
            nopts = 1;
733

    
734
        new_output_stream(s, nb_output_files);
735
    }
736

    
737
    if (!nopts)
738
        s->timestamp = av_gettime();
739

    
740
    av_close_input_file(ic);
741
    return 0;
742
}
743

    
744
static double
745
get_sync_ipts(const AVOutputStream *ost)
746
{
747
    const AVInputStream *ist = ost->sync_ist;
748
    return (double)(ist->pts - start_time)/AV_TIME_BASE;
749
}
750

    
751
static void write_frame(AVFormatContext *s, AVPacket *pkt, AVCodecContext *avctx, AVBitStreamFilterContext *bsfc){
752
    int ret;
753

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

    
773
        bsfc= bsfc->next;
774
    }
775

    
776
    ret= av_interleaved_write_frame(s, pkt);
777
    if(ret < 0){
778
        print_error("av_interleaved_write_frame()", ret);
779
        ffmpeg_exit(1);
780
    }
781
}
782

    
783
#define MAX_AUDIO_PACKET_SIZE (128 * 1024)
784

    
785
static void do_audio_out(AVFormatContext *s,
786
                         AVOutputStream *ost,
787
                         AVInputStream *ist,
788
                         unsigned char *buf, int size)
789
{
790
    uint8_t *buftmp;
791
    int64_t audio_out_size, audio_buf_size;
792
    int64_t allocated_for_size= size;
793

    
794
    int size_out, frame_bytes, ret, resample_changed;
795
    AVCodecContext *enc= ost->st->codec;
796
    AVCodecContext *dec= ist->st->codec;
797
    int osize= av_get_bits_per_sample_fmt(enc->sample_fmt)/8;
798
    int isize= av_get_bits_per_sample_fmt(dec->sample_fmt)/8;
799
    const int coded_bps = av_get_bits_per_sample(enc->codec->id);
800

    
801
need_realloc:
802
    audio_buf_size= (allocated_for_size + isize*dec->channels - 1) / (isize*dec->channels);
803
    audio_buf_size= (audio_buf_size*enc->sample_rate + dec->sample_rate) / dec->sample_rate;
804
    audio_buf_size= audio_buf_size*2 + 10000; //safety factors for the deprecated resampling API
805
    audio_buf_size= FFMAX(audio_buf_size, enc->frame_size);
806
    audio_buf_size*= osize*enc->channels;
807

    
808
    audio_out_size= FFMAX(audio_buf_size, enc->frame_size * osize * enc->channels);
809
    if(coded_bps > 8*osize)
810
        audio_out_size= audio_out_size * coded_bps / (8*osize);
811
    audio_out_size += FF_MIN_BUFFER_SIZE;
812

    
813
    if(audio_out_size > INT_MAX || audio_buf_size > INT_MAX){
814
        fprintf(stderr, "Buffer sizes too large\n");
815
        ffmpeg_exit(1);
816
    }
817

    
818
    av_fast_malloc(&audio_buf, &allocated_audio_buf_size, audio_buf_size);
819
    av_fast_malloc(&audio_out, &allocated_audio_out_size, audio_out_size);
820
    if (!audio_buf || !audio_out){
821
        fprintf(stderr, "Out of memory in do_audio_out\n");
822
        ffmpeg_exit(1);
823
    }
824

    
825
    if (enc->channels != dec->channels)
826
        ost->audio_resample = 1;
827

    
828
    resample_changed = ost->resample_sample_fmt  != dec->sample_fmt ||
829
                       ost->resample_channels    != dec->channels   ||
830
                       ost->resample_sample_rate != dec->sample_rate;
831

    
832
    if ((ost->audio_resample && !ost->resample) || resample_changed) {
833
        if (resample_changed) {
834
            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",
835
                   ist->file_index, ist->index,
836
                   ost->resample_sample_rate, av_get_sample_fmt_name(ost->resample_sample_fmt), ost->resample_channels,
837
                   dec->sample_rate, av_get_sample_fmt_name(dec->sample_fmt), dec->channels);
838
            ost->resample_sample_fmt  = dec->sample_fmt;
839
            ost->resample_channels    = dec->channels;
840
            ost->resample_sample_rate = dec->sample_rate;
841
            if (ost->resample)
842
                audio_resample_close(ost->resample);
843
        }
844
        /* if audio_sync_method is >1 the resampler is needed for audio drift compensation */
845
        if (audio_sync_method <= 1 &&
846
            ost->resample_sample_fmt  == enc->sample_fmt &&
847
            ost->resample_channels    == enc->channels   &&
848
            ost->resample_sample_rate == enc->sample_rate) {
849
            ost->resample = NULL;
850
            ost->audio_resample = 0;
851
        } else {
852
            if (dec->sample_fmt != AV_SAMPLE_FMT_S16)
853
                fprintf(stderr, "Warning, using s16 intermediate sample format for resampling\n");
854
            ost->resample = av_audio_resample_init(enc->channels,    dec->channels,
855
                                                   enc->sample_rate, dec->sample_rate,
856
                                                   enc->sample_fmt,  dec->sample_fmt,
857
                                                   16, 10, 0, 0.8);
858
            if (!ost->resample) {
859
                fprintf(stderr, "Can not resample %d channels @ %d Hz to %d channels @ %d Hz\n",
860
                        dec->channels, dec->sample_rate,
861
                        enc->channels, enc->sample_rate);
862
                ffmpeg_exit(1);
863
            }
864
        }
865
    }
866

    
867
#define MAKE_SFMT_PAIR(a,b) ((a)+AV_SAMPLE_FMT_NB*(b))
868
    if (!ost->audio_resample && dec->sample_fmt!=enc->sample_fmt &&
869
        MAKE_SFMT_PAIR(enc->sample_fmt,dec->sample_fmt)!=ost->reformat_pair) {
870
        if (ost->reformat_ctx)
871
            av_audio_convert_free(ost->reformat_ctx);
872
        ost->reformat_ctx = av_audio_convert_alloc(enc->sample_fmt, 1,
873
                                                   dec->sample_fmt, 1, NULL, 0);
874
        if (!ost->reformat_ctx) {
875
            fprintf(stderr, "Cannot convert %s sample format to %s sample format\n",
876
                av_get_sample_fmt_name(dec->sample_fmt),
877
                av_get_sample_fmt_name(enc->sample_fmt));
878
            ffmpeg_exit(1);
879
        }
880
        ost->reformat_pair=MAKE_SFMT_PAIR(enc->sample_fmt,dec->sample_fmt);
881
    }
882

    
883
    if(audio_sync_method){
884
        double delta = get_sync_ipts(ost) * enc->sample_rate - ost->sync_opts
885
                - av_fifo_size(ost->fifo)/(enc->channels * 2);
886
        double idelta= delta*dec->sample_rate / enc->sample_rate;
887
        int byte_delta= ((int)idelta)*2*dec->channels;
888

    
889
        //FIXME resample delay
890
        if(fabs(delta) > 50){
891
            if(ist->is_start || fabs(delta) > audio_drift_threshold*enc->sample_rate){
892
                if(byte_delta < 0){
893
                    byte_delta= FFMAX(byte_delta, -size);
894
                    size += byte_delta;
895
                    buf  -= byte_delta;
896
                    if(verbose > 2)
897
                        fprintf(stderr, "discarding %d audio samples\n", (int)-delta);
898
                    if(!size)
899
                        return;
900
                    ist->is_start=0;
901
                }else{
902
                    static uint8_t *input_tmp= NULL;
903
                    input_tmp= av_realloc(input_tmp, byte_delta + size);
904

    
905
                    if(byte_delta > allocated_for_size - size){
906
                        allocated_for_size= byte_delta + (int64_t)size;
907
                        goto need_realloc;
908
                    }
909
                    ist->is_start=0;
910

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

    
931
    if (ost->audio_resample) {
932
        buftmp = audio_buf;
933
        size_out = audio_resample(ost->resample,
934
                                  (short *)buftmp, (short *)buf,
935
                                  size / (dec->channels * isize));
936
        size_out = size_out * enc->channels * osize;
937
    } else {
938
        buftmp = buf;
939
        size_out = size;
940
    }
941

    
942
    if (!ost->audio_resample && dec->sample_fmt!=enc->sample_fmt) {
943
        const void *ibuf[6]= {buftmp};
944
        void *obuf[6]= {audio_buf};
945
        int istride[6]= {isize};
946
        int ostride[6]= {osize};
947
        int len= size_out/istride[0];
948
        if (av_audio_convert(ost->reformat_ctx, obuf, ostride, ibuf, istride, len)<0) {
949
            printf("av_audio_convert() failed\n");
950
            if (exit_on_error)
951
                ffmpeg_exit(1);
952
            return;
953
        }
954
        buftmp = audio_buf;
955
        size_out = len*osize;
956
    }
957

    
958
    /* now encode as many frames as possible */
959
    if (enc->frame_size > 1) {
960
        /* output resampled raw samples */
961
        if (av_fifo_realloc2(ost->fifo, av_fifo_size(ost->fifo) + size_out) < 0) {
962
            fprintf(stderr, "av_fifo_realloc2() failed\n");
963
            ffmpeg_exit(1);
964
        }
965
        av_fifo_generic_write(ost->fifo, buftmp, size_out, NULL);
966

    
967
        frame_bytes = enc->frame_size * osize * enc->channels;
968

    
969
        while (av_fifo_size(ost->fifo) >= frame_bytes) {
970
            AVPacket pkt;
971
            av_init_packet(&pkt);
972

    
973
            av_fifo_generic_read(ost->fifo, audio_buf, frame_bytes, NULL);
974

    
975
            //FIXME pass ost->sync_opts as AVFrame.pts in avcodec_encode_audio()
976

    
977
            ret = avcodec_encode_audio(enc, audio_out, audio_out_size,
978
                                       (short *)audio_buf);
979
            if (ret < 0) {
980
                fprintf(stderr, "Audio encoding failed\n");
981
                ffmpeg_exit(1);
982
            }
983
            audio_size += ret;
984
            pkt.stream_index= ost->index;
985
            pkt.data= audio_out;
986
            pkt.size= ret;
987
            if(enc->coded_frame && enc->coded_frame->pts != AV_NOPTS_VALUE)
988
                pkt.pts= av_rescale_q(enc->coded_frame->pts, enc->time_base, ost->st->time_base);
989
            pkt.flags |= AV_PKT_FLAG_KEY;
990
            write_frame(s, &pkt, enc, ost->bitstream_filters);
991

    
992
            ost->sync_opts += enc->frame_size;
993
        }
994
    } else {
995
        AVPacket pkt;
996
        av_init_packet(&pkt);
997

    
998
        ost->sync_opts += size_out / (osize * enc->channels);
999

    
1000
        /* output a pcm frame */
1001
        /* determine the size of the coded buffer */
1002
        size_out /= osize;
1003
        if (coded_bps)
1004
            size_out = size_out*coded_bps/8;
1005

    
1006
        if(size_out > audio_out_size){
1007
            fprintf(stderr, "Internal error, buffer size too small\n");
1008
            ffmpeg_exit(1);
1009
        }
1010

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

    
1029
static void pre_process_video_frame(AVInputStream *ist, AVPicture *picture, void **bufp)
1030
{
1031
    AVCodecContext *dec;
1032
    AVPicture *picture2;
1033
    AVPicture picture_tmp;
1034
    uint8_t *buf = 0;
1035

    
1036
    dec = ist->st->codec;
1037

    
1038
    /* deinterlace : must be done before any resize */
1039
    if (do_deinterlace) {
1040
        int size;
1041

    
1042
        /* create temporary picture */
1043
        size = avpicture_get_size(dec->pix_fmt, dec->width, dec->height);
1044
        buf = av_malloc(size);
1045
        if (!buf)
1046
            return;
1047

    
1048
        picture2 = &picture_tmp;
1049
        avpicture_fill(picture2, buf, dec->pix_fmt, dec->width, dec->height);
1050

    
1051
        if(avpicture_deinterlace(picture2, picture,
1052
                                 dec->pix_fmt, dec->width, dec->height) < 0) {
1053
            /* if error, do not deinterlace */
1054
            fprintf(stderr, "Deinterlacing failed\n");
1055
            av_free(buf);
1056
            buf = NULL;
1057
            picture2 = picture;
1058
        }
1059
    } else {
1060
        picture2 = picture;
1061
    }
1062

    
1063
    if (picture != picture2)
1064
        *picture = *picture2;
1065
    *bufp = buf;
1066
}
1067

    
1068
/* we begin to correct av delay at this threshold */
1069
#define AV_DELAY_MAX 0.100
1070

    
1071
static void do_subtitle_out(AVFormatContext *s,
1072
                            AVOutputStream *ost,
1073
                            AVInputStream *ist,
1074
                            AVSubtitle *sub,
1075
                            int64_t pts)
1076
{
1077
    static uint8_t *subtitle_out = NULL;
1078
    int subtitle_out_max_size = 1024 * 1024;
1079
    int subtitle_out_size, nb, i;
1080
    AVCodecContext *enc;
1081
    AVPacket pkt;
1082

    
1083
    if (pts == AV_NOPTS_VALUE) {
1084
        fprintf(stderr, "Subtitle packets must have a pts\n");
1085
        if (exit_on_error)
1086
            ffmpeg_exit(1);
1087
        return;
1088
    }
1089

    
1090
    enc = ost->st->codec;
1091

    
1092
    if (!subtitle_out) {
1093
        subtitle_out = av_malloc(subtitle_out_max_size);
1094
    }
1095

    
1096
    /* Note: DVB subtitle need one packet to draw them and one other
1097
       packet to clear them */
1098
    /* XXX: signal it in the codec context ? */
1099
    if (enc->codec_id == CODEC_ID_DVB_SUBTITLE)
1100
        nb = 2;
1101
    else
1102
        nb = 1;
1103

    
1104
    for(i = 0; i < nb; i++) {
1105
        sub->pts = av_rescale_q(pts, ist->st->time_base, AV_TIME_BASE_Q);
1106
        // start_display_time is required to be 0
1107
        sub->pts              += av_rescale_q(sub->start_display_time, (AVRational){1, 1000}, AV_TIME_BASE_Q);
1108
        sub->end_display_time -= sub->start_display_time;
1109
        sub->start_display_time = 0;
1110
        subtitle_out_size = avcodec_encode_subtitle(enc, subtitle_out,
1111
                                                    subtitle_out_max_size, sub);
1112
        if (subtitle_out_size < 0) {
1113
            fprintf(stderr, "Subtitle encoding failed\n");
1114
            ffmpeg_exit(1);
1115
        }
1116

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

    
1134
static int bit_buffer_size= 1024*256;
1135
static uint8_t *bit_buffer= NULL;
1136

    
1137
static void do_video_out(AVFormatContext *s,
1138
                         AVOutputStream *ost,
1139
                         AVInputStream *ist,
1140
                         AVFrame *in_picture,
1141
                         int *frame_size)
1142
{
1143
    int nb_frames, i, ret;
1144
    AVFrame *final_picture, *formatted_picture, *resampling_dst, *padding_src;
1145
    AVCodecContext *enc, *dec;
1146
    double sync_ipts;
1147

    
1148
    enc = ost->st->codec;
1149
    dec = ist->st->codec;
1150

    
1151
    sync_ipts = get_sync_ipts(ost) / av_q2d(enc->time_base);
1152

    
1153
    /* by default, we output a single frame */
1154
    nb_frames = 1;
1155

    
1156
    *frame_size = 0;
1157

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

    
1183
    nb_frames= FFMIN(nb_frames, max_frames[AVMEDIA_TYPE_VIDEO] - ost->frame_number);
1184
    if (nb_frames <= 0)
1185
        return;
1186

    
1187
    formatted_picture = in_picture;
1188
    final_picture = formatted_picture;
1189
    padding_src = formatted_picture;
1190
    resampling_dst = &ost->pict_tmp;
1191

    
1192
    if (   ost->resample_height != ist->st->codec->height
1193
        || ost->resample_width  != ist->st->codec->width
1194
        || (ost->resample_pix_fmt!= ist->st->codec->pix_fmt) ) {
1195

    
1196
        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));
1197
        if(!ost->video_resample)
1198
            ffmpeg_exit(1);
1199
    }
1200

    
1201
#if !CONFIG_AVFILTER
1202
    if (ost->video_resample) {
1203
        padding_src = NULL;
1204
        final_picture = &ost->pict_tmp;
1205
        if(  ost->resample_height != ist->st->codec->height
1206
          || ost->resample_width  != ist->st->codec->width
1207
          || (ost->resample_pix_fmt!= ist->st->codec->pix_fmt) ) {
1208

    
1209
            /* initialize a new scaler context */
1210
            sws_freeContext(ost->img_resample_ctx);
1211
            sws_flags = av_get_int(sws_opts, "sws_flags", NULL);
1212
            ost->img_resample_ctx = sws_getContext(
1213
                ist->st->codec->width,
1214
                ist->st->codec->height,
1215
                ist->st->codec->pix_fmt,
1216
                ost->st->codec->width,
1217
                ost->st->codec->height,
1218
                ost->st->codec->pix_fmt,
1219
                sws_flags, NULL, NULL, NULL);
1220
            if (ost->img_resample_ctx == NULL) {
1221
                fprintf(stderr, "Cannot get resampling context\n");
1222
                ffmpeg_exit(1);
1223
            }
1224
        }
1225
        sws_scale(ost->img_resample_ctx, formatted_picture->data, formatted_picture->linesize,
1226
              0, ost->resample_height, resampling_dst->data, resampling_dst->linesize);
1227
    }
1228
#endif
1229

    
1230
    /* duplicates frame if needed */
1231
    for(i=0;i<nb_frames;i++) {
1232
        AVPacket pkt;
1233
        av_init_packet(&pkt);
1234
        pkt.stream_index= ost->index;
1235

    
1236
        if (s->oformat->flags & AVFMT_RAWPICTURE) {
1237
            /* raw pictures are written as AVPicture structure to
1238
               avoid any copies. We support temorarily the older
1239
               method. */
1240
            AVFrame* old_frame = enc->coded_frame;
1241
            enc->coded_frame = dec->coded_frame; //FIXME/XXX remove this hack
1242
            pkt.data= (uint8_t *)final_picture;
1243
            pkt.size=  sizeof(AVPicture);
1244
            pkt.pts= av_rescale_q(ost->sync_opts, enc->time_base, ost->st->time_base);
1245
            pkt.flags |= AV_PKT_FLAG_KEY;
1246

    
1247
            write_frame(s, &pkt, ost->st->codec, ost->bitstream_filters);
1248
            enc->coded_frame = old_frame;
1249
        } else {
1250
            AVFrame big_picture;
1251

    
1252
            big_picture= *final_picture;
1253
            /* better than nothing: use input picture interlaced
1254
               settings */
1255
            big_picture.interlaced_frame = in_picture->interlaced_frame;
1256
            if(avcodec_opts[AVMEDIA_TYPE_VIDEO]->flags & (CODEC_FLAG_INTERLACED_DCT|CODEC_FLAG_INTERLACED_ME)){
1257
                if(top_field_first == -1)
1258
                    big_picture.top_field_first = in_picture->top_field_first;
1259
                else
1260
                    big_picture.top_field_first = top_field_first;
1261
            }
1262

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

    
1285
            if(ret>0){
1286
                pkt.data= bit_buffer;
1287
                pkt.size= ret;
1288
                if(enc->coded_frame->pts != AV_NOPTS_VALUE)
1289
                    pkt.pts= av_rescale_q(enc->coded_frame->pts, enc->time_base, ost->st->time_base);
1290
/*av_log(NULL, AV_LOG_DEBUG, "encoder -> %"PRId64"/%"PRId64"\n",
1291
   pkt.pts != AV_NOPTS_VALUE ? av_rescale(pkt.pts, enc->time_base.den, AV_TIME_BASE*(int64_t)enc->time_base.num) : -1,
1292
   pkt.dts != AV_NOPTS_VALUE ? av_rescale(pkt.dts, enc->time_base.den, AV_TIME_BASE*(int64_t)enc->time_base.num) : -1);*/
1293

    
1294
                if(enc->coded_frame->key_frame)
1295
                    pkt.flags |= AV_PKT_FLAG_KEY;
1296
                write_frame(s, &pkt, ost->st->codec, ost->bitstream_filters);
1297
                *frame_size = ret;
1298
                video_size += ret;
1299
                //fprintf(stderr,"\nFrame: %3d size: %5d type: %d",
1300
                //        enc->frame_number-1, ret, enc->pict_type);
1301
                /* if two pass, output log */
1302
                if (ost->logfile && enc->stats_out) {
1303
                    fprintf(ost->logfile, "%s", enc->stats_out);
1304
                }
1305
            }
1306
        }
1307
        ost->sync_opts++;
1308
        ost->frame_number++;
1309
    }
1310
}
1311

    
1312
static double psnr(double d){
1313
    return -10.0*log(d)/log(10.0);
1314
}
1315

    
1316
static void do_video_stats(AVFormatContext *os, AVOutputStream *ost,
1317
                           int frame_size)
1318
{
1319
    AVCodecContext *enc;
1320
    int frame_number;
1321
    double ti1, bitrate, avg_bitrate;
1322

    
1323
    /* this is executed just the first time do_video_stats is called */
1324
    if (!vstats_file) {
1325
        vstats_file = fopen(vstats_filename, "w");
1326
        if (!vstats_file) {
1327
            perror("fopen");
1328
            ffmpeg_exit(1);
1329
        }
1330
    }
1331

    
1332
    enc = ost->st->codec;
1333
    if (enc->codec_type == AVMEDIA_TYPE_VIDEO) {
1334
        frame_number = ost->frame_number;
1335
        fprintf(vstats_file, "frame= %5d q= %2.1f ", frame_number, enc->coded_frame->quality/(float)FF_QP2LAMBDA);
1336
        if (enc->flags&CODEC_FLAG_PSNR)
1337
            fprintf(vstats_file, "PSNR= %6.2f ", psnr(enc->coded_frame->error[0]/(enc->width*enc->height*255.0*255.0)));
1338

    
1339
        fprintf(vstats_file,"f_size= %6d ", frame_size);
1340
        /* compute pts value */
1341
        ti1 = ost->sync_opts * av_q2d(enc->time_base);
1342
        if (ti1 < 0.01)
1343
            ti1 = 0.01;
1344

    
1345
        bitrate = (frame_size * 8) / av_q2d(enc->time_base) / 1000.0;
1346
        avg_bitrate = (double)(video_size * 8) / ti1 / 1000.0;
1347
        fprintf(vstats_file, "s_size= %8.0fkB time= %0.3f br= %7.1fkbits/s avg_br= %7.1fkbits/s ",
1348
            (double)video_size / 1024, ti1, bitrate, avg_bitrate);
1349
        fprintf(vstats_file,"type= %c\n", av_get_pict_type_char(enc->coded_frame->pict_type));
1350
    }
1351
}
1352

    
1353
static void print_report(AVFormatContext **output_files,
1354
                         AVOutputStream **ost_table, int nb_ostreams,
1355
                         int is_last_report)
1356
{
1357
    char buf[1024];
1358
    AVOutputStream *ost;
1359
    AVFormatContext *oc;
1360
    int64_t total_size;
1361
    AVCodecContext *enc;
1362
    int frame_number, vid, i;
1363
    double bitrate, ti1, pts;
1364
    static int64_t last_time = -1;
1365
    static int qp_histogram[52];
1366

    
1367
    if (!is_last_report) {
1368
        int64_t cur_time;
1369
        /* display the report every 0.5 seconds */
1370
        cur_time = av_gettime();
1371
        if (last_time == -1) {
1372
            last_time = cur_time;
1373
            return;
1374
        }
1375
        if ((cur_time - last_time) < 500000)
1376
            return;
1377
        last_time = cur_time;
1378
    }
1379

    
1380

    
1381
    oc = output_files[0];
1382

    
1383
    total_size = url_fsize(oc->pb);
1384
    if(total_size<0) // FIXME improve url_fsize() so it works with non seekable output too
1385
        total_size= url_ftell(oc->pb);
1386

    
1387
    buf[0] = '\0';
1388
    ti1 = 1e10;
1389
    vid = 0;
1390
    for(i=0;i<nb_ostreams;i++) {
1391
        ost = ost_table[i];
1392
        enc = ost->st->codec;
1393
        if (vid && enc->codec_type == AVMEDIA_TYPE_VIDEO) {
1394
            snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "q=%2.1f ",
1395
                     !ost->st->stream_copy ?
1396
                     enc->coded_frame->quality/(float)FF_QP2LAMBDA : -1);
1397
        }
1398
        if (!vid && enc->codec_type == AVMEDIA_TYPE_VIDEO) {
1399
            float t = (av_gettime()-timer_start) / 1000000.0;
1400

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

    
1447
    if (verbose || is_last_report) {
1448
        bitrate = (double)(total_size * 8) / ti1 / 1000.0;
1449

    
1450
        snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
1451
            "size=%8.0fkB time=%0.2f bitrate=%6.1fkbits/s",
1452
            (double)total_size / 1024, ti1, bitrate);
1453

    
1454
        if (nb_frames_dup || nb_frames_drop)
1455
          snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), " dup=%d drop=%d",
1456
                  nb_frames_dup, nb_frames_drop);
1457

    
1458
        if (verbose >= 0)
1459
            fprintf(stderr, "%s    \r", buf);
1460

    
1461
        fflush(stderr);
1462
    }
1463

    
1464
    if (is_last_report && verbose >= 0){
1465
        int64_t raw= audio_size + video_size + extra_size;
1466
        fprintf(stderr, "\n");
1467
        fprintf(stderr, "video:%1.0fkB audio:%1.0fkB global headers:%1.0fkB muxing overhead %f%%\n",
1468
                video_size/1024.0,
1469
                audio_size/1024.0,
1470
                extra_size/1024.0,
1471
                100.0*(total_size - raw)/raw
1472
        );
1473
    }
1474
}
1475

    
1476
/* pkt = NULL means EOF (needed to flush decoder buffers) */
1477
static int output_packet(AVInputStream *ist, int ist_index,
1478
                         AVOutputStream **ost_table, int nb_ostreams,
1479
                         const AVPacket *pkt)
1480
{
1481
    AVFormatContext *os;
1482
    AVOutputStream *ost;
1483
    int ret, i;
1484
    int got_picture;
1485
    AVFrame picture;
1486
    void *buffer_to_free;
1487
    static unsigned int samples_size= 0;
1488
    AVSubtitle subtitle, *subtitle_to_free;
1489
    int64_t pkt_pts = AV_NOPTS_VALUE;
1490
#if CONFIG_AVFILTER
1491
    int frame_available;
1492
#endif
1493

    
1494
    AVPacket avpkt;
1495
    int bps = av_get_bits_per_sample_fmt(ist->st->codec->sample_fmt)>>3;
1496

    
1497
    if(ist->next_pts == AV_NOPTS_VALUE)
1498
        ist->next_pts= ist->pts;
1499

    
1500
    if (pkt == NULL) {
1501
        /* EOF handling */
1502
        av_init_packet(&avpkt);
1503
        avpkt.data = NULL;
1504
        avpkt.size = 0;
1505
        goto handle_eof;
1506
    } else {
1507
        avpkt = *pkt;
1508
    }
1509

    
1510
    if(pkt->dts != AV_NOPTS_VALUE)
1511
        ist->next_pts = ist->pts = av_rescale_q(pkt->dts, ist->st->time_base, AV_TIME_BASE_Q);
1512
    if(pkt->pts != AV_NOPTS_VALUE)
1513
        pkt_pts = av_rescale_q(pkt->pts, ist->st->time_base, AV_TIME_BASE_Q);
1514

    
1515
    //while we have more to decode or while the decoder did output something on EOF
1516
    while (avpkt.size > 0 || (!pkt && ist->next_pts != ist->pts)) {
1517
        uint8_t *data_buf, *decoded_data_buf;
1518
        int data_size, decoded_data_size;
1519
    handle_eof:
1520
        ist->pts= ist->next_pts;
1521

    
1522
        if(avpkt.size && avpkt.size != pkt->size &&
1523
           ((!ist->showed_multi_packet_warning && verbose>0) || verbose>1)){
1524
            fprintf(stderr, "Multiple frames in a packet from stream %d\n", pkt->stream_index);
1525
            ist->showed_multi_packet_warning=1;
1526
        }
1527

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

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

    
1620
        buffer_to_free = NULL;
1621
        if (ist->st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
1622
            pre_process_video_frame(ist, (AVPicture *)&picture,
1623
                                    &buffer_to_free);
1624
        }
1625

    
1626
#if CONFIG_AVFILTER
1627
        if (ist->st->codec->codec_type == AVMEDIA_TYPE_VIDEO && ist->input_video_filter) {
1628
            AVRational sar;
1629
            if (ist->st->sample_aspect_ratio.num) sar = ist->st->sample_aspect_ratio;
1630
            else                                  sar = ist->st->codec->sample_aspect_ratio;
1631
            // add it to be filtered
1632
            av_vsrc_buffer_add_frame(ist->input_video_filter, &picture,
1633
                                     ist->pts,
1634
                                     sar);
1635
        }
1636
#endif
1637

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

    
1652
        /* frame rate emulation */
1653
        if (rate_emu) {
1654
            int64_t pts = av_rescale(ist->pts, 1000000, AV_TIME_BASE);
1655
            int64_t now = av_gettime() - ist->start;
1656
            if (pts > now)
1657
                usleep(pts - now);
1658
        }
1659
#if CONFIG_AVFILTER
1660
        frame_available = ist->st->codec->codec_type != AVMEDIA_TYPE_VIDEO ||
1661
            !ist->output_video_filter || avfilter_poll_frame(ist->output_video_filter->inputs[0]);
1662
#endif
1663
        /* if output time reached then transcode raw format,
1664
           encode packets and output them */
1665
        if (start_time == 0 || ist->pts >= start_time)
1666
#if CONFIG_AVFILTER
1667
        while (frame_available) {
1668
            AVRational ist_pts_tb;
1669
            if (ist->st->codec->codec_type == AVMEDIA_TYPE_VIDEO && ist->output_video_filter)
1670
                get_filtered_video_frame(ist->output_video_filter, &picture, &ist->picref, &ist_pts_tb);
1671
            if (ist->picref)
1672
                ist->pts = av_rescale_q(ist->picref->pts, ist_pts_tb, AV_TIME_BASE_Q);
1673
#endif
1674
            for(i=0;i<nb_ostreams;i++) {
1675
                int frame_size;
1676

    
1677
                ost = ost_table[i];
1678
                if (ost->source_index == ist_index) {
1679
                    os = output_files[ost->file_index];
1680

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

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

    
1711
                        av_init_packet(&opkt);
1712

    
1713
                        if ((!ost->frame_number && !(pkt->flags & AV_PKT_FLAG_KEY)) && !copy_initial_nonkeyframes)
1714
                            continue;
1715

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

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

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

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

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

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

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

    
1757
                        write_frame(os, &opkt, ost->st->codec, ost->bitstream_filters);
1758
                        ost->st->codec->frame_number++;
1759
                        ost->frame_number++;
1760
                        av_free_packet(&opkt);
1761
                    }
1762
                }
1763
            }
1764

    
1765
#if CONFIG_AVFILTER
1766
            frame_available = (ist->st->codec->codec_type == AVMEDIA_TYPE_VIDEO) &&
1767
                              ist->output_video_filter && avfilter_poll_frame(ist->output_video_filter->inputs[0]);
1768
            if(ist->picref)
1769
                avfilter_unref_buffer(ist->picref);
1770
        }
1771
#endif
1772
        av_free(buffer_to_free);
1773
        /* XXX: allocate the subtitles in the codec ? */
1774
        if (subtitle_to_free) {
1775
            avsubtitle_free(subtitle_to_free);
1776
            subtitle_to_free = NULL;
1777
        }
1778
    }
1779
 discard_packet:
1780
    if (pkt == NULL) {
1781
        /* EOF handling */
1782

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

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

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

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

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

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

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

    
1865
    return 0;
1866
 fail_decode:
1867
    return -1;
1868
}
1869

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

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

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

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

    
1892

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

    
1898
        out_ch = av_mallocz(sizeof(AVChapter));
1899
        if (!out_ch)
1900
            return AVERROR(ENOMEM);
1901

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

    
1907
        if (metadata_chapters_autocopy)
1908
            av_metadata_copy(&out_ch->metadata, in_ch->metadata, 0);
1909

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

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

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

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

    
1963
    file_table= av_mallocz(nb_input_files * sizeof(AVInputFile));
1964
    if (!file_table)
1965
        goto fail;
1966

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

    
1977
    ist_table = av_mallocz(nb_istreams * sizeof(AVInputStream *));
1978
    if (!ist_table)
1979
        goto fail;
1980

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

    
1998
            if (rate_emu) {
1999
                ist->start = av_gettime();
2000
            }
2001
        }
2002
    }
2003

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

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

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

    
2043
    ost_table = av_mallocz(sizeof(AVOutputStream *) * nb_ostreams);
2044
    if (!ost_table)
2045
        goto fail;
2046
    n = 0;
2047
    for(k=0;k<nb_output_files;k++) {
2048
        os = output_files[k];
2049
        for(i=0;i<os->nb_streams;i++,n++) {
2050
            int found;
2051
            ost = ost_table[n] = output_streams_for_file[k][i];
2052
            ost->st = os->streams[i];
2053
            if (nb_stream_maps > 0) {
2054
                ost->source_index = file_table[stream_maps[n].file_index].ist_index +
2055
                    stream_maps[n].stream_index;
2056

    
2057
                /* Sanity check that the stream types match */
2058
                if (ist_table[ost->source_index]->st->codec->codec_type != ost->st->codec->codec_type) {
2059
                    int i= ost->file_index;
2060
                    dump_format(output_files[i], i, output_files[i]->filename, 1);
2061
                    fprintf(stderr, "Codec type mismatch for mapping #%d.%d -> #%d.%d\n",
2062
                        stream_maps[n].file_index, stream_maps[n].stream_index,
2063
                        ost->file_index, ost->index);
2064
                    ffmpeg_exit(1);
2065
                }
2066

    
2067
            } else {
2068
                int best_nb_frames=-1;
2069
                /* get corresponding input stream index : we select the first one with the right type */
2070
                found = 0;
2071
                for(j=0;j<nb_istreams;j++) {
2072
                    int skip=0;
2073
                    ist = ist_table[j];
2074
                    if(opt_programid){
2075
                        int pi,si;
2076
                        AVFormatContext *f= input_files[ ist->file_index ];
2077
                        skip=1;
2078
                        for(pi=0; pi<f->nb_programs; pi++){
2079
                            AVProgram *p= f->programs[pi];
2080
                            if(p->id == opt_programid)
2081
                                for(si=0; si<p->nb_stream_indexes; si++){
2082
                                    if(f->streams[ p->stream_index[si] ] == ist->st)
2083
                                        skip=0;
2084
                                }
2085
                        }
2086
                    }
2087
                    if (ist->discard && ist->st->discard != AVDISCARD_ALL && !skip &&
2088
                        ist->st->codec->codec_type == ost->st->codec->codec_type) {
2089
                        if(best_nb_frames < ist->st->codec_info_nb_frames){
2090
                            best_nb_frames= ist->st->codec_info_nb_frames;
2091
                            ost->source_index = j;
2092
                            found = 1;
2093
                        }
2094
                    }
2095
                }
2096

    
2097
                if (!found) {
2098
                    if(! opt_programid) {
2099
                        /* try again and reuse existing stream */
2100
                        for(j=0;j<nb_istreams;j++) {
2101
                            ist = ist_table[j];
2102
                            if (   ist->st->codec->codec_type == ost->st->codec->codec_type
2103
                                && ist->st->discard != AVDISCARD_ALL) {
2104
                                ost->source_index = j;
2105
                                found = 1;
2106
                            }
2107
                        }
2108
                    }
2109
                    if (!found) {
2110
                        int i= ost->file_index;
2111
                        dump_format(output_files[i], i, output_files[i]->filename, 1);
2112
                        fprintf(stderr, "Could not find input stream matching output stream #%d.%d\n",
2113
                                ost->file_index, ost->index);
2114
                        ffmpeg_exit(1);
2115
                    }
2116
                }
2117
            }
2118
            ist = ist_table[ost->source_index];
2119
            ist->discard = 0;
2120
            ost->sync_ist = (nb_stream_maps > 0) ?
2121
                ist_table[file_table[stream_maps[n].sync_file_index].ist_index +
2122
                         stream_maps[n].sync_stream_index] : ist;
2123
        }
2124
    }
2125

    
2126
    /* for each output stream, we compute the right encoding parameters */
2127
    for(i=0;i<nb_ostreams;i++) {
2128
        ost = ost_table[i];
2129
        os = output_files[ost->file_index];
2130
        ist = ist_table[ost->source_index];
2131

    
2132
        codec = ost->st->codec;
2133
        icodec = ist->st->codec;
2134

    
2135
        if (metadata_streams_autocopy)
2136
            av_metadata_copy(&ost->st->metadata, ist->st->metadata,
2137
                             AV_METADATA_DONT_OVERWRITE);
2138

    
2139
        ost->st->disposition = ist->st->disposition;
2140
        codec->bits_per_raw_sample= icodec->bits_per_raw_sample;
2141
        codec->chroma_sample_location = icodec->chroma_sample_location;
2142

    
2143
        if (ost->st->stream_copy) {
2144
            uint64_t extra_size = (uint64_t)icodec->extradata_size + FF_INPUT_BUFFER_PADDING_SIZE;
2145

    
2146
            if (extra_size > INT_MAX)
2147
                goto fail;
2148

    
2149
            /* if stream_copy is selected, no need to decode or encode */
2150
            codec->codec_id = icodec->codec_id;
2151
            codec->codec_type = icodec->codec_type;
2152

    
2153
            if(!codec->codec_tag){
2154
                if(   !os->oformat->codec_tag
2155
                   || av_codec_get_id (os->oformat->codec_tag, icodec->codec_tag) == codec->codec_id
2156
                   || av_codec_get_tag(os->oformat->codec_tag, icodec->codec_id) <= 0)
2157
                    codec->codec_tag = icodec->codec_tag;
2158
            }
2159

    
2160
            codec->bit_rate = icodec->bit_rate;
2161
            codec->rc_max_rate    = icodec->rc_max_rate;
2162
            codec->rc_buffer_size = icodec->rc_buffer_size;
2163
            codec->extradata= av_mallocz(extra_size);
2164
            if (!codec->extradata)
2165
                goto fail;
2166
            memcpy(codec->extradata, icodec->extradata, icodec->extradata_size);
2167
            codec->extradata_size= icodec->extradata_size;
2168
            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){
2169
                codec->time_base = icodec->time_base;
2170
                codec->time_base.num *= icodec->ticks_per_frame;
2171
                av_reduce(&codec->time_base.num, &codec->time_base.den,
2172
                          codec->time_base.num, codec->time_base.den, INT_MAX);
2173
            }else
2174
                codec->time_base = ist->st->time_base;
2175
            switch(codec->codec_type) {
2176
            case AVMEDIA_TYPE_AUDIO:
2177
                if(audio_volume != 256) {
2178
                    fprintf(stderr,"-acodec copy and -vol are incompatible (frames are not decoded)\n");
2179
                    ffmpeg_exit(1);
2180
                }
2181
                codec->channel_layout = icodec->channel_layout;
2182
                codec->sample_rate = icodec->sample_rate;
2183
                codec->channels = icodec->channels;
2184
                codec->frame_size = icodec->frame_size;
2185
                codec->block_align= icodec->block_align;
2186
                if(codec->block_align == 1 && codec->codec_id == CODEC_ID_MP3)
2187
                    codec->block_align= 0;
2188
                if(codec->codec_id == CODEC_ID_AC3)
2189
                    codec->block_align= 0;
2190
                break;
2191
            case AVMEDIA_TYPE_VIDEO:
2192
                codec->pix_fmt = icodec->pix_fmt;
2193
                codec->width = icodec->width;
2194
                codec->height = icodec->height;
2195
                codec->has_b_frames = icodec->has_b_frames;
2196
                break;
2197
            case AVMEDIA_TYPE_SUBTITLE:
2198
                codec->width = icodec->width;
2199
                codec->height = icodec->height;
2200
                break;
2201
            default:
2202
                abort();
2203
            }
2204
        } else {
2205
            switch(codec->codec_type) {
2206
            case AVMEDIA_TYPE_AUDIO:
2207
                ost->fifo= av_fifo_alloc(1024);
2208
                if(!ost->fifo)
2209
                    goto fail;
2210
                ost->reformat_pair = MAKE_SFMT_PAIR(AV_SAMPLE_FMT_NONE,AV_SAMPLE_FMT_NONE);
2211
                ost->audio_resample = codec->sample_rate != icodec->sample_rate || audio_sync_method > 1;
2212
                icodec->request_channels = codec->channels;
2213
                ist->decoding_needed = 1;
2214
                ost->encoding_needed = 1;
2215
                ost->resample_sample_fmt  = icodec->sample_fmt;
2216
                ost->resample_sample_rate = icodec->sample_rate;
2217
                ost->resample_channels    = icodec->channels;
2218
                break;
2219
            case AVMEDIA_TYPE_VIDEO:
2220
                if (ost->st->codec->pix_fmt == PIX_FMT_NONE) {
2221
                    fprintf(stderr, "Video pixel format is unknown, stream cannot be encoded\n");
2222
                    ffmpeg_exit(1);
2223
                }
2224
                ost->video_resample = (codec->width != icodec->width   ||
2225
                                       codec->height != icodec->height ||
2226
                        (codec->pix_fmt != icodec->pix_fmt));
2227
                if (ost->video_resample) {
2228
#if !CONFIG_AVFILTER
2229
                    avcodec_get_frame_defaults(&ost->pict_tmp);
2230
                    if(avpicture_alloc((AVPicture*)&ost->pict_tmp, codec->pix_fmt,
2231
                                         codec->width, codec->height)) {
2232
                        fprintf(stderr, "Cannot allocate temp picture, check pix fmt\n");
2233
                        ffmpeg_exit(1);
2234
                    }
2235
                    sws_flags = av_get_int(sws_opts, "sws_flags", NULL);
2236
                    ost->img_resample_ctx = sws_getContext(
2237
                        icodec->width,
2238
                        icodec->height,
2239
                            icodec->pix_fmt,
2240
                            codec->width,
2241
                            codec->height,
2242
                            codec->pix_fmt,
2243
                            sws_flags, NULL, NULL, NULL);
2244
                    if (ost->img_resample_ctx == NULL) {
2245
                        fprintf(stderr, "Cannot get resampling context\n");
2246
                        ffmpeg_exit(1);
2247
                    }
2248

    
2249
                    ost->original_height = icodec->height;
2250
                    ost->original_width  = icodec->width;
2251
#endif
2252
                    codec->bits_per_raw_sample= 0;
2253
                }
2254
                ost->resample_height = icodec->height;
2255
                ost->resample_width  = icodec->width;
2256
                ost->resample_pix_fmt= icodec->pix_fmt;
2257
                ost->encoding_needed = 1;
2258
                ist->decoding_needed = 1;
2259

    
2260
#if CONFIG_AVFILTER
2261
                if (configure_filters(ist, ost)) {
2262
                    fprintf(stderr, "Error opening filters!\n");
2263
                    exit(1);
2264
                }
2265
#endif
2266
                break;
2267
            case AVMEDIA_TYPE_SUBTITLE:
2268
                ost->encoding_needed = 1;
2269
                ist->decoding_needed = 1;
2270
                break;
2271
            default:
2272
                abort();
2273
                break;
2274
            }
2275
            /* two pass mode */
2276
            if (ost->encoding_needed &&
2277
                (codec->flags & (CODEC_FLAG_PASS1 | CODEC_FLAG_PASS2))) {
2278
                char logfilename[1024];
2279
                FILE *f;
2280

    
2281
                snprintf(logfilename, sizeof(logfilename), "%s-%d.log",
2282
                         pass_logfilename_prefix ? pass_logfilename_prefix : DEFAULT_PASS_LOGFILENAME_PREFIX,
2283
                         i);
2284
                if (codec->flags & CODEC_FLAG_PASS1) {
2285
                    f = fopen(logfilename, "wb");
2286
                    if (!f) {
2287
                        fprintf(stderr, "Cannot write log file '%s' for pass-1 encoding: %s\n", logfilename, strerror(errno));
2288
                        ffmpeg_exit(1);
2289
                    }
2290
                    ost->logfile = f;
2291
                } else {
2292
                    char  *logbuffer;
2293
                    size_t logbuffer_size;
2294
                    if (read_file(logfilename, &logbuffer, &logbuffer_size) < 0) {
2295
                        fprintf(stderr, "Error reading log file '%s' for pass-2 encoding\n", logfilename);
2296
                        ffmpeg_exit(1);
2297
                    }
2298
                    codec->stats_in = logbuffer;
2299
                }
2300
            }
2301
        }
2302
        if(codec->codec_type == AVMEDIA_TYPE_VIDEO){
2303
            int size= codec->width * codec->height;
2304
            bit_buffer_size= FFMAX(bit_buffer_size, 6*size + 200);
2305
        }
2306
    }
2307

    
2308
    if (!bit_buffer)
2309
        bit_buffer = av_malloc(bit_buffer_size);
2310
    if (!bit_buffer) {
2311
        fprintf(stderr, "Cannot allocate %d bytes output buffer\n",
2312
                bit_buffer_size);
2313
        ret = AVERROR(ENOMEM);
2314
        goto fail;
2315
    }
2316

    
2317
    /* open each encoder */
2318
    for(i=0;i<nb_ostreams;i++) {
2319
        ost = ost_table[i];
2320
        if (ost->encoding_needed) {
2321
            AVCodec *codec = i < nb_output_codecs ? output_codecs[i] : NULL;
2322
            AVCodecContext *dec = ist_table[ost->source_index]->st->codec;
2323
            if (!codec)
2324
                codec = avcodec_find_encoder(ost->st->codec->codec_id);
2325
            if (!codec) {
2326
                snprintf(error, sizeof(error), "Encoder (codec id %d) not found for output stream #%d.%d",
2327
                         ost->st->codec->codec_id, ost->file_index, ost->index);
2328
                ret = AVERROR(EINVAL);
2329
                goto dump_format;
2330
            }
2331
            if (dec->subtitle_header) {
2332
                ost->st->codec->subtitle_header = av_malloc(dec->subtitle_header_size);
2333
                if (!ost->st->codec->subtitle_header) {
2334
                    ret = AVERROR(ENOMEM);
2335
                    goto dump_format;
2336
                }
2337
                memcpy(ost->st->codec->subtitle_header, dec->subtitle_header, dec->subtitle_header_size);
2338
                ost->st->codec->subtitle_header_size = dec->subtitle_header_size;
2339
            }
2340
            if (avcodec_open(ost->st->codec, codec) < 0) {
2341
                snprintf(error, sizeof(error), "Error while opening encoder for output stream #%d.%d - maybe incorrect parameters such as bit_rate, rate, width or height",
2342
                        ost->file_index, ost->index);
2343
                ret = AVERROR(EINVAL);
2344
                goto dump_format;
2345
            }
2346
            extra_size += ost->st->codec->extradata_size;
2347
        }
2348
    }
2349

    
2350
    /* open each decoder */
2351
    for(i=0;i<nb_istreams;i++) {
2352
        ist = ist_table[i];
2353
        if (ist->decoding_needed) {
2354
            AVCodec *codec = i < nb_input_codecs ? input_codecs[i] : NULL;
2355
            if (!codec)
2356
                codec = avcodec_find_decoder(ist->st->codec->codec_id);
2357
            if (!codec) {
2358
                snprintf(error, sizeof(error), "Decoder (codec id %d) not found for input stream #%d.%d",
2359
                        ist->st->codec->codec_id, ist->file_index, ist->index);
2360
                ret = AVERROR(EINVAL);
2361
                goto dump_format;
2362
            }
2363
            if (avcodec_open(ist->st->codec, codec) < 0) {
2364
                snprintf(error, sizeof(error), "Error while opening decoder for input stream #%d.%d",
2365
                        ist->file_index, ist->index);
2366
                ret = AVERROR(EINVAL);
2367
                goto dump_format;
2368
            }
2369
            //if (ist->st->codec->codec_type == AVMEDIA_TYPE_VIDEO)
2370
            //    ist->st->codec->flags |= CODEC_FLAG_REPEAT_FIELD;
2371
        }
2372
    }
2373

    
2374
    /* init pts */
2375
    for(i=0;i<nb_istreams;i++) {
2376
        AVStream *st;
2377
        ist = ist_table[i];
2378
        st= ist->st;
2379
        ist->pts = st->avg_frame_rate.num ? - st->codec->has_b_frames*AV_TIME_BASE / av_q2d(st->avg_frame_rate) : 0;
2380
        ist->next_pts = AV_NOPTS_VALUE;
2381
        init_pts_correction(&ist->pts_ctx);
2382
        ist->is_start = 1;
2383
    }
2384

    
2385
    /* set meta data information from input file if required */
2386
    for (i=0;i<nb_meta_data_maps;i++) {
2387
        AVFormatContext *files[2];
2388
        AVMetadata      **meta[2];
2389
        int j;
2390

    
2391
#define METADATA_CHECK_INDEX(index, nb_elems, desc)\
2392
        if ((index) < 0 || (index) >= (nb_elems)) {\
2393
            snprintf(error, sizeof(error), "Invalid %s index %d while processing metadata maps\n",\
2394
                     (desc), (index));\
2395
            ret = AVERROR(EINVAL);\
2396
            goto dump_format;\
2397
        }
2398

    
2399
        int out_file_index = meta_data_maps[i][0].file;
2400
        int in_file_index = meta_data_maps[i][1].file;
2401
        if (in_file_index < 0 || out_file_index < 0)
2402
            continue;
2403
        METADATA_CHECK_INDEX(out_file_index, nb_output_files, "output file")
2404
        METADATA_CHECK_INDEX(in_file_index, nb_input_files, "input file")
2405

    
2406
        files[0] = output_files[out_file_index];
2407
        files[1] = input_files[in_file_index];
2408

    
2409
        for (j = 0; j < 2; j++) {
2410
            AVMetaDataMap *map = &meta_data_maps[i][j];
2411

    
2412
            switch (map->type) {
2413
            case 'g':
2414
                meta[j] = &files[j]->metadata;
2415
                break;
2416
            case 's':
2417
                METADATA_CHECK_INDEX(map->index, files[j]->nb_streams, "stream")
2418
                meta[j] = &files[j]->streams[map->index]->metadata;
2419
                break;
2420
            case 'c':
2421
                METADATA_CHECK_INDEX(map->index, files[j]->nb_chapters, "chapter")
2422
                meta[j] = &files[j]->chapters[map->index]->metadata;
2423
                break;
2424
            case 'p':
2425
                METADATA_CHECK_INDEX(map->index, files[j]->nb_programs, "program")
2426
                meta[j] = &files[j]->programs[map->index]->metadata;
2427
                break;
2428
            }
2429
        }
2430

    
2431
        av_metadata_copy(meta[0], *meta[1], AV_METADATA_DONT_OVERWRITE);
2432
    }
2433

    
2434
    /* copy global metadata by default */
2435
    if (metadata_global_autocopy) {
2436

    
2437
        for (i = 0; i < nb_output_files; i++)
2438
            av_metadata_copy(&output_files[i]->metadata, input_files[0]->metadata,
2439
                             AV_METADATA_DONT_OVERWRITE);
2440
    }
2441

    
2442
    /* copy chapters according to chapter maps */
2443
    for (i = 0; i < nb_chapter_maps; i++) {
2444
        int infile  = chapter_maps[i].in_file;
2445
        int outfile = chapter_maps[i].out_file;
2446

    
2447
        if (infile < 0 || outfile < 0)
2448
            continue;
2449
        if (infile >= nb_input_files) {
2450
            snprintf(error, sizeof(error), "Invalid input file index %d in chapter mapping.\n", infile);
2451
            ret = AVERROR(EINVAL);
2452
            goto dump_format;
2453
        }
2454
        if (outfile >= nb_output_files) {
2455
            snprintf(error, sizeof(error), "Invalid output file index %d in chapter mapping.\n",outfile);
2456
            ret = AVERROR(EINVAL);
2457
            goto dump_format;
2458
        }
2459
        copy_chapters(infile, outfile);
2460
    }
2461

    
2462
    /* copy chapters from the first input file that has them*/
2463
    if (!nb_chapter_maps)
2464
        for (i = 0; i < nb_input_files; i++) {
2465
            if (!input_files[i]->nb_chapters)
2466
                continue;
2467

    
2468
            for (j = 0; j < nb_output_files; j++)
2469
                if ((ret = copy_chapters(i, j)) < 0)
2470
                    goto dump_format;
2471
            break;
2472
        }
2473

    
2474
    /* open files and write file headers */
2475
    for(i=0;i<nb_output_files;i++) {
2476
        os = output_files[i];
2477
        if (av_write_header(os) < 0) {
2478
            snprintf(error, sizeof(error), "Could not write header for output file #%d (incorrect codec parameters ?)", i);
2479
            ret = AVERROR(EINVAL);
2480
            goto dump_format;
2481
        }
2482
        if (strcmp(output_files[i]->oformat->name, "rtp")) {
2483
            want_sdp = 0;
2484
        }
2485
    }
2486

    
2487
 dump_format:
2488
    /* dump the file output parameters - cannot be done before in case
2489
       of stream copy */
2490
    for(i=0;i<nb_output_files;i++) {
2491
        dump_format(output_files[i], i, output_files[i]->filename, 1);
2492
    }
2493

    
2494
    /* dump the stream mapping */
2495
    if (verbose >= 0) {
2496
        fprintf(stderr, "Stream mapping:\n");
2497
        for(i=0;i<nb_ostreams;i++) {
2498
            ost = ost_table[i];
2499
            fprintf(stderr, "  Stream #%d.%d -> #%d.%d",
2500
                    ist_table[ost->source_index]->file_index,
2501
                    ist_table[ost->source_index]->index,
2502
                    ost->file_index,
2503
                    ost->index);
2504
            if (ost->sync_ist != ist_table[ost->source_index])
2505
                fprintf(stderr, " [sync #%d.%d]",
2506
                        ost->sync_ist->file_index,
2507
                        ost->sync_ist->index);
2508
            fprintf(stderr, "\n");
2509
        }
2510
    }
2511

    
2512
    if (ret) {
2513
        fprintf(stderr, "%s\n", error);
2514
        goto fail;
2515
    }
2516

    
2517
    if (want_sdp) {
2518
        print_sdp(output_files, nb_output_files);
2519
    }
2520

    
2521
    if (!using_stdin && verbose >= 0) {
2522
        fprintf(stderr, "Press [q] to stop encoding\n");
2523
        url_set_interrupt_cb(decode_interrupt_cb);
2524
    }
2525
    term_init();
2526

    
2527
    timer_start = av_gettime();
2528

    
2529
    for(; received_sigterm == 0;) {
2530
        int file_index, ist_index;
2531
        AVPacket pkt;
2532
        double ipts_min;
2533
        double opts_min;
2534

    
2535
    redo:
2536
        ipts_min= 1e100;
2537
        opts_min= 1e100;
2538
        /* if 'q' pressed, exits */
2539
        if (!using_stdin) {
2540
            if (q_pressed)
2541
                break;
2542
            /* read_key() returns 0 on EOF */
2543
            key = read_key();
2544
            if (key == 'q')
2545
                break;
2546
        }
2547

    
2548
        /* select the stream that we must read now by looking at the
2549
           smallest output pts */
2550
        file_index = -1;
2551
        for(i=0;i<nb_ostreams;i++) {
2552
            double ipts, opts;
2553
            ost = ost_table[i];
2554
            os = output_files[ost->file_index];
2555
            ist = ist_table[ost->source_index];
2556
            if(ist->is_past_recording_time || no_packet[ist->file_index])
2557
                continue;
2558
                opts = ost->st->pts.val * av_q2d(ost->st->time_base);
2559
            ipts = (double)ist->pts;
2560
            if (!file_table[ist->file_index].eof_reached){
2561
                if(ipts < ipts_min) {
2562
                    ipts_min = ipts;
2563
                    if(input_sync ) file_index = ist->file_index;
2564
                }
2565
                if(opts < opts_min) {
2566
                    opts_min = opts;
2567
                    if(!input_sync) file_index = ist->file_index;
2568
                }
2569
            }
2570
            if(ost->frame_number >= max_frames[ost->st->codec->codec_type]){
2571
                file_index= -1;
2572
                break;
2573
            }
2574
        }
2575
        /* if none, if is finished */
2576
        if (file_index < 0) {
2577
            if(no_packet_count){
2578
                no_packet_count=0;
2579
                memset(no_packet, 0, sizeof(no_packet));
2580
                usleep(10000);
2581
                continue;
2582
            }
2583
            break;
2584
        }
2585

    
2586
        /* finish if limit size exhausted */
2587
        if (limit_filesize != 0 && limit_filesize <= url_ftell(output_files[0]->pb))
2588
            break;
2589

    
2590
        /* read a frame from it and output it in the fifo */
2591
        is = input_files[file_index];
2592
        ret= av_read_frame(is, &pkt);
2593
        if(ret == AVERROR(EAGAIN)){
2594
            no_packet[file_index]=1;
2595
            no_packet_count++;
2596
            continue;
2597
        }
2598
        if (ret < 0) {
2599
            file_table[file_index].eof_reached = 1;
2600
            if (opt_shortest)
2601
                break;
2602
            else
2603
                continue;
2604
        }
2605

    
2606
        no_packet_count=0;
2607
        memset(no_packet, 0, sizeof(no_packet));
2608

    
2609
        if (do_pkt_dump) {
2610
            av_pkt_dump_log(NULL, AV_LOG_DEBUG, &pkt, do_hex_dump);
2611
        }
2612
        /* the following test is needed in case new streams appear
2613
           dynamically in stream : we ignore them */
2614
        if (pkt.stream_index >= file_table[file_index].nb_streams)
2615
            goto discard_packet;
2616
        ist_index = file_table[file_index].ist_index + pkt.stream_index;
2617
        ist = ist_table[ist_index];
2618
        if (ist->discard)
2619
            goto discard_packet;
2620

    
2621
        if (pkt.dts != AV_NOPTS_VALUE)
2622
            pkt.dts += av_rescale_q(input_files_ts_offset[ist->file_index], AV_TIME_BASE_Q, ist->st->time_base);
2623
        if (pkt.pts != AV_NOPTS_VALUE)
2624
            pkt.pts += av_rescale_q(input_files_ts_offset[ist->file_index], AV_TIME_BASE_Q, ist->st->time_base);
2625

    
2626
        if (pkt.stream_index < nb_input_files_ts_scale[file_index]
2627
            && input_files_ts_scale[file_index][pkt.stream_index]){
2628
            if(pkt.pts != AV_NOPTS_VALUE)
2629
                pkt.pts *= input_files_ts_scale[file_index][pkt.stream_index];
2630
            if(pkt.dts != AV_NOPTS_VALUE)
2631
                pkt.dts *= input_files_ts_scale[file_index][pkt.stream_index];
2632
        }
2633

    
2634
//        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);
2635
        if (pkt.dts != AV_NOPTS_VALUE && ist->next_pts != AV_NOPTS_VALUE
2636
            && (is->iformat->flags & AVFMT_TS_DISCONT)) {
2637
            int64_t pkt_dts= av_rescale_q(pkt.dts, ist->st->time_base, AV_TIME_BASE_Q);
2638
            int64_t delta= pkt_dts - ist->next_pts;
2639
            if((FFABS(delta) > 1LL*dts_delta_threshold*AV_TIME_BASE || pkt_dts+1<ist->pts)&& !copy_ts){
2640
                input_files_ts_offset[ist->file_index]-= delta;
2641
                if (verbose > 2)
2642
                    fprintf(stderr, "timestamp discontinuity %"PRId64", new offset= %"PRId64"\n", delta, input_files_ts_offset[ist->file_index]);
2643
                pkt.dts-= av_rescale_q(delta, AV_TIME_BASE_Q, ist->st->time_base);
2644
                if(pkt.pts != AV_NOPTS_VALUE)
2645
                    pkt.pts-= av_rescale_q(delta, AV_TIME_BASE_Q, ist->st->time_base);
2646
            }
2647
        }
2648

    
2649
        /* finish if recording time exhausted */
2650
        if (recording_time != INT64_MAX &&
2651
            av_compare_ts(pkt.pts, ist->st->time_base, recording_time + start_time, (AVRational){1, 1000000}) >= 0) {
2652
            ist->is_past_recording_time = 1;
2653
            goto discard_packet;
2654
        }
2655

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

    
2659
            if (verbose >= 0)
2660
                fprintf(stderr, "Error while decoding stream #%d.%d\n",
2661
                        ist->file_index, ist->index);
2662
            if (exit_on_error)
2663
                ffmpeg_exit(1);
2664
            av_free_packet(&pkt);
2665
            goto redo;
2666
        }
2667

    
2668
    discard_packet:
2669
        av_free_packet(&pkt);
2670

    
2671
        /* dump report by using the output first video and audio streams */
2672
        print_report(output_files, ost_table, nb_ostreams, 0);
2673
    }
2674

    
2675
    /* at the end of stream, we must flush the decoder buffers */
2676
    for(i=0;i<nb_istreams;i++) {
2677
        ist = ist_table[i];
2678
        if (ist->decoding_needed) {
2679
            output_packet(ist, i, ost_table, nb_ostreams, NULL);
2680
        }
2681
    }
2682

    
2683
    term_exit();
2684

    
2685
    /* write the trailer if needed and close file */
2686
    for(i=0;i<nb_output_files;i++) {
2687
        os = output_files[i];
2688
        av_write_trailer(os);
2689
    }
2690

    
2691
    /* dump report by using the first video and audio streams */
2692
    print_report(output_files, ost_table, nb_ostreams, 1);
2693

    
2694
    /* close each encoder */
2695
    for(i=0;i<nb_ostreams;i++) {
2696
        ost = ost_table[i];
2697
        if (ost->encoding_needed) {
2698
            av_freep(&ost->st->codec->stats_in);
2699
            avcodec_close(ost->st->codec);
2700
        }
2701
    }
2702

    
2703
    /* close each decoder */
2704
    for(i=0;i<nb_istreams;i++) {
2705
        ist = ist_table[i];
2706
        if (ist->decoding_needed) {
2707
            avcodec_close(ist->st->codec);
2708
        }
2709
    }
2710
#if CONFIG_AVFILTER
2711
    if (graph) {
2712
        avfilter_graph_free(graph);
2713
        av_freep(&graph);
2714
    }
2715
#endif
2716

    
2717
    /* finished ! */
2718
    ret = 0;
2719

    
2720
 fail:
2721
    av_freep(&bit_buffer);
2722
    av_free(file_table);
2723

    
2724
    if (ist_table) {
2725
        for(i=0;i<nb_istreams;i++) {
2726
            ist = ist_table[i];
2727
            av_free(ist);
2728
        }
2729
        av_free(ist_table);
2730
    }
2731
    if (ost_table) {
2732
        for(i=0;i<nb_ostreams;i++) {
2733
            ost = ost_table[i];
2734
            if (ost) {
2735
                if (ost->st->stream_copy)
2736
                    av_freep(&ost->st->codec->extradata);
2737
                if (ost->logfile) {
2738
                    fclose(ost->logfile);
2739
                    ost->logfile = NULL;
2740
                }
2741
                av_fifo_free(ost->fifo); /* works even if fifo is not
2742
                                             initialized but set to zero */
2743
                av_freep(&ost->st->codec->subtitle_header);
2744
                av_free(ost->pict_tmp.data[0]);
2745
                av_free(ost->forced_kf_pts);
2746
                if (ost->video_resample)
2747
                    sws_freeContext(ost->img_resample_ctx);
2748
                if (ost->resample)
2749
                    audio_resample_close(ost->resample);
2750
                if (ost->reformat_ctx)
2751
                    av_audio_convert_free(ost->reformat_ctx);
2752
                av_free(ost);
2753
            }
2754
        }
2755
        av_free(ost_table);
2756
    }
2757
    return ret;
2758
}
2759

    
2760
static void opt_format(const char *arg)
2761
{
2762
    last_asked_format = arg;
2763
}
2764

    
2765
static void opt_video_rc_override_string(const char *arg)
2766
{
2767
    video_rc_override_string = arg;
2768
}
2769

    
2770
static int opt_me_threshold(const char *opt, const char *arg)
2771
{
2772
    me_threshold = parse_number_or_die(opt, arg, OPT_INT64, INT_MIN, INT_MAX);
2773
    return 0;
2774
}
2775

    
2776
static int opt_verbose(const char *opt, const char *arg)
2777
{
2778
    verbose = parse_number_or_die(opt, arg, OPT_INT64, -10, 10);
2779
    return 0;
2780
}
2781

    
2782
static int opt_frame_rate(const char *opt, const char *arg)
2783
{
2784
    if (av_parse_video_rate(&frame_rate, arg) < 0) {
2785
        fprintf(stderr, "Incorrect value for %s: %s\n", opt, arg);
2786
        ffmpeg_exit(1);
2787
    }
2788
    return 0;
2789
}
2790

    
2791
static int opt_bitrate(const char *opt, const char *arg)
2792
{
2793
    int codec_type = opt[0]=='a' ? AVMEDIA_TYPE_AUDIO : AVMEDIA_TYPE_VIDEO;
2794

    
2795
    opt_default(opt, arg);
2796

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

    
2800
    return 0;
2801
}
2802

    
2803
static int opt_frame_crop(const char *opt, const char *arg)
2804
{
2805
    fprintf(stderr, "Option '%s' has been removed, use the crop filter instead\n", opt);
2806
    return AVERROR(EINVAL);
2807
}
2808

    
2809
static void opt_frame_size(const char *arg)
2810
{
2811
    if (av_parse_video_size(&frame_width, &frame_height, arg) < 0) {
2812
        fprintf(stderr, "Incorrect frame size\n");
2813
        ffmpeg_exit(1);
2814
    }
2815
}
2816

    
2817
static int opt_pad(const char *opt, const char *arg) {
2818
    fprintf(stderr, "Option '%s' has been removed, use the pad filter instead\n", opt);
2819
    return -1;
2820
}
2821

    
2822
static void opt_frame_pix_fmt(const char *arg)
2823
{
2824
    if (strcmp(arg, "list")) {
2825
        frame_pix_fmt = av_get_pix_fmt(arg);
2826
        if (frame_pix_fmt == PIX_FMT_NONE) {
2827
            fprintf(stderr, "Unknown pixel format requested: %s\n", arg);
2828
            ffmpeg_exit(1);
2829
        }
2830
    } else {
2831
        show_pix_fmts();
2832
        ffmpeg_exit(0);
2833
    }
2834
}
2835

    
2836
static void opt_frame_aspect_ratio(const char *arg)
2837
{
2838
    int x = 0, y = 0;
2839
    double ar = 0;
2840
    const char *p;
2841
    char *end;
2842

    
2843
    p = strchr(arg, ':');
2844
    if (p) {
2845
        x = strtol(arg, &end, 10);
2846
        if (end == p)
2847
            y = strtol(end+1, &end, 10);
2848
        if (x > 0 && y > 0)
2849
            ar = (double)x / (double)y;
2850
    } else
2851
        ar = strtod(arg, NULL);
2852

    
2853
    if (!ar) {
2854
        fprintf(stderr, "Incorrect aspect ratio specification.\n");
2855
        ffmpeg_exit(1);
2856
    }
2857
    frame_aspect_ratio = ar;
2858

    
2859
    x = vfilters ? strlen(vfilters) : 0;
2860
    vfilters = av_realloc(vfilters, x+100);
2861
    snprintf(vfilters+x, x+100, "%csetdar=%f\n", x?',':' ', ar);
2862
}
2863

    
2864
static int opt_metadata(const char *opt, const char *arg)
2865
{
2866
    char *mid= strchr(arg, '=');
2867

    
2868
    if(!mid){
2869
        fprintf(stderr, "Missing =\n");
2870
        ffmpeg_exit(1);
2871
    }
2872
    *mid++= 0;
2873

    
2874
    av_metadata_set2(&metadata, arg, mid, 0);
2875

    
2876
    return 0;
2877
}
2878

    
2879
static void opt_qscale(const char *arg)
2880
{
2881
    video_qscale = atof(arg);
2882
    if (video_qscale <= 0 ||
2883
        video_qscale > 255) {
2884
        fprintf(stderr, "qscale must be > 0.0 and <= 255\n");
2885
        ffmpeg_exit(1);
2886
    }
2887
}
2888

    
2889
static void opt_top_field_first(const char *arg)
2890
{
2891
    top_field_first= atoi(arg);
2892
}
2893

    
2894
static int opt_thread_count(const char *opt, const char *arg)
2895
{
2896
    thread_count= parse_number_or_die(opt, arg, OPT_INT64, 0, INT_MAX);
2897
#if !HAVE_THREADS
2898
    if (verbose >= 0)
2899
        fprintf(stderr, "Warning: not compiled with thread support, using thread emulation\n");
2900
#endif
2901
    return 0;
2902
}
2903

    
2904
static void opt_audio_sample_fmt(const char *arg)
2905
{
2906
    if (strcmp(arg, "list")) {
2907
        audio_sample_fmt = av_get_sample_fmt(arg);
2908
        if (audio_sample_fmt == AV_SAMPLE_FMT_NONE) {
2909
            av_log(NULL, AV_LOG_ERROR, "Invalid sample format '%s'\n", arg);
2910
            ffmpeg_exit(1);
2911
        }
2912
    } else {
2913
        list_fmts(av_get_sample_fmt_string, AV_SAMPLE_FMT_NB);
2914
        ffmpeg_exit(0);
2915
    }
2916
}
2917

    
2918
static int opt_audio_rate(const char *opt, const char *arg)
2919
{
2920
    audio_sample_rate = parse_number_or_die(opt, arg, OPT_INT64, 0, INT_MAX);
2921
    return 0;
2922
}
2923

    
2924
static int opt_audio_channels(const char *opt, const char *arg)
2925
{
2926
    audio_channels = parse_number_or_die(opt, arg, OPT_INT64, 0, INT_MAX);
2927
    return 0;
2928
}
2929

    
2930
static void opt_video_channel(const char *arg)
2931
{
2932
    video_channel = strtol(arg, NULL, 0);
2933
}
2934

    
2935
static void opt_video_standard(const char *arg)
2936
{
2937
    video_standard = av_strdup(arg);
2938
}
2939

    
2940
static void opt_codec(int *pstream_copy, char **pcodec_name,
2941
                      int codec_type, const char *arg)
2942
{
2943
    av_freep(pcodec_name);
2944
    if (!strcmp(arg, "copy")) {
2945
        *pstream_copy = 1;
2946
    } else {
2947
        *pcodec_name = av_strdup(arg);
2948
    }
2949
}
2950

    
2951
static void opt_audio_codec(const char *arg)
2952
{
2953
    opt_codec(&audio_stream_copy, &audio_codec_name, AVMEDIA_TYPE_AUDIO, arg);
2954
}
2955

    
2956
static void opt_video_codec(const char *arg)
2957
{
2958
    opt_codec(&video_stream_copy, &video_codec_name, AVMEDIA_TYPE_VIDEO, arg);
2959
}
2960

    
2961
static void opt_subtitle_codec(const char *arg)
2962
{
2963
    opt_codec(&subtitle_stream_copy, &subtitle_codec_name, AVMEDIA_TYPE_SUBTITLE, arg);
2964
}
2965

    
2966
static int opt_codec_tag(const char *opt, const char *arg)
2967
{
2968
    char *tail;
2969
    uint32_t *codec_tag;
2970

    
2971
    codec_tag = !strcmp(opt, "atag") ? &audio_codec_tag :
2972
                !strcmp(opt, "vtag") ? &video_codec_tag :
2973
                !strcmp(opt, "stag") ? &subtitle_codec_tag : NULL;
2974
    if (!codec_tag)
2975
        return -1;
2976

    
2977
    *codec_tag = strtol(arg, &tail, 0);
2978
    if (!tail || *tail)
2979
        *codec_tag = AV_RL32(arg);
2980

    
2981
    return 0;
2982
}
2983

    
2984
static void opt_map(const char *arg)
2985
{
2986
    AVStreamMap *m;
2987
    char *p;
2988

    
2989
    stream_maps = grow_array(stream_maps, sizeof(*stream_maps), &nb_stream_maps, nb_stream_maps + 1);
2990
    m = &stream_maps[nb_stream_maps-1];
2991

    
2992
    m->file_index = strtol(arg, &p, 0);
2993
    if (*p)
2994
        p++;
2995

    
2996
    m->stream_index = strtol(p, &p, 0);
2997
    if (*p) {
2998
        p++;
2999
        m->sync_file_index = strtol(p, &p, 0);
3000
        if (*p)
3001
            p++;
3002
        m->sync_stream_index = strtol(p, &p, 0);
3003
    } else {
3004
        m->sync_file_index = m->file_index;
3005
        m->sync_stream_index = m->stream_index;
3006
    }
3007
}
3008

    
3009
static void parse_meta_type(char *arg, char *type, int *index, char **endptr)
3010
{
3011
    *endptr = arg;
3012
    if (*arg == ',') {
3013
        *type = *(++arg);
3014
        switch (*arg) {
3015
        case 'g':
3016
            break;
3017
        case 's':
3018
        case 'c':
3019
        case 'p':
3020
            *index = strtol(++arg, endptr, 0);
3021
            break;
3022
        default:
3023
            fprintf(stderr, "Invalid metadata type %c.\n", *arg);
3024
            ffmpeg_exit(1);
3025
        }
3026
    } else
3027
        *type = 'g';
3028
}
3029

    
3030
static void opt_map_metadata(const char *arg)
3031
{
3032
    AVMetaDataMap *m, *m1;
3033
    char *p;
3034

    
3035
    meta_data_maps = grow_array(meta_data_maps, sizeof(*meta_data_maps),
3036
                                &nb_meta_data_maps, nb_meta_data_maps + 1);
3037

    
3038
    m = &meta_data_maps[nb_meta_data_maps - 1][0];
3039
    m->file = strtol(arg, &p, 0);
3040
    parse_meta_type(p, &m->type, &m->index, &p);
3041
    if (*p)
3042
        p++;
3043

    
3044
    m1 = &meta_data_maps[nb_meta_data_maps - 1][1];
3045
    m1->file = strtol(p, &p, 0);
3046
    parse_meta_type(p, &m1->type, &m1->index, &p);
3047

    
3048
    if (m->type == 'g' || m1->type == 'g')
3049
        metadata_global_autocopy = 0;
3050
    if (m->type == 's' || m1->type == 's')
3051
        metadata_streams_autocopy = 0;
3052
    if (m->type == 'c' || m1->type == 'c')
3053
        metadata_chapters_autocopy = 0;
3054
}
3055

    
3056
static void opt_map_meta_data(const char *arg)
3057
{
3058
    fprintf(stderr, "-map_meta_data is deprecated and will be removed soon. "
3059
                    "Use -map_metadata instead.\n");
3060
    opt_map_metadata(arg);
3061
}
3062

    
3063
static void opt_map_chapters(const char *arg)
3064
{
3065
    AVChapterMap *c;
3066
    char *p;
3067

    
3068
    chapter_maps = grow_array(chapter_maps, sizeof(*chapter_maps), &nb_chapter_maps,
3069
                              nb_chapter_maps + 1);
3070
    c = &chapter_maps[nb_chapter_maps - 1];
3071
    c->out_file = strtol(arg, &p, 0);
3072
    if (*p)
3073
        p++;
3074

    
3075
    c->in_file = strtol(p, &p, 0);
3076
}
3077

    
3078
static void opt_input_ts_scale(const char *arg)
3079
{
3080
    unsigned int stream;
3081
    double scale;
3082
    char *p;
3083

    
3084
    stream = strtol(arg, &p, 0);
3085
    if (*p)
3086
        p++;
3087
    scale= strtod(p, &p);
3088

    
3089
    if(stream >= MAX_STREAMS)
3090
        ffmpeg_exit(1);
3091

    
3092
    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);
3093
    input_files_ts_scale[nb_input_files][stream]= scale;
3094
}
3095

    
3096
static int opt_recording_time(const char *opt, const char *arg)
3097
{
3098
    recording_time = parse_time_or_die(opt, arg, 1);
3099
    return 0;
3100
}
3101

    
3102
static int opt_start_time(const char *opt, const char *arg)
3103
{
3104
    start_time = parse_time_or_die(opt, arg, 1);
3105
    return 0;
3106
}
3107

    
3108
static int opt_recording_timestamp(const char *opt, const char *arg)
3109
{
3110
    recording_timestamp = parse_time_or_die(opt, arg, 0) / 1000000;
3111
    return 0;
3112
}
3113

    
3114
static int opt_input_ts_offset(const char *opt, const char *arg)
3115
{
3116
    input_ts_offset = parse_time_or_die(opt, arg, 1);
3117
    return 0;
3118
}
3119

    
3120
static enum CodecID find_codec_or_die(const char *name, int type, int encoder, int strict)
3121
{
3122
    const char *codec_string = encoder ? "encoder" : "decoder";
3123
    AVCodec *codec;
3124

    
3125
    if(!name)
3126
        return CODEC_ID_NONE;
3127
    codec = encoder ?
3128
        avcodec_find_encoder_by_name(name) :
3129
        avcodec_find_decoder_by_name(name);
3130
    if(!codec) {
3131
        fprintf(stderr, "Unknown %s '%s'\n", codec_string, name);
3132
        ffmpeg_exit(1);
3133
    }
3134
    if(codec->type != type) {
3135
        fprintf(stderr, "Invalid %s type '%s'\n", codec_string, name);
3136
        ffmpeg_exit(1);
3137
    }
3138
    if(codec->capabilities & CODEC_CAP_EXPERIMENTAL &&
3139
       strict > FF_COMPLIANCE_EXPERIMENTAL) {
3140
        fprintf(stderr, "%s '%s' is experimental and might produce bad "
3141
                "results.\nAdd '-strict experimental' if you want to use it.\n",
3142
                codec_string, codec->name);
3143
        codec = encoder ?
3144
            avcodec_find_encoder(codec->id) :
3145
            avcodec_find_decoder(codec->id);
3146
        if (!(codec->capabilities & CODEC_CAP_EXPERIMENTAL))
3147
            fprintf(stderr, "Or use the non experimental %s '%s'.\n",
3148
                    codec_string, codec->name);
3149
        ffmpeg_exit(1);
3150
    }
3151
    return codec->id;
3152
}
3153

    
3154
static void opt_input_file(const char *filename)
3155
{
3156
    AVFormatContext *ic;
3157
    AVFormatParameters params, *ap = &params;
3158
    AVInputFormat *file_iformat = NULL;
3159
    int err, i, ret, rfps, rfps_base;
3160
    int64_t timestamp;
3161

    
3162
    if (last_asked_format) {
3163
        if (!(file_iformat = av_find_input_format(last_asked_format))) {
3164
            fprintf(stderr, "Unknown input format: '%s'\n", last_asked_format);
3165
            ffmpeg_exit(1);
3166
        }
3167
        last_asked_format = NULL;
3168
    }
3169

    
3170
    if (!strcmp(filename, "-"))
3171
        filename = "pipe:";
3172

    
3173
    using_stdin |= !strncmp(filename, "pipe:", 5) ||
3174
                    !strcmp(filename, "/dev/stdin");
3175

    
3176
    /* get default parameters from command line */
3177
    ic = avformat_alloc_context();
3178
    if (!ic) {
3179
        print_error(filename, AVERROR(ENOMEM));
3180
        ffmpeg_exit(1);
3181
    }
3182

    
3183
    memset(ap, 0, sizeof(*ap));
3184
    ap->prealloced_context = 1;
3185
    ap->sample_rate = audio_sample_rate;
3186
    ap->channels = audio_channels;
3187
    ap->time_base.den = frame_rate.num;
3188
    ap->time_base.num = frame_rate.den;
3189
    ap->width = frame_width;
3190
    ap->height = frame_height;
3191
    ap->pix_fmt = frame_pix_fmt;
3192
   // ap->sample_fmt = audio_sample_fmt; //FIXME:not implemented in libavformat
3193
    ap->channel = video_channel;
3194
    ap->standard = video_standard;
3195

    
3196
    set_context_opts(ic, avformat_opts, AV_OPT_FLAG_DECODING_PARAM, NULL);
3197

    
3198
    ic->video_codec_id   =
3199
        find_codec_or_die(video_codec_name   , AVMEDIA_TYPE_VIDEO   , 0,
3200
                          avcodec_opts[AVMEDIA_TYPE_VIDEO   ]->strict_std_compliance);
3201
    ic->audio_codec_id   =
3202
        find_codec_or_die(audio_codec_name   , AVMEDIA_TYPE_AUDIO   , 0,
3203
                          avcodec_opts[AVMEDIA_TYPE_AUDIO   ]->strict_std_compliance);
3204
    ic->subtitle_codec_id=
3205
        find_codec_or_die(subtitle_codec_name, AVMEDIA_TYPE_SUBTITLE, 0,
3206
                          avcodec_opts[AVMEDIA_TYPE_SUBTITLE]->strict_std_compliance);
3207
    ic->flags |= AVFMT_FLAG_NONBLOCK;
3208

    
3209
    /* open the input file with generic libav function */
3210
    err = av_open_input_file(&ic, filename, file_iformat, 0, ap);
3211
    if (err < 0) {
3212
        print_error(filename, err);
3213
        ffmpeg_exit(1);
3214
    }
3215
    if(opt_programid) {
3216
        int i, j;
3217
        int found=0;
3218
        for(i=0; i<ic->nb_streams; i++){
3219
            ic->streams[i]->discard= AVDISCARD_ALL;
3220
        }
3221
        for(i=0; i<ic->nb_programs; i++){
3222
            AVProgram *p= ic->programs[i];
3223
            if(p->id != opt_programid){
3224
                p->discard = AVDISCARD_ALL;
3225
            }else{
3226
                found=1;
3227
                for(j=0; j<p->nb_stream_indexes; j++){
3228
                    ic->streams[p->stream_index[j]]->discard= AVDISCARD_DEFAULT;
3229
                }
3230
            }
3231
        }
3232
        if(!found){
3233
            fprintf(stderr, "Specified program id not found\n");
3234
            ffmpeg_exit(1);
3235
        }
3236
        opt_programid=0;
3237
    }
3238

    
3239
    ic->loop_input = loop_input;
3240

    
3241
    /* If not enough info to get the stream parameters, we decode the
3242
       first frames to get it. (used in mpeg case for example) */
3243
    ret = av_find_stream_info(ic);
3244
    if (ret < 0 && verbose >= 0) {
3245
        fprintf(stderr, "%s: could not find codec parameters\n", filename);
3246
        av_close_input_file(ic);
3247
        ffmpeg_exit(1);
3248
    }
3249

    
3250
    timestamp = start_time;
3251
    /* add the stream start time */
3252
    if (ic->start_time != AV_NOPTS_VALUE)
3253
        timestamp += ic->start_time;
3254

    
3255
    /* if seeking requested, we execute it */
3256
    if (start_time != 0) {
3257
        ret = av_seek_frame(ic, -1, timestamp, AVSEEK_FLAG_BACKWARD);
3258
        if (ret < 0) {
3259
            fprintf(stderr, "%s: could not seek to position %0.3f\n",
3260
                    filename, (double)timestamp / AV_TIME_BASE);
3261
        }
3262
        /* reset seek info */
3263
        start_time = 0;
3264
    }
3265

    
3266
    /* update the current parameters so that they match the one of the input stream */
3267
    for(i=0;i<ic->nb_streams;i++) {
3268
        AVStream *st = ic->streams[i];
3269
        AVCodecContext *dec = st->codec;
3270
        avcodec_thread_init(dec, thread_count);
3271
        input_codecs = grow_array(input_codecs, sizeof(*input_codecs), &nb_input_codecs, nb_input_codecs + 1);
3272
        switch (dec->codec_type) {
3273
        case AVMEDIA_TYPE_AUDIO:
3274
            input_codecs[nb_input_codecs-1] = avcodec_find_decoder_by_name(audio_codec_name);
3275
            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]);
3276
            //fprintf(stderr, "\nInput Audio channels: %d", dec->channels);
3277
            channel_layout    = dec->channel_layout;
3278
            audio_channels    = dec->channels;
3279
            audio_sample_rate = dec->sample_rate;
3280
            audio_sample_fmt  = dec->sample_fmt;
3281
            if(audio_disable)
3282
                st->discard= AVDISCARD_ALL;
3283
            /* Note that av_find_stream_info can add more streams, and we
3284
             * currently have no chance of setting up lowres decoding
3285
             * early enough for them. */
3286
            if (dec->lowres)
3287
                audio_sample_rate >>= dec->lowres;
3288
            break;
3289
        case AVMEDIA_TYPE_VIDEO:
3290
            input_codecs[nb_input_codecs-1] = avcodec_find_decoder_by_name(video_codec_name);
3291
            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]);
3292
            frame_height = dec->height;
3293
            frame_width  = dec->width;
3294
            if(ic->streams[i]->sample_aspect_ratio.num)
3295
                frame_aspect_ratio=av_q2d(ic->streams[i]->sample_aspect_ratio);
3296
            else
3297
                frame_aspect_ratio=av_q2d(dec->sample_aspect_ratio);
3298
            frame_aspect_ratio *= (float) dec->width / dec->height;
3299
            frame_pix_fmt = dec->pix_fmt;
3300
            rfps      = ic->streams[i]->r_frame_rate.num;
3301
            rfps_base = ic->streams[i]->r_frame_rate.den;
3302
            if (dec->lowres) {
3303
                dec->flags |= CODEC_FLAG_EMU_EDGE;
3304
                frame_height >>= dec->lowres;
3305
                frame_width  >>= dec->lowres;
3306
                dec->height = frame_height;
3307
                dec->width  = frame_width;
3308
            }
3309
            if(me_threshold)
3310
                dec->debug |= FF_DEBUG_MV;
3311

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

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

    
3318
                    (float)rfps / rfps_base, rfps, rfps_base);
3319
            }
3320
            /* update the current frame rate to match the stream frame rate */
3321
            frame_rate.num = rfps;
3322
            frame_rate.den = rfps_base;
3323

    
3324
            if(video_disable)
3325
                st->discard= AVDISCARD_ALL;
3326
            else if(video_discard)
3327
                st->discard= video_discard;
3328
            break;
3329
        case AVMEDIA_TYPE_DATA:
3330
            break;
3331
        case AVMEDIA_TYPE_SUBTITLE:
3332
            input_codecs[nb_input_codecs-1] = avcodec_find_decoder_by_name(subtitle_codec_name);
3333
            if(subtitle_disable)
3334
                st->discard = AVDISCARD_ALL;
3335
            break;
3336
        case AVMEDIA_TYPE_ATTACHMENT:
3337
        case AVMEDIA_TYPE_UNKNOWN:
3338
            break;
3339
        default:
3340
            abort();
3341
        }
3342
    }
3343

    
3344
    input_files[nb_input_files] = ic;
3345
    input_files_ts_offset[nb_input_files] = input_ts_offset - (copy_ts ? 0 : timestamp);
3346
    /* dump the file content */
3347
    if (verbose >= 0)
3348
        dump_format(ic, nb_input_files, filename, 0);
3349

    
3350
    nb_input_files++;
3351

    
3352
    video_channel = 0;
3353

    
3354
    av_freep(&video_codec_name);
3355
    av_freep(&audio_codec_name);
3356
    av_freep(&subtitle_codec_name);
3357
}
3358

    
3359
static void check_audio_video_sub_inputs(int *has_video_ptr, int *has_audio_ptr,
3360
                                         int *has_subtitle_ptr)
3361
{
3362
    int has_video, has_audio, has_subtitle, i, j;
3363
    AVFormatContext *ic;
3364

    
3365
    has_video = 0;
3366
    has_audio = 0;
3367
    has_subtitle = 0;
3368
    for(j=0;j<nb_input_files;j++) {
3369
        ic = input_files[j];
3370
        for(i=0;i<ic->nb_streams;i++) {
3371
            AVCodecContext *enc = ic->streams[i]->codec;
3372
            switch(enc->codec_type) {
3373
            case AVMEDIA_TYPE_AUDIO:
3374
                has_audio = 1;
3375
                break;
3376
            case AVMEDIA_TYPE_VIDEO:
3377
                has_video = 1;
3378
                break;
3379
            case AVMEDIA_TYPE_SUBTITLE:
3380
                has_subtitle = 1;
3381
                break;
3382
            case AVMEDIA_TYPE_DATA:
3383
            case AVMEDIA_TYPE_ATTACHMENT:
3384
            case AVMEDIA_TYPE_UNKNOWN:
3385
                break;
3386
            default:
3387
                abort();
3388
            }
3389
        }
3390
    }
3391
    *has_video_ptr = has_video;
3392
    *has_audio_ptr = has_audio;
3393
    *has_subtitle_ptr = has_subtitle;
3394
}
3395

    
3396
static void new_video_stream(AVFormatContext *oc, int file_idx)
3397
{
3398
    AVStream *st;
3399
    AVOutputStream *ost;
3400
    AVCodecContext *video_enc;
3401
    enum CodecID codec_id = CODEC_ID_NONE;
3402
    AVCodec *codec= NULL;
3403

    
3404
    st = av_new_stream(oc, oc->nb_streams < nb_streamid_map ? streamid_map[oc->nb_streams] : 0);
3405
    if (!st) {
3406
        fprintf(stderr, "Could not alloc stream\n");
3407
        ffmpeg_exit(1);
3408
    }
3409
    ost = new_output_stream(oc, file_idx);
3410

    
3411
    output_codecs = grow_array(output_codecs, sizeof(*output_codecs), &nb_output_codecs, nb_output_codecs + 1);
3412
    if(!video_stream_copy){
3413
        if (video_codec_name) {
3414
            codec_id = find_codec_or_die(video_codec_name, AVMEDIA_TYPE_VIDEO, 1,
3415
                                         avcodec_opts[AVMEDIA_TYPE_VIDEO]->strict_std_compliance);
3416
            codec = avcodec_find_encoder_by_name(video_codec_name);
3417
            output_codecs[nb_output_codecs-1] = codec;
3418
        } else {
3419
            codec_id = av_guess_codec(oc->oformat, NULL, oc->filename, NULL, AVMEDIA_TYPE_VIDEO);
3420
            codec = avcodec_find_encoder(codec_id);
3421
        }
3422
    }
3423

    
3424
    avcodec_get_context_defaults3(st->codec, codec);
3425
    ost->bitstream_filters = video_bitstream_filters;
3426
    video_bitstream_filters= NULL;
3427

    
3428
    avcodec_thread_init(st->codec, thread_count);
3429

    
3430
    video_enc = st->codec;
3431

    
3432
    if(video_codec_tag)
3433
        video_enc->codec_tag= video_codec_tag;
3434

    
3435
    if(   (video_global_header&1)
3436
       || (video_global_header==0 && (oc->oformat->flags & AVFMT_GLOBALHEADER))){
3437
        video_enc->flags |= CODEC_FLAG_GLOBAL_HEADER;
3438
        avcodec_opts[AVMEDIA_TYPE_VIDEO]->flags|= CODEC_FLAG_GLOBAL_HEADER;
3439
    }
3440
    if(video_global_header&2){
3441
        video_enc->flags2 |= CODEC_FLAG2_LOCAL_HEADER;
3442
        avcodec_opts[AVMEDIA_TYPE_VIDEO]->flags2|= CODEC_FLAG2_LOCAL_HEADER;
3443
    }
3444

    
3445
    if (video_stream_copy) {
3446
        st->stream_copy = 1;
3447
        video_enc->codec_type = AVMEDIA_TYPE_VIDEO;
3448
        video_enc->sample_aspect_ratio =
3449
        st->sample_aspect_ratio = av_d2q(frame_aspect_ratio*frame_height/frame_width, 255);
3450
    } else {
3451
        const char *p;
3452
        int i;
3453
        AVRational fps= frame_rate.num ? frame_rate : (AVRational){25,1};
3454

    
3455
        video_enc->codec_id = codec_id;
3456
        set_context_opts(video_enc, avcodec_opts[AVMEDIA_TYPE_VIDEO], AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_ENCODING_PARAM, codec);
3457

    
3458
        if (codec && codec->supported_framerates && !force_fps)
3459
            fps = codec->supported_framerates[av_find_nearest_q_idx(fps, codec->supported_framerates)];
3460
        video_enc->time_base.den = fps.num;
3461
        video_enc->time_base.num = fps.den;
3462

    
3463
        video_enc->width = frame_width;
3464
        video_enc->height = frame_height;
3465
        video_enc->sample_aspect_ratio = av_d2q(frame_aspect_ratio*video_enc->height/video_enc->width, 255);
3466
        video_enc->pix_fmt = frame_pix_fmt;
3467
        st->sample_aspect_ratio = video_enc->sample_aspect_ratio;
3468

    
3469
        choose_pixel_fmt(st, codec);
3470

    
3471
        if (intra_only)
3472
            video_enc->gop_size = 0;
3473
        if (video_qscale || same_quality) {
3474
            video_enc->flags |= CODEC_FLAG_QSCALE;
3475
            video_enc->global_quality=
3476
                st->quality = FF_QP2LAMBDA * video_qscale;
3477
        }
3478

    
3479
        if(intra_matrix)
3480
            video_enc->intra_matrix = intra_matrix;
3481
        if(inter_matrix)
3482
            video_enc->inter_matrix = inter_matrix;
3483

    
3484
        p= video_rc_override_string;
3485
        for(i=0; p; i++){
3486
            int start, end, q;
3487
            int e=sscanf(p, "%d,%d,%d", &start, &end, &q);
3488
            if(e!=3){
3489
                fprintf(stderr, "error parsing rc_override\n");
3490
                ffmpeg_exit(1);
3491
            }
3492
            video_enc->rc_override=
3493
                av_realloc(video_enc->rc_override,
3494
                           sizeof(RcOverride)*(i+1));
3495
            video_enc->rc_override[i].start_frame= start;
3496
            video_enc->rc_override[i].end_frame  = end;
3497
            if(q>0){
3498
                video_enc->rc_override[i].qscale= q;
3499
                video_enc->rc_override[i].quality_factor= 1.0;
3500
            }
3501
            else{
3502
                video_enc->rc_override[i].qscale= 0;
3503
                video_enc->rc_override[i].quality_factor= -q/100.0;
3504
            }
3505
            p= strchr(p, '/');
3506
            if(p) p++;
3507
        }
3508
        video_enc->rc_override_count=i;
3509
        if (!video_enc->rc_initial_buffer_occupancy)
3510
            video_enc->rc_initial_buffer_occupancy = video_enc->rc_buffer_size*3/4;
3511
        video_enc->me_threshold= me_threshold;
3512
        video_enc->intra_dc_precision= intra_dc_precision - 8;
3513

    
3514
        if (do_psnr)
3515
            video_enc->flags|= CODEC_FLAG_PSNR;
3516

    
3517
        /* two pass mode */
3518
        if (do_pass) {
3519
            if (do_pass == 1) {
3520
                video_enc->flags |= CODEC_FLAG_PASS1;
3521
            } else {
3522
                video_enc->flags |= CODEC_FLAG_PASS2;
3523
            }
3524
        }
3525

    
3526
        if (forced_key_frames)
3527
            parse_forced_key_frames(forced_key_frames, ost, video_enc);
3528
    }
3529
    if (video_language) {
3530
        av_metadata_set2(&st->metadata, "language", video_language, 0);
3531
        av_freep(&video_language);
3532
    }
3533

    
3534
    /* reset some key parameters */
3535
    video_disable = 0;
3536
    av_freep(&video_codec_name);
3537
    av_freep(&forced_key_frames);
3538
    video_stream_copy = 0;
3539
    frame_pix_fmt = PIX_FMT_NONE;
3540
}
3541

    
3542
static void new_audio_stream(AVFormatContext *oc, int file_idx)
3543
{
3544
    AVStream *st;
3545
    AVOutputStream *ost;
3546
    AVCodec *codec= NULL;
3547
    AVCodecContext *audio_enc;
3548
    enum CodecID codec_id = CODEC_ID_NONE;
3549

    
3550
    st = av_new_stream(oc, oc->nb_streams < nb_streamid_map ? streamid_map[oc->nb_streams] : 0);
3551
    if (!st) {
3552
        fprintf(stderr, "Could not alloc stream\n");
3553
        ffmpeg_exit(1);
3554
    }
3555
    ost = new_output_stream(oc, file_idx);
3556

    
3557
    output_codecs = grow_array(output_codecs, sizeof(*output_codecs), &nb_output_codecs, nb_output_codecs + 1);
3558
    if(!audio_stream_copy){
3559
        if (audio_codec_name) {
3560
            codec_id = find_codec_or_die(audio_codec_name, AVMEDIA_TYPE_AUDIO, 1,
3561
                                         avcodec_opts[AVMEDIA_TYPE_AUDIO]->strict_std_compliance);
3562
            codec = avcodec_find_encoder_by_name(audio_codec_name);
3563
            output_codecs[nb_output_codecs-1] = codec;
3564
        } else {
3565
            codec_id = av_guess_codec(oc->oformat, NULL, oc->filename, NULL, AVMEDIA_TYPE_AUDIO);
3566
            codec = avcodec_find_encoder(codec_id);
3567
        }
3568
    }
3569

    
3570
    avcodec_get_context_defaults3(st->codec, codec);
3571

    
3572
    ost->bitstream_filters = audio_bitstream_filters;
3573
    audio_bitstream_filters= NULL;
3574

    
3575
    avcodec_thread_init(st->codec, thread_count);
3576

    
3577
    audio_enc = st->codec;
3578
    audio_enc->codec_type = AVMEDIA_TYPE_AUDIO;
3579

    
3580
    if(audio_codec_tag)
3581
        audio_enc->codec_tag= audio_codec_tag;
3582

    
3583
    if (oc->oformat->flags & AVFMT_GLOBALHEADER) {
3584
        audio_enc->flags |= CODEC_FLAG_GLOBAL_HEADER;
3585
        avcodec_opts[AVMEDIA_TYPE_AUDIO]->flags|= CODEC_FLAG_GLOBAL_HEADER;
3586
    }
3587
    if (audio_stream_copy) {
3588
        st->stream_copy = 1;
3589
        audio_enc->channels = audio_channels;
3590
        audio_enc->sample_rate = audio_sample_rate;
3591
    } else {
3592
        audio_enc->codec_id = codec_id;
3593
        set_context_opts(audio_enc, avcodec_opts[AVMEDIA_TYPE_AUDIO], AV_OPT_FLAG_AUDIO_PARAM | AV_OPT_FLAG_ENCODING_PARAM, codec);
3594

    
3595
        if (audio_qscale > QSCALE_NONE) {
3596
            audio_enc->flags |= CODEC_FLAG_QSCALE;
3597
            audio_enc->global_quality = st->quality = FF_QP2LAMBDA * audio_qscale;
3598
        }
3599
        audio_enc->channels = audio_channels;
3600
        audio_enc->sample_fmt = audio_sample_fmt;
3601
        audio_enc->sample_rate = audio_sample_rate;
3602
        audio_enc->channel_layout = channel_layout;
3603
        if (av_get_channel_layout_nb_channels(channel_layout) != audio_channels)
3604
            audio_enc->channel_layout = 0;
3605
        choose_sample_fmt(st, codec);
3606
        choose_sample_rate(st, codec);
3607
    }
3608
    audio_enc->time_base= (AVRational){1, audio_sample_rate};
3609
    if (audio_language) {
3610
        av_metadata_set2(&st->metadata, "language", audio_language, 0);
3611
        av_freep(&audio_language);
3612
    }
3613

    
3614
    /* reset some key parameters */
3615
    audio_disable = 0;
3616
    av_freep(&audio_codec_name);
3617
    audio_stream_copy = 0;
3618
}
3619

    
3620
static void new_subtitle_stream(AVFormatContext *oc, int file_idx)
3621
{
3622
    AVStream *st;
3623
    AVOutputStream *ost;
3624
    AVCodec *codec=NULL;
3625
    AVCodecContext *subtitle_enc;
3626
    enum CodecID codec_id = CODEC_ID_NONE;
3627

    
3628
    st = av_new_stream(oc, oc->nb_streams < nb_streamid_map ? streamid_map[oc->nb_streams] : 0);
3629
    if (!st) {
3630
        fprintf(stderr, "Could not alloc stream\n");
3631
        ffmpeg_exit(1);
3632
    }
3633
    ost = new_output_stream(oc, file_idx);
3634
    subtitle_enc = st->codec;
3635
    output_codecs = grow_array(output_codecs, sizeof(*output_codecs), &nb_output_codecs, nb_output_codecs + 1);
3636
    if(!subtitle_stream_copy){
3637
        if (subtitle_codec_name) {
3638
            codec_id = find_codec_or_die(subtitle_codec_name, AVMEDIA_TYPE_SUBTITLE, 1,
3639
                                         avcodec_opts[AVMEDIA_TYPE_SUBTITLE]->strict_std_compliance);
3640
            codec= output_codecs[nb_output_codecs-1] = avcodec_find_encoder_by_name(subtitle_codec_name);
3641
        } else {
3642
            codec_id = av_guess_codec(oc->oformat, NULL, oc->filename, NULL, AVMEDIA_TYPE_SUBTITLE);
3643
            codec = avcodec_find_encoder(codec_id);
3644
        }
3645
    }
3646
    avcodec_get_context_defaults3(st->codec, codec);
3647

    
3648
    ost->bitstream_filters = subtitle_bitstream_filters;
3649
    subtitle_bitstream_filters= NULL;
3650

    
3651
    subtitle_enc->codec_type = AVMEDIA_TYPE_SUBTITLE;
3652

    
3653
    if(subtitle_codec_tag)
3654
        subtitle_enc->codec_tag= subtitle_codec_tag;
3655

    
3656
    if (oc->oformat->flags & AVFMT_GLOBALHEADER) {
3657
        subtitle_enc->flags |= CODEC_FLAG_GLOBAL_HEADER;
3658
        avcodec_opts[AVMEDIA_TYPE_SUBTITLE]->flags |= CODEC_FLAG_GLOBAL_HEADER;
3659
    }
3660
    if (subtitle_stream_copy) {
3661
        st->stream_copy = 1;
3662
    } else {
3663
        subtitle_enc->codec_id = codec_id;
3664
        set_context_opts(avcodec_opts[AVMEDIA_TYPE_SUBTITLE], subtitle_enc, AV_OPT_FLAG_SUBTITLE_PARAM | AV_OPT_FLAG_ENCODING_PARAM, codec);
3665
    }
3666

    
3667
    if (subtitle_language) {
3668
        av_metadata_set2(&st->metadata, "language", subtitle_language, 0);
3669
        av_freep(&subtitle_language);
3670
    }
3671

    
3672
    subtitle_disable = 0;
3673
    av_freep(&subtitle_codec_name);
3674
    subtitle_stream_copy = 0;
3675
}
3676

    
3677
static int opt_new_stream(const char *opt, const char *arg)
3678
{
3679
    AVFormatContext *oc;
3680
    int file_idx = nb_output_files - 1;
3681
    if (nb_output_files <= 0) {
3682
        fprintf(stderr, "At least one output file must be specified\n");
3683
        ffmpeg_exit(1);
3684
    }
3685
    oc = output_files[file_idx];
3686

    
3687
    if      (!strcmp(opt, "newvideo"   )) new_video_stream   (oc, file_idx);
3688
    else if (!strcmp(opt, "newaudio"   )) new_audio_stream   (oc, file_idx);
3689
    else if (!strcmp(opt, "newsubtitle")) new_subtitle_stream(oc, file_idx);
3690
    else av_assert0(0);
3691
    return 0;
3692
}
3693

    
3694
/* arg format is "output-stream-index:streamid-value". */
3695
static int opt_streamid(const char *opt, const char *arg)
3696
{
3697
    int idx;
3698
    char *p;
3699
    char idx_str[16];
3700

    
3701
    strncpy(idx_str, arg, sizeof(idx_str));
3702
    idx_str[sizeof(idx_str)-1] = '\0';
3703
    p = strchr(idx_str, ':');
3704
    if (!p) {
3705
        fprintf(stderr,
3706
                "Invalid value '%s' for option '%s', required syntax is 'index:value'\n",
3707
                arg, opt);
3708
        ffmpeg_exit(1);
3709
    }
3710
    *p++ = '\0';
3711
    idx = parse_number_or_die(opt, idx_str, OPT_INT, 0, MAX_STREAMS-1);
3712
    streamid_map = grow_array(streamid_map, sizeof(*streamid_map), &nb_streamid_map, idx+1);
3713
    streamid_map[idx] = parse_number_or_die(opt, p, OPT_INT, 0, INT_MAX);
3714
    return 0;
3715
}
3716

    
3717
static void opt_output_file(const char *filename)
3718
{
3719
    AVFormatContext *oc;
3720
    int err, use_video, use_audio, use_subtitle;
3721
    int input_has_video, input_has_audio, input_has_subtitle;
3722
    AVFormatParameters params, *ap = &params;
3723
    AVOutputFormat *file_oformat;
3724

    
3725
    if (!strcmp(filename, "-"))
3726
        filename = "pipe:";
3727

    
3728
    oc = avformat_alloc_context();
3729
    if (!oc) {
3730
        print_error(filename, AVERROR(ENOMEM));
3731
        ffmpeg_exit(1);
3732
    }
3733

    
3734
    if (last_asked_format) {
3735
        file_oformat = av_guess_format(last_asked_format, NULL, NULL);
3736
        if (!file_oformat) {
3737
            fprintf(stderr, "Requested output format '%s' is not a suitable output format\n", last_asked_format);
3738
            ffmpeg_exit(1);
3739
        }
3740
        last_asked_format = NULL;
3741
    } else {
3742
        file_oformat = av_guess_format(NULL, filename, NULL);
3743
        if (!file_oformat) {
3744
            fprintf(stderr, "Unable to find a suitable output format for '%s'\n",
3745
                    filename);
3746
            ffmpeg_exit(1);
3747
        }
3748
    }
3749

    
3750
    oc->oformat = file_oformat;
3751
    av_strlcpy(oc->filename, filename, sizeof(oc->filename));
3752

    
3753
    if (!strcmp(file_oformat->name, "ffm") &&
3754
        av_strstart(filename, "http:", NULL)) {
3755
        /* special case for files sent to ffserver: we get the stream
3756
           parameters from ffserver */
3757
        int err = read_ffserver_streams(oc, filename);
3758
        if (err < 0) {
3759
            print_error(filename, err);
3760
            ffmpeg_exit(1);
3761
        }
3762
    } else {
3763
        use_video = file_oformat->video_codec != CODEC_ID_NONE || video_stream_copy || video_codec_name;
3764
        use_audio = file_oformat->audio_codec != CODEC_ID_NONE || audio_stream_copy || audio_codec_name;
3765
        use_subtitle = file_oformat->subtitle_codec != CODEC_ID_NONE || subtitle_stream_copy || subtitle_codec_name;
3766

    
3767
        /* disable if no corresponding type found and at least one
3768
           input file */
3769
        if (nb_input_files > 0) {
3770
            check_audio_video_sub_inputs(&input_has_video, &input_has_audio,
3771
                                         &input_has_subtitle);
3772
            if (!input_has_video)
3773
                use_video = 0;
3774
            if (!input_has_audio)
3775
                use_audio = 0;
3776
            if (!input_has_subtitle)
3777
                use_subtitle = 0;
3778
        }
3779

    
3780
        /* manual disable */
3781
        if (audio_disable)    use_audio    = 0;
3782
        if (video_disable)    use_video    = 0;
3783
        if (subtitle_disable) use_subtitle = 0;
3784

    
3785
        if (use_video)    new_video_stream(oc, nb_output_files);
3786
        if (use_audio)    new_audio_stream(oc, nb_output_files);
3787
        if (use_subtitle) new_subtitle_stream(oc, nb_output_files);
3788

    
3789
        oc->timestamp = recording_timestamp;
3790

    
3791
        av_metadata_copy(&oc->metadata, metadata, 0);
3792
        av_metadata_free(&metadata);
3793
    }
3794

    
3795
    output_files[nb_output_files++] = oc;
3796

    
3797
    /* check filename in case of an image number is expected */
3798
    if (oc->oformat->flags & AVFMT_NEEDNUMBER) {
3799
        if (!av_filename_number_test(oc->filename)) {
3800
            print_error(oc->filename, AVERROR_NUMEXPECTED);
3801
            ffmpeg_exit(1);
3802
        }
3803
    }
3804

    
3805
    if (!(oc->oformat->flags & AVFMT_NOFILE)) {
3806
        /* test if it already exists to avoid loosing precious files */
3807
        if (!file_overwrite &&
3808
            (strchr(filename, ':') == NULL ||
3809
             filename[1] == ':' ||
3810
             av_strstart(filename, "file:", NULL))) {
3811
            if (url_exist(filename)) {
3812
                if (!using_stdin) {
3813
                    fprintf(stderr,"File '%s' already exists. Overwrite ? [y/N] ", filename);
3814
                    fflush(stderr);
3815
                    if (!read_yesno()) {
3816
                        fprintf(stderr, "Not overwriting - exiting\n");
3817
                        ffmpeg_exit(1);
3818
                    }
3819
                }
3820
                else {
3821
                    fprintf(stderr,"File '%s' already exists. Exiting.\n", filename);
3822
                    ffmpeg_exit(1);
3823
                }
3824
            }
3825
        }
3826

    
3827
        /* open the file */
3828
        if ((err = url_fopen(&oc->pb, filename, URL_WRONLY)) < 0) {
3829
            print_error(filename, err);
3830
            ffmpeg_exit(1);
3831
        }
3832
    }
3833

    
3834
    memset(ap, 0, sizeof(*ap));
3835
    if (av_set_parameters(oc, ap) < 0) {
3836
        fprintf(stderr, "%s: Invalid encoding parameters\n",
3837
                oc->filename);
3838
        ffmpeg_exit(1);
3839
    }
3840

    
3841
    oc->preload= (int)(mux_preload*AV_TIME_BASE);
3842
    oc->max_delay= (int)(mux_max_delay*AV_TIME_BASE);
3843
    oc->loop_output = loop_output;
3844
    oc->flags |= AVFMT_FLAG_NONBLOCK;
3845

    
3846
    set_context_opts(oc, avformat_opts, AV_OPT_FLAG_ENCODING_PARAM, NULL);
3847

    
3848
    av_freep(&forced_key_frames);
3849
}
3850

    
3851
/* same option as mencoder */
3852
static void opt_pass(const char *pass_str)
3853
{
3854
    int pass;
3855
    pass = atoi(pass_str);
3856
    if (pass != 1 && pass != 2) {
3857
        fprintf(stderr, "pass number can be only 1 or 2\n");
3858
        ffmpeg_exit(1);
3859
    }
3860
    do_pass = pass;
3861
}
3862

    
3863
static int64_t getutime(void)
3864
{
3865
#if HAVE_GETRUSAGE
3866
    struct rusage rusage;
3867

    
3868
    getrusage(RUSAGE_SELF, &rusage);
3869
    return (rusage.ru_utime.tv_sec * 1000000LL) + rusage.ru_utime.tv_usec;
3870
#elif HAVE_GETPROCESSTIMES
3871
    HANDLE proc;
3872
    FILETIME c, e, k, u;
3873
    proc = GetCurrentProcess();
3874
    GetProcessTimes(proc, &c, &e, &k, &u);
3875
    return ((int64_t) u.dwHighDateTime << 32 | u.dwLowDateTime) / 10;
3876
#else
3877
    return av_gettime();
3878
#endif
3879
}
3880

    
3881
static int64_t getmaxrss(void)
3882
{
3883
#if HAVE_GETRUSAGE && HAVE_STRUCT_RUSAGE_RU_MAXRSS
3884
    struct rusage rusage;
3885
    getrusage(RUSAGE_SELF, &rusage);
3886
    return (int64_t)rusage.ru_maxrss * 1024;
3887
#elif HAVE_GETPROCESSMEMORYINFO
3888
    HANDLE proc;
3889
    PROCESS_MEMORY_COUNTERS memcounters;
3890
    proc = GetCurrentProcess();
3891
    memcounters.cb = sizeof(memcounters);
3892
    GetProcessMemoryInfo(proc, &memcounters, sizeof(memcounters));
3893
    return memcounters.PeakPagefileUsage;
3894
#else
3895
    return 0;
3896
#endif
3897
}
3898

    
3899
static void parse_matrix_coeffs(uint16_t *dest, const char *str)
3900
{
3901
    int i;
3902
    const char *p = str;
3903
    for(i = 0;; i++) {
3904
        dest[i] = atoi(p);
3905
        if(i == 63)
3906
            break;
3907
        p = strchr(p, ',');
3908
        if(!p) {
3909
            fprintf(stderr, "Syntax error in matrix \"%s\" at coeff %d\n", str, i);
3910
            ffmpeg_exit(1);
3911
        }
3912
        p++;
3913
    }
3914
}
3915

    
3916
static void opt_inter_matrix(const char *arg)
3917
{
3918
    inter_matrix = av_mallocz(sizeof(uint16_t) * 64);
3919
    parse_matrix_coeffs(inter_matrix, arg);
3920
}
3921

    
3922
static void opt_intra_matrix(const char *arg)
3923
{
3924
    intra_matrix = av_mallocz(sizeof(uint16_t) * 64);
3925
    parse_matrix_coeffs(intra_matrix, arg);
3926
}
3927

    
3928
static void show_usage(void)
3929
{
3930
    printf("Hyper fast Audio and Video encoder\n");
3931
    printf("usage: ffmpeg [options] [[infile options] -i infile]... {[outfile options] outfile}...\n");
3932
    printf("\n");
3933
}
3934

    
3935
static void show_help(void)
3936
{
3937
    AVCodec *c;
3938
    AVOutputFormat *oformat = NULL;
3939

    
3940
    av_log_set_callback(log_callback_help);
3941
    show_usage();
3942
    show_help_options(options, "Main options:\n",
3943
                      OPT_EXPERT | OPT_AUDIO | OPT_VIDEO | OPT_SUBTITLE | OPT_GRAB, 0);
3944
    show_help_options(options, "\nAdvanced options:\n",
3945
                      OPT_EXPERT | OPT_AUDIO | OPT_VIDEO | OPT_SUBTITLE | OPT_GRAB,
3946
                      OPT_EXPERT);
3947
    show_help_options(options, "\nVideo options:\n",
3948
                      OPT_EXPERT | OPT_AUDIO | OPT_VIDEO | OPT_GRAB,
3949
                      OPT_VIDEO);
3950
    show_help_options(options, "\nAdvanced Video options:\n",
3951
                      OPT_EXPERT | OPT_AUDIO | OPT_VIDEO | OPT_GRAB,
3952
                      OPT_VIDEO | OPT_EXPERT);
3953
    show_help_options(options, "\nAudio options:\n",
3954
                      OPT_EXPERT | OPT_AUDIO | OPT_VIDEO | OPT_GRAB,
3955
                      OPT_AUDIO);
3956
    show_help_options(options, "\nAdvanced Audio options:\n",
3957
                      OPT_EXPERT | OPT_AUDIO | OPT_VIDEO | OPT_GRAB,
3958
                      OPT_AUDIO | OPT_EXPERT);
3959
    show_help_options(options, "\nSubtitle options:\n",
3960
                      OPT_SUBTITLE | OPT_GRAB,
3961
                      OPT_SUBTITLE);
3962
    show_help_options(options, "\nAudio/Video grab options:\n",
3963
                      OPT_GRAB,
3964
                      OPT_GRAB);
3965
    printf("\n");
3966
    av_opt_show2(avcodec_opts[0], NULL, AV_OPT_FLAG_ENCODING_PARAM|AV_OPT_FLAG_DECODING_PARAM, 0);
3967
    printf("\n");
3968

    
3969
    /* individual codec options */
3970
    c = NULL;
3971
    while ((c = av_codec_next(c))) {
3972
        if (c->priv_class) {
3973
            av_opt_show2(&c->priv_class, NULL, AV_OPT_FLAG_ENCODING_PARAM|AV_OPT_FLAG_DECODING_PARAM, 0);
3974
            printf("\n");
3975
        }
3976
    }
3977

    
3978
    av_opt_show2(avformat_opts, NULL, AV_OPT_FLAG_ENCODING_PARAM|AV_OPT_FLAG_DECODING_PARAM, 0);
3979
    printf("\n");
3980

    
3981
    /* individual muxer options */
3982
    while ((oformat = av_oformat_next(oformat))) {
3983
        if (oformat->priv_class) {
3984
            av_opt_show2(&oformat->priv_class, NULL, AV_OPT_FLAG_ENCODING_PARAM, 0);
3985
            printf("\n");
3986
        }
3987
    }
3988

    
3989
    av_opt_show2(sws_opts, NULL, AV_OPT_FLAG_ENCODING_PARAM|AV_OPT_FLAG_DECODING_PARAM, 0);
3990
}
3991

    
3992
static void opt_target(const char *arg)
3993
{
3994
    enum { PAL, NTSC, FILM, UNKNOWN } norm = UNKNOWN;
3995
    static const char *const frame_rates[] = {"25", "30000/1001", "24000/1001"};
3996

    
3997
    if(!strncmp(arg, "pal-", 4)) {
3998
        norm = PAL;
3999
        arg += 4;
4000
    } else if(!strncmp(arg, "ntsc-", 5)) {
4001
        norm = NTSC;
4002
        arg += 5;
4003
    } else if(!strncmp(arg, "film-", 5)) {
4004
        norm = FILM;
4005
        arg += 5;
4006
    } else {
4007
        int fr;
4008
        /* Calculate FR via float to avoid int overflow */
4009
        fr = (int)(frame_rate.num * 1000.0 / frame_rate.den);
4010
        if(fr == 25000) {
4011
            norm = PAL;
4012
        } else if((fr == 29970) || (fr == 23976)) {
4013
            norm = NTSC;
4014
        } else {
4015
            /* Try to determine PAL/NTSC by peeking in the input files */
4016
            if(nb_input_files) {
4017
                int i, j;
4018
                for(j = 0; j < nb_input_files; j++) {
4019
                    for(i = 0; i < input_files[j]->nb_streams; i++) {
4020
                        AVCodecContext *c = input_files[j]->streams[i]->codec;
4021
                        if(c->codec_type != AVMEDIA_TYPE_VIDEO)
4022
                            continue;
4023
                        fr = c->time_base.den * 1000 / c->time_base.num;
4024
                        if(fr == 25000) {
4025
                            norm = PAL;
4026
                            break;
4027
                        } else if((fr == 29970) || (fr == 23976)) {
4028
                            norm = NTSC;
4029
                            break;
4030
                        }
4031
                    }
4032
                    if(norm != UNKNOWN)
4033
                        break;
4034
                }
4035
            }
4036
        }
4037
        if(verbose && norm != UNKNOWN)
4038
            fprintf(stderr, "Assuming %s for target.\n", norm == PAL ? "PAL" : "NTSC");
4039
    }
4040

    
4041
    if(norm == UNKNOWN) {
4042
        fprintf(stderr, "Could not determine norm (PAL/NTSC/NTSC-Film) for target.\n");
4043
        fprintf(stderr, "Please prefix target with \"pal-\", \"ntsc-\" or \"film-\",\n");
4044
        fprintf(stderr, "or set a framerate with \"-r xxx\".\n");
4045
        ffmpeg_exit(1);
4046
    }
4047

    
4048
    if(!strcmp(arg, "vcd")) {
4049

    
4050
        opt_video_codec("mpeg1video");
4051
        opt_audio_codec("mp2");
4052
        opt_format("vcd");
4053

    
4054
        opt_frame_size(norm == PAL ? "352x288" : "352x240");
4055
        opt_frame_rate(NULL, frame_rates[norm]);
4056
        opt_default("g", norm == PAL ? "15" : "18");
4057

    
4058
        opt_default("b", "1150000");
4059
        opt_default("maxrate", "1150000");
4060
        opt_default("minrate", "1150000");
4061
        opt_default("bufsize", "327680"); // 40*1024*8;
4062

    
4063
        opt_default("ab", "224000");
4064
        audio_sample_rate = 44100;
4065
        audio_channels = 2;
4066

    
4067
        opt_default("packetsize", "2324");
4068
        opt_default("muxrate", "1411200"); // 2352 * 75 * 8;
4069

    
4070
        /* We have to offset the PTS, so that it is consistent with the SCR.
4071
           SCR starts at 36000, but the first two packs contain only padding
4072
           and the first pack from the other stream, respectively, may also have
4073
           been written before.
4074
           So the real data starts at SCR 36000+3*1200. */
4075
        mux_preload= (36000+3*1200) / 90000.0; //0.44
4076
    } else if(!strcmp(arg, "svcd")) {
4077

    
4078
        opt_video_codec("mpeg2video");
4079
        opt_audio_codec("mp2");
4080
        opt_format("svcd");
4081

    
4082
        opt_frame_size(norm == PAL ? "480x576" : "480x480");
4083
        opt_frame_rate(NULL, frame_rates[norm]);
4084
        opt_default("g", norm == PAL ? "15" : "18");
4085

    
4086
        opt_default("b", "2040000");
4087
        opt_default("maxrate", "2516000");
4088
        opt_default("minrate", "0"); //1145000;
4089
        opt_default("bufsize", "1835008"); //224*1024*8;
4090
        opt_default("flags", "+scan_offset");
4091

    
4092

    
4093
        opt_default("ab", "224000");
4094
        audio_sample_rate = 44100;
4095

    
4096
        opt_default("packetsize", "2324");
4097

    
4098
    } else if(!strcmp(arg, "dvd")) {
4099

    
4100
        opt_video_codec("mpeg2video");
4101
        opt_audio_codec("ac3");
4102
        opt_format("dvd");
4103

    
4104
        opt_frame_size(norm == PAL ? "720x576" : "720x480");
4105
        opt_frame_rate(NULL, frame_rates[norm]);
4106
        opt_default("g", norm == PAL ? "15" : "18");
4107

    
4108
        opt_default("b", "6000000");
4109
        opt_default("maxrate", "9000000");
4110
        opt_default("minrate", "0"); //1500000;
4111
        opt_default("bufsize", "1835008"); //224*1024*8;
4112

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

    
4116
        opt_default("ab", "448000");
4117
        audio_sample_rate = 48000;
4118

    
4119
    } else if(!strncmp(arg, "dv", 2)) {
4120

    
4121
        opt_format("dv");
4122

    
4123
        opt_frame_size(norm == PAL ? "720x576" : "720x480");
4124
        opt_frame_pix_fmt(!strncmp(arg, "dv50", 4) ? "yuv422p" :
4125
                          (norm == PAL ? "yuv420p" : "yuv411p"));
4126
        opt_frame_rate(NULL, frame_rates[norm]);
4127

    
4128
        audio_sample_rate = 48000;
4129
        audio_channels = 2;
4130

    
4131
    } else {
4132
        fprintf(stderr, "Unknown target: %s\n", arg);
4133
        ffmpeg_exit(1);
4134
    }
4135
}
4136

    
4137
static void opt_vstats_file (const char *arg)
4138
{
4139
    av_free (vstats_filename);
4140
    vstats_filename=av_strdup (arg);
4141
}
4142

    
4143
static void opt_vstats (void)
4144
{
4145
    char filename[40];
4146
    time_t today2 = time(NULL);
4147
    struct tm *today = localtime(&today2);
4148

    
4149
    snprintf(filename, sizeof(filename), "vstats_%02d%02d%02d.log", today->tm_hour, today->tm_min,
4150
             today->tm_sec);
4151
    opt_vstats_file(filename);
4152
}
4153

    
4154
static int opt_bsf(const char *opt, const char *arg)
4155
{
4156
    AVBitStreamFilterContext *bsfc= av_bitstream_filter_init(arg); //FIXME split name and args for filter at '='
4157
    AVBitStreamFilterContext **bsfp;
4158

    
4159
    if(!bsfc){
4160
        fprintf(stderr, "Unknown bitstream filter %s\n", arg);
4161
        ffmpeg_exit(1);
4162
    }
4163

    
4164
    bsfp= *opt == 'v' ? &video_bitstream_filters :
4165
          *opt == 'a' ? &audio_bitstream_filters :
4166
                        &subtitle_bitstream_filters;
4167
    while(*bsfp)
4168
        bsfp= &(*bsfp)->next;
4169

    
4170
    *bsfp= bsfc;
4171

    
4172
    return 0;
4173
}
4174

    
4175
static int opt_preset(const char *opt, const char *arg)
4176
{
4177
    FILE *f=NULL;
4178
    char filename[1000], tmp[1000], tmp2[1000], line[1000];
4179
    char *codec_name = *opt == 'v' ? video_codec_name :
4180
                       *opt == 'a' ? audio_codec_name :
4181
                                     subtitle_codec_name;
4182

    
4183
    if (!(f = get_preset_file(filename, sizeof(filename), arg, *opt == 'f', codec_name))) {
4184
        fprintf(stderr, "File for preset '%s' not found\n", arg);
4185
        ffmpeg_exit(1);
4186
    }
4187

    
4188
    while(!feof(f)){
4189
        int e= fscanf(f, "%999[^\n]\n", line) - 1;
4190
        if(line[0] == '#' && !e)
4191
            continue;
4192
        e|= sscanf(line, "%999[^=]=%999[^\n]\n", tmp, tmp2) - 2;
4193
        if(e){
4194
            fprintf(stderr, "%s: Invalid syntax: '%s'\n", filename, line);
4195
            ffmpeg_exit(1);
4196
        }
4197
        if(!strcmp(tmp, "acodec")){
4198
            opt_audio_codec(tmp2);
4199
        }else if(!strcmp(tmp, "vcodec")){
4200
            opt_video_codec(tmp2);
4201
        }else if(!strcmp(tmp, "scodec")){
4202
            opt_subtitle_codec(tmp2);
4203
        }else if(opt_default(tmp, tmp2) < 0){
4204
            fprintf(stderr, "%s: Invalid option or argument: '%s', parsed as '%s' = '%s'\n", filename, line, tmp, tmp2);
4205
            ffmpeg_exit(1);
4206
        }
4207
    }
4208

    
4209
    fclose(f);
4210

    
4211
    return 0;
4212
}
4213

    
4214
static const OptionDef options[] = {
4215
    /* main options */
4216
#include "cmdutils_common_opts.h"
4217
    { "f", HAS_ARG, {(void*)opt_format}, "force format", "fmt" },
4218
    { "i", HAS_ARG, {(void*)opt_input_file}, "input file name", "filename" },
4219
    { "y", OPT_BOOL, {(void*)&file_overwrite}, "overwrite output files" },
4220
    { "map", HAS_ARG | OPT_EXPERT, {(void*)opt_map}, "set input stream mapping", "file:stream[:syncfile:syncstream]" },
4221
    { "map_meta_data", HAS_ARG | OPT_EXPERT, {(void*)opt_map_meta_data}, "DEPRECATED set meta data information of outfile from infile",
4222
      "outfile[,metadata]:infile[,metadata]" },
4223
    { "map_metadata", HAS_ARG | OPT_EXPERT, {(void*)opt_map_metadata}, "set metadata information of outfile from infile",
4224
      "outfile[,metadata]:infile[,metadata]" },
4225
    { "map_chapters",  HAS_ARG | OPT_EXPERT, {(void*)opt_map_chapters},  "set chapters mapping", "outfile:infile" },
4226
    { "t", OPT_FUNC2 | HAS_ARG, {(void*)opt_recording_time}, "record or transcode \"duration\" seconds of audio/video", "duration" },
4227
    { "fs", HAS_ARG | OPT_INT64, {(void*)&limit_filesize}, "set the limit file size in bytes", "limit_size" }, //
4228
    { "ss", OPT_FUNC2 | HAS_ARG, {(void*)opt_start_time}, "set the start time offset", "time_off" },
4229
    { "itsoffset", OPT_FUNC2 | HAS_ARG, {(void*)opt_input_ts_offset}, "set the input ts offset", "time_off" },
4230
    { "itsscale", HAS_ARG, {(void*)opt_input_ts_scale}, "set the input ts scale", "stream:scale" },
4231
    { "timestamp", OPT_FUNC2 | HAS_ARG, {(void*)opt_recording_timestamp}, "set the recording timestamp ('now' to set the current time)", "time" },
4232
    { "metadata", OPT_FUNC2 | HAS_ARG, {(void*)opt_metadata}, "add metadata", "string=string" },
4233
    { "dframes", OPT_INT | HAS_ARG, {(void*)&max_frames[AVMEDIA_TYPE_DATA]}, "set the number of data frames to record", "number" },
4234
    { "benchmark", OPT_BOOL | OPT_EXPERT, {(void*)&do_benchmark},
4235
      "add timings for benchmarking" },
4236
    { "timelimit", OPT_FUNC2 | HAS_ARG, {(void*)opt_timelimit}, "set max runtime in seconds", "limit" },
4237
    { "dump", OPT_BOOL | OPT_EXPERT, {(void*)&do_pkt_dump},
4238
      "dump each input packet" },
4239
    { "hex", OPT_BOOL | OPT_EXPERT, {(void*)&do_hex_dump},
4240
      "when dumping packets, also dump the payload" },
4241
    { "re", OPT_BOOL | OPT_EXPERT, {(void*)&rate_emu}, "read input at native frame rate", "" },
4242
    { "loop_input", OPT_BOOL | OPT_EXPERT, {(void*)&loop_input}, "loop (current only works with images)" },
4243
    { "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)", "" },
4244
    { "v", HAS_ARG | OPT_FUNC2, {(void*)opt_verbose}, "set ffmpeg verbosity level", "number" },
4245
    { "target", HAS_ARG, {(void*)opt_target}, "specify target file type (\"vcd\", \"svcd\", \"dvd\", \"dv\", \"dv50\", \"pal-vcd\", \"ntsc-svcd\", ...)", "type" },
4246
    { "threads", OPT_FUNC2 | HAS_ARG | OPT_EXPERT, {(void*)opt_thread_count}, "thread count", "count" },
4247
    { "vsync", HAS_ARG | OPT_INT | OPT_EXPERT, {(void*)&video_sync_method}, "video sync method", "" },
4248
    { "async", HAS_ARG | OPT_INT | OPT_EXPERT, {(void*)&audio_sync_method}, "audio sync method", "" },
4249
    { "adrift_threshold", HAS_ARG | OPT_FLOAT | OPT_EXPERT, {(void*)&audio_drift_threshold}, "audio drift threshold", "threshold" },
4250
    { "vglobal", HAS_ARG | OPT_INT | OPT_EXPERT, {(void*)&video_global_header}, "video global header storage type", "" },
4251
    { "copyts", OPT_BOOL | OPT_EXPERT, {(void*)&copy_ts}, "copy timestamps" },
4252
    { "copytb", OPT_BOOL | OPT_EXPERT, {(void*)&copy_tb}, "copy input stream time base when stream copying" },
4253
    { "shortest", OPT_BOOL | OPT_EXPERT, {(void*)&opt_shortest}, "finish encoding within shortest input" }, //
4254
    { "dts_delta_threshold", HAS_ARG | OPT_FLOAT | OPT_EXPERT, {(void*)&dts_delta_threshold}, "timestamp discontinuity delta threshold", "threshold" },
4255
    { "programid", HAS_ARG | OPT_INT | OPT_EXPERT, {(void*)&opt_programid}, "desired program number", "" },
4256
    { "xerror", OPT_BOOL, {(void*)&exit_on_error}, "exit on error", "error" },
4257
    { "copyinkf", OPT_BOOL | OPT_EXPERT, {(void*)&copy_initial_nonkeyframes}, "copy initial non-keyframes" },
4258

    
4259
    /* video options */
4260
    { "b", OPT_FUNC2 | HAS_ARG | OPT_VIDEO, {(void*)opt_bitrate}, "set bitrate (in bits/s)", "bitrate" },
4261
    { "vb", OPT_FUNC2 | HAS_ARG | OPT_VIDEO, {(void*)opt_bitrate}, "set bitrate (in bits/s)", "bitrate" },
4262
    { "vframes", OPT_INT | HAS_ARG | OPT_VIDEO, {(void*)&max_frames[AVMEDIA_TYPE_VIDEO]}, "set the number of video frames to record", "number" },
4263
    { "r", OPT_FUNC2 | HAS_ARG | OPT_VIDEO, {(void*)opt_frame_rate}, "set frame rate (Hz value, fraction or abbreviation)", "rate" },
4264
    { "s", HAS_ARG | OPT_VIDEO, {(void*)opt_frame_size}, "set frame size (WxH or abbreviation)", "size" },
4265
    { "aspect", HAS_ARG | OPT_VIDEO, {(void*)opt_frame_aspect_ratio}, "set aspect ratio (4:3, 16:9 or 1.3333, 1.7777)", "aspect" },
4266
    { "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" },
4267
    { "croptop", OPT_FUNC2 | HAS_ARG | OPT_VIDEO, {(void*)opt_frame_crop}, "Removed, use the crop filter instead", "size" },
4268
    { "cropbottom", OPT_FUNC2 | HAS_ARG | OPT_VIDEO, {(void*)opt_frame_crop}, "Removed, use the crop filter instead", "size" },
4269
    { "cropleft", OPT_FUNC2 | HAS_ARG | OPT_VIDEO, {(void*)opt_frame_crop}, "Removed, use the crop filter instead", "size" },
4270
    { "cropright", OPT_FUNC2 | HAS_ARG | OPT_VIDEO, {(void*)opt_frame_crop}, "Removed, use the crop filter instead", "size" },
4271
    { "padtop", OPT_FUNC2 | HAS_ARG | OPT_VIDEO, {(void*)opt_pad}, "Removed, use the pad filter instead", "size" },
4272
    { "padbottom", OPT_FUNC2 | HAS_ARG | OPT_VIDEO, {(void*)opt_pad}, "Removed, use the pad filter instead", "size" },
4273
    { "padleft", OPT_FUNC2 | HAS_ARG | OPT_VIDEO, {(void*)opt_pad}, "Removed, use the pad filter instead", "size" },
4274
    { "padright", OPT_FUNC2 | HAS_ARG | OPT_VIDEO, {(void*)opt_pad}, "Removed, use the pad filter instead", "size" },
4275
    { "padcolor", OPT_FUNC2 | HAS_ARG | OPT_VIDEO, {(void*)opt_pad}, "Removed, use the pad filter instead", "color" },
4276
    { "intra", OPT_BOOL | OPT_EXPERT | OPT_VIDEO, {(void*)&intra_only}, "use only intra frames"},
4277
    { "vn", OPT_BOOL | OPT_VIDEO, {(void*)&video_disable}, "disable video" },
4278
    { "vdt", OPT_INT | HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)&video_discard}, "discard threshold", "n" },
4279
    { "qscale", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_qscale}, "use fixed video quantizer scale (VBR)", "q" },
4280
    { "rc_override", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_video_rc_override_string}, "rate control override for specific intervals", "override" },
4281
    { "vcodec", HAS_ARG | OPT_VIDEO, {(void*)opt_video_codec}, "force video codec ('copy' to copy stream)", "codec" },
4282
    { "me_threshold", HAS_ARG | OPT_FUNC2 | OPT_EXPERT | OPT_VIDEO, {(void*)opt_me_threshold}, "motion estimaton threshold",  "threshold" },
4283
    { "sameq", OPT_BOOL | OPT_VIDEO, {(void*)&same_quality},
4284
      "use same video quality as source (implies VBR)" },
4285
    { "pass", HAS_ARG | OPT_VIDEO, {(void*)&opt_pass}, "select the pass number (1 or 2)", "n" },
4286
    { "passlogfile", HAS_ARG | OPT_STRING | OPT_VIDEO, {(void*)&pass_logfilename_prefix}, "select two pass log file name prefix", "prefix" },
4287
    { "deinterlace", OPT_BOOL | OPT_EXPERT | OPT_VIDEO, {(void*)&do_deinterlace},
4288
      "deinterlace pictures" },
4289
    { "psnr", OPT_BOOL | OPT_EXPERT | OPT_VIDEO, {(void*)&do_psnr}, "calculate PSNR of compressed frames" },
4290
    { "vstats", OPT_EXPERT | OPT_VIDEO, {(void*)&opt_vstats}, "dump video coding statistics to file" },
4291
    { "vstats_file", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_vstats_file}, "dump video coding statistics to file", "file" },
4292
#if CONFIG_AVFILTER
4293
    { "vf", OPT_STRING | HAS_ARG, {(void*)&vfilters}, "video filters", "filter list" },
4294
#endif
4295
    { "intra_matrix", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_intra_matrix}, "specify intra matrix coeffs", "matrix" },
4296
    { "inter_matrix", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_inter_matrix}, "specify inter matrix coeffs", "matrix" },
4297
    { "top", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_top_field_first}, "top=1/bottom=0/auto=-1 field first", "" },
4298
    { "dc", OPT_INT | HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)&intra_dc_precision}, "intra_dc_precision", "precision" },
4299
    { "vtag", OPT_FUNC2 | HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_codec_tag}, "force video tag/fourcc", "fourcc/tag" },
4300
    { "newvideo", OPT_VIDEO | OPT_FUNC2, {(void*)opt_new_stream}, "add a new video stream to the current output stream" },
4301
    { "vlang", HAS_ARG | OPT_STRING | OPT_VIDEO, {(void *)&video_language}, "set the ISO 639 language code (3 letters) of the current video stream" , "code" },
4302
    { "qphist", OPT_BOOL | OPT_EXPERT | OPT_VIDEO, { (void *)&qp_hist }, "show QP histogram" },
4303
    { "force_fps", OPT_BOOL | OPT_EXPERT | OPT_VIDEO, {(void*)&force_fps}, "force the selected framerate, disable the best supported framerate selection" },
4304
    { "streamid", OPT_FUNC2 | HAS_ARG | OPT_EXPERT, {(void*)opt_streamid}, "set the value of an outfile streamid", "streamIndex:value" },
4305
    { "force_key_frames", OPT_STRING | HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void *)&forced_key_frames}, "force key frames at specified timestamps", "timestamps" },
4306

    
4307
    /* audio options */
4308
    { "ab", OPT_FUNC2 | HAS_ARG | OPT_AUDIO, {(void*)opt_bitrate}, "set bitrate (in bits/s)", "bitrate" },
4309
    { "aframes", OPT_INT | HAS_ARG | OPT_AUDIO, {(void*)&max_frames[AVMEDIA_TYPE_AUDIO]}, "set the number of audio frames to record", "number" },
4310
    { "aq", OPT_FLOAT | HAS_ARG | OPT_AUDIO, {(void*)&audio_qscale}, "set audio quality (codec-specific)", "quality", },
4311
    { "ar", HAS_ARG | OPT_FUNC2 | OPT_AUDIO, {(void*)opt_audio_rate}, "set audio sampling rate (in Hz)", "rate" },
4312
    { "ac", HAS_ARG | OPT_FUNC2 | OPT_AUDIO, {(void*)opt_audio_channels}, "set number of audio channels", "channels" },
4313
    { "an", OPT_BOOL | OPT_AUDIO, {(void*)&audio_disable}, "disable audio" },
4314
    { "acodec", HAS_ARG | OPT_AUDIO, {(void*)opt_audio_codec}, "force audio codec ('copy' to copy stream)", "codec" },
4315
    { "atag", OPT_FUNC2 | HAS_ARG | OPT_EXPERT | OPT_AUDIO, {(void*)opt_codec_tag}, "force audio tag/fourcc", "fourcc/tag" },
4316
    { "vol", OPT_INT | HAS_ARG | OPT_AUDIO, {(void*)&audio_volume}, "change audio volume (256=normal)" , "volume" }, //
4317
    { "newaudio", OPT_AUDIO | OPT_FUNC2, {(void*)opt_new_stream}, "add a new audio stream to the current output stream" },
4318
    { "alang", HAS_ARG | OPT_STRING | OPT_AUDIO, {(void *)&audio_language}, "set the ISO 639 language code (3 letters) of the current audio stream" , "code" },
4319
    { "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" },
4320

    
4321
    /* subtitle options */
4322
    { "sn", OPT_BOOL | OPT_SUBTITLE, {(void*)&subtitle_disable}, "disable subtitle" },
4323
    { "scodec", HAS_ARG | OPT_SUBTITLE, {(void*)opt_subtitle_codec}, "force subtitle codec ('copy' to copy stream)", "codec" },
4324
    { "newsubtitle", OPT_SUBTITLE | OPT_FUNC2, {(void*)opt_new_stream}, "add a new subtitle stream to the current output stream" },
4325
    { "slang", HAS_ARG | OPT_STRING | OPT_SUBTITLE, {(void *)&subtitle_language}, "set the ISO 639 language code (3 letters) of the current subtitle stream" , "code" },
4326
    { "stag", OPT_FUNC2 | HAS_ARG | OPT_EXPERT | OPT_SUBTITLE, {(void*)opt_codec_tag}, "force subtitle tag/fourcc", "fourcc/tag" },
4327

    
4328
    /* grab options */
4329
    { "vc", HAS_ARG | OPT_EXPERT | OPT_VIDEO | OPT_GRAB, {(void*)opt_video_channel}, "set video grab channel (DV1394 only)", "channel" },
4330
    { "tvstd", HAS_ARG | OPT_EXPERT | OPT_VIDEO | OPT_GRAB, {(void*)opt_video_standard}, "set television standard (NTSC, PAL (SECAM))", "standard" },
4331
    { "isync", OPT_BOOL | OPT_EXPERT | OPT_GRAB, {(void*)&input_sync}, "sync read on input", "" },
4332

    
4333
    /* muxer options */
4334
    { "muxdelay", OPT_FLOAT | HAS_ARG | OPT_EXPERT, {(void*)&mux_max_delay}, "set the maximum demux-decode delay", "seconds" },
4335
    { "muxpreload", OPT_FLOAT | HAS_ARG | OPT_EXPERT, {(void*)&mux_preload}, "set the initial demux-decode delay", "seconds" },
4336

    
4337
    { "absf", OPT_FUNC2 | HAS_ARG | OPT_AUDIO | OPT_EXPERT, {(void*)opt_bsf}, "", "bitstream_filter" },
4338
    { "vbsf", OPT_FUNC2 | HAS_ARG | OPT_VIDEO | OPT_EXPERT, {(void*)opt_bsf}, "", "bitstream_filter" },
4339
    { "sbsf", OPT_FUNC2 | HAS_ARG | OPT_SUBTITLE | OPT_EXPERT, {(void*)opt_bsf}, "", "bitstream_filter" },
4340

    
4341
    { "apre", OPT_FUNC2 | HAS_ARG | OPT_AUDIO | OPT_EXPERT, {(void*)opt_preset}, "set the audio options to the indicated preset", "preset" },
4342
    { "vpre", OPT_FUNC2 | HAS_ARG | OPT_VIDEO | OPT_EXPERT, {(void*)opt_preset}, "set the video options to the indicated preset", "preset" },
4343
    { "spre", OPT_FUNC2 | HAS_ARG | OPT_SUBTITLE | OPT_EXPERT, {(void*)opt_preset}, "set the subtitle options to the indicated preset", "preset" },
4344
    { "fpre", OPT_FUNC2 | HAS_ARG | OPT_EXPERT, {(void*)opt_preset}, "set options from indicated preset file", "filename" },
4345

    
4346
    { "default", OPT_FUNC2 | HAS_ARG | OPT_AUDIO | OPT_VIDEO | OPT_EXPERT, {(void*)opt_default}, "generic catch all option", "" },
4347
    { NULL, },
4348
};
4349

    
4350
int main(int argc, char **argv)
4351
{
4352
    int64_t ti;
4353

    
4354
    av_log_set_flags(AV_LOG_SKIP_REPEATED);
4355

    
4356
    avcodec_register_all();
4357
#if CONFIG_AVDEVICE
4358
    avdevice_register_all();
4359
#endif
4360
#if CONFIG_AVFILTER
4361
    avfilter_register_all();
4362
#endif
4363
    av_register_all();
4364

    
4365
#if HAVE_ISATTY
4366
    if(isatty(STDIN_FILENO))
4367
        url_set_interrupt_cb(decode_interrupt_cb);
4368
#endif
4369

    
4370
    init_opts();
4371

    
4372
    show_banner();
4373

    
4374
    /* parse options */
4375
    parse_options(argc, argv, options, opt_output_file);
4376

    
4377
    if(nb_output_files <= 0 && nb_input_files == 0) {
4378
        show_usage();
4379
        fprintf(stderr, "Use -h to get full help or, even better, run 'man ffmpeg'\n");
4380
        ffmpeg_exit(1);
4381
    }
4382

    
4383
    /* file converter / grab */
4384
    if (nb_output_files <= 0) {
4385
        fprintf(stderr, "At least one output file must be specified\n");
4386
        ffmpeg_exit(1);
4387
    }
4388

    
4389
    if (nb_input_files == 0) {
4390
        fprintf(stderr, "At least one input file must be specified\n");
4391
        ffmpeg_exit(1);
4392
    }
4393

    
4394
    ti = getutime();
4395
    if (transcode(output_files, nb_output_files, input_files, nb_input_files,
4396
                  stream_maps, nb_stream_maps) < 0)
4397
        ffmpeg_exit(1);
4398
    ti = getutime() - ti;
4399
    if (do_benchmark) {
4400
        int maxrss = getmaxrss() / 1024;
4401
        printf("bench: utime=%0.3fs maxrss=%ikB\n", ti / 1000000.0, maxrss);
4402
    }
4403

    
4404
    return ffmpeg_exit(0);
4405
}