ffmpeg.c 159 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
/* needed for usleep() */
23
#define _XOPEN_SOURCE 600
24

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

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

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 62
#include <windows.h>
#endif
63 64 65 66
#if HAVE_GETPROCESSMEMORYINFO
#include <windows.h>
#include <psapi.h>
#endif
67

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

Dave Yeo's avatar
Dave Yeo committed
72
#if HAVE_KBHIT
Ramiro Polla's avatar
Ramiro Polla committed
73
#include <conio.h>
Fabrice Bellard's avatar
Fabrice Bellard committed
74
#endif
75
#include <time.h>
Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
76

Fabrice Bellard's avatar
Fabrice Bellard committed
77 78
#include "cmdutils.h"

79
#include "libavutil/avassert.h"
80

81
const char program_name[] = "FFmpeg";
82
const int program_birth_year = 2000;
83

Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
84 85 86 87
/* select an input stream for an output stream */
typedef struct AVStreamMap {
    int file_index;
    int stream_index;
88 89
    int sync_file_index;
    int sync_stream_index;
Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
90 91
} AVStreamMap;

92 93 94
/**
 * select an input file for an output file
 */
95
typedef struct AVMetaDataMap {
96 97 98
    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
99 100
} AVMetaDataMap;

101 102 103 104 105
typedef struct AVChapterMap {
    int in_file;
    int out_file;
} AVChapterMap;

106
static const OptionDef options[];
Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
107

108
#define MAX_FILES 100
109
#define MAX_STREAMS 1024    /* arbitrary sanity check value */
Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
110

111 112
#define FFM_PACKET_SIZE 4096 //XXX a duplicate of the line in ffm.h

113
static const char *last_asked_format = NULL;
Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
114
static AVFormatContext *input_files[MAX_FILES];
115
static int64_t input_files_ts_offset[MAX_FILES];
116
static double *input_files_ts_scale[MAX_FILES] = {NULL};
117
static AVCodec **input_codecs = NULL;
Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
118
static int nb_input_files = 0;
119
static int nb_input_codecs = 0;
120
static int nb_input_files_ts_scale[MAX_FILES] = {0};
Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
121 122

static AVFormatContext *output_files[MAX_FILES];
123
static AVCodec **output_codecs = NULL;
Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
124
static int nb_output_files = 0;
125
static int nb_output_codecs = 0;
Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
126

127
static AVStreamMap *stream_maps = NULL;
Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
128 129
static int nb_stream_maps;

130 131
/* first item specifies output metadata, second is input */
static AVMetaDataMap (*meta_data_maps)[2] = NULL;
132
static int nb_meta_data_maps;
133
static int metadata_global_autocopy   = 1;
134 135
static int metadata_streams_autocopy  = 1;
static int metadata_chapters_autocopy = 1;
136

137 138 139
static AVChapterMap *chapter_maps = NULL;
static int nb_chapter_maps;

140
/* indexed by output file stream index */
141 142
static int *streamid_map = NULL;
static int nb_streamid_map = 0;
143

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

static int intra_only = 0;
static int audio_sample_rate = 44100;
175
static int64_t channel_layout = 0;
176 177
#define QSCALE_NONE -99999
static float audio_qscale = QSCALE_NONE;
Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
178 179
static int audio_disable = 0;
static int audio_channels = 1;
180
static char  *audio_codec_name = NULL;
181
static unsigned int audio_codec_tag = 0;
182 183
static char *audio_language = NULL;

184
static int subtitle_disable = 0;
185
static char *subtitle_codec_name = NULL;
186
static char *subtitle_language = NULL;
187
static unsigned int subtitle_codec_tag = 0;
Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
188

189 190
static float mux_preload= 0.5;
static float mux_max_delay= 0.7;
191

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

219 220
static int rate_emu = 0;

221
static int  video_channel = 0;
222
static char *video_standard;
223

224
static int audio_volume = 256;
225

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

241
static float dts_delta_threshold = 10;
242

Michael Niedermayer's avatar
Michael Niedermayer committed
243
static unsigned int sws_flags = SWS_BICUBIC;
244

Benoit Fouet's avatar
Benoit Fouet committed
245
static int64_t timer_start;
Michael Niedermayer's avatar
Michael Niedermayer committed
246

247 248
static uint8_t *audio_buf;
static uint8_t *audio_out;
249
static unsigned int allocated_audio_out_size, allocated_audio_buf_size;
250 251 252

