ffmpeg.c 156 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 "libavutil/colorspace.h"
40
#include "libavutil/fifo.h"
41
#include "libavutil/pixdesc.h"
42
#include "libavutil/avstring.h"
43
#include "libavutil/libm.h"
44
#include "libavformat/os_support.h"
45

46 47 48 49 50 51 52
#if CONFIG_AVFILTER
# include "libavfilter/avfilter.h"
# include "libavfilter/avfiltergraph.h"
# include "libavfilter/graphparser.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
#if HAVE_TERMIOS_H
Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
70 71 72 73
#include <fcntl.h>
#include <sys/ioctl.h>
#include <sys/time.h>
#include <termios.h>
74
#elif HAVE_CONIO_H
Ramiro Polla's avatar
Ramiro Polla committed
75
#include <conio.h>
Fabrice Bellard's avatar
Fabrice Bellard committed
76
#endif
77
#include <time.h>
Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
78

Fabrice Bellard's avatar
Fabrice Bellard committed
79 80
#include "cmdutils.h"

81 82 83
#undef NDEBUG
#include <assert.h>

84
const char program_name[] = "FFmpeg";
85
const int program_birth_year = 2000;
86

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

95 96 97 98 99 100
/** select an input file for an output file */
typedef struct AVMetaDataMap {
    int out_file;
    int in_file;
} AVMetaDataMap;

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

103
#define MAX_FILES 100
Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
104

105
static const char *last_asked_format = NULL;
Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
106
static AVFormatContext *input_files[MAX_FILES];
107
static int64_t input_files_ts_offset[MAX_FILES];
108
static double input_files_ts_scale[MAX_FILES][MAX_STREAMS];
Aurelien Jacobs's avatar
Aurelien Jacobs committed
109
static AVCodec *input_codecs[MAX_FILES*MAX_STREAMS];
Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
110
static int nb_input_files = 0;
Aurelien Jacobs's avatar
Aurelien Jacobs committed
111
static int nb_icodecs;
Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
112 113

static AVFormatContext *output_files[MAX_FILES];
Aurelien Jacobs's avatar
Aurelien Jacobs committed
114
static AVCodec *output_codecs[MAX_FILES*MAX_STREAMS];
Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
115
static int nb_output_files = 0;
Aurelien Jacobs's avatar
Aurelien Jacobs committed
116
static int nb_ocodecs;
Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
117

118
static AVStreamMap stream_maps[MAX_FILES*MAX_STREAMS];
Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
119 120
static int nb_stream_maps;

121 122 123
static AVMetaDataMap meta_data_maps[MAX_FILES];
static int nb_meta_data_maps;

124 125 126
/* indexed by output file stream index */
static int streamid_map[MAX_STREAMS];

Michael Niedermayer's avatar
Michael Niedermayer committed
127 128
static int frame_width  = 0;
static int frame_height = 0;
129
static float frame_aspect_ratio = 0;
130
static enum PixelFormat frame_pix_fmt = PIX_FMT_NONE;
131
static enum SampleFormat audio_sample_fmt = SAMPLE_FMT_NONE;
132 133 134 135
static int frame_topBand  = 0;
static int frame_bottomBand = 0;
static int frame_leftBand  = 0;
static int frame_rightBand = 0;
136
static int max_frames[4] = {INT_MAX, INT_MAX, INT_MAX, INT_MAX};
137
static AVRational frame_rate;
138
static float video_qscale = 0;
139 140
static uint16_t *intra_matrix = NULL;
static uint16_t *inter_matrix = NULL;
141
static const char *video_rc_override_string=NULL;
Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
142
static int video_disable = 0;
143
static int video_discard = 0;
144
static char *video_codec_name = NULL;
145
static unsigned int video_codec_tag = 0;
146
static char *video_language = NULL;
Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
147
static int same_quality = 0;
148
static int do_deinterlace = 0;
149
static int top_field_first = -1;
150
static int me_threshold = 0;
Michael Niedermayer's avatar
-cbp  
Michael Niedermayer committed
151
static int intra_dc_precision = 8;
152
static int loop_input = 0;
153
static int loop_output = AVFMT_NOOUTPUTLOOP;
154
static int qp_hist = 0;
155 156
#if CONFIG_AVFILTER
static char *vfilters = NULL;
157
AVFilterGraph *graph = NULL;
158
#endif
Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
159 160 161

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

