ffmpeg.c 164 KB
Newer Older
Fabrice Bellard's avatar
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
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
Fabrice Bellard committed
11
 *
12
 * Libav is distributed in the hope that it will be useful,
Fabrice Bellard's avatar
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
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
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
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
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
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
Fabrice Bellard committed
101

102
#define MAX_FILES 100
103
#define MAX_STREAMS 1024    /* arbitrary sanity check value */
Fabrice Bellard's avatar
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;
108
static int64_t input_files_ts_offset[MAX_FILES];
109
static double *input_files_ts_scale[MAX_FILES] = {NULL};
110 111
static AVCodec **input_codecs = NULL;
static int nb_input_codecs = 0;
112
static int nb_input_files_ts_scale[MAX_FILES] = {0};
Fabrice Bellard's avatar
Fabrice Bellard committed
113 114

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

119
static AVStreamMap *stream_maps = NULL;
Fabrice Bellard's avatar
Fabrice Bellard committed
120 121
static int nb_stream_maps;

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

129 130 131
static AVChapterMap *chapter_maps = NULL;
static int nb_chapter_maps;

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

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

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

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

180 181 182 183
static int data_disable = 0;
static char *data_codec_name = NULL;
static unsigned int data_codec_tag = 0;

184 185
static float mux_preload= 0.5;
static float mux_max_delay= 0.7;
186

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

214 215
static int rate_emu = 0;

216
static int  video_channel = 0;
217
static char *video_standard;
218

219
static int audio_volume = 256;
220

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

235
static float dts_delta_threshold = 10;
236

Benoit Fouet's avatar
Benoit Fouet committed
237
static int64_t timer_start;
238

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

static short *samples;

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

Stefano Sabatini's avatar
Stefano Sabatini committed
249
#define DEFAULT_PASS_LOGFILENAME_PREFIX "ffmpeg2pass"
Fabrice Bellard's avatar
Fabrice Bellard committed
250

251 252
struct AVInputStream;

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

274 275
    float frame_aspect_ratio;

276 277 278 279 280
    /* forced key frames */
    int64_t *forced_kf_pts;
    int forced_kf_count;
    int forced_kf_index;

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

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

300
   int sws_flags;
Fabrice Bellard's avatar
Fabrice Bellard committed
301 302
} AVOutputStream;

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

Fabrice Bellard's avatar
Fabrice Bellard committed
306 307 308 309 310
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' */
311
    int64_t sample_index;      /* current sample */
312 313

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

typedef struct AVInputFile {
328
    AVFormatContext *ctx;
Fabrice Bellard's avatar
Fabrice Bellard committed
329 330 331 332 333
    int eof_reached;      /* true if eof reached */
    int ist_index;        /* index of first stream in ist_table */
    int buffer_size;      /* current total buffer size */
} AVInputFile;

334 335 336 337 338
static AVInputStream *input_streams = NULL;
static int         nb_input_streams = 0;
static AVInputFile   *input_files   = NULL;
static int         nb_input_files   = 0;

339 340
#if CONFIG_AVFILTER

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

352
    ost->graph = avfilter_graph_alloc();
353

354 355 356 357 358 359 360 361 362
    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);

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

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

386
    snprintf(args, sizeof(args), "flags=0x%X", ost->sws_flags);
387
    ost->graph->scale_sws_opts = av_strdup(args);
388

389
    if (ost->avfilter) {
390 391 392 393
        AVFilterInOut *outputs = av_malloc(sizeof(AVFilterInOut));
        AVFilterInOut *inputs  = av_malloc(sizeof(AVFilterInOut));

        outputs->name    = av_strdup("in");
394
        outputs->filter_ctx = last_filter;
395 396 397 398
        outputs->pad_idx = 0;
        outputs->next    = NULL;

        inputs->name    = av_strdup("out");
399
        inputs->filter_ctx = ost->output_video_filter;
400 401 402
        inputs->pad_idx = 0;
        inputs->next    = NULL;

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

411
    if ((ret = avfilter_graph_config(ost->graph, NULL)) < 0)
412
        return ret;
413

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

    return 0;
}
#endif /* CONFIG_AVFILTER */

