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

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

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

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

65
#if HAVE_SYS_SELECT_H
66 67 68
#include <sys/select.h>
#endif

69
#include <time.h>
Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
70

Fabrice Bellard's avatar
Fabrice Bellard committed
71 72
#include "cmdutils.h"

73
#include "libavutil/avassert.h"
74

75
const char program_name[] = "ffmpeg";
76
const int program_birth_year = 2000;
77

Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
78 79 80 81
/* select an input stream for an output stream */
typedef struct AVStreamMap {
    int file_index;
    int stream_index;
82 83
    int sync_file_index;
    int sync_stream_index;
Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
84 85
} AVStreamMap;

86 87 88
/**
 * select an input file for an output file
 */
89
typedef struct AVMetaDataMap {
90 91 92
    int  file;      //< file index
    char type;      //< type of metadata to copy -- (g)lobal, (s)tream, (c)hapter or (p)rogram
    int  index;     //< stream/chapter/program number
93 94
} AVMetaDataMap;

95 96 97 98 99
typedef struct AVChapterMap {
    int in_file;
    int out_file;
} AVChapterMap;

100
static const OptionDef options[];
Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
101

102
#define MAX_FILES 100
103
#define MAX_STREAMS 1024    /* arbitrary sanity check value */
Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
104

105 106
#define FFM_PACKET_SIZE 4096 //XXX a duplicate of the line in ffm.h

107
static const char *last_asked_format = NULL;
Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
108
static AVFormatContext *input_files[MAX_FILES];
109
static int64_t input_files_ts_offset[MAX_FILES];
110
static double *input_files_ts_scale[MAX_FILES] = {NULL};
111
static AVCodec **input_codecs = NULL;
Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
112
static int nb_input_files = 0;
113
static int nb_input_codecs = 0;
114
static int nb_input_files_ts_scale[MAX_FILES] = {0};
Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
115 116

static AVFormatContext *output_files[MAX_FILES];
117
static AVCodec **output_codecs = NULL;
Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
118
static int nb_output_files = 0;
119
static int nb_output_codecs = 0;
Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
120

121
static AVStreamMap *stream_maps = NULL;
Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
122 123
static int nb_stream_maps;

124 125
/* first item specifies output metadata, second is input */
static AVMetaDataMap (*meta_data_maps)[2] = NULL;
126
static int nb_meta_data_maps;
127
static int metadata_global_autocopy   = 1;
128 129
static int metadata_streams_autocopy  = 1;
static int metadata_chapters_autocopy = 1;
130

131 132 133
static AVChapterMap *chapter_maps = NULL;
static int nb_chapter_maps;

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

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

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

177
static int subtitle_disable = 0;
178
static char *subtitle_codec_name = NULL;
179
static char *subtitle_language = NULL;
180
static unsigned int subtitle_codec_tag = 0;
Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
181

182 183 184 185
static int data_disable = 0;
static char *data_codec_name = NULL;
static unsigned int data_codec_tag = 0;

186 187
static float mux_preload= 0.5;
static float mux_max_delay= 0.7;
188

189
static int64_t recording_time = INT64_MAX;
190
static int64_t start_time = 0;
191
static int64_t recording_timestamp = 0;
192
static int64_t input_ts_offset = 0;
Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
193
static int file_overwrite = 0;
194
static AVMetadata *metadata;
Fabrice Bellard's avatar
Fabrice Bellard committed
195
static int do_benchmark = 0;
196
static int do_hex_dump = 0;
197
static int do_pkt_dump = 0;
198
static int do_psnr = 0;
199
static int do_pass = 0;
Stefano Sabatini's avatar
Stefano Sabatini committed
200
static char *pass_logfilename_prefix = NULL;
201 202
static int audio_stream_copy = 0;
static int video_stream_copy = 0;
203
static int subtitle_stream_copy = 0;
204
static int data_stream_copy = 0;
205
static int video_sync_method= -1;
206
static int audio_sync_method= 0;
Michael Niedermayer's avatar
Michael Niedermayer committed
207
static float audio_drift_threshold= 0.1;
208
static int copy_ts= 0;
209
static int copy_tb;
210
static int opt_shortest = 0;
211
static char *vstats_filename;
212
static FILE *vstats_file;
213
static int opt_programid = 0;
214
static int copy_initial_nonkeyframes = 0;
215