171
static int subtitle_disable = 0;
172
static char *subtitle_codec_name = NULL;
173
static char *subtitle_language = NULL;
174
static unsigned int subtitle_codec_tag = 0;
Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
175

176 177
static float mux_preload= 0.5;
static float mux_max_delay= 0.7;
178

179
static int64_t recording_time = INT64_MAX;
180
static int64_t start_time = 0;
181
static int64_t recording_timestamp = 0;
182
static int64_t input_ts_offset = 0;
Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
183
static int file_overwrite = 0;
184 185
static int metadata_count;
static AVMetadataTag *metadata;
Fabrice Bellard's avatar
Fabrice Bellard committed
186
static int do_benchmark = 0;
187
static int do_hex_dump = 0;
188
static int do_pkt_dump = 0;
189
static int do_psnr = 0;
190
static int do_pass = 0;
Stefano Sabatini's avatar
Stefano Sabatini committed
191
static char *pass_logfilename_prefix = NULL;
192 193
static int audio_stream_copy = 0;
static int video_stream_copy = 0;
194
static int subtitle_stream_copy = 0;
195
static int video_sync_method= -1;
196
static int audio_sync_method= 0;
Michael Niedermayer's avatar
Michael Niedermayer committed
197
static float audio_drift_threshold= 0.1;
198
static int copy_ts= 0;
199
static int opt_shortest = 0;
200
static int video_global_header = 0;
201
static char *vstats_filename;
202
static FILE *vstats_file;
203
static int opt_programid = 0;
204
static int copy_initial_nonkeyframes = 0;
205

206 207
static int rate_emu = 0;

208
static int  video_channel = 0;
209
static char *video_standard;
210

211
static int audio_volume = 256;
212

213
static int exit_on_error = 0;
214
static int using_stdin = 0;
215
static int verbose = 1;
216
static int thread_count= 1;
217
static int q_pressed = 0;
218 219 220
static int64_t video_size = 0;
static int64_t audio_size = 0;
static int64_t extra_size = 0;
221 222
static int nb_frames_dup = 0;
static int nb_frames_drop = 0;
223
static int input_sync;
224
static uint64_t limit_filesize = 0;
225
static int force_fps = 0;
226

227
static int pgmyuv_compatibility_hack=0;
228
static float dts_delta_threshold = 10;
229

Michael Niedermayer's avatar
Michael Niedermayer committed
230
static unsigned int sws_flags = SWS_BICUBIC;
231

Benoit Fouet's avatar
Benoit Fouet committed
232
static int64_t timer_start;
Michael Niedermayer's avatar
Michael Niedermayer committed
233

234 235
static uint8_t *audio_buf;
static uint8_t *audio_out;
236
unsigned int allocated_audio_out_size, allocated_audio_buf_size;
237 238 239

static short *samples;

240 241
static AVBitStreamFilterContext *video_bitstream_filters=NULL;
static AVBitStreamFilterContext *audio_bitstream_filters=NULL;
242
static AVBitStreamFilterContext *subtitle_bitstream_filters=NULL;
243
static AVBitStreamFilterContext *bitstream_filters[MAX_FILES][MAX_STREAMS];
244

Stefano Sabatini's avatar
Stefano Sabatini committed
245
#define DEFAULT_PASS_LOGFILENAME_PREFIX "ffmpeg2pass"
Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
246

247 248
struct AVInputStream;

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

269 270 271 272 273
    /* full frame size of first frame */
    int original_height;
    int original_width;

    /* cropping area sizes */
274
    int video_crop;
275 276
    int topBand;
    int bottomBand;
277
    int leftBand;
278 279 280 281 282 283 284
    int rightBand;

    /* cropping area of first frame */
    int original_topBand;
    int original_bottomBand;
    int original_leftBand;
    int original_rightBand;
