ffmpeg.c 137 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 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 "avformat.h"
Luca Abeni's avatar
Luca Abeni committed
31
#include "avdevice.h"
32
#include "swscale.h"
33
#include "framehook.h"
34
#include "opt.h"
35
#include "fifo.h"
36
#include "avstring.h"
37
#include "os_support.h"
38

39 40 41 42
#if !defined(HAVE_GETRUSAGE) && defined(HAVE_GETPROCESSTIMES)
#include <windows.h>
#endif

Ramiro Polla's avatar
Ramiro Polla committed
43
#if defined(HAVE_TERMIOS_H)
Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
44 45 46 47 48
#include <unistd.h>
#include <fcntl.h>
#include <sys/ioctl.h>
#include <sys/time.h>
#include <termios.h>
Fabrice Bellard's avatar
Fabrice Bellard committed
49
#include <sys/resource.h>
Ramiro Polla's avatar
Ramiro Polla committed
50 51
#elif defined(HAVE_CONIO_H)
#include <conio.h>
Fabrice Bellard's avatar
Fabrice Bellard committed
52
#endif
Michael Niedermayer's avatar
10000l  
Michael Niedermayer committed
53
#undef time //needed because HAVE_AV_CONFIG_H is defined on top
54
#include <time.h>
Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
55

56
#include "version.h"
Fabrice Bellard's avatar
Fabrice Bellard committed
57 58
#include "cmdutils.h"

59 60 61
#undef NDEBUG
#include <assert.h>

Michael Niedermayer's avatar
Michael Niedermayer committed
62 63
#undef exit

64 65 66
static const char program_name[] = "FFmpeg";
static const int program_birth_year = 2000;

Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
67 68 69 70
/* select an input stream for an output stream */
typedef struct AVStreamMap {
    int file_index;
    int stream_index;
71 72
    int sync_file_index;
    int sync_stream_index;
Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
73 74
} AVStreamMap;

75 76 77 78 79 80
/** select an input file for an output file */
typedef struct AVMetaDataMap {
    int out_file;
    int in_file;
} AVMetaDataMap;

Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
81 82 83 84 85
extern const OptionDef options[];

#define MAX_FILES 20

static AVFormatContext *input_files[MAX_FILES];
86
static int64_t input_files_ts_offset[MAX_FILES];
Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
87 88 89 90 91 92 93 94
static int nb_input_files = 0;

static AVFormatContext *output_files[MAX_FILES];
static int nb_output_files = 0;

static AVStreamMap stream_maps[MAX_FILES];
static int nb_stream_maps;

95 96 97
static AVMetaDataMap meta_data_maps[MAX_FILES];
static int nb_meta_data_maps;

98 99
static AVInputFormat *file_iformat;
static AVOutputFormat *file_oformat;
Michael Niedermayer's avatar
Michael Niedermayer committed
100 101
static int frame_width  = 0;
static int frame_height = 0;
102
static float frame_aspect_ratio = 0;
103
static enum PixelFormat frame_pix_fmt = PIX_FMT_NONE;
104 105 106 107 108
static int frame_padtop  = 0;
static int frame_padbottom = 0;
static int frame_padleft  = 0;
static int frame_padright = 0;
static int padcolor[3] = {16,128,128}; /* default to black */
109 110 111 112
static int frame_topBand  = 0;
static int frame_bottomBand = 0;
static int frame_leftBand  = 0;
static int frame_rightBand = 0;
113
static int max_frames[4] = {INT_MAX, INT_MAX, INT_MAX, INT_MAX};
114
static AVRational frame_rate = (AVRational) {0,0};
115
static float video_qscale = 0;
116
static int video_qdiff = 3;
117 118
static uint16_t *intra_matrix = NULL;
static uint16_t *inter_matrix = NULL;
119
#if 0 //experimental, (can be removed)
Michael Niedermayer's avatar
Michael Niedermayer committed
120 121 122
static float video_rc_qsquish=1.0;
static float video_rc_qmod_amp=0;
static int video_rc_qmod_freq=0;
123
#endif
124
static const char *video_rc_override_string=NULL;
Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
125
static int video_disable = 0;
126
static int video_discard = 0;
127
static char *video_codec_name = NULL;
Michael Niedermayer's avatar
Michael Niedermayer committed
128
static int video_codec_tag = 0;
Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
129
static int same_quality = 0;
130
static int do_deinterlace = 0;
Michael Niedermayer's avatar
Michael Niedermayer committed
131
static int strict = 0;
132
static int top_field_first = -1;
133
static int me_threshold = 0;
Michael Niedermayer's avatar
-cbp  
Michael Niedermayer committed
134
static int intra_dc_precision = 8;
135
static int loop_input = 0;
136
static int loop_output = AVFMT_NOOUTPUTLOOP;
137
static int qp_hist = 0;
Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
138 139 140