216 217
static int rate_emu = 0;

218
static int  video_channel = 0;
219
static char *video_standard;
220

221
static int audio_volume = 256;
222

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

237
static float dts_delta_threshold = 10;
238

Benoit Fouet's avatar
Benoit Fouet committed
239
static int64_t timer_start;
Michael Niedermayer's avatar
Michael Niedermayer committed
240

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

static short *samples;

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

Stefano Sabatini's avatar
Stefano Sabatini committed
251
#define DEFAULT_PASS_LOGFILENAME_PREFIX "ffmpeg2pass"
Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
252

253 254
struct AVInputStream;

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

276 277
    float frame_aspect_ratio;

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

Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
283 284 285
    /* audio only */
    int audio_resample;
    ReSampleContext *resample; /* for audio resampling */
286 287 288
    int resample_sample_fmt;
    int resample_channels;
    int resample_sample_rate;
289 290
    int reformat_pair;
    AVAudioConvert *reformat_ctx;
291
    AVFifoBuffer *fifo;     /* for compression: one audio fifo per codec */
292
    FILE *logfile;
293

294 295 296 297 298 299 300 301
#if CONFIG_AVFILTER
    AVFilterContext *output_video_filter;
    AVFilterContext *input_video_filter;
    AVFilterBufferRef *picref;
    char *avfilter;
    AVFilterGraph *graph;
#endif

302
   int sws_flags;
Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
303 304
} AVOutputStream;

305 306 307
static AVOutputStream **output_streams_for_file[MAX_FILES] = { NULL };
static int nb_output_streams_for_file[MAX_FILES] = { 0 };

Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
308 309 310 311 312
typedef struct AVInputStream {
    int file_index;
    AVStream *st;
    int discard;             /* true if stream data should be discarded */
    int decoding_needed;     /* true if the packets must be decoded in 'raw_fifo' */
313
    int64_t sample_index;      /* current sample */
314 315

    int64_t       start;     /* time when read started */
316 317
    int64_t       next_pts;  /* synthetic pts for cases where pkt.pts
                                is not defined */
318
    int64_t       pts;       /* current pts */
319
    PtsCorrectionContext pts_ctx;
320
    int is_start;            /* is 1 at the start and after a discontinuity */
321
    int showed_multi_packet_warning;
322
    int is_past_recording_time;
323 324 325 326
#if CONFIG_AVFILTER
    AVFrame *filter_frame;
    int has_filter_frame;
#endif
Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
327 328 329 330 331 332
} AVInputStream;

typedef struct AVInputFile {
    int eof_reached;      /* true if eof reached */
    int ist_index;        /* index of first stream in ist_table */
    int buffer_size;      /* current total buffer size */
333
    int nb_streams;       /* nb streams we are aware of */
Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
334 335
} AVInputFile;

336 337
#if CONFIG_AVFILTER

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

349
    ost->graph = avfilter_graph_alloc();
350

351 352 353 354 355 356 357 358 359
    if (ist->st->sample_aspect_ratio.num){
        sample_aspect_ratio = ist->st->sample_aspect_ratio;
    }else
        sample_aspect_ratio = ist->st->codec->sample_aspect_ratio;

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

360 361
    ret = avfilter_graph_create_filter(&ost->input_video_filter, avfilter_get_by_name("buffer"),
                                       "src", args, NULL, ost->graph);
362
    if (ret < 0)
363
        return ret;
364 365
    ret = avfilter_graph_create_filter(&ost->output_video_filter, &ffsink,
                                       "out", NULL, &ffsink_ctx, ost->graph);
366
    if (ret < 0)
367
        return ret;
368
    last_filter = ost->input_video_filter;
369