285

Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
286 287 288
    /* audio only */
    int audio_resample;
    ReSampleContext *resample; /* for audio resampling */
289 290
    int reformat_pair;
    AVAudioConvert *reformat_ctx;
291
    AVFifoBuffer *fifo;     /* for compression: one audio fifo per codec */
292
    FILE *logfile;
Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
293 294 295 296 297 298 299 300
} AVOutputStream;

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' */
301
    int64_t sample_index;      /* current sample */
302 303

    int64_t       start;     /* time when read started */
304 305
    int64_t       next_pts;  /* synthetic pts for cases where pkt.pts
                                is not defined */
306
    int64_t       pts;       /* current pts */
307
    int is_start;            /* is 1 at the start and after a discontinuity */
308
    int showed_multi_packet_warning;
309
    int is_past_recording_time;
310 311 312 313 314 315 316
#if CONFIG_AVFILTER
    AVFilterContext *out_video_filter;
    AVFilterContext *input_video_filter;
    AVFrame *filter_frame;
    int has_filter_frame;
    AVFilterPicRef *picref;
#endif
Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
317 318 319 320 321 322
} 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 */
323
    int nb_streams;       /* nb streams we are aware of */
Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
324 325
} AVInputFile;

326
#if HAVE_TERMIOS_H
Fabrice Bellard's avatar
Fabrice Bellard committed
327

Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
328 329
/* init terminal so that we can grab keys */
static struct termios oldtty;
330
#endif
Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
331

332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378
#if CONFIG_AVFILTER
typedef struct {
    int pix_fmt;
} FilterOutPriv;


static int output_init(AVFilterContext *ctx, const char *args, void *opaque)
{
    FilterOutPriv *priv = ctx->priv;

    if(!opaque) return -1;

    priv->pix_fmt = *((int *)opaque);

    return 0;
}

static void output_end_frame(AVFilterLink *link)
{
}

static int output_query_formats(AVFilterContext *ctx)
{
    FilterOutPriv *priv = ctx->priv;
    enum PixelFormat pix_fmts[] = { priv->pix_fmt, PIX_FMT_NONE };

    avfilter_set_common_formats(ctx, avfilter_make_format_list(pix_fmts));
    return 0;
}

static int get_filtered_video_pic(AVFilterContext *ctx,
                                  AVFilterPicRef **picref, AVFrame *pic2,
                                  uint64_t *pts)
{
    AVFilterPicRef *pic;

    if(avfilter_request_frame(ctx->inputs[0]))
        return -1;
    if(!(pic = ctx->inputs[0]->cur_pic))
        return -1;
    *picref = pic;
    ctx->inputs[0]->cur_pic = NULL;

    *pts          = pic->pts;

    memcpy(pic2->data,     pic->data,     sizeof(pic->data));
    memcpy(pic2->linesize, pic->linesize, sizeof(pic->linesize));
379 380
    pic2->interlaced_frame = pic->interlaced;
    pic2->top_field_first  = pic->top_field_first;
381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403

    return 1;
}

static AVFilter output_filter =
{
    .name      = "ffmpeg_output",

    .priv_size = sizeof(FilterOutPriv),
    .init      = output_init,

    .query_formats = output_query_formats,

    .inputs    = (AVFilterPad[]) {{ .name          = "default",
                                    .type          = AVMEDIA_TYPE_VIDEO,
                                    .end_frame     = output_end_frame,
                                    .min_perms     = AV_PERM_READ, },
                                  { .name = NULL }},
    .outputs   = (AVFilterPad[]) {{ .name = NULL }},
};