static int intra_only = 0;
static int audio_sample_rate = 44100;
141 142
#define QSCALE_NONE -99999
static float audio_qscale = QSCALE_NONE;
Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
143 144
static int audio_disable = 0;
static int audio_channels = 1;
145
static char  *audio_codec_name = NULL;
Michael Niedermayer's avatar
Michael Niedermayer committed
146
static int audio_codec_tag = 0;
147 148
static char *audio_language = NULL;

149
static int subtitle_disable = 0;
150
static char *subtitle_codec_name = NULL;
151
static char *subtitle_language = NULL;
Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
152

153 154
static float mux_preload= 0.5;
static float mux_max_delay= 0.7;
155

156
static int64_t recording_time = 0;
157
static int64_t start_time = 0;
158
static int64_t rec_timestamp = 0;
159
static int64_t input_ts_offset = 0;
Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
160 161 162 163 164
static int file_overwrite = 0;
static char *str_title = NULL;
static char *str_author = NULL;
static char *str_copyright = NULL;
static char *str_comment = NULL;
165
static char *str_genre = NULL;
166
static char *str_album = NULL;
Fabrice Bellard's avatar
Fabrice Bellard committed
167
static int do_benchmark = 0;
168
static int do_hex_dump = 0;
169
static int do_pkt_dump = 0;
170
static int do_psnr = 0;
171 172
static int do_pass = 0;
static char *pass_logfilename = NULL;
173 174
static int audio_stream_copy = 0;
static int video_stream_copy = 0;
175
static int subtitle_stream_copy = 0;
176 177
static int video_sync_method= 1;
static int audio_sync_method= 0;
Michael Niedermayer's avatar
Michael Niedermayer committed
178
static float audio_drift_threshold= 0.1;
179
static int copy_ts= 0;
180
static int opt_shortest = 0; //
181
static int video_global_header = 0;
182
static char *vstats_filename;
183
static FILE *vstats_file;
184
static int opt_programid = 0;
185

186 187
static int rate_emu = 0;

188
static int  video_channel = 0;
189
static char *video_standard;
190

191
static int audio_volume = 256;
192

193
static int using_stdin = 0;
194
static int using_vhook = 0;
195
static int verbose = 1;
196
static int thread_count= 1;
197
static int q_pressed = 0;
198 199 200
static int64_t video_size = 0;
static int64_t audio_size = 0;
static int64_t extra_size = 0;
201 202
static int nb_frames_dup = 0;
static int nb_frames_drop = 0;
203
static int input_sync;
204
static uint64_t limit_filesize = 0; //
205

206
static int pgmyuv_compatibility_hack=0;
207
static float dts_delta_threshold = 10;
208

Michael Niedermayer's avatar
Michael Niedermayer committed
209
static unsigned int sws_flags = SWS_BICUBIC;
210

Benoit Fouet's avatar
Benoit Fouet committed
211 212 213 214 215 216
static const char **opt_names;
static int opt_name_count;
static AVCodecContext *avctx_opts[CODEC_TYPE_NB];
static AVFormatContext *avformat_opts;
static struct SwsContext *sws_opts;
static int64_t timer_start;
Michael Niedermayer's avatar
Michael Niedermayer committed
217

218 219
static AVBitStreamFilterContext *video_bitstream_filters=NULL;
static AVBitStreamFilterContext *audio_bitstream_filters=NULL;
220
static AVBitStreamFilterContext *subtitle_bitstream_filters=NULL;
221
static AVBitStreamFilterContext *bitstream_filters[MAX_FILES][MAX_STREAMS];
222

223
#define DEFAULT_PASS_LOGFILENAME "ffmpeg2pass"
Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
224