Fabrice Bellard's avatar
Fabrice Bellard committed
425 426
static void term_exit(void)
{
427
    av_log(NULL, AV_LOG_QUIET, "");
428
}
Fabrice Bellard's avatar
Fabrice Bellard committed
429

430
static volatile int received_sigterm = 0;
431
static volatile int received_nb_signals = 0;
432 433 434 435 436

static void
sigterm_handler(int sig)
{
    received_sigterm = sig;
437
    received_nb_signals++;
438 439 440
    term_exit();
}

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

450 451
static int decode_interrupt_cb(void)
{
452
    return received_nb_signals > 1;
453 454
}

455
static int ffmpeg_exit(int ret)
456 457 458 459 460 461
{
    int i;

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

    av_free(intra_matrix);
    av_free(inter_matrix);

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

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

485 486 487
    av_freep(&input_streams);
    av_freep(&input_files);

488 489 490
    av_free(video_codec_name);
    av_free(audio_codec_name);
    av_free(subtitle_codec_name);
491
    av_free(data_codec_name);
492 493 494

    av_free(video_standard);

495
    uninit_opts();
496 497
    av_free(audio_buf);
    av_free(audio_out);
498
    allocated_audio_buf_size= allocated_audio_out_size= 0;
499
    av_free(samples);
500

501 502 503 504
#if CONFIG_AVFILTER
    avfilter_uninit();
#endif

505 506 507 508 509 510 511
    if (received_sigterm) {
        fprintf(stderr,
            "Received signal %d: terminating.\n",
            (int) received_sigterm);
        exit (255);
    }

512 513
    exit(ret); /* not all OS-es handle main() return value */
    return ret;
514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533
}

/* 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;
534 535
}

536 537 538
static void choose_sample_fmt(AVStream *st, AVCodec *codec)
{
    if(codec && codec->sample_fmts){
539
        const enum AVSampleFormat *p= codec->sample_fmts;
540 541 542 543
        for(; *p!=-1; p++){
            if(*p == st->codec->sample_fmt)
                break;
        }
544 545 546 547 548 549
        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]));
550
            st->codec->sample_fmt = codec->sample_fmts[0];
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 589 590 591 592 593 594
/**
 * 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;
    }
}

595 596 597 598
static void choose_sample_rate(AVStream *st, AVCodec *codec)
{
    if(codec && codec->supported_samplerates){
        const int *p= codec->supported_samplerates;
599
        int best=0;
600 601 602 603 604 605 606 607
        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;
            }
        }
608 609 610
        if(best_dist){
            av_log(st->codec, AV_LOG_WARNING, "Requested sampling rate unsupported using closest supported (%d)\n", best);
        }
611 612 613 614
        st->codec->sample_rate= best;
    }
}

615 616 617 618
static void choose_pixel_fmt(AVStream *st, AVCodec *codec)
{
    if(codec && codec->pix_fmts){
        const enum PixelFormat *p= codec->pix_fmts;
619 620 621 622 623 624 625
        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};
            }
        }
626 627 628 629
        for(; *p!=-1; p++){
            if(*p == st->codec->pix_fmt)
                break;
        }
630 631 632 633 634 635 636
        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);
637
            st->codec->pix_fmt = codec->pix_fmts[0];
638
        }
639 640 641
    }
}

642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659
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;
660 661

    ost->sws_flags = av_get_int(sws_opts, "sws_flags", NULL);
662 663 664
    return ost;
}

665
static int read_ffserver_streams(AVFormatContext *s, const char *filename)
Fabrice Bellard's avatar
Fabrice Bellard committed
666
{
667
    int i, err;
Fabrice Bellard's avatar
Fabrice Bellard committed
668
    AVFormatContext *ic;
669
    int nopts = 0;
Fabrice Bellard's avatar
Fabrice Bellard committed
670

671 672 673
    err = av_open_input_file(&ic, filename, NULL, FFM_PACKET_SIZE, NULL);
    if (err < 0)
        return err;
Fabrice Bellard's avatar
Fabrice Bellard committed
674
    /* copy stream format */
675
    s->nb_streams = 0;
676
    s->streams = av_mallocz(sizeof(AVStream *) * ic->nb_streams);