static int configure_filters(AVInputStream *ist, AVOutputStream *ost)
{
404
    AVFilterContext *last_filter, *filter;
405 406 407 408 409
    /** filter graph containing all filters including input & output */
    AVCodecContext *codec = ost->st->codec;
    AVCodecContext *icodec = ist->st->codec;
    char args[255];

410
    graph = av_mallocz(sizeof(AVFilterGraph));
411

412
    if (!(ist->input_video_filter = avfilter_open(avfilter_get_by_name("buffer"), "src")))
413
        return -1;
414
    if (!(ist->out_video_filter = avfilter_open(&output_filter, "out")))
415 416 417 418
        return -1;

    snprintf(args, 255, "%d:%d:%d", ist->st->codec->width,
             ist->st->codec->height, ist->st->codec->pix_fmt);
419
    if (avfilter_init_filter(ist->input_video_filter, args, NULL))
420
        return -1;
421
    if (avfilter_init_filter(ist->out_video_filter, NULL, &codec->pix_fmt))
422 423 424
        return -1;

    /* add input and output filters to the overall graph */
425 426
    avfilter_graph_add_filter(graph, ist->input_video_filter);
    avfilter_graph_add_filter(graph, ist->out_video_filter);
427

428
    last_filter = ist->input_video_filter;
429

430
    if (ost->video_crop) {
431
        snprintf(args, 255, "%d:%d:%d:%d", ost->leftBand, ost->topBand,
432 433
                 codec->width,
                 codec->height);
434 435
        filter = avfilter_open(avfilter_get_by_name("crop"), NULL);
        if (!filter)
436
            return -1;
437
        if (avfilter_init_filter(filter, args, NULL))
438
            return -1;
439
        if (avfilter_link(last_filter, 0, filter, 0))
440
            return -1;
441 442
        last_filter = filter;
        avfilter_graph_add_filter(graph, last_filter);
443 444 445
    }

    if((codec->width !=
446 447
        icodec->width - (frame_leftBand + frame_rightBand)) ||
       (codec->height != icodec->height - (frame_topBand  + frame_bottomBand))) {
448
        snprintf(args, 255, "%d:%d:flags=0x%X",
449 450
                 codec->width,
                 codec->height,
451
                 (int)av_get_int(sws_opts, "sws_flags", NULL));
452 453
        filter = avfilter_open(avfilter_get_by_name("scale"), NULL);
        if (!filter)
454
            return -1;
455
        if (avfilter_init_filter(filter, args, NULL))
456
            return -1;
457
        if (avfilter_link(last_filter, 0, filter, 0))
458
            return -1;
459 460
        last_filter = filter;
        avfilter_graph_add_filter(graph, last_filter);
461 462
    }

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

466
    if (vfilters) {
467 468 469 470
        AVFilterInOut *outputs = av_malloc(sizeof(AVFilterInOut));
        AVFilterInOut *inputs  = av_malloc(sizeof(AVFilterInOut));

        outputs->name    = av_strdup("in");
471
        outputs->filter  = last_filter;
472 473 474 475 476 477 478 479
        outputs->pad_idx = 0;
        outputs->next    = NULL;

        inputs->name    = av_strdup("out");
        inputs->filter  = ist->out_video_filter;
        inputs->pad_idx = 0;
        inputs->next    = NULL;

480
        if (avfilter_graph_parse(graph, vfilters, inputs, outputs, NULL) < 0)
481 482 483
            return -1;
        av_freep(&vfilters);
    } else {
484
        if (avfilter_link(last_filter, 0, ist->out_video_filter, 0) < 0)
485 486 487 488
            return -1;
    }

    /* configure all the filter links */
489
    if (avfilter_graph_check_validity(graph, NULL))
490
        return -1;
491
    if (avfilter_graph_config_formats(graph, NULL))
492
        return -1;
493
    if (avfilter_graph_config_links(graph, NULL))
494 495 496 497 498 499 500 501 502
        return -1;

    codec->width = ist->out_video_filter->inputs[0]->w;
    codec->height = ist->out_video_filter->inputs[0]->h;

    return 0;
}
#endif /* CONFIG_AVFILTER */

Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
503 504
static void term_exit(void)
{
505
#if HAVE_TERMIOS_H
Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
506
    tcsetattr (0, TCSANOW, &oldtty);
507
#endif
508
}
Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
509