225 226
struct AVInputStream;

Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
227 228 229 230 231
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 */
232 233 234 235
    int encoding_needed;     /* true if encoding needed for this stream */
    int frame_number;
    /* input pts and corresponding output pts
       for A/V sync */
236 237
    //double sync_ipts;        /* dts from the AVPacket of the demuxer in second units */
    struct AVInputStream *sync_ist; /* input stream to sync against */
238
    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
239
    /* video only */
240
    int video_resample;
241
    AVFrame pict_tmp;      /* temporary image for resampling */
242 243
    struct SwsContext *img_resample_ctx; /* for image resampling */
    int resample_height;
244

245
    int video_crop;
246 247
    int topBand;             /* cropping area sizes */
    int leftBand;
248

249
    int video_pad;
250 251 252 253
    int padtop;              /* padding area sizes */
    int padbottom;
    int padleft;
    int padright;
254

Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
255 256 257
    /* audio only */
    int audio_resample;
    ReSampleContext *resample; /* for audio resampling */
258
    AVFifoBuffer fifo;     /* for compression: one audio fifo per codec */
259
    FILE *logfile;
Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
260 261 262 263 264 265 266 267
} 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' */
268
    int64_t sample_index;      /* current sample */
269 270 271

    int64_t       start;     /* time when read started */
    unsigned long frame;     /* current frame */
272 273
    int64_t       next_pts;  /* synthetic pts for cases where pkt.pts
                                is not defined */
274
    int64_t       pts;       /* current pts */
275
    int is_start;            /* is 1 at the start and after a discontinuity */
Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
276 277 278 279 280 281
} 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 */
282
    int nb_streams;       /* nb streams we are aware of */
Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
283 284
} AVInputFile;

285
#ifdef HAVE_TERMIOS_H
Fabrice Bellard's avatar
Fabrice Bellard committed
286

Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
287 288
/* init terminal so that we can grab keys */
static struct termios oldtty;
289
#endif
Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
290 291 292

static void term_exit(void)
{
293
#ifdef HAVE_TERMIOS_H
Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
294
    tcsetattr (0, TCSANOW, &oldtty);
295
#endif
Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
296 297
}

298 299 300 301 302 303 304 305 306
static volatile sig_atomic_t received_sigterm = 0;

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

Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
307 308
static void term_init(void)
{
309
#ifdef HAVE_TERMIOS_H
Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
310 311 312 313 314 315 316 317 318 319 320 321 322
    struct termios tty;

    tcgetattr (0, &tty);
    oldtty = tty;

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

Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
324
    tcsetattr (0, TCSANOW, &tty);
325 326
    signal(SIGQUIT, sigterm_handler); /* Quit (POSIX).  */
#endif
Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
327

328 329 330 331 332
    signal(SIGINT , sigterm_handler); /* Interrupt (ANSI).  */
    signal(SIGTERM, sigterm_handler); /* Termination (ANSI).  */
    /*
    register a function to be called at normal program termination
    */
Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
333
    atexit(term_exit);
334 335 336
#ifdef CONFIG_BEOS_NETSERVER
    fcntl(0, F_SETFL, fcntl(0, F_GETFL) | O_NONBLOCK);
#endif
Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
337 338 339 340 341
}

/* read a key without blocking */
static int read_key(void)
{
Ramiro Polla's avatar
Ramiro Polla committed
342
#if defined(HAVE_TERMIOS_H)
343
    int n = 1;
Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
344
    unsigned char ch;
345 346
#ifndef CONFIG_BEOS_NETSERVER
    struct timeval tv;
Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
347 348 349 350 351 352 353
    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);
354
#endif
Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
355
    if (n > 0) {
356 357
        n = read(0, &ch, 1);
        if (n == 1)
Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
358
            return ch;
359 360

        return n;
Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
361
    }
Ramiro Polla's avatar
Ramiro Polla committed
362 363 364
#elif defined(HAVE_CONIO_H)
    if(kbhit())
        return(getch());
365
#endif
Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
366 367 368
    return -1;
}

369 370 371 372 373
static int decode_interrupt_cb(void)
{
    return q_pressed || (q_pressed = read_key() == 'q');
}