static short *samples;

253 254
static AVBitStreamFilterContext *video_bitstream_filters=NULL;
static AVBitStreamFilterContext *audio_bitstream_filters=NULL;
255
static AVBitStreamFilterContext *subtitle_bitstream_filters=NULL;
256

Stefano Sabatini's avatar
Stefano Sabatini committed
257
#define DEFAULT_PASS_LOGFILENAME_PREFIX "ffmpeg2pass"
Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
258

259 260
struct AVInputStream;

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

282 283 284 285
    /* full frame size of first frame */
    int original_height;
    int original_width;

286 287 288 289 290
    /* forced key frames */
    int64_t *forced_kf_pts;
    int forced_kf_count;
    int forced_kf_index;

Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
291 292 293
    /* audio only */
    int audio_resample;
    ReSampleContext *resample; /* for audio resampling */
294 295 296
    int resample_sample_fmt;
    int resample_channels;
    int resample_sample_rate;
297 298
    int reformat_pair;
    AVAudioConvert *reformat_ctx;
299
    AVFifoBuffer *fifo;     /* for compression: one audio fifo per codec */
300
    FILE *logfile;
Fabrice Bellard's avatar
merge  
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
merge  
Fabrice Bellard committed
306 307 308 309 310 311
typedef struct AVInputStream {
    int file_index;
    int 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' */
312
    int64_t sample_index;      /* current sample */
313 314

    int64_t       start;     /* time when read started */
315 316
    int64_t       next_pts;  /* synthetic pts for cases where pkt.pts
                                is not defined */
317
    int64_t       pts;       /* current pts */
318
    PtsCorrectionContext pts_ctx;
319
    int is_start;            /* is 1 at the start and after a discontinuity */
320
    int showed_multi_packet_warning;
321
    int is_past_recording_time;
322
#if CONFIG_AVFILTER
323
    AVFilterContext *output_video_filter;
324 325 326
    AVFilterContext *input_video_filter;
    AVFrame *filter_frame;
    int has_filter_frame;
327
    AVFilterBufferRef *picref;
328
#endif
Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
329 330 331 332 333 334
} 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 */
335
    int nb_streams;       /* nb streams we are aware of */
Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
336 337
} AVInputFile;

338 339 340 341
#if CONFIG_AVFILTER

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

350
    graph = avfilter_graph_alloc();
351

352
    snprintf(args, 255, "%d:%d:%d:%d:%d", ist->st->codec->width,
353
             ist->st->codec->height, ist->st->codec->pix_fmt, 1, AV_TIME_BASE);
354 355 356
    ret = avfilter_graph_create_filter(&ist->input_video_filter, avfilter_get_by_name("buffer"),
                                       "src", args, NULL, graph);
    if (ret < 0)
357
        return ret;
358 359 360
    ret = avfilter_graph_create_filter(&ist->output_video_filter, &ffsink,
                                       "out", NULL, &ffsink_ctx, graph);
    if (ret < 0)
361
        return ret;
362
    last_filter = ist->input_video_filter;
363

Stefano Sabatini's avatar
Stefano Sabatini committed
364
    if (codec->width  != icodec->width || codec->height != icodec->height) {
365
        snprintf(args, 255, "%d:%d:flags=0x%X",
366 367
                 codec->width,
                 codec->height,
368
                 (int)av_get_int(sws_opts, "sws_flags", NULL));
369 370
        if ((ret = avfilter_graph_create_filter(&filter, avfilter_get_by_name("scale"),
                                                NULL, args, NULL, graph)) < 0)
371 372 373
            return ret;
        if ((ret = avfilter_link(last_filter, 0, filter, 0)) < 0)
            return ret;
374
        last_filter = filter;
375 376
    }

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

380
    if (vfilters) {
381 382 383 384
        AVFilterInOut *outputs = av_malloc(sizeof(AVFilterInOut));
        AVFilterInOut *inputs  = av_malloc(sizeof(AVFilterInOut));

        outputs->name    = av_strdup("in");
385
        outputs->filter_ctx = last_filter;
386 387 388 389
        outputs->pad_idx = 0;
        outputs->next    = NULL;

        inputs->name    = av_strdup("out");
390
        inputs->filter_ctx = ist->output_video_filter;
391 392 393
        inputs->pad_idx = 0;
        inputs->next    = NULL;

394 395
        if ((ret = avfilter_graph_parse(graph, vfilters, inputs, outputs, NULL)) < 0)
            return ret;
396 397
        av_freep(&vfilters);
    } else {
398
        if ((ret = avfilter_link(last_filter, 0, ist->output_video_filter, 0)) < 0)
399
            return ret;
400 401
    }