Fabrice Bellard's avatar
Fabrice Bellard committed
677 678
    for(i=0;i<ic->nb_streams;i++) {
        AVStream *st;
679
        AVCodec *codec;
Michael Niedermayer's avatar
Michael Niedermayer committed
680

681 682
        s->nb_streams++;

683
        // FIXME: a more elegant solution is needed
684
        st = av_mallocz(sizeof(AVStream));
Fabrice Bellard's avatar
Fabrice Bellard committed
685
        memcpy(st, ic->streams[i], sizeof(AVStream));
686
        st->codec = avcodec_alloc_context();
687 688
        if (!st->codec) {
            print_error(filename, AVERROR(ENOMEM));
689
            ffmpeg_exit(1);
690
        }
691
        avcodec_copy_context(st->codec, ic->streams[i]->codec);
Fabrice Bellard's avatar
Fabrice Bellard committed
692
        s->streams[i] = st;
693

694 695 696 697 698 699 700 701 702 703 704 705
        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);
        }
706

707 708
        if(st->codec->flags & CODEC_FLAG_BITEXACT)
            nopts = 1;
709 710

        new_output_stream(s, nb_output_files);
Fabrice Bellard's avatar
Fabrice Bellard committed
711 712
    }

713 714 715
    if (!nopts)
        s->timestamp = av_gettime();

Fabrice Bellard's avatar
Fabrice Bellard committed
716 717 718 719
    av_close_input_file(ic);
    return 0;
}

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

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

730 731 732 733 734
    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,
735
                                          pkt->flags & AV_PKT_FLAG_KEY);
736
        if(a>0){
737 738
            av_free_packet(pkt);
            new_pkt.destruct= av_destruct_packet;
739
        } else if(a<0){
740 741 742
            fprintf(stderr, "%s failed for stream %d, codec %s",
                    bsfc->filter->name, pkt->stream_index,
                    avctx->codec ? avctx->codec->name : "copy");
743
            print_error("", a);
744
            if (exit_on_error)
745
                ffmpeg_exit(1);
746 747 748 749 750 751
        }
        *pkt= new_pkt;

        bsfc= bsfc->next;
    }

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

759
#define MAX_AUDIO_PACKET_SIZE (128 * 1024)
Fabrice Bellard's avatar
Fabrice Bellard committed
760