374
static int read_ffserver_streams(AVFormatContext *s, const char *filename)
Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
375
{
376
    int i, err;
Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
377 378
    AVFormatContext *ic;

379 380 381
    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
382 383 384 385
    /* copy stream format */
    s->nb_streams = ic->nb_streams;
    for(i=0;i<ic->nb_streams;i++) {
        AVStream *st;
Michael Niedermayer's avatar
cleanup  
Michael Niedermayer committed
386

387
        // FIXME: a more elegant solution is needed
388
        st = av_mallocz(sizeof(AVStream));
Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
389
        memcpy(st, ic->streams[i], sizeof(AVStream));
390 391
        st->codec = avcodec_alloc_context();
        memcpy(st->codec, ic->streams[i]->codec, sizeof(AVCodecContext));
Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
392 393 394 395 396 397 398
        s->streams[i] = st;
    }

    av_close_input_file(ic);
    return 0;
}

399 400 401 402
static double
get_sync_ipts(const AVOutputStream *ost)
{
    const AVInputStream *ist = ost->sync_ist;
403
    return (double)(ist->pts - start_time)/AV_TIME_BASE;
404 405
}

406
static void write_frame(AVFormatContext *s, AVPacket *pkt, AVCodecContext *avctx, AVBitStreamFilterContext *bsfc){
407 408
    int ret;

409 410 411 412 413 414
    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,
                                          pkt->flags & PKT_FLAG_KEY);
415
        if(a>0){
416 417
            av_free_packet(pkt);
            new_pkt.destruct= av_destruct_packet;
418
        } else if(a<0){
419 420 421
            fprintf(stderr, "%s failed for stream %d, codec %s",
                    bsfc->filter->name, pkt->stream_index,
                    avctx->codec ? avctx->codec->name : "copy");
422
            print_error("", a);
423 424 425 426 427 428
        }
        *pkt= new_pkt;

        bsfc= bsfc->next;
    }

429 430 431 432 433
    ret= av_interleaved_write_frame(s, pkt);
    if(ret < 0){
        print_error("av_interleaved_write_frame()", ret);
        exit(1);
    }
434 435
}

436
#define MAX_AUDIO_PACKET_SIZE (128 * 1024)
Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
437

438 439
static void do_audio_out(AVFormatContext *s,
                         AVOutputStream *ost,
Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
440 441 442
                         AVInputStream *ist,
                         unsigned char *buf, int size)
{
443
    uint8_t *buftmp;
444 445
    static uint8_t *audio_buf = NULL;
    static uint8_t *audio_out = NULL;
Michael Niedermayer's avatar
10l  
Michael Niedermayer committed
446
    const int audio_out_size= 4*MAX_AUDIO_PACKET_SIZE;
447

Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
448
    int size_out, frame_bytes, ret;
449
    AVCodecContext *enc= ost->st->codec;
450
    AVCodecContext *dec= ist->st->codec;
Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
451

452 453 454 455
    /* SC: dynamic allocation of buffers */
    if (!audio_buf)
        audio_buf = av_malloc(2*MAX_AUDIO_PACKET_SIZE);
    if (!audio_out)
Michael Niedermayer's avatar
10l  
Michael Niedermayer committed
456
        audio_out = av_malloc(audio_out_size);
457 458 459
    if (!audio_buf || !audio_out)
        return;               /* Should signal an error ! */

460 461 462 463 464 465 466 467 468 469 470 471 472 473
    if (enc->channels != dec->channels)
        ost->audio_resample = 1;

    if (ost->audio_resample && !ost->resample) {
        ost->resample = audio_resample_init(enc->channels,    dec->channels,
                                            enc->sample_rate, dec->sample_rate);
        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);
            exit(1);
        }
    }

474
    if(audio_sync_method){
475
        double delta = get_sync_ipts(ost) * enc->sample_rate - ost->sync_opts
476
                - av_fifo_size(&ost->fifo)/(ost->st->codec->channels * 2);
477 478
        double idelta= delta*ist->st->codec->sample_rate / enc->sample_rate;
        int byte_delta= ((int)idelta)*2*ist->st->codec->channels;
479

480 481
        //FIXME resample delay
        if(fabs(delta) > 50){
Michael Niedermayer's avatar
Michael Niedermayer committed
482
            if(ist->is_start || fabs(delta) > audio_drift_threshold*enc->sample_rate){
483
                if(byte_delta < 0){
484
                    byte_delta= FFMAX(byte_delta, -size);
485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508
                    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);

                    if(byte_delta + size <= MAX_AUDIO_PACKET_SIZE)
                        ist->is_start=0;
                    else
                        byte_delta= MAX_AUDIO_PACKET_SIZE - size;

                    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){
509
                int comp= av_clip(delta, -audio_sync_method, audio_sync_method);
510 511 512
                assert(ost->audio_resample);
                if(verbose > 2)
                    fprintf(stderr, "compensating audio timestamp drift:%f compensation:%d in:%d\n", delta, comp, enc->sample_rate);
513
//                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));
514 515
                av_resample_compensate(*(struct AVResampleContext**)ost->resample, comp, enc->sample_rate);
            }
516
        }
517
    }else