510
static volatile int received_sigterm = 0;
511 512 513 514 515 516 517 518

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

Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
519 520
static void term_init(void)
{
521
#if HAVE_TERMIOS_H
Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
522 523 524 525
    struct termios tty;

    tcgetattr (0, &tty);
    oldtty = tty;
526
    atexit(term_exit);
Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
527 528 529 530 531 532 533 534 535

    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;
536

Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
537
    tcsetattr (0, TCSANOW, &tty);
538 539
    signal(SIGQUIT, sigterm_handler); /* Quit (POSIX).  */
#endif
Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
540

541 542
    signal(SIGINT , sigterm_handler); /* Interrupt (ANSI).  */
    signal(SIGTERM, sigterm_handler); /* Termination (ANSI).  */
Måns Rullgård's avatar
Måns Rullgård committed
543 544 545
#ifdef SIGXCPU
    signal(SIGXCPU, sigterm_handler);
#endif
Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
546 547 548 549 550
}

/* read a key without blocking */
static int read_key(void)
{
551
#if HAVE_TERMIOS_H
552
    int n = 1;
Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
553
    unsigned char ch;
554
    struct timeval tv;
Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
555 556 557 558 559 560 561 562
    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) {
563 564
        n = read(0, &ch, 1);
        if (n == 1)
Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
565
            return ch;
566 567

        return n;
Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
568
    }
569
#elif HAVE_CONIO_H
Ramiro Polla's avatar
Ramiro Polla committed
570 571
    if(kbhit())
        return(getch());
572
#endif
Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
573 574 575
    return -1;
}

576 577 578 579 580
static int decode_interrupt_cb(void)
{
    return q_pressed || (q_pressed = read_key() == 'q');
}

581
static int av_exit(int ret)
582 583 584 585 586 587 588 589
{
    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
590
        if (!(s->oformat->flags & AVFMT_NOFILE) && s->pb)
591 592
            url_fclose(s->pb);
        for(j=0;j<s->nb_streams;j++) {
593
            av_metadata_free(&s->streams[j]->metadata);
594 595 596
            av_free(s->streams[j]->codec);
            av_free(s->streams[j]);
        }
597 598 599 600 601 602 603
        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);
604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623
        av_free(s);
    }
    for(i=0;i<nb_input_files;i++)
        av_close_input_file(input_files[i]);

    av_free(intra_matrix);
    av_free(inter_matrix);

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

    av_free(opt_names);

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

    av_free(video_standard);

624
    for (i=0;i<AVMEDIA_TYPE_NB;i++)
625 626 627
        av_free(avcodec_opts[i]);
    av_free(avformat_opts);
    av_free(sws_opts);
628 629
    av_free(audio_buf);
    av_free(audio_out);
630
    allocated_audio_buf_size= allocated_audio_out_size= 0;
631
    av_free(samples);
632

633 634 635 636
#if CONFIG_AVFILTER
    avfilter_uninit();
#endif

637 638 639 640 641 642 643
    if (received_sigterm) {
        fprintf(stderr,
            "Received signal %d: terminating.\n",
            (int) received_sigterm);
        exit (255);
    }

644 645
    exit(ret); /* not all OS-es handle main() return value */
    return ret;
646 647
}

648 649 650 651 652 653 654 655 656 657 658 659 660
static void choose_sample_fmt(AVStream *st, AVCodec *codec)
{
    if(codec && codec->sample_fmts){
        const enum SampleFormat *p= codec->sample_fmts;
        for(; *p!=-1; p++){
            if(*p == st->codec->sample_fmt)
                break;
        }
        if(*p == -1)
            st->codec->sample_fmt = codec->sample_fmts[0];
    }
}

661 662 663 664
static void choose_sample_rate(AVStream *st, AVCodec *codec)
{
    if(codec && codec->supported_samplerates){
        const int *p= codec->supported_samplerates;
665
        int best=0;
666 667 668 669 670 671 672 673
        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;
            }
        }
674 675 676
        if(best_dist){
            av_log(st->codec, AV_LOG_WARNING, "Requested sampling rate unsupported using closest supported (%d)\n", best);
        }
677 678 679 680
        st->codec->sample_rate= best;
    }
}

