ffmpeg.c 160 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 6 7
 * This file is part of FFmpeg.
 *
 * FFmpeg 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
 * FFmpeg 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 FFmpeg; 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 37
#include "libavformat/avformat.h"
#include "libavdevice/avdevice.h"
#include "libswscale/swscale.h"
#include "libavcodec/opt.h"
38
#include "libavcodec/audioconvert.h"
39
#include "libavcore/audioconvert.h"
40
#include "libavcore/parseutils.h"
41
#include "libavcore/samplefmt.h"
42
#include "libavutil/colorspace.h"
43
#include "libavutil/fifo.h"
44
#include "libavutil/intreadwrite.h"
45
#include "libavutil/pixdesc.h"
46
#include "libavutil/avstring.h"
47
#include "libavutil/libm.h"
48
#include "libavformat/os_support.h"
49

50 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

72
#if HAVE_TERMIOS_H
Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
73 74 75 76
#include <fcntl.h>
#include <sys/ioctl.h>
#include <sys/time.h>
#include <termios.h>
77
#elif HAVE_CONIO_H
Ramiro Polla's avatar
Ramiro Polla committed
78
#include <conio.h>
Fabrice Bellard's avatar
Fabrice Bellard committed
79
#endif
80
#include <time.h>
Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
81

Fabrice Bellard's avatar
Fabrice Bellard committed
82 83
#include "cmdutils.h"

84
#include "libavutil/avassert.h"
85

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

Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
89 90 91 92
/* select an input stream for an output stream */
typedef struct AVStreamMap {
    int file_index;
    int stream_index;
93 94
    int sync_file_index;
    int sync_stream_index;
Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
95 96
} AVStreamMap;

97 98 99
/**
 * select an input file for an output file
 */
100
typedef struct AVMetaDataMap {
101 102 103
    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
104 105
} AVMetaDataMap;

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

111
static const OptionDef options[];
Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
112

113
#define MAX_FILES 100
114 115 116
#if !FF_API_MAX_STREAMS
#define MAX_STREAMS 1024    /* arbitrary sanity check value */
#endif
Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
117

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

static AVFormatContext *output_files[MAX_FILES];
128
static AVCodec **output_codecs = NULL;
Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
129
static int nb_output_files = 0;
130
static int nb_output_codecs = 0;
Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
131

132
static AVStreamMap *stream_maps = NULL;
Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
133 134
static int nb_stream_maps;

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

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

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

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

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

189
static int subtitle_disable = 0;
190
static char *subtitle_codec_name = NULL;
191
static char *subtitle_language = NULL;
192
static unsigned int subtitle_codec_tag = 0;
Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
193

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

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

224 225
static int rate_emu = 0;

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

229
static int audio_volume = 256;
230

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

246
static float dts_delta_threshold = 10;
247

Michael Niedermayer's avatar
Michael Niedermayer committed
248
static unsigned int sws_flags = SWS_BICUBIC;
249

Benoit Fouet's avatar
Benoit Fouet committed
250
static int64_t timer_start;
Michael Niedermayer's avatar
Michael Niedermayer committed
251

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

static short *samples;

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

Stefano Sabatini's avatar
Stefano Sabatini committed
262
#define DEFAULT_PASS_LOGFILENAME_PREFIX "ffmpeg2pass"
Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
263

264 265
struct AVInputStream;

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

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

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

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

308 309 310
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
311 312 313 314 315 316
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' */
317
    int64_t sample_index;      /* current sample */
318 319

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

343
#if HAVE_TERMIOS_H
Fabrice Bellard's avatar
Fabrice Bellard committed
344

Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
345 346
/* init terminal so that we can grab keys */
static struct termios oldtty;
347
#endif
Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
348

349 350 351 352
#if CONFIG_AVFILTER

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

361
    graph = avfilter_graph_alloc();
362

363
    snprintf(args, 255, "%d:%d:%d:%d:%d", ist->st->codec->width,
364
             ist->st->codec->height, ist->st->codec->pix_fmt, 1, AV_TIME_BASE);
365 366 367
    ret = avfilter_graph_create_filter(&ist->input_video_filter, avfilter_get_by_name("buffer"),
                                       "src", args, NULL, graph);
    if (ret < 0)
368
        return ret;