402
    if ((ret = avfilter_graph_config(graph, NULL)) < 0)
403
        return ret;
404

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

    return 0;
}
#endif /* CONFIG_AVFILTER */

Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
412 413
static void term_exit(void)
{
414
    av_log(NULL, AV_LOG_QUIET, "");
415
}
Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
416

417
static volatile int received_sigterm = 0;
418 419 420 421 422 423 424 425

static void
sigterm_handler(int sig)
{
    received_sigterm = sig;
    term_exit();
}

Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
426 427
static void term_init(void)
{
428 429
    signal(SIGINT , sigterm_handler); /* Interrupt (ANSI).  */
    signal(SIGTERM, sigterm_handler); /* Termination (ANSI).  */
Måns Rullgård's avatar
Måns Rullgård committed
430 431 432
#ifdef SIGXCPU
    signal(SIGXCPU, sigterm_handler);
#endif
Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
433 434 435 436 437
}

/* read a key without blocking */
static int read_key(void)
{
Dave Yeo's avatar
Dave Yeo committed
438
#if HAVE_KBHIT
Ramiro Polla's avatar
Ramiro Polla committed
439 440
    if(kbhit())
        return(getch());
441
#endif
Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
442 443 444
    return -1;
}

445 446 447 448 449
static int decode_interrupt_cb(void)
{
    return q_pressed || (q_pressed = read_key() == 'q');
}

450
static int ffmpeg_exit(int ret)
451 452 453 454 455 456
{
    int i;

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

    av_free(intra_matrix);
    av_free(inter_matrix);

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

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

    av_free(video_codec_name);
    av_free(audio_codec_name);
    av_free(subtitle_codec_name);

    av_free(video_standard);

486
    uninit_opts();
487 488
    av_free(audio_buf);
    av_free(audio_out);
489
    allocated_audio_buf_size= allocated_audio_out_size= 0;
490
    av_free(samples);
491

492 493 494 495
#if CONFIG_AVFILTER
    avfilter_uninit();
#endif

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

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

/* 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;
525 526
}

527 528 529
static void choose_sample_fmt(AVStream *st, AVCodec *codec)
{
    if(codec && codec->sample_fmts){
530
        const enum AVSampleFormat *p= codec->sample_fmts;
531 532 533 534
        for(; *p!=-1; p++){
            if(*p == st->codec->sample_fmt)
                break;
        }
535 536 537 538 539 540
        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]));
541
            st->codec->sample_fmt = codec->sample_fmts[0];
542
        }
543 544 545
    }
}

546 547 548 549
static void choose_sample_rate(AVStream *st, AVCodec *codec)
{
    if(codec && codec->supported_samplerates){
        const int *p= codec->supported_samplerates;
550
        int best=0;
551 552 553 554 555 556 557 558
        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;
            }
        }
559 560 561
        if(best_dist){
            av_log(st->codec, AV_LOG_WARNING, "Requested sampling rate unsupported using closest supported (%d)\n", best);
        }
562 563 564 565
        st->codec->sample_rate= best;
    }
}

566 567 568 569
static void choose_pixel_fmt(AVStream *st, AVCodec *codec)
{
    if(codec && codec->pix_fmts){
        const enum PixelFormat *p= codec->pix_fmts;
570 571 572 573 574 575 576
        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};
            }
        }
577 578 579 580
        for(; *p!=-1; p++){
            if(*p == st->codec->pix_fmt)
                break;
        }
581
        if(*p == -1)
582 583 584 585
            st->codec->pix_fmt = codec->pix_fmts[0];
    }
}

586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606
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;
    return ost;
}

607
static int read_ffserver_streams(AVFormatContext *s, const char *filename)
Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
608
{
609
    int i, err;
Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
610
    AVFormatContext *ic;
611
    int nopts = 0;
Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
612

613 614 615
    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
616
    /* copy stream format */
617
    s->nb_streams = 0;
Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
618 619
    for(i=0;i<ic->nb_streams;i++) {
        AVStream *st;
620
        AVCodec *codec;
Michael Niedermayer's avatar
cleanup  
Michael Niedermayer committed
621

622 623
        s->nb_streams++;

624
        // FIXME: a more elegant solution is needed
625
        st = av_mallocz(sizeof(AVStream));
Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
626
        memcpy(st, ic->streams[i], sizeof(AVStream));
627
        st->codec = avcodec_alloc_context();
628 629
        if (!st->codec) {
            print_error(filename, AVERROR(ENOMEM));
630
            ffmpeg_exit(1);
631
        }
632
        avcodec_copy_context(st->codec, ic->streams[i]->codec);
Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
633
        s->streams[i] = st;
634

635 636 637 638 639 640 641 642 643 644 645 646
        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);
        }