Stefano Sabatini's avatar
Stefano Sabatini committed
370
    if (codec->width  != icodec->width || codec->height != icodec->height) {
371
        snprintf(args, 255, "%d:%d:flags=0x%X",
372 373
                 codec->width,
                 codec->height,
374
                 ost->sws_flags);
375
        if ((ret = avfilter_graph_create_filter(&filter, avfilter_get_by_name("scale"),
376
                                                NULL, args, NULL, ost->graph)) < 0)
377 378 379
            return ret;
        if ((ret = avfilter_link(last_filter, 0, filter, 0)) < 0)
            return ret;
380
        last_filter = filter;
381 382
    }

383
    snprintf(args, sizeof(args), "flags=0x%X", ost->sws_flags);
384
    ost->graph->scale_sws_opts = av_strdup(args);
385

386
    if (ost->avfilter) {
387 388 389 390
        AVFilterInOut *outputs = av_malloc(sizeof(AVFilterInOut));
        AVFilterInOut *inputs  = av_malloc(sizeof(AVFilterInOut));

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

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

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

408
    if ((ret = avfilter_graph_config(ost->graph, NULL)) < 0)
409
        return ret;
410

411 412
    codec->width  = ost->output_video_filter->inputs[0]->w;
    codec->height = ost->output_video_filter->inputs[0]->h;
413
    codec->sample_aspect_ratio = ost->st->sample_aspect_ratio =
414 415
        ost->frame_aspect_ratio ? // overriden by the -aspect cli option
        av_d2q(ost->frame_aspect_ratio*codec->height/codec->width, 255) :
416
        ost->output_video_filter->inputs[0]->sample_aspect_ratio;
417 418 419 420 421

    return 0;
}
#endif /* CONFIG_AVFILTER */

Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
422 423
static void term_exit(void)
{
424
    av_log(NULL, AV_LOG_QUIET, "");
425
}
Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
426

427
static volatile int received_sigterm = 0;
428
static volatile int received_nb_signals = 0;
429 430 431 432 433

static void
sigterm_handler(int sig)
{
    received_sigterm = sig;
434
    received_nb_signals++;
435 436 437
    term_exit();
}

Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
438 439
static void term_init(void)
{
440 441
    signal(SIGINT , sigterm_handler); /* Interrupt (ANSI).  */
    signal(SIGTERM, sigterm_handler); /* Termination (ANSI).  */
Måns Rullgård's avatar
Måns Rullgård committed
442 443 444
#ifdef SIGXCPU
    signal(SIGXCPU, sigterm_handler);
#endif
Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
445 446
}

447 448
static int decode_interrupt_cb(void)
{
449
    return received_nb_signals > 1;
450 451
}

452
static int ffmpeg_exit(int ret)
453 454 455 456 457 458
{
    int i;

    /* close files */
    for(i=0;i<nb_output_files;i++) {
        AVFormatContext *s = output_files[i];
Ramiro Polla's avatar
Ramiro Polla committed
459
        if (!(s->oformat->flags & AVFMT_NOFILE) && s->pb)
460
            avio_close(s->pb);
461
        avformat_free_context(s);
462
        av_free(output_streams_for_file[i]);
463
    }
464
    for(i=0;i<nb_input_files;i++) {
465
        av_close_input_file(input_files[i]);
466 467
        av_free(input_files_ts_scale[i]);
    }
468 469 470 471 472 473 474 475

    av_free(intra_matrix);
    av_free(inter_matrix);

    if (vstats_file)
        fclose(vstats_file);
    av_free(vstats_filename);

476
    av_free(streamid_map);
477
    av_free(input_codecs);
478
    av_free(output_codecs);
479
    av_free(stream_maps);
480
    av_free(meta_data_maps);
481 482 483 484

    av_free(video_codec_name);
    av_free(audio_codec_name);
    av_free(subtitle_codec_name);
485
    av_free(data_codec_name);
486 487 488

    av_free(video_standard);

489
    uninit_opts();
490 491
    av_free(audio_buf);
    av_free(audio_out);
492
    allocated_audio_buf_size= allocated_audio_out_size= 0;
493
    av_free(samples);
494

495 496 497 498
#if CONFIG_AVFILTER
    avfilter_uninit();
#endif

499 500 501 502 503 504 505
    if (received_sigterm) {
        fprintf(stderr,
            "Received signal %d: terminating.\n",
            (int) received_sigterm);
        exit (255);
    }

506 507
    exit(ret); /* not all OS-es handle main() return value */
    return ret;
508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527
}