369 370 371
    ret = avfilter_graph_create_filter(&ist->output_video_filter, &ffsink,
                                       "out", NULL, &ffsink_ctx, graph);
    if (ret < 0)
372
        return ret;
373
    last_filter = ist->input_video_filter;
374

Stefano Sabatini's avatar
Stefano Sabatini committed
375
    if (codec->width  != icodec->width || codec->height != icodec->height) {
376
        snprintf(args, 255, "%d:%d:flags=0x%X",
377 378
                 codec->width,
                 codec->height,
379
                 (int)av_get_int(sws_opts, "sws_flags", NULL));
380 381
        if ((ret = avfilter_graph_create_filter(&filter, avfilter_get_by_name("scale"),
                                                NULL, args, NULL, graph)) < 0)
382 383 384
            return ret;
        if ((ret = avfilter_link(last_filter, 0, filter, 0)) < 0)
            return ret;
385
        last_filter = filter;
386 387
    }

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

391
    if (vfilters) {
392 393 394 395
        AVFilterInOut *outputs = av_malloc(sizeof(AVFilterInOut));
        AVFilterInOut *inputs  = av_malloc(sizeof(AVFilterInOut));

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

        inputs->name    = av_strdup("out");
401
        inputs->filter_ctx = ist->output_video_filter;
402 403 404
        inputs->pad_idx = 0;
        inputs->next    = NULL;

405 406
        if ((ret = avfilter_graph_parse(graph, vfilters, inputs, outputs, NULL)) < 0)
            return ret;
407 408
        av_freep(&vfilters);
    } else {
409
        if ((ret = avfilter_link(last_filter, 0, ist->output_video_filter, 0)) < 0)
410
            return ret;
411 412
    }

413
    if ((ret = avfilter_graph_config(graph, NULL)) < 0)
414
        return ret;
415

416 417
    codec->width  = ist->output_video_filter->inputs[0]->w;
    codec->height = ist->output_video_filter->inputs[0]->h;
418 419 420 421 422

    return 0;
}
#endif /* CONFIG_AVFILTER */

Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
423 424
static void term_exit(void)
{
425
    av_log(NULL, AV_LOG_QUIET, "");
426
#if HAVE_TERMIOS_H
Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
427
    tcsetattr (0, TCSANOW, &oldtty);
428
#endif
429
}
Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
430

431
static volatile int received_sigterm = 0;
432 433 434 435 436 437 438 439

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

Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
440 441
static void term_init(void)
{
442
#if HAVE_TERMIOS_H
Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
443 444 445 446
    struct termios tty;

    tcgetattr (0, &tty);
    oldtty = tty;
447
    atexit(term_exit);
Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
448 449 450 451 452 453 454 455 456

    tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
                          |INLCR|IGNCR|ICRNL|IXON);
    tty.c_oflag |= OPOST;
    tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
    tty.c_cflag &= ~(CSIZE|PARENB);
    tty.c_cflag |= CS8;
    tty.c_cc[VMIN] = 1;
    tty.c_cc[VTIME] = 0;
457

Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
458
    tcsetattr (0, TCSANOW, &tty);
459 460
    signal(SIGQUIT, sigterm_handler); /* Quit (POSIX).  */
#endif
Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
461

462 463
    signal(SIGINT , sigterm_handler); /* Interrupt (ANSI).  */
    signal(SIGTERM, sigterm_handler); /* Termination (ANSI).  */
Måns Rullgård's avatar
Måns Rullgård committed
464 465 466
#ifdef SIGXCPU
    signal(SIGXCPU, sigterm_handler);
#endif
Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
467 468 469 470 471
}

/* read a key without blocking */
static int read_key(void)
{
472
#if HAVE_TERMIOS_H
473
    int n = 1;
Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
474
    unsigned char ch;
475
    struct timeval tv;
Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
476 477 478 479 480 481 482 483
    fd_set rfds;

    FD_ZERO(&rfds);
    FD_SET(0, &rfds);
    tv.tv_sec = 0;
    tv.tv_usec = 0;
    n = select(1, &rfds, NULL, NULL, &tv);
    if (n > 0) {
484 485
        n = read(0, &ch, 1);
        if (n == 1)
Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
486
            return ch;
487 488

        return n;
Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
489
    }
490
#elif HAVE_CONIO_H
Ramiro Polla's avatar
Ramiro Polla committed
491 492
    if(kbhit())
        return(getch());
493
#endif
Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
494 495 496
    return -1;
}