761 762
static void do_audio_out(AVFormatContext *s,
                         AVOutputStream *ost,
Fabrice Bellard's avatar
Fabrice Bellard committed
763 764 765
                         AVInputStream *ist,
                         unsigned char *buf, int size)
{
766
    uint8_t *buftmp;
767
    int64_t audio_out_size, audio_buf_size;
768
    int64_t allocated_for_size= size;
769

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

777 778
need_realloc:
    audio_buf_size= (allocated_for_size + isize*dec->channels - 1) / (isize*dec->channels);
779
    audio_buf_size= (audio_buf_size*enc->sample_rate + dec->sample_rate) / dec->sample_rate;
Vitor Sessak's avatar
Vitor Sessak committed
780
    audio_buf_size= audio_buf_size*2 + 10000; //safety factors for the deprecated resampling API
781
    audio_buf_size= FFMAX(audio_buf_size, enc->frame_size);
782 783 784 785 786 787 788 789 790
    audio_buf_size*= osize*enc->channels;

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

    if(audio_out_size > INT_MAX || audio_buf_size > INT_MAX){
        fprintf(stderr, "Buffer sizes too large\n");
791
        ffmpeg_exit(1);
792
    }
Fabrice Bellard's avatar
Fabrice Bellard committed
793

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

801
    if (enc->channels != dec->channels || enc->sample_rate != dec->sample_rate)
802 803
        ost->audio_resample = 1;

804 805 806 807 808 809 810
    resample_changed = ost->resample_sample_fmt  != dec->sample_fmt ||
                       ost->resample_channels    != dec->channels   ||
                       ost->resample_sample_rate != dec->sample_rate;

    if ((ost->audio_resample && !ost->resample) || resample_changed) {
        if (resample_changed) {
            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",
811
                   ist->file_index, ist->st->index,
812 813 814 815 816 817 818 819
                   ost->resample_sample_rate, av_get_sample_fmt_name(ost->resample_sample_fmt), ost->resample_channels,
                   dec->sample_rate, av_get_sample_fmt_name(dec->sample_fmt), dec->channels);
            ost->resample_sample_fmt  = dec->sample_fmt;
            ost->resample_channels    = dec->channels;
            ost->resample_sample_rate = dec->sample_rate;
            if (ost->resample)
                audio_resample_close(ost->resample);
        }
820 821 822
        /* if audio_sync_method is >1 the resampler is needed for audio drift compensation */
        if (audio_sync_method <= 1 &&
            ost->resample_sample_fmt  == enc->sample_fmt &&
823 824 825 826
            ost->resample_channels    == enc->channels   &&
            ost->resample_sample_rate == enc->sample_rate) {
            ost->resample = NULL;
            ost->audio_resample = 0;
827
        } else if (ost->audio_resample) {
Stefano Sabatini's avatar
Stefano Sabatini committed
828 829 830 831 832 833 834 835 836 837 838 839
            if (dec->sample_fmt != AV_SAMPLE_FMT_S16)
                fprintf(stderr, "Warning, using s16 intermediate sample format for resampling\n");
            ost->resample = av_audio_resample_init(enc->channels,    dec->channels,
                                                   enc->sample_rate, dec->sample_rate,
                                                   enc->sample_fmt,  dec->sample_fmt,
                                                   16, 10, 0, 0.8);
            if (!ost->resample) {
                fprintf(stderr, "Can not resample %d channels @ %d Hz to %d channels @ %d Hz\n",
                        dec->channels, dec->sample_rate,
                        enc->channels, enc->sample_rate);
                ffmpeg_exit(1);
            }
840
        }
841 842
    }

843
#define MAKE_SFMT_PAIR(a,b) ((a)+AV_SAMPLE_FMT_NB*(b))
844
    if (!ost->audio_resample && dec->sample_fmt!=enc->sample_fmt &&
845 846 847 848 849 850 851
        MAKE_SFMT_PAIR(enc->sample_fmt,dec->sample_fmt)!=ost->reformat_pair) {
        if (ost->reformat_ctx)
            av_audio_convert_free(ost->reformat_ctx);
        ost->reformat_ctx = av_audio_convert_alloc(enc->sample_fmt, 1,
                                                   dec->sample_fmt, 1, NULL, 0);
        if (!ost->reformat_ctx) {
            fprintf(stderr, "Cannot convert %s sample format to %s sample format\n",
852 853
                av_get_sample_fmt_name(dec->sample_fmt),
                av_get_sample_fmt_name(enc->sample_fmt));
854
            ffmpeg_exit(1);
855 856 857 858
        }
        ost->reformat_pair=MAKE_SFMT_PAIR(enc->sample_fmt,dec->sample_fmt);
    }

859
    if(audio_sync_method){
860
        double delta = get_sync_ipts(ost) * enc->sample_rate - ost->sync_opts
861 862
                - av_fifo_size(ost->fifo)/(enc->channels * 2);
        double idelta= delta*dec->sample_rate / enc->sample_rate;
863
        int byte_delta= ((int)idelta)*2*dec->channels;
864

865 866
        //FIXME resample delay
        if(fabs(delta) > 50){
867
            if(ist->is_start || fabs(delta) > audio_drift_threshold*enc->sample_rate){
868
                if(byte_delta < 0){
869
                    byte_delta= FFMAX(byte_delta, -size);
870 871 872 873 874 875 876 877 878 879 880
                    size += byte_delta;
                    buf  -= byte_delta;
                    if(verbose > 2)
                        fprintf(stderr, "discarding %d audio samples\n", (int)-delta);
                    if(!size)
                        return;
                    ist->is_start=0;
                }else{
                    static uint8_t *input_tmp= NULL;
                    input_tmp= av_realloc(input_tmp, byte_delta + size);

881 882 883 884 885
                    if(byte_delta > allocated_for_size - size){
                        allocated_for_size= byte_delta + (int64_t)size;
                        goto need_realloc;
                    }
                    ist->is_start=0;
886 887 888 889 890 891 892 893 894

                    memset(input_tmp, 0, byte_delta);
                    memcpy(input_tmp + byte_delta, buf, size);
                    buf= input_tmp;
                    size += byte_delta;
                    if(verbose > 2)
                        fprintf(stderr, "adding %d audio samples of silence\n", (int)delta);
                }
            }else if(audio_sync_method>1){
895
                int comp= av_clip(delta, -audio_sync_method, audio_sync_method);
896
                av_assert0(ost->audio_resample);
897 898
                if(verbose > 2)
                    fprintf(stderr, "compensating audio timestamp drift:%f compensation:%d in:%d\n", delta, comp, enc->sample_rate);
899
//                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));
900 901
                av_resample_compensate(*(struct AVResampleContext**)ost->resample, comp, enc->sample_rate);
            }
902
        }
903
    }else