518
        ost->sync_opts= lrintf(get_sync_ipts(ost) * enc->sample_rate)
519
                        - av_fifo_size(&ost->fifo)/(ost->st->codec->channels * 2); //FIXME wrong
Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
520 521 522

    if (ost->audio_resample) {
        buftmp = audio_buf;
523
        size_out = audio_resample(ost->resample,
Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
524
                                  (short *)buftmp, (short *)buf,
525
                                  size / (ist->st->codec->channels * 2));
Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
526 527 528 529 530 531 532
        size_out = size_out * enc->channels * 2;
    } else {
        buftmp = buf;
        size_out = size;
    }

    /* now encode as many frames as possible */
533
    if (enc->frame_size > 1) {
Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
534
        /* output resampled raw samples */
Michael Niedermayer's avatar
Michael Niedermayer committed
535
        av_fifo_realloc(&ost->fifo, av_fifo_size(&ost->fifo) + size_out + 1);
536
        av_fifo_write(&ost->fifo, buftmp, size_out);
Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
537 538

        frame_bytes = enc->frame_size * 2 * enc->channels;
539

540
        while (av_fifo_read(&ost->fifo, audio_buf, frame_bytes) == 0) {
541 542 543
            AVPacket pkt;
            av_init_packet(&pkt);

544 545
            //FIXME pass ost->sync_opts as AVFrame.pts in avcodec_encode_audio()

546
            ret = avcodec_encode_audio(enc, audio_out, audio_out_size,
547
                                       (short *)audio_buf);
548
            audio_size += ret;
549 550 551
            pkt.stream_index= ost->index;
            pkt.data= audio_out;
            pkt.size= ret;
552
            if(enc->coded_frame && enc->coded_frame->pts != AV_NOPTS_VALUE)
553
                pkt.pts= av_rescale_q(enc->coded_frame->pts, enc->time_base, ost->st->time_base);
554
            pkt.flags |= PKT_FLAG_KEY;
555
            write_frame(s, &pkt, ost->st->codec, bitstream_filters[ost->file_index][pkt.stream_index]);
556

557
            ost->sync_opts += enc->frame_size;
Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
558 559
        }
    } else {
560 561
        AVPacket pkt;
        av_init_packet(&pkt);
562

563
        ost->sync_opts += size_out / (2 * enc->channels);
564

565 566 567
        /* output a pcm frame */
        /* XXX: change encoding codec API to avoid this ? */
        switch(enc->codec->id) {
568 569 570 571 572 573 574 575 576 577 578 579 580
        case CODEC_ID_PCM_S32LE:
        case CODEC_ID_PCM_S32BE:
        case CODEC_ID_PCM_U32LE:
        case CODEC_ID_PCM_U32BE:
            size_out = size_out << 1;
            break;
        case CODEC_ID_PCM_S24LE:
        case CODEC_ID_PCM_S24BE:
        case CODEC_ID_PCM_U24LE:
        case CODEC_ID_PCM_U24BE:
        case CODEC_ID_PCM_S24DAUD:
            size_out = size_out / 2 * 3;
            break;
581 582 583 584 585 586 587 588 589
        case CODEC_ID_PCM_S16LE:
        case CODEC_ID_PCM_S16BE:
        case CODEC_ID_PCM_U16LE:
        case CODEC_ID_PCM_U16BE:
            break;
        default:
            size_out = size_out >> 1;
            break;
        }
590
        //FIXME pass ost->sync_opts as AVFrame.pts in avcodec_encode_audio()
591
        ret = avcodec_encode_audio(enc, audio_out, size_out,
592
                                   (short *)buftmp);
593
        audio_size += ret;
594 595 596
        pkt.stream_index= ost->index;
        pkt.data= audio_out;
        pkt.size= ret;
597
        if(enc->coded_frame && enc->coded_frame->pts != AV_NOPTS_VALUE)
598
            pkt.pts= av_rescale_q(enc->coded_frame->pts, enc->time_base, ost->st->time_base);
599
        pkt.flags |= PKT_FLAG_KEY;
600
        write_frame(s, &pkt, ost->st->codec, bitstream_filters[ost->file_index][pkt.stream_index]);
Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
601 602 603
    }
}