497 498 499 500 501
static int decode_interrupt_cb(void)
{
    return q_pressed || (q_pressed = read_key() == 'q');
}

502
static int ffmpeg_exit(int ret)
503 504 505 506 507 508 509 510
{
    int i;

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

    av_free(intra_matrix);
    av_free(inter_matrix);

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

    av_free(opt_names);
542
    av_free(streamid_map);
543
    av_free(input_codecs);
544
    av_free(output_codecs);
545
    av_free(stream_maps);
546
    av_free(meta_data_maps);
547 548 549 550 551 552 553

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

    av_free(video_standard);

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

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

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

571 572
    exit(ret); /* not all OS-es handle main() return value */
    return ret;
573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592
}

/* 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;
593 594
}

595 596 597
static void choose_sample_fmt(AVStream *st, AVCodec *codec)
{
    if(codec && codec->sample_fmts){
598
        const enum AVSampleFormat *p= codec->sample_fmts;
599 600 601 602
        for(; *p!=-1; p++){
            if(*p == st->codec->sample_fmt)
                break;
        }
603 604 605 606 607 608
        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]));
609
            st->codec->sample_fmt = codec->sample_fmts[0];
610
        }
611 612 613
    }
}

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

634 635 636 637
static void choose_pixel_fmt(AVStream *st, AVCodec *codec)
{
    if(codec && codec->pix_fmts){
        const enum PixelFormat *p= codec->pix_fmts;
638 639 640 641 642 643 644
        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};
            }
        }
645 646 647 648
        for(; *p!=-1; p++){
            if(*p == st->codec->pix_fmt)
                break;
        }
649
        if(*p == -1)
650 651 652 653
            st->codec->pix_fmt = codec->pix_fmts[0];
    }
}

654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674
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;
}

675
static int read_ffserver_streams(AVFormatContext *s, const char *filename)
Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
676
{
677
    int i, err;
Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
678
    AVFormatContext *ic;
679
    int nopts = 0;
Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
680

681 682 683
    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
684
    /* copy stream format */
685
    s->nb_streams = 0;
Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
686 687
    for(i=0;i<ic->nb_streams;i++) {
        AVStream *st;
688
        AVCodec *codec;
Michael Niedermayer's avatar
cleanup  
Michael Niedermayer committed
689

690 691
        s->nb_streams++;

692
        // FIXME: a more elegant solution is needed
693
        st = av_mallocz(sizeof(AVStream));
Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
694
        memcpy(st, ic->streams[i], sizeof(AVStream));
695
        st->codec = avcodec_alloc_context();
696 697
        if (!st->codec) {
            print_error(filename, AVERROR(ENOMEM));
698
            ffmpeg_exit(1);
699
        }
700
        avcodec_copy_context(st->codec, ic->streams[i]->codec);
Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
701
        s->streams[i] = st;
702

703 704 705 706 707 708 709 710 711 712 713 714
        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);
        }
715

Baptiste Coudurier's avatar
Baptiste Coudurier committed
716 717 718 719 720
        if(!st->codec->thread_count)
            st->codec->thread_count = 1;
        if(st->codec->thread_count>1)
            avcodec_thread_init(st->codec, st->codec->thread_count);

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

        new_output_stream(s, nb_output_files);
Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
725 726
    }

727 728 729
    if (!nopts)
        s->timestamp = av_gettime();

Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
730 731 732 733
    av_close_input_file(ic);
    return 0;
}

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

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

744 745 746 747 748
    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,
749
                                          pkt->flags & AV_PKT_FLAG_KEY);
750
        if(a>0){
751 752
            av_free_packet(pkt);
            new_pkt.destruct= av_destruct_packet;
753
        } else if(a<0){
754 755 756
            fprintf(stderr, "%s failed for stream %d, codec %s",
                    bsfc->filter->name, pkt->stream_index,
                    avctx->codec ? avctx->codec->name : "copy");
757
            print_error("", a);
758
            if (exit_on_error)
759
                ffmpeg_exit(1);
760 761