ffmpeg.c 136 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>

62 63 64
#if !defined(INFINITY) && defined(HUGE_VAL)
#define INFINITY HUGE_VAL
#endif
Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
65

Michael Niedermayer's avatar
Michael Niedermayer committed
66 67
#undef exit

68 69 70
static const char program_name[] = "FFmpeg";
static const int program_birth_year = 2000;

Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
71 72 73 74
/* select an input stream for an output stream */
typedef struct AVStreamMap {
    int file_index;
    int stream_index;
75 76
    int sync_file_index;
    int sync_stream_index;
Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
77 78
} AVStreamMap;

79 80 81 82 83 84
/** 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
85 86 87 88 89
extern const OptionDef options[];

#define MAX_FILES 20

static AVFormatContext *input_files[MAX_FILES];
90
static int64_t input_files_ts_offset[MAX_FILES];
Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
91 92 93 94 95 96 97 98
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;

99 100 101
static AVMetaDataMap meta_data_maps[MAX_FILES];
static int nb_meta_data_maps;

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

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

153
static int subtitle_disable = 0;
154
static char *subtitle_codec_name = NULL;
155
static char *subtitle_language = NULL;
Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
156

157 158
static float mux_preload= 0.5;
static float mux_max_delay= 0.7;
159

160
static int64_t recording_time = 0;
161
static int64_t start_time = 0;
162
static int64_t rec_timestamp = 0;
163
static int64_t input_ts_offset = 0;
Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
164 165 166 167 168
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;
169
static char *str_genre = NULL;
170
static char *str_album = NULL;
Fabrice Bellard's avatar
Fabrice Bellard committed
171
static int do_benchmark = 0;
172
static int do_hex_dump = 0;
173
static int do_pkt_dump = 0;
174
static int do_psnr = 0;
175 176
static int do_pass = 0;
static char *pass_logfilename = NULL;
177 178
static int audio_stream_copy = 0;
static int video_stream_copy = 0;
179
static int subtitle_stream_copy = 0;
180 181
static int video_sync_method= 1;
static int audio_sync_method= 0;
Michael Niedermayer's avatar
Michael Niedermayer committed
182
static float audio_drift_threshold= 0.1;
183
static int copy_ts= 0;
184
static int opt_shortest = 0; //
185
static int video_global_header = 0;
186
static char *vstats_filename;
187
static FILE *vstats_file;
188
static int opt_programid = 0;
189

190 191
static int rate_emu = 0;

192
static int  video_channel = 0;
193
static char *video_standard;
194

195
static int audio_volume = 256;
196

197
static int using_stdin = 0;
198
static int using_vhook = 0;
199
static int verbose = 1;
200
static int thread_count= 1;
201
static int q_pressed = 0;
202 203 204
static int64_t video_size = 0;
static int64_t audio_size = 0;
static int64_t extra_size = 0;
205 206
static int nb_frames_dup = 0;
static int nb_frames_drop = 0;
207
static int input_sync;
208
static uint64_t limit_filesize = 0; //
209

210
static int pgmyuv_compatibility_hack=0;
211
static float dts_delta_threshold = 10;
212

213 214
static int sws_flags = SWS_BICUBIC;

Benoit Fouet's avatar
Benoit Fouet committed
215 216 217 218 219 220
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
221

222 223 224
static AVBitStreamFilterContext *video_bitstream_filters=NULL;
static AVBitStreamFilterContext *audio_bitstream_filters=NULL;
static AVBitStreamFilterContext *bitstream_filters[MAX_FILES][MAX_STREAMS];
225

226
#define DEFAULT_PASS_LOGFILENAME "ffmpeg2pass"
Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
227

228 229
struct AVInputStream;

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

248
    int video_crop;
249 250
    int topBand;             /* cropping area sizes */
    int leftBand;
251

252
    int video_pad;
253 254 255 256
    int padtop;              /* padding area sizes */
    int padbottom;
    int padleft;
    int padright;
257

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

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

288
#ifdef HAVE_TERMIOS_H
Fabrice Bellard's avatar
Fabrice Bellard committed
289

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

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