/* similar to ff_dynarray_add() and av_fast_realloc() */
static void *grow_array(void *array, int elem_size, int *size, int new_size)
{
    if (new_size >= INT_MAX / elem_size) {
        fprintf(stderr, "Array too big.\n");
        ffmpeg_exit(1);
    }
    if (*size < new_size) {
        uint8_t *tmp = av_realloc(array, new_size*elem_size);
        if (!tmp) {
            fprintf(stderr, "Could not alloc buffer.\n");
            ffmpeg_exit(1);
        }
        memset(tmp + *size*elem_size, 0, (new_size-*size) * elem_size);
        *size = new_size;
        return tmp;
    }
    return array;
528 529
}

530 531 532
static void choose_sample_fmt(AVStream *st, AVCodec *codec)
{
    if(codec && codec->sample_fmts){
533
        const enum AVSampleFormat *p= codec->sample_fmts;
534 535 536 537
        for(; *p!=-1; p++){
            if(*p == st->codec->sample_fmt)
                break;
        }
538 539 540 541 542 543
        if (*p == -1) {
            av_log(NULL, AV_LOG_WARNING,
                   "Incompatible sample format '%s' for codec '%s', auto-selecting format '%s'\n",
                   av_get_sample_fmt_name(st->codec->sample_fmt),
                   codec->name,
                   av_get_sample_fmt_name(codec->sample_fmts[0]));
544
            st->codec->sample_fmt = codec->sample_fmts[0];
545
        }
546 547 548
    }
}

549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588
/**
 * Update the requested input sample format based on the output sample format.
 * This is currently only used to request float output from decoders which
 * support multiple sample formats, one of which is AV_SAMPLE_FMT_FLT.
 * Ideally this will be removed in the future when decoders do not do format
 * conversion and only output in their native format.
 */
static void update_sample_fmt(AVCodecContext *dec, AVCodec *dec_codec,
                              AVCodecContext *enc)
{
    /* if sample formats match or a decoder sample format has already been
       requested, just return */
    if (enc->sample_fmt == dec->sample_fmt ||
        dec->request_sample_fmt > AV_SAMPLE_FMT_NONE)
        return;

    /* if decoder supports more than one output format */
    if (dec_codec && dec_codec->sample_fmts &&
        dec_codec->sample_fmts[0] != AV_SAMPLE_FMT_NONE &&
        dec_codec->sample_fmts[1] != AV_SAMPLE_FMT_NONE) {
        enum AVSampleFormat *p;
        int min_dec = -1, min_inc = -1;

        /* find a matching sample format in the encoder */
        for (p = dec_codec->sample_fmts; *p != AV_SAMPLE_FMT_NONE; p++) {
            if (*p == enc->sample_fmt) {
                dec->request_sample_fmt = *p;
                return;
            } else if (*p > enc->sample_fmt) {
                min_inc = FFMIN(min_inc, *p - enc->sample_fmt);
            } else
                min_dec = FFMIN(min_dec, enc->sample_fmt - *p);
        }

        /* if none match, provide the one that matches quality closest */
        dec->request_sample_fmt = min_inc > 0 ? enc->sample_fmt + min_inc :
                                  enc->sample_fmt - min_dec;
    }
}

589 590 591 592
static void choose_sample_rate(AVStream *st, AVCodec *codec)
{
    if(codec && codec->supported_samplerates){
        const int *p= codec->supported_samplerates;
593
        int best=0;
594 595 596 597 598 599 600 601
        int best_dist=INT_MAX;
        for(; *p; p++){
            int dist= abs(st->codec->sample_rate - *p);
            if(dist < best_dist){
                best_dist= dist;
                best= *p;
            }
        }
602 603 604
        if(best_dist){
            av_log(st->codec, AV_LOG_WARNING, "Requested sampling rate unsupported using closest supported (%d)\n", best);
        }
605 606 607 608
        st->codec->sample_rate= best;
    }
}