647

648 649
        if(st->codec->flags & CODEC_FLAG_BITEXACT)
            nopts = 1;
650 651

        new_output_stream(s, nb_output_files);
Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
652 653
    }

654 655 656
    if (!nopts)
        s->timestamp = av_gettime();

Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
657 658 659 660
    av_close_input_file(ic);
    return 0;
}

661 662 663 664
static double
get_sync_ipts(const AVOutputStream *ost)
{
    const AVInputStream *ist = ost->sync_ist;
665
    return (double)(ist->pts - start_time)/AV_TIME_BASE;
666 667
}

668
static void write_frame(AVFormatContext *s, AVPacket *pkt, AVCodecContext *avctx, AVBitStreamFilterContext *bsfc){
669 670
    int ret;

671 672 673 674 675
    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,
676
                                          pkt->flags & AV_PKT_FLAG_KEY);
677
        if(a>0){
678 679
            av_free_packet(pkt);
            new_pkt.destruct= av_destruct_packet;
680
        } else if(a<0){
681 682 683
            fprintf(stderr, "%s failed for stream %d, codec %s",
                    bsfc->filter->name, pkt->stream_index,
                    avctx->codec ? avctx->codec->name : "copy");
684
            print_error("", a);
685
            if (exit_on_error)
686
                ffmpeg_exit(1);
687 688 689 690 691 692
        }
        *pkt= new_pkt;

        bsfc= bsfc->next;
    }

693 694 695
    ret= av_interleaved_write_frame(s, pkt);
    if(ret < 0){
        print_error("av_interleaved_write_frame()", ret);
696
        ffmpeg_exit(1);
697
    }
698 699
}

700
#define MAX_AUDIO_PACKET_SIZE (128 * 1024)
Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
701

702 703
static void do_audio_out(AVFormatContext *s,
                         AVOutputStream *ost,
Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
704 705 706
                         AVInputStream *ist,
                         unsigned char *buf, int size)
{
707
    uint8_t *buftmp;
708
    int64_t audio_out_size, audio_buf_size;
709
    int64_t allocated_for_size= size;
710

711
    int size_out, frame_bytes, ret, resample_changed;
712
    AVCodecContext *enc= ost->st->codec;
713
    AVCodecContext *dec= ist->st->codec;
714 715
    int osize= av_get_bits_per_sample_fmt(enc->sample_fmt)/8;
    int isize= av_get_bits_per_sample_fmt(dec->sample_fmt)/8;
716 717
    const int coded_bps = av_get_bits_per_sample(enc->codec->id);

718 719
need_realloc:
    audio_buf_size= (allocated_for_size + isize*dec->channels - 1) / (isize*dec->channels);
720
    audio_buf_size= (audio_buf_size*enc->sample_rate + dec->sample_rate) / dec->sample_rate;
Vitor Sessak's avatar
Vitor Sessak committed
721
    audio_buf_size= audio_buf_size*2 + 10000; //safety factors for the deprecated resampling API
722
    audio_buf_size= FFMAX(audio_buf_size, enc->frame_size);
723 724 725 726 727 728 729 730 731
    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");
732
        ffmpeg_exit(1);
733
    }
Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
734

735 736
    av_fast_malloc(&audio_buf, &allocated_audio_buf_size, audio_buf_size);
    av_fast_malloc(&audio_out, &allocated_audio_out_size, audio_out_size);
737 738
    if (!audio_buf || !audio_out){
        fprintf(stderr, "Out of memory in do_audio_out\n");
739
        ffmpeg_exit(1);
740
    }
741

742 743 744
    if (enc->channels != dec->channels)
        ost->audio_resample = 1;

745 746 747 748 749 750 751 752 753 754 755 756 757 758 759