301 302 303 304 305 306 307 308 309
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
310 311
static void term_init(void)
{
312
#ifdef HAVE_TERMIOS_H
Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
313 314 315 316 317 318 319 320 321 322 323 324 325
    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;
326

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

331 332 333 334 335
    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
336
    atexit(term_exit);
337 338 339
#ifdef CONFIG_BEOS_NETSERVER
    fcntl(0, F_SETFL, fcntl(0, F_GETFL) | O_NONBLOCK);
#endif
Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
340 341 342 343 344
}

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

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

372 373 374 375 376
static int decode_interrupt_cb(void)
{
    return q_pressed || (q_pressed = read_key() == 'q');
}

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

382 383 384
    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
385 386 387 388
    /* 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
389

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

    av_close_input_file(ic);
    return 0;
}

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

409
static void write_frame(AVFormatContext *s, AVPacket *pkt, AVCodecContext *avctx, AVBitStreamFilterContext *bsfc){
410 411
    int ret;

412 413 414 415 416 417 418 419 420 421 422 423 424 425 426
    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);
        if(a){
            av_free_packet(pkt);
            new_pkt.destruct= av_destruct_packet;
        }
        *pkt= new_pkt;

        bsfc= bsfc->next;
    }

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

434
#define MAX_AUDIO_PACKET_SIZE (128 * 1024)
Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
435

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

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

450 451 452 453
    /* 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
454
        audio_out = av_malloc(audio_out_size);
455 456 457
    if (!audio_buf || !audio_out)
        return;               /* Should signal an error ! */

458 459 460 461 462 463 464 465 466 467 468 469 470 471
    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);
        }
    }

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

478 479
        //FIXME resample delay
        if(fabs(delta) > 50){
Michael Niedermayer's avatar
Michael Niedermayer committed
480
            if(ist->is_start || fabs(delta) > audio_drift_threshold*enc->sample_rate){
481
                if(byte_delta < 0){
482
                    byte_delta= FFMAX(byte_delta, -size);
483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506
                    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){
507
                int comp= av_clip(delta, -audio_sync_method, audio_sync_method);
508 509 510
                assert(ost->audio_resample);
                if(verbose > 2)
                    fprintf(stderr, "compensating audio timestamp drift:%f compensation:%d in:%d\n", delta, comp, enc->sample_rate);
511
//                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));
512 513
                av_resample_compensate(*(struct AVResampleContext**)ost->resample, comp, enc->sample_rate);
            }
514
        }
515
    }else
516
        ost->sync_opts= lrintf(get_sync_ipts(ost) * enc->sample_rate)
517
                        - av_fifo_size(&ost->fifo)/(ost->st->codec->channels * 2); //FIXME wrong
Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
518 519 520

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

    /* now encode as many frames as possible */
531
    if (enc->frame_size > 1) {
Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
532
        /* output resampled raw samples */
533
        av_fifo_write(&ost->fifo, buftmp, size_out);
Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
534 535

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

537
        while (av_fifo_read(&ost->fifo, audio_buf, frame_bytes) == 0) {
538 539 540
            AVPacket pkt;
            av_init_packet(&pkt);

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

552
            ost->sync_opts += enc->frame_size;
Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
553 554
        }
    } else {
555 556
        AVPacket pkt;
        av_init_packet(&pkt);
557

558
        ost->sync_opts += size_out / (2 * enc->channels);
559

560 561 562
        /* output a pcm frame */
        /* XXX: change encoding codec API to avoid this ? */
        switch(enc->codec->id) {
563 564 565 566 567 568 569 570 571 572 573 574 575
        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;
576 577 578 579 580 581 582 583 584
        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;
        }
585
        ret = avcodec_encode_audio(enc, audio_out, size_out,
586
                                   (short *)buftmp);
587
        audio_size += ret;
588 589 590
        pkt.stream_index= ost->index;
        pkt.data= audio_out;
        pkt.size= ret;
591
        if(enc->coded_frame && enc->coded_frame->pts != AV_NOPTS_VALUE)
592
            pkt.pts= av_rescale_q(enc->coded_frame->pts, enc->time_base, ost->st->time_base);
593
        pkt.flags |= PKT_FLAG_KEY;
594
        write_frame(s, &pkt, ost->st->codec, bitstream_filters[ost->file_index][pkt.stream_index]);
Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
595 596 597
    }
}