681 682 683 684 685 686 687 688 689 690
static void choose_pixel_fmt(AVStream *st, AVCodec *codec)
{
    if(codec && codec->pix_fmts){
        const enum PixelFormat *p= codec->pix_fmts;
        for(; *p!=-1; p++){
            if(*p == st->codec->pix_fmt)
                break;
        }
        if(*p == -1
           && !(   st->codec->codec_id==CODEC_ID_MJPEG
691
                && st->codec->strict_std_compliance <= FF_COMPLIANCE_UNOFFICIAL
692 693 694 695 696 697
                && (   st->codec->pix_fmt == PIX_FMT_YUV420P
                    || st->codec->pix_fmt == PIX_FMT_YUV422P)))
            st->codec->pix_fmt = codec->pix_fmts[0];
    }
}

698
static int read_ffserver_streams(AVFormatContext *s, const char *filename)
Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
699
{
700
    int i, err;
Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
701
    AVFormatContext *ic;
702
    int nopts = 0;
Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
703

704 705 706
    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
707 708 709 710
    /* copy stream format */
    s->nb_streams = ic->nb_streams;
    for(i=0;i<ic->nb_streams;i++) {
        AVStream *st;
711
        AVCodec *codec;
Michael Niedermayer's avatar
cleanup  
Michael Niedermayer committed
712

713
        // FIXME: a more elegant solution is needed
714
        st = av_mallocz(sizeof(AVStream));
Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
715
        memcpy(st, ic->streams[i], sizeof(AVStream));
716
        st->codec = avcodec_alloc_context();
717 718 719 720
        if (!st->codec) {
            print_error(filename, AVERROR(ENOMEM));
            av_exit(1);
        }
721
        avcodec_copy_context(st->codec, ic->streams[i]->codec);
Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
722
        s->streams[i] = st;
723

724 725 726 727 728 729 730 731 732 733 734 735
        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);
        }
736

Baptiste Coudurier's avatar
Baptiste Coudurier committed
737 738 739 740 741
        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);

742 743
        if(st->codec->flags & CODEC_FLAG_BITEXACT)
            nopts = 1;
Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
744 745
    }

746 747 748
    if (!nopts)
        s->timestamp = av_gettime();

Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
749 750 751 752
    av_close_input_file(ic);
    return 0;
}

753 754 755 756
static double
get_sync_ipts(const AVOutputStream *ost)
{
    const AVInputStream *ist = ost->sync_ist;
757
    return (double)(ist->pts - start_time)/AV_TIME_BASE;
758 759
}

760
static void write_frame(AVFormatContext *s, AVPacket *pkt, AVCodecContext *avctx, AVBitStreamFilterContext *bsfc){
761 762
    int ret;

763 764 765 766 767
    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,
768
                                          pkt->flags & AV_PKT_FLAG_KEY);
769
        if(a>0){
770 771
            av_free_packet(pkt);
            new_pkt.destruct= av_destruct_packet;
772
        } else if(a<0){
773 774 775
            fprintf(stderr, "%s failed for stream %d, codec %s",
                    bsfc->filter->name, pkt->stream_index,
                    avctx->codec ? avctx->codec->name : "copy");
776
            print_error("", a);
777 778
            if (exit_on_error)
                av_exit(1);
779 780 781 782 783 784
        }
        *pkt= new_pkt;

        bsfc= bsfc->next;
    }

785 786 787
    ret= av_interleaved_write_frame(s, pkt);
    if(ret < 0){
        print_error("av_interleaved_write_frame()", ret);
788
        av_exit(1);
789
    }
790 791
}

792
#define MAX_AUDIO_PACKET_SIZE (128 * 1024)
Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
793

794 795
static void do_audio_out(AVFormatContext *s,
                         AVOutputStream *ost,
Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
796 797 798
                         AVInputStream *ist,
                         unsigned char *buf, int size)
{
799
    uint8_t *buftmp;
800
    int64_t audio_out_size, audio_buf_size;
801
    int64_t allocated_for_size= size;
802

Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
803
    int size_out, frame_bytes, ret;
804
    AVCodecContext *enc= ost->st->codec;
805
    AVCodecContext *dec= ist->st->codec;
806 807
    int osize= av_get_bits_per_sample_format(enc->sample_fmt)/8;
    int isize= av_get_bits_per_sample_format(dec->sample_fmt)/8;