604 605 606 607 608
static void pre_process_video_frame(AVInputStream *ist, AVPicture *picture, void **bufp)
{
    AVCodecContext *dec;
    AVPicture *picture2;
    AVPicture picture_tmp;
609
    uint8_t *buf = 0;
610

611
    dec = ist->st->codec;
612 613

    /* deinterlace : must be done before any resize */
614
    if (do_deinterlace || using_vhook) {
615 616 617 618 619 620 621
        int size;

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

623 624 625
        picture2 = &picture_tmp;
        avpicture_fill(picture2, buf, dec->pix_fmt, dec->width, dec->height);

Michael Niedermayer's avatar
10l  
Michael Niedermayer committed
626
        if (do_deinterlace){
627
            if(avpicture_deinterlace(picture2, picture,
Michael Niedermayer's avatar
10l  
Michael Niedermayer committed
628 629 630 631 632 633 634
                                     dec->pix_fmt, dec->width, dec->height) < 0) {
                /* if error, do not deinterlace */
                av_free(buf);
                buf = NULL;
                picture2 = picture;
            }
        } else {
635
            av_picture_copy(picture2, picture, dec->pix_fmt, dec->width, dec->height);
636
        }
637 638 639 640
    } else {
        picture2 = picture;
    }

641
    if (ENABLE_VHOOK)
Diego Biurrun's avatar
Diego Biurrun committed
642 643
        frame_hook_process(picture2, dec->pix_fmt, dec->width, dec->height,
                           1000000 * ist->pts / AV_TIME_BASE);
644 645 646 647 648 649

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

650 651
/* we begin to correct av delay at this threshold */
#define AV_DELAY_MAX 0.100
Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
652

653 654
static void do_subtitle_out(AVFormatContext *s,
                            AVOutputStream *ost,
655 656 657 658 659 660 661 662 663 664 665 666 667 668 669
                            AVInputStream *ist,
                            AVSubtitle *sub,
                            int64_t pts)
{
    static uint8_t *subtitle_out = NULL;
    int subtitle_out_max_size = 65536;
    int subtitle_out_size, nb, i;
    AVCodecContext *enc;
    AVPacket pkt;

    if (pts == AV_NOPTS_VALUE) {
        fprintf(stderr, "Subtitle packets must have a pts\n");
        return;
    }

670
    enc = ost->st->codec;
671 672 673 674 675 676 677 678 679 680 681 682 683 684

    if (!subtitle_out) {
        subtitle_out = av_malloc(subtitle_out_max_size);
    }

    /* Note: DVB subtitle need one packet to draw them and one other
       packet to clear them */
    /* XXX: signal it in the codec context ? */
    if (enc->codec_id == CODEC_ID_DVB_SUBTITLE)
        nb = 2;
    else
        nb = 1;

    for(i = 0; i < nb; i++) {
685
        subtitle_out_size = avcodec_encode_subtitle(enc, subtitle_out,
686
                                                    subtitle_out_max_size, sub);
687

688 689 690 691
        av_init_packet(&pkt);
        pkt.stream_index = ost->index;
        pkt.data = subtitle_out;
        pkt.size = subtitle_out_size;
692
        pkt.pts = av_rescale_q(pts, ist->st->time_base, ost->st->time_base);
693 694 695 696 697 698 699 700
        if (enc->codec_id == CODEC_ID_DVB_SUBTITLE) {
            /* XXX: the pts correction is handled here. Maybe handling
               it in the codec would be better */
            if (i == 0)
                pkt.pts += 90 * sub->start_display_time;
            else
                pkt.pts += 90 * sub->end_display_time;
        }
701
        write_frame(s, &pkt, ost->st->codec, bitstream_filters[ost->file_index][pkt.stream_index]);
702 703 704
    }
}

705
static int bit_buffer_size= 1024*256;
706
static uint8_t *bit_buffer= NULL;
707

708 709
static void do_video_out(AVFormatContext *s,
                         AVOutputStream *ost,
Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
710
                         AVInputStream *ist,
711
                         AVFrame *in_picture,
712
                         int *frame_size)
Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
713
{
714
    int nb_frames, i, ret;
715
    AVFrame *final_picture, *formatted_picture, *resampling_dst, *padding_src;
716
    AVFrame picture_crop_temp, picture_pad_temp;
717
    AVCodecContext *enc, *dec;
718

719
    avcodec_get_frame_defaults(&picture_crop_temp);
720
    avcodec_get_frame_defaults(&picture_pad_temp);
721

722 723
    enc = ost->st->codec;
    dec = ist->st->codec;
Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
724

725 726 727
    /* by default, we output a single frame */
    nb_frames = 1;

728 729
    *frame_size = 0;

730
    if(video_sync_method){
731
        double vdelta;
732
        vdelta = get_sync_ipts(ost) / av_q2d(enc->time_base) - ost->sync_opts;
733 734 735
        //FIXME set to 0.5 after we fix some dts/pts bugs like in avidec.c
        if (vdelta < -1.1)
            nb_frames = 0;
736 737
        else if (video_sync_method == 2)
            ost->sync_opts= lrintf(get_sync_ipts(ost) / av_q2d(enc->time_base));
738
        else if (vdelta > 1.1)
Michael Niedermayer's avatar
Michael Niedermayer committed
739
            nb_frames = lrintf(vdelta);
740
//fprintf(stderr, "vdelta:%f, ost->sync_opts:%"PRId64", ost->sync_ipts:%f nb_frames:%d\n", vdelta, ost->sync_opts, ost->sync_ipts, nb_frames);
741 742 743 744
        if (nb_frames == 0){
            ++nb_frames_drop;
            if (verbose>2)
                fprintf(stderr, "*** drop!\n");
745 746
        }else if (nb_frames > 1) {
            nb_frames_dup += nb_frames;
747
            if (verbose>2)
748
                fprintf(stderr, "*** %d dup!\n", nb_frames-1);
749 750
        }
    }else
751
        ost->sync_opts= lrintf(get_sync_ipts(ost) / av_q2d(enc->time_base));
752

753
    nb_frames= FFMIN(nb_frames, max_frames[CODEC_TYPE_VIDEO] - ost->frame_number);
754
    if (nb_frames <= 0)
Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
755
        return;
756

757
    if (ost->video_crop) {
758
        if (av_picture_crop((AVPicture *)&picture_crop_temp, (AVPicture *)in_picture, dec->pix_fmt, ost->topBand, ost->leftBand) < 0) {
759
            av_log(NULL, AV_LOG_ERROR, "error cropping picture\n");
Limin Wang's avatar
Limin Wang committed
760
            return;
761 762
        }
        formatted_picture = &picture_crop_temp;
763 764
    } else {
        formatted_picture = in_picture;
765 766 767 768 769 770 771 772
    }

    final_picture = formatted_picture;
    padding_src = formatted_picture;
    resampling_dst = &ost->pict_tmp;
    if (ost->video_pad) {
        final_picture = &ost->pict_tmp;
        if (ost->video_resample) {
773
            if (av_picture_crop((AVPicture *)&picture_pad_temp, (AVPicture *)final_picture, enc->pix_fmt, ost->padtop, ost->padleft) < 0) {
774
                av_log(NULL, AV_LOG_ERROR, "error padding picture\n");
Limin Wang's avatar
Limin Wang committed
775
                return;
776 777 778 779 780
            }
            resampling_dst = &picture_pad_temp;
        }
    }

Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
781
    if (ost->video_resample) {
782
        padding_src = NULL;
783
        final_picture = &ost->pict_tmp;
784 785
        sws_scale(ost->img_resample_ctx, formatted_picture->data, formatted_picture->linesize,
              0, ost->resample_height, resampling_dst->data, resampling_dst->linesize);
786
    }
787 788

    if (ost->video_pad) {
789
        av_picture_pad((AVPicture*)final_picture, (AVPicture *)padding_src,
790 791
                enc->height, enc->width, enc->pix_fmt,
                ost->padtop, ost->padbottom, ost->padleft, ost->padright, padcolor);
<