598 599 600 601 602
static void pre_process_video_frame(AVInputStream *ist, AVPicture *picture, void **bufp)
{
    AVCodecContext *dec;
    AVPicture *picture2;
    AVPicture picture_tmp;
603
    uint8_t *buf = 0;
604

605
    dec = ist->st->codec;
606 607

    /* deinterlace : must be done before any resize */
608
    if (do_deinterlace || using_vhook) {
609 610 611 612 613 614 615
        int size;

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

617 618 619
        picture2 = &picture_tmp;
        avpicture_fill(picture2, buf, dec->pix_fmt, dec->width, dec->height);

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

635
    if (ENABLE_VHOOK)
Diego Biurrun's avatar
Diego Biurrun committed
636 637
        frame_hook_process(picture2, dec->pix_fmt, dec->width, dec->height,
                           1000000 * ist->pts / AV_TIME_BASE);
638 639 640 641 642 643

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

644 645
/* we begin to correct av delay at this threshold */
#define AV_DELAY_MAX 0.100
Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
646

647 648
static void do_subtitle_out(AVFormatContext *s,
                            AVOutputStream *ost,
649 650 651 652 653 654 655 656 657 658 659 660 661 662 663
                            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;
    }

664
    enc = ost->st->codec;
665 666 667 668 669 670 671 672 673 674 675 676 677 678

    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++) {
679
        subtitle_out_size = avcodec_encode_subtitle(enc, subtitle_out,
680
                                                    subtitle_out_max_size, sub);
681

682 683 684 685
        av_init_packet(&pkt);
        pkt.stream_index = ost->index;
        pkt.data = subtitle_out;
        pkt.size = subtitle_out_size;
686
        pkt.pts = av_rescale_q(pts, ist->st->time_base, ost->st->time_base);
687 688 689 690 691 692 693 694
        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;
        }
695
        write_frame(s, &pkt, ost->st->codec, bitstream_filters[ost->file_index][pkt.stream_index]);
696 697 698
    }
}

699
static int bit_buffer_size= 1024*256;
700
static uint8_t *bit_buffer= NULL;
701

702 703
static void do_video_out(AVFormatContext *s,
                         AVOutputStream *ost,
Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
704
                         AVInputStream *ist,
705
                         AVFrame *in_picture,
706
                         int *frame_size)
Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
707
{
708
    int nb_frames, i, ret;
709
    AVFrame *final_picture, *formatted_picture, *resampling_dst, *padding_src;
710
    AVFrame picture_crop_temp, picture_pad_temp;
711
    AVCodecContext *enc, *dec;
712

713
    avcodec_get_frame_defaults(&picture_crop_temp);
714
    avcodec_get_frame_defaults(&picture_pad_temp);
715

716 717
    enc = ost->st->codec;
    dec = ist->st->codec;
Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
718

719 720 721
    /* by default, we output a single frame */
    nb_frames = 1;

722 723
    *frame_size = 0;

724
    if(video_sync_method){
725
        double vdelta;
726
        vdelta = get_sync_ipts(ost) / av_q2d(enc->time_base) - ost->sync_opts;
727 728 729 730
        //FIXME set to 0.5 after we fix some dts/pts bugs like in avidec.c
        if (vdelta < -1.1)
            nb_frames = 0;
        else if (vdelta > 1.1)
Michael Niedermayer's avatar
Michael Niedermayer committed
731
            nb_frames = lrintf(vdelta);
732
//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);
733 734 735 736
        if (nb_frames == 0){
            ++nb_frames_drop;
            if (verbose>2)
                fprintf(stderr, "*** drop!\n");
737 738
        }else if (nb_frames > 1) {
            nb_frames_dup += nb_frames;
739
            if (verbose>2)
740
                fprintf(stderr, "*** %d dup!\n", nb_frames-1);
741 742
        }
    }else
743
        ost->sync_opts= lrintf(get_sync_ipts(ost) / av_q2d(enc->time_base));
744

745
    nb_frames= FFMIN(nb_frames, max_frames[CODEC_TYPE_VIDEO] - ost->frame_number);
746
    if (nb_frames <= 0)
Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
747
        return;
748

749
    if (ost->video_crop) {
750
        if (av_picture_crop((AVPicture *)&picture_crop_temp, (AVPicture *)in_picture, dec->pix_fmt, ost->topBand, ost->leftBand) < 0) {
751
            av_log(NULL, AV_LOG_ERROR, "error cropping picture\n");
Limin Wang's avatar
Limin Wang committed
752
            return;
753 754
        }
        formatted_picture = &picture_crop_temp;
755 756
    } else {
        formatted_picture = in_picture;
757 758 759 760 761 762 763 764
    }

    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) {
765
            if (av_picture_crop((AVPicture *)&picture_pad_temp, (AVPicture *)final_picture, enc->pix_fmt, ost->padtop, ost->padleft) < 0) {
766
                av_log(NULL, AV_LOG_ERROR, "error padding picture\n");
Limin Wang's avatar
Limin Wang committed
767
                return;
768 769 770 771 772
            }
            resampling_dst = &picture_pad_temp;
        }
    }

Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
773
    if (ost->video_resample) {
774
        padding_src = NULL;
775
        final_picture = &ost->pict_tmp;
776 777
        sws_scale(ost->img_resample_ctx, formatted_picture->data, formatted_picture->linesize,
              0, ost->resample_height, resampling_dst->data, resampling_dst->linesize);
778
    }