904
        ost->sync_opts= lrintf(get_sync_ipts(ost) * enc->sample_rate)
905
                        - av_fifo_size(ost->fifo)/(enc->channels * 2); //FIXME wrong
Fabrice Bellard's avatar
Fabrice Bellard committed
906 907 908

    if (ost->audio_resample) {
        buftmp = audio_buf;
909
        size_out = audio_resample(ost->resample,
Fabrice Bellard's avatar
Fabrice Bellard committed
910
                                  (short *)buftmp, (short *)buf,
911
                                  size / (dec->channels * isize));
912
        size_out = size_out * enc->channels * osize;
Fabrice Bellard's avatar
Fabrice Bellard committed
913 914 915 916 917
    } else {
        buftmp = buf;
        size_out = size;
    }

918
    if (!ost->audio_resample && dec->sample_fmt!=enc->sample_fmt) {
919
        const void *ibuf[6]= {buftmp};
920
        void *obuf[6]= {audio_buf};
921 922
        int istride[6]= {isize};
        int ostride[6]= {osize};
923 924 925
        int len= size_out/istride[0];
        if (av_audio_convert(ost->reformat_ctx, obuf, ostride, ibuf, istride, len)<0) {
            printf("av_audio_convert() failed\n");
926
            if (exit_on_error)
927
                ffmpeg_exit(1);
928 929
            return;
        }
930
        buftmp = audio_buf;
931
        size_out = len*osize;
932 933
    }

Fabrice Bellard's avatar
Fabrice Bellard committed
934
    /* now encode as many frames as possible */