609 610 611 612
static void choose_pixel_fmt(AVStream *st, AVCodec *codec)
{
    if(codec && codec->pix_fmts){
        const enum PixelFormat *p= codec->pix_fmts;
613 614 615 616 617 618 619
        if(st->codec->strict_std_compliance <= FF_COMPLIANCE_UNOFFICIAL){
            if(st->codec->codec_id==CODEC_ID_MJPEG){
                p= (const enum PixelFormat[]){PIX_FMT_YUVJ420P, PIX_FMT_YUVJ422P, PIX_FMT_YUV420P, PIX_FMT_YUV422P, PIX_FMT_NONE};
            }else if(st->codec->codec_id==CODEC_ID_LJPEG){
                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};
            }
        }
620 621 622 623
        for(; *p!=-1; p++){
            if(*p == st->codec->pix_fmt)
                break;
        }
624 625 626 627 628 629 630
        if (*p == -1) {
            if(st->codec->pix_fmt != PIX_FMT_NONE)
                av_log(NULL, AV_LOG_WARNING,
                        "Incompatible pixel format '%s' for codec '%s', auto-selecting format '%s'\n",
                        av_pix_fmt_descriptors[st->codec->pix_fmt].name,
                        codec->name,
                        av_pix_fmt_descriptors[codec->pix_fmts[0]].name);
631
            st->codec->pix_fmt = codec->pix_fmts[0];
632
        }
633 634 635
    }
}

636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653
static AVOutputStream *new_output_stream(AVFormatContext *oc, int file_idx)
{
    int idx = oc->nb_streams - 1;
    AVOutputStream *ost;

    output_streams_for_file[file_idx] =
        grow_array(output_streams_for_file[file_idx],
                   sizeof(*output_streams_for_file[file_idx]),
                   &nb_output_streams_for_file[file_idx],
                   oc->nb_streams);
    ost = output_streams_for_file[file_idx][idx] =
        av_mallocz(sizeof(AVOutputStream));
    if (!ost) {
        fprintf(stderr, "Could not alloc output stream\n");
        ffmpeg_exit(1);
    }
    ost->file_index = file_idx;
    ost->index = idx;
654 655

    ost->sws_flags = av_get_int(sws_opts, "sws_flags", NULL);
656 657 658
    return ost;
}

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

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

674 675
        s->nb_streams++;

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

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

700 701
        if(st->codec->flags & CODEC_FLAG_BITEXACT)
            nopts = 1;
702 703

        new_output_stream(s, nb_output_files);
Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
704 705
    }

706 707 708
    if (!nopts)
        s->timestamp = av_gettime();

Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
709 710 711 712
    av_close_input_file(ic);
    return 0;
}

713 714 715 716
static double
get_sync_ipts(const AVOutputStream *ost)
{
    const AVInputStream *ist = ost->sync_ist;
717
    return (double)(ist->pts - start_time)/AV_TIME_BASE;
718 719
}

720
static void write_frame(AVFormatContext *s, AVPacket *pkt, AVCodecContext *avctx, AVBitStreamFilterContext *bsfc){
721 722
    int ret;

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

        bsfc= bsfc->next;
    }

745 746 747
    ret= av_interleaved_write_frame(s, pkt);
    if(ret < 0){
        print_error("av_interleaved_write_frame()", ret);
748
        ffmpeg_exit(1);
749
    }
750 751
}

752
#define MAX_AUDIO_PACKET_SIZE (128 * 1024)
Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
753

754 755
static void do_audio_out(AVFormatContext *s,
                         AVOutputStream *ost,
Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
756 757 758
                         AVInputStream *ist,
                         unsigned char *buf, int size)
{
759
    uint8_t *buftmp;
760
    int64_t audio_out_size, audio_buf_size;
761
    int64_t allocated_for_size= size;
762

763
    int size_out, frame_bytes, ret, resample_changed;
764
    AVCodecContext *enc= ost->st->codec;
765
    AVCodecContext *dec= ist->st->codec;
766 767
    int osize= av_get_bits_per_sample_fmt(enc->sample_fmt)/8;
    int isize= av_get_bits_per_sample_fmt(dec->sample_fmt)/8;
768 769
    const int coded_bps = av_get_bits_per_sample(enc->codec->id);