779 780

    if (ost->video_pad) {
781
        av_picture_pad((AVPicture*)final_picture, (AVPicture *)padding_src,
782 783
                enc->height, enc->width, enc->pix_fmt,
                ost->padtop, ost->padbottom, ost->padleft, ost->padright, padcolor);
Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
784
    }
785

Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
786
    /* duplicates frame if needed */
787
    for(i=0;i<nb_frames;i++) {
788 789 790 791
        AVPacket pkt;
        av_init_packet(&pkt);
        pkt.stream_index= ost->index;

792 793 794 795
        if (s->oformat->flags & AVFMT_RAWPICTURE) {
            /* raw pictures are written as AVPicture structure to
               avoid any copies. We support temorarily the older
               method. */
796
            AVFrame* old_frame = enc->coded_frame;
797
            enc->coded_frame = dec->coded_frame; //FIXME/XXX remove this hack
798 799
            pkt.data= (uint8_t *)final_picture;
            pkt.size=  sizeof(AVPicture);
800 801
            pkt.pts= av_rescale_q(ost->sync_opts, enc->time_base, ost->st->time_base);
            pkt.flags |= PKT_FLAG_KEY;
802

803
            write_frame(s, &pkt, ost->st->codec, bitstream_filters[ost->file_index][pkt.stream_index]);
804
            enc->coded_frame = old_frame;
805
        } else {
Michael Niedermayer's avatar
Michael Niedermayer committed
806
            AVFrame big_picture;
807 808

            big_picture= *final_picture;
809 810 811
            /* better than nothing: use input picture interlaced
               settings */
            big_picture.interlaced_frame = in_picture->interlaced_frame;
812
            if(avctx_opts[CODEC_TYPE_VIDEO]->flags & (CODEC_FLAG_INTERLACED_DCT|CODEC_FLAG_INTERLACED_ME)){
813 814 815
                if(top_field_first == -1)
                    big_picture.top_field_first = in_picture->top_field_first;
                else
Michael Niedermayer's avatar
Michael Niedermayer committed
816
                    big_picture.top_field_first = top_field_first;
817
            }
818

Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
819 820 821
            /* handles sameq here. This is not correct because it may
               not be a global option */
            if (same_quality) {
Michael Niedermayer's avatar
cleanup  
Michael Niedermayer committed
822 823 824
                big_picture.quality = ist->st->quality;
            }else
                big_picture.quality = ost->st->quality;