935
    if (enc->frame_size > 1) {
Fabrice Bellard's avatar
Fabrice Bellard committed
936
        /* output resampled raw samples */
937
        if (av_fifo_realloc2(ost->fifo, av_fifo_size(ost->fifo) + size_out) < 0) {
938
            fprintf(stderr, "av_fifo_realloc2() failed\n");
939
            ffmpeg_exit(1);
940
        }
941
        av_fifo_generic_write(ost->fifo, buftmp, size_out, NULL);
Fabrice Bellard's avatar
Fabrice Bellard committed
942

943
        frame_bytes = enc->frame_size * osize * enc->channels;
944

945
        while (av_fifo_size(ost->fifo) >= frame_bytes) {
946 947 948
            AVPacket pkt;
            av_init_packet(&pkt);

949
            av_fifo_generic_read(ost->fifo, audio_buf, frame_bytes, NULL);
950

951 952
            //FIXME pass ost->sync_opts as AVFrame.pts in avcodec_encode_audio()

953
            ret = avcodec_encode_audio(enc, audio_out, audio_out_size,
954
                                       (short *)audio_buf);
955 956
            if (ret < 0) {
                fprintf(stderr, "Audio encoding failed\n");
957
                ffmpeg_exit(1);
958
            }
959
            audio_size += ret;
960 961 962
            pkt.stream_index= ost->index;
            pkt.data= audio_out;
            pkt.size= ret;
963
            if(enc->coded_frame && enc->coded_frame->pts != AV_NOPTS_VALUE)
964
                pkt.pts= av_rescale_q(enc->coded_frame->pts, enc->time_base, ost->st->time_base);
965
            pkt.flags |= AV_PKT_FLAG_KEY;
966
            write_frame(s, &pkt, enc, ost->bitstream_filters);
967

968
            ost->sync_opts += enc->frame_size;
Fabrice Bellard's avatar
Fabrice Bellard committed
969 970
        }
    } else {
971 972
        AVPacket pkt;
        av_init_packet(&pkt);
973

974
        ost->sync_opts += size_out / (osize * enc->channels);
975

976
        /* output a pcm frame */
977 978 979
        /* determine the size of the coded buffer */
        size_out /= osize;
        if (coded_bps)
980
            size_out = size_out*coded_bps/8;
981

982 983
        if(size_out > audio_out_size){
            fprintf(stderr, "Internal error, buffer size too small\n");
984
            ffmpeg_exit(1);
985 986
        }

987
        //FIXME pass ost->sync_opts as AVFrame.pts in avcodec_encode_audio()
988
        ret = avcodec_encode_audio(enc, audio_out, size_out,
989
                                   (short *)buftmp);
990 991
        if (ret < 0) {
            fprintf(stderr, "Audio encoding failed\n");
992
            ffmpeg_exit(1);
993
        }
994
        audio_size += ret;
995 996 997
        pkt.stream_index= ost->index;
        pkt.data= audio_out;
        pkt.size= ret;
998
        if(enc->coded_frame && enc->coded_frame->pts != AV_NOPTS_VALUE)
999
            pkt.pts= av_rescale_q(enc->coded_frame->pts, enc->time_base, ost->st->time_base);
1000
        pkt.flags |= AV_PKT_FLAG_KEY;
1001
        write_frame(s, &pkt, enc, ost->bitstream_filters);
Fabrice Bellard's avatar
Fabrice Bellard committed
1002 1003 1004
    }
}

1005 1006 1007 1008 1009
static void pre_process_video_frame(AVInputStream *ist, AVPicture *picture, void **bufp)
{
    AVCodecContext *dec;
    AVPicture *picture2;
    AVPicture picture_tmp;
1010
    uint8_t *buf = 0;
1011

1012
    dec = ist->st->codec;
1013 1014

    /* deinterlace : must be done before any resize */
1015
    if (do_deinterlace) {
1016 1017 1018 1019 1020 1021 1022
        int size;

        /* create temporary picture */
        size = avpicture_get_size(dec->pix_fmt, dec->width, dec->height);
        buf = av_malloc(size);
        if (!buf)
            return;
1023

1024 1025 1026
        picture2 = &picture_tmp;
        avpicture_fill(picture2, buf, dec->pix_fmt, dec->width, dec->height);

Ramiro Polla's avatar
Ramiro Polla committed
1027 1028 1029 1030 1031 1032 1033 1034
        if(avpicture_deinterlace(picture2, picture,
                                 dec->pix_fmt, dec->width, dec->height) < 0) {
            /* if error, do not deinterlace */
            fprintf(stderr, "Deinterlacing failed\n");
            av_free(buf);
            buf = NULL;
            picture2 = picture;
        }
1035 1036 1037 1038 1039 1040 1041 1042 1043
    } else {
        picture2 = picture;
    }

    if (picture != picture2)
        *picture = *picture2;
    *bufp = buf;
}

1044 1045
/* we begin to correct av delay at this threshold */
#define AV_DELAY_MAX 0.100
Fabrice Bellard's avatar
Fabrice Bellard committed
1046

1047 1048
static void do_subtitle_out(AVFormatContext *s,
                            AVOutputStream *ost,
1049 1050 1051 1052 1053
                            AVInputStream *ist,
                            AVSubtitle *sub,
                            int64_t pts)
{
    static uint8_t *subtitle_out = NULL;
1054
    int subtitle_out_max_size = 1024 * 1024;
1055 1056 1057 1058 1059 1060
    int subtitle_out_size, nb, i;
    AVCodecContext *enc;
    AVPacket pkt;

    if (pts == AV_NOPTS_VALUE) {
        fprintf(stderr, "Subtitle packets must have a pts\n");
1061
        if (exit_on_error)
1062
            ffmpeg_exit(1);
1063 1064 1065
        return;
    }

Michael Niedermayer's avatar