Statistics
| Branch: | Revision:

ffmpeg / libavcodec / xvidff.c @ 2029f312

History | View | Annotate | Download (24.5 KB)

1
/*
2
 * Interface to xvidcore for mpeg4 encoding
3
 * Copyright (c) 2004 Adam Thayer <krevnik@comcast.net>
4
 *
5
 * This file is part of FFmpeg.
6
 *
7
 * FFmpeg is free software; you can redistribute it and/or
8
 * modify it under the terms of the GNU Lesser General Public
9
 * License as published by the Free Software Foundation; either
10
 * version 2.1 of the License, or (at your option) any later version.
11
 *
12
 * FFmpeg is distributed in the hope that it will be useful,
13
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15
 * Lesser General Public License for more details.
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
20
 */
21

    
22
/**
23
 * @file xvidmpeg4.c
24
 * Interface to xvidcore for MPEG-4 compliant encoding.
25
 * @author Adam Thayer (krevnik@comcast.net)
26
 */
27

    
28
#include <xvid.h>
29
#include <unistd.h>
30
#include "avcodec.h"
31
#include "xvid_internal.h"
32

    
33
/**
34
 * Buffer management macros.
35
 */
36
#define BUFFER_SIZE                 1024
37
#define BUFFER_REMAINING(x)         (BUFFER_SIZE - strlen(x))
38
#define BUFFER_CAT(x)               (&((x)[strlen(x)]))
39

    
40
/* For PPC Use */
41
#if HAVE_ALTIVEC==1
42
extern int has_altivec(void);
43
#endif
44

    
45
/**
46
 * Structure for the private XviD context.
47
 * This stores all the private context for the codec.
48
 */
49
typedef struct xvid_context {
50
    void *encoder_handle;          /** Handle for XviD Encoder */
51
    int xsize, ysize;              /** Frame size */
52
    int vop_flags;                 /** VOP flags for XviD Encoder */
53
    int vol_flags;                 /** VOL flags for XviD Encoder */
54
    int me_flags;                  /** Motion Estimation flags */
55
    int qscale;                    /** Do we use constant scale? */
56
    int quicktime_format;          /** Are we in a QT-based format? */
57
    AVFrame encoded_picture;       /** Encoded frame information */
58
    char *twopassbuffer;           /** Character buffer for two-pass */
59
    char *old_twopassbuffer;       /** Old character buffer (two-pass) */
60
    char *twopassfile;             /** second pass temp file name */
61
    unsigned char *intra_matrix;   /** P-Frame Quant Matrix */
62
    unsigned char *inter_matrix;   /** I-Frame Quant Matrix */
63
} xvid_context_t;
64

    
65
/**
66
 * Structure for the private first-pass plugin.
67
 */
68
typedef struct xvid_ff_pass1 {
69
    int     version;                /** XviD version */
70
    xvid_context_t *context;        /** Pointer to private context */
71
} xvid_ff_pass1_t;
72

    
73
/* Prototypes - See function implementation for details */
74
int xvid_strip_vol_header(AVCodecContext *avctx, unsigned char *frame, unsigned int header_len, unsigned int frame_len);
75
int xvid_ff_2pass(void *ref, int opt, void *p1, void *p2);
76
void xvid_correct_framerate(AVCodecContext *avctx);
77

    
78
/**
79
 * Creates the private context for the encoder.
80
 * All buffers are allocated, settings are loaded from the user,
81
 * and the encoder context created.
82
 *
83
 * @param avctx AVCodecContext pointer to context
84
 * @return Returns 0 on success, -1 on failure
85
 */
86
int ff_xvid_encode_init(AVCodecContext *avctx)  {
87
    int xerr, i;
88
    int xvid_flags = avctx->flags;
89
    xvid_context_t *x = avctx->priv_data;
90
    uint16_t *intra, *inter;
91
    int fd;
92

    
93
    xvid_plugin_single_t single;
94
    xvid_ff_pass1_t rc2pass1;
95
    xvid_plugin_2pass2_t rc2pass2;
96
    xvid_gbl_init_t xvid_gbl_init;
97
    xvid_enc_create_t xvid_enc_create;
98
    xvid_enc_plugin_t plugins[7];
99

    
100
    /* Bring in VOP flags from ffmpeg command-line */
101
    x->vop_flags = XVID_VOP_HALFPEL; /* Bare minimum quality */
102
    if( xvid_flags & CODEC_FLAG_4MV )
103
        x->vop_flags |= XVID_VOP_INTER4V; /* Level 3 */
104
    if( xvid_flags & CODEC_FLAG_TRELLIS_QUANT)
105
        x->vop_flags |= XVID_VOP_TRELLISQUANT; /* Level 5 */
106
    if( xvid_flags & CODEC_FLAG_AC_PRED )
107
        x->vop_flags |= XVID_VOP_HQACPRED; /* Level 6 */
108
    if( xvid_flags & CODEC_FLAG_GRAY )
109
        x->vop_flags |= XVID_VOP_GREYSCALE;
110

    
111
    /* Decide which ME quality setting to use */
112
    x->me_flags = 0;
113
    switch( avctx->me_method ) {
114
       case ME_FULL:   /* Quality 6 */
115
           x->me_flags |=  XVID_ME_EXTSEARCH16
116
                       |   XVID_ME_EXTSEARCH8;
117

    
118
       case ME_EPZS:   /* Quality 4 */
119
           x->me_flags |=  XVID_ME_ADVANCEDDIAMOND8
120
                       |   XVID_ME_HALFPELREFINE8
121
                       |   XVID_ME_CHROMA_PVOP
122
                       |   XVID_ME_CHROMA_BVOP;
123

    
124
       case ME_LOG:    /* Quality 2 */
125
       case ME_PHODS:
126
       case ME_X1:
127
           x->me_flags |=  XVID_ME_ADVANCEDDIAMOND16
128
                       |   XVID_ME_HALFPELREFINE16;
129

    
130
       case ME_ZERO:   /* Quality 0 */
131
       default:
132
           break;
133
    }
134

    
135
    /* Decide how we should decide blocks */
136
    switch( avctx->mb_decision ) {
137
       case 2:
138
           x->vop_flags |= XVID_VOP_MODEDECISION_RD;
139
           x->me_flags |=  XVID_ME_HALFPELREFINE8_RD
140
                       |   XVID_ME_QUARTERPELREFINE8_RD
141
                       |   XVID_ME_EXTSEARCH_RD
142
                       |   XVID_ME_CHECKPREDICTION_RD;
143
       case 1:
144
           if( !(x->vop_flags & XVID_VOP_MODEDECISION_RD) )
145
               x->vop_flags |= XVID_VOP_FAST_MODEDECISION_RD;
146
           x->me_flags |=  XVID_ME_HALFPELREFINE16_RD
147
                       |   XVID_ME_QUARTERPELREFINE16_RD;
148

    
149
       default:
150
           break;
151
    }
152

    
153
    /* Bring in VOL flags from ffmpeg command-line */
154
    x->vol_flags = 0;
155
    if( xvid_flags & CODEC_FLAG_GMC ) {
156
        x->vol_flags |= XVID_VOL_GMC;
157
        x->me_flags |= XVID_ME_GME_REFINE;
158
    }
159
    if( xvid_flags & CODEC_FLAG_QPEL ) {
160
        x->vol_flags |= XVID_VOL_QUARTERPEL;
161
        x->me_flags |= XVID_ME_QUARTERPELREFINE16;
162
        if( x->vop_flags & XVID_VOP_INTER4V )
163
            x->me_flags |= XVID_ME_QUARTERPELREFINE8;
164
    }
165

    
166
    memset(&xvid_gbl_init, 0, sizeof(xvid_gbl_init));
167
    xvid_gbl_init.version = XVID_VERSION;
168
    xvid_gbl_init.debug = 0;
169

    
170
#ifdef ARCH_POWERPC
171
    /* XviD's PPC support is borked, use libavcodec to detect */
172
#if HAVE_ALTIVEC==1
173
    if( has_altivec() ) {
174
        xvid_gbl_init.cpu_flags = XVID_CPU_FORCE | XVID_CPU_ALTIVEC;
175
    } else
176
#endif
177
        xvid_gbl_init.cpu_flags = XVID_CPU_FORCE;
178
#else
179
    /* XviD can detect on x86 */
180
    xvid_gbl_init.cpu_flags = 0;
181
#endif
182

    
183
    /* Initialize */
184
    xvid_global(NULL, XVID_GBL_INIT, &xvid_gbl_init, NULL);
185

    
186
    /* Create the encoder reference */
187
    memset(&xvid_enc_create, 0, sizeof(xvid_enc_create));
188
    xvid_enc_create.version = XVID_VERSION;
189

    
190
    /* Store the desired frame size */
191
    xvid_enc_create.width = x->xsize = avctx->width;
192
    xvid_enc_create.height = x->ysize = avctx->height;
193

    
194
    /* XviD can determine the proper profile to use */
195
    /* xvid_enc_create.profile = XVID_PROFILE_S_L3; */
196

    
197
    /* We don't use zones or threads */
198
    xvid_enc_create.zones = NULL;
199
    xvid_enc_create.num_zones = 0;
200
    xvid_enc_create.num_threads = 0;
201

    
202
    xvid_enc_create.plugins = plugins;
203
    xvid_enc_create.num_plugins = 0;
204

    
205
    /* Initialize Buffers */
206
    x->twopassbuffer = NULL;
207
    x->old_twopassbuffer = NULL;
208
    x->twopassfile = NULL;
209

    
210
    if( xvid_flags & CODEC_FLAG_PASS1 ) {
211
        memset(&rc2pass1, 0, sizeof(xvid_ff_pass1_t));
212
        rc2pass1.version = XVID_VERSION;
213
        rc2pass1.context = x;
214
        x->twopassbuffer = av_malloc(BUFFER_SIZE);
215
        x->old_twopassbuffer = av_malloc(BUFFER_SIZE);
216
        if( x->twopassbuffer == NULL || x->old_twopassbuffer == NULL ) {
217
            av_log(avctx, AV_LOG_ERROR,
218
                "XviD: Cannot allocate 2-pass log buffers\n");
219
            return -1;
220
        }
221
        x->twopassbuffer[0] = x->old_twopassbuffer[0] = 0;
222

    
223
        plugins[xvid_enc_create.num_plugins].func = xvid_ff_2pass;
224
        plugins[xvid_enc_create.num_plugins].param = &rc2pass1;
225
        xvid_enc_create.num_plugins++;
226
    } else if( xvid_flags & CODEC_FLAG_PASS2 ) {
227
        memset(&rc2pass2, 0, sizeof(xvid_plugin_2pass2_t));
228
        rc2pass2.version = XVID_VERSION;
229
        rc2pass2.bitrate = avctx->bit_rate;
230

    
231
        fd = av_tempfile("xvidff.", &(x->twopassfile));
232
        if( fd == -1 ) {
233
            av_log(avctx, AV_LOG_ERROR,
234
                "XviD: Cannot write 2-pass pipe\n");
235
            return -1;
236
        }
237

    
238
        if( avctx->stats_in == NULL ) {
239
            av_log(avctx, AV_LOG_ERROR,
240
                "XviD: No 2-pass information loaded for second pass\n");
241
            return -1;
242
        }
243

    
244
        if( strlen(avctx->stats_in) >
245
              write(fd, avctx->stats_in, strlen(avctx->stats_in)) ) {
246
            close(fd);
247
            av_log(avctx, AV_LOG_ERROR,
248
                "XviD: Cannot write to 2-pass pipe\n");
249
            return -1;
250
        }
251

    
252
        close(fd);
253
        rc2pass2.filename = x->twopassfile;
254
        plugins[xvid_enc_create.num_plugins].func = xvid_plugin_2pass2;
255
        plugins[xvid_enc_create.num_plugins].param = &rc2pass2;
256
        xvid_enc_create.num_plugins++;
257
    } else if( !(xvid_flags & CODEC_FLAG_QSCALE) ) {
258
        /* Single Pass Bitrate Control! */
259
        memset(&single, 0, sizeof(xvid_plugin_single_t));
260
        single.version = XVID_VERSION;
261
        single.bitrate = avctx->bit_rate;
262

    
263
        plugins[xvid_enc_create.num_plugins].func = xvid_plugin_single;
264
        plugins[xvid_enc_create.num_plugins].param = &single;
265
        xvid_enc_create.num_plugins++;
266
    }
267

    
268
    /* Luminance Masking */
269
    if( 0.0 != avctx->lumi_masking ) {
270
        plugins[xvid_enc_create.num_plugins].func = xvid_plugin_lumimasking;
271
        plugins[xvid_enc_create.num_plugins].param = NULL;
272
        xvid_enc_create.num_plugins++;
273
    }
274

    
275
    /* Frame Rate and Key Frames */
276
    xvid_correct_framerate(avctx);
277
    xvid_enc_create.fincr = avctx->time_base.num;
278
    xvid_enc_create.fbase = avctx->time_base.den;
279
    if( avctx->gop_size > 0 )
280
        xvid_enc_create.max_key_interval = avctx->gop_size;
281
    else
282
        xvid_enc_create.max_key_interval = 240; /* XviD's best default */
283

    
284
    /* Quants */
285
    if( xvid_flags & CODEC_FLAG_QSCALE ) x->qscale = 1;
286
    else x->qscale = 0;
287

    
288
    xvid_enc_create.min_quant[0] = avctx->qmin;
289
    xvid_enc_create.min_quant[1] = avctx->qmin;
290
    xvid_enc_create.min_quant[2] = avctx->qmin;
291
    xvid_enc_create.max_quant[0] = avctx->qmax;
292
    xvid_enc_create.max_quant[1] = avctx->qmax;
293
    xvid_enc_create.max_quant[2] = avctx->qmax;
294

    
295
    /* Quant Matrices */
296
    x->intra_matrix = x->inter_matrix = NULL;
297
    if( avctx->mpeg_quant )
298
       x->vol_flags |= XVID_VOL_MPEGQUANT;
299
    if( (avctx->intra_matrix || avctx->inter_matrix) ) {
300
       x->vol_flags |= XVID_VOL_MPEGQUANT;
301

    
302
       if( avctx->intra_matrix ) {
303
           intra = avctx->intra_matrix;
304
           x->intra_matrix = av_malloc(sizeof(unsigned char) * 64);
305
       } else
306
           intra = NULL;
307
       if( avctx->inter_matrix ) {
308
           inter = avctx->inter_matrix;
309
           x->inter_matrix = av_malloc(sizeof(unsigned char) * 64);
310
       } else
311
           inter = NULL;
312

    
313
       for( i = 0; i < 64; i++ ) {
314
           if( intra )
315
               x->intra_matrix[i] = (unsigned char)intra[i];
316
           if( inter )
317
               x->inter_matrix[i] = (unsigned char)inter[i];
318
       }
319
    }
320

    
321
    /* Misc Settings */
322
    xvid_enc_create.frame_drop_ratio = 0;
323
    xvid_enc_create.global = 0;
324
    if( xvid_flags & CODEC_FLAG_CLOSED_GOP )
325
        xvid_enc_create.global |= XVID_GLOBAL_CLOSED_GOP;
326

    
327
    /* Determines which codec mode we are operating in */
328
    avctx->extradata = NULL;
329
    avctx->extradata_size = 0;
330
    if( xvid_flags & CODEC_FLAG_GLOBAL_HEADER ) {
331
        /* In this case, we are claiming to be MPEG4 */
332
        x->quicktime_format = 1;
333
        avctx->codec_id = CODEC_ID_MPEG4;
334
    } else {
335
        /* We are claiming to be XviD */
336
        x->quicktime_format = 0;
337
        if(!avctx->codec_tag)
338
            avctx->codec_tag = ff_get_fourcc("xvid");
339
    }
340

    
341
    /* Bframes */
342
    xvid_enc_create.max_bframes = avctx->max_b_frames;
343
    xvid_enc_create.bquant_offset = 100 * avctx->b_quant_offset;
344
    xvid_enc_create.bquant_ratio = 100 * avctx->b_quant_factor;
345
    if( avctx->max_b_frames > 0  && !x->quicktime_format ) xvid_enc_create.global |= XVID_GLOBAL_PACKED;
346

    
347
    /* Create encoder context */
348
    xerr = xvid_encore(NULL, XVID_ENC_CREATE, &xvid_enc_create, NULL);
349
    if( xerr ) {
350
        av_log(avctx, AV_LOG_ERROR, "XviD: Could not create encoder reference\n");
351
        return -1;
352
    }
353

    
354
    x->encoder_handle = xvid_enc_create.handle;
355
    avctx->coded_frame = &x->encoded_picture;
356

    
357
    return 0;
358
}
359

    
360
/**
361
 * Encodes a single frame.
362
 *
363
 * @param avctx AVCodecContext pointer to context
364
 * @param frame Pointer to encoded frame buffer
365
 * @param buf_size Size of encoded frame buffer
366
 * @param data Pointer to AVFrame of unencoded frame
367
 * @return Returns 0 on success, -1 on failure
368
 */
369
int ff_xvid_encode_frame(AVCodecContext *avctx,
370
                         unsigned char *frame, int buf_size, void *data) {
371
    int xerr, i;
372
    char *tmp;
373
    xvid_context_t *x = avctx->priv_data;
374
    AVFrame *picture = data;
375
    AVFrame *p = &(x->encoded_picture);
376

    
377
    xvid_enc_frame_t xvid_enc_frame;
378
    xvid_enc_stats_t xvid_enc_stats;
379

    
380
    /* Start setting up the frame */
381
    memset(&xvid_enc_frame, 0, sizeof(xvid_enc_frame));
382
    xvid_enc_frame.version = XVID_VERSION;
383
    memset(&xvid_enc_stats, 0, sizeof(xvid_enc_stats));
384
    xvid_enc_stats.version = XVID_VERSION;
385
    *p = *picture;
386

    
387
    /* Let XviD know where to put the frame. */
388
    xvid_enc_frame.bitstream = frame;
389
    xvid_enc_frame.length = buf_size;
390

    
391
    /* Initialize input image fields */
392
    if( avctx->pix_fmt != PIX_FMT_YUV420P ) {
393
        av_log(avctx, AV_LOG_ERROR, "XviD: Color spaces other than 420p not supported\n");
394
        return -1;
395
    }
396

    
397
    xvid_enc_frame.input.csp = XVID_CSP_PLANAR; /* YUV420P */
398

    
399
    for( i = 0; i < 4; i++ ) {
400
        xvid_enc_frame.input.plane[i] = picture->data[i];
401
        xvid_enc_frame.input.stride[i] = picture->linesize[i];
402
    }
403

    
404
    /* Encoder Flags */
405
    xvid_enc_frame.vop_flags = x->vop_flags;
406
    xvid_enc_frame.vol_flags = x->vol_flags;
407
    xvid_enc_frame.motion = x->me_flags;
408
    xvid_enc_frame.type = XVID_TYPE_AUTO;
409

    
410
    /* Quant Setting */
411
    if( x->qscale ) xvid_enc_frame.quant = picture->quality / FF_QP2LAMBDA;
412
    else xvid_enc_frame.quant = 0;
413

    
414
    /* Matrices */
415
    xvid_enc_frame.quant_intra_matrix = x->intra_matrix;
416
    xvid_enc_frame.quant_inter_matrix = x->inter_matrix;
417

    
418
    /* Encode */
419
    xerr = xvid_encore(x->encoder_handle, XVID_ENC_ENCODE,
420
        &xvid_enc_frame, &xvid_enc_stats);
421

    
422
    /* Two-pass log buffer swapping */
423
    avctx->stats_out = NULL;
424
    if( x->twopassbuffer ) {
425
        tmp = x->old_twopassbuffer;
426
        x->old_twopassbuffer = x->twopassbuffer;
427
        x->twopassbuffer = tmp;
428
        x->twopassbuffer[0] = 0;
429
        if( x->old_twopassbuffer[0] != 0 ) {
430
            avctx->stats_out = x->old_twopassbuffer;
431
        }
432
    }
433

    
434
    if( 0 <= xerr ) {
435
        p->quality = xvid_enc_stats.quant * FF_QP2LAMBDA;
436
        if( xvid_enc_stats.type == XVID_TYPE_PVOP )
437
            p->pict_type = FF_P_TYPE;
438
        else if( xvid_enc_stats.type == XVID_TYPE_BVOP )
439
            p->pict_type = FF_B_TYPE;
440
        else if( xvid_enc_stats.type == XVID_TYPE_SVOP )
441
            p->pict_type = FF_S_TYPE;
442
        else
443
            p->pict_type = FF_I_TYPE;
444
        if( xvid_enc_frame.out_flags & XVID_KEYFRAME ) {
445
            p->key_frame = 1;
446
            if( x->quicktime_format )
447
                return xvid_strip_vol_header(avctx, frame,
448
                    xvid_enc_stats.hlength, xerr);
449
         } else
450
            p->key_frame = 0;
451

    
452
        return xerr;
453
    } else {
454
        av_log(avctx, AV_LOG_ERROR, "XviD: Encoding Error Occurred: %i\n", xerr);
455
        return -1;
456
    }
457
}
458

    
459
/**
460
 * Destroys the private context for the encoder.
461
 * All buffers are freed, and the XviD encoder context is destroyed.
462
 *
463
 * @param avctx AVCodecContext pointer to context
464
 * @return Returns 0, success guaranteed
465
 */
466
int ff_xvid_encode_close(AVCodecContext *avctx) {
467
    xvid_context_t *x = avctx->priv_data;
468

    
469
    xvid_encore(x->encoder_handle, XVID_ENC_DESTROY, NULL, NULL);
470

    
471
    if( avctx->extradata != NULL )
472
        av_free(avctx->extradata);
473
    if( x->twopassbuffer != NULL ) {
474
        av_free(x->twopassbuffer);
475
        av_free(x->old_twopassbuffer);
476
    }
477
    if( x->twopassfile != NULL )
478
        av_free(x->twopassfile);
479
    if( x->intra_matrix != NULL )
480
        av_free(x->intra_matrix);
481
    if( x->inter_matrix != NULL )
482
        av_free(x->inter_matrix);
483

    
484
    return 0;
485
}
486

    
487
/**
488
 * Routine to create a global VO/VOL header for MP4 container.
489
 * What we do here is extract the header from the XviD bitstream
490
 * as it is encoded. We also strip the repeated headers from the
491
 * bitstream when a global header is requested for MPEG-4 ISO
492
 * compliance.
493
 *
494
 * @param avctx AVCodecContext pointer to context
495
 * @param frame Pointer to encoded frame data
496
 * @param header_len Length of header to search
497
 * @param frame_len Length of encoded frame data
498
 * @return Returns new length of frame data
499
 */
500
int xvid_strip_vol_header(AVCodecContext *avctx,
501
                  unsigned char *frame,
502
                  unsigned int header_len,
503
                  unsigned int frame_len) {
504
    int vo_len = 0, i;
505

    
506
    for( i = 0; i < header_len - 3; i++ ) {
507
        if( frame[i] == 0x00 &&
508
            frame[i+1] == 0x00 &&
509
            frame[i+2] == 0x01 &&
510
            frame[i+3] == 0xB6 ) {
511
            vo_len = i;
512
            break;
513
        }
514
    }
515

    
516
    if( vo_len > 0 ) {
517
        /* We need to store the header, so extract it */
518
        if( avctx->extradata == NULL ) {
519
            avctx->extradata = av_malloc(vo_len);
520
            memcpy(avctx->extradata, frame, vo_len);
521
            avctx->extradata_size = vo_len;
522
        }
523
        /* Less dangerous now, memmove properly copies the two
524
           chunks of overlapping data */
525
        memmove(frame, &(frame[vo_len]), frame_len - vo_len);
526
        return frame_len - vo_len;
527
    } else
528
        return frame_len;
529
}
530

    
531
/**
532
 * Routine to correct a possibly erroneous framerate being fed to us.
533
 * XviD currently chokes on framerates where the ticks per frame is
534
 * extremely large. This function works to correct problems in this area
535
 * by estimating a new framerate and taking the simpler fraction of
536
 * the two presented.
537
 *
538
 * @param avctx Context that contains the framerate to correct.
539
 */
540
void xvid_correct_framerate(AVCodecContext *avctx) {
541
    int frate, fbase;
542
    int est_frate, est_fbase;
543
    int gcd;
544
    float est_fps, fps;
545

    
546
    frate = avctx->time_base.den;
547
    fbase = avctx->time_base.num;
548

    
549
    gcd = ff_gcd(frate, fbase);
550
    if( gcd > 1 ) {
551
        frate /= gcd;
552
        fbase /= gcd;
553
    }
554

    
555
    if( frate <= 65000 && fbase <= 65000 ) {
556
        avctx->time_base.den = frate;
557
        avctx->time_base.num = fbase;
558
        return;
559
    }
560

    
561
    fps = (float)frate / (float)fbase;
562
    est_fps = roundf(fps * 1000.0) / 1000.0;
563

    
564
    est_frate = (int)est_fps;
565
    if( est_fps > (int)est_fps ) {
566
        est_frate = (est_frate + 1) * 1000;
567
        est_fbase = (int)roundf((float)est_frate / est_fps);
568
    } else
569
        est_fbase = 1;
570

    
571
    gcd = ff_gcd(est_frate, est_fbase);
572
    if( gcd > 1 ) {
573
        est_frate /= gcd;
574
        est_fbase /= gcd;
575
    }
576

    
577
    if( fbase > est_fbase ) {
578
        avctx->time_base.den = est_frate;
579
        avctx->time_base.num = est_fbase;
580
        av_log(avctx, AV_LOG_DEBUG,
581
            "XviD: framerate re-estimated: %.2f, %.3f%% correction\n",
582
            est_fps, (((est_fps - fps)/fps) * 100.0));
583
    } else {
584
        avctx->time_base.den = frate;
585
        avctx->time_base.num = fbase;
586
    }
587
}
588

    
589
/*
590
 * XviD 2-Pass Kludge Section
591
 *
592
 * XviD's default 2-pass doesn't allow us to create data as we need to, so
593
 * this section spends time replacing the first pass plugin so we can write
594
 * statistic information as libavcodec requests in. We have another kludge
595
 * that allows us to pass data to the second pass in XviD without a custom
596
 * rate-control plugin.
597
 */
598

    
599
/**
600
 * Initializes the two-pass plugin and context.
601
 *
602
 * @param param Input construction parameter structure
603
 * @param handle Private context handle
604
 * @return Returns XVID_ERR_xxxx on failure, or 0 on success.
605
 */
606
static int xvid_ff_2pass_create(xvid_plg_create_t * param,
607
                                void ** handle) {
608
    xvid_ff_pass1_t *x = (xvid_ff_pass1_t *)param->param;
609
    char *log = x->context->twopassbuffer;
610

    
611
    /* Do a quick bounds check */
612
    if( log == NULL )
613
        return XVID_ERR_FAIL;
614

    
615
    /* We use snprintf() */
616
    /* This is because we can safely prevent a buffer overflow */
617
    log[0] = 0;
618
    snprintf(log, BUFFER_REMAINING(log),
619
        "# ffmpeg 2-pass log file, using xvid codec\n");
620
    snprintf(BUFFER_CAT(log), BUFFER_REMAINING(log),
621
        "# Do not modify. libxvidcore version: %d.%d.%d\n\n",
622
        XVID_VERSION_MAJOR(XVID_VERSION),
623
        XVID_VERSION_MINOR(XVID_VERSION),
624
        XVID_VERSION_PATCH(XVID_VERSION));
625

    
626
    *handle = x->context;
627
    return 0;
628
}
629

    
630
/**
631
 * Destroys the two-pass plugin context.
632
 *
633
 * @param ref Context pointer for the plugin
634
 * @param param Destrooy context
635
 * @return Returns 0, success guaranteed
636
 */
637
static int xvid_ff_2pass_destroy(xvid_context_t *ref,
638
                                xvid_plg_destroy_t *param) {
639
    /* Currently cannot think of anything to do on destruction */
640
    /* Still, the framework should be here for reference/use */
641
    if( ref->twopassbuffer != NULL )
642
        ref->twopassbuffer[0] = 0;
643
    return 0;
644
}
645

    
646
/**
647
 * Enables fast encode mode during the first pass.
648
 *
649
 * @param ref Context pointer for the plugin
650
 * @param param Frame data
651
 * @return Returns 0, success guaranteed
652
 */
653
static int xvid_ff_2pass_before(xvid_context_t *ref,
654
                                xvid_plg_data_t *param) {
655
    int motion_remove;
656
    int motion_replacements;
657
    int vop_remove;
658

    
659
    /* Nothing to do here, result is changed too much */
660
    if( param->zone && param->zone->mode == XVID_ZONE_QUANT )
661
        return 0;
662

    
663
    /* We can implement a 'turbo' first pass mode here */
664
    param->quant = 2;
665

    
666
    /* Init values */
667
    motion_remove = ~XVID_ME_CHROMA_PVOP &
668
                    ~XVID_ME_CHROMA_BVOP &
669
                    ~XVID_ME_EXTSEARCH16 &
670
                    ~XVID_ME_ADVANCEDDIAMOND16;
671
    motion_replacements = XVID_ME_FAST_MODEINTERPOLATE |
672
                          XVID_ME_SKIP_DELTASEARCH |
673
                          XVID_ME_FASTREFINE16 |
674
                          XVID_ME_BFRAME_EARLYSTOP;
675
    vop_remove = ~XVID_VOP_MODEDECISION_RD &
676
                 ~XVID_VOP_FAST_MODEDECISION_RD &
677
                 ~XVID_VOP_TRELLISQUANT &
678
                 ~XVID_VOP_INTER4V &
679
                 ~XVID_VOP_HQACPRED;
680

    
681
    param->vol_flags &= ~XVID_VOL_GMC;
682
    param->vop_flags &= vop_remove;
683
    param->motion_flags &= motion_remove;
684
    param->motion_flags |= motion_replacements;
685

    
686
    return 0;
687
}
688

    
689
/**
690
 * Captures statistic data and writes it during first pass.
691
 *
692
 * @param ref Context pointer for the plugin
693
 * @param param Statistic data
694
 * @return Returns XVID_ERR_xxxx on failure, or 0 on success
695
 */
696
static int xvid_ff_2pass_after(xvid_context_t *ref,
697
                                xvid_plg_data_t *param) {
698
    char *log = ref->twopassbuffer;
699
    char *frame_types = " ipbs";
700
    char frame_type;
701

    
702
    /* Quick bounds check */
703
    if( log == NULL )
704
        return XVID_ERR_FAIL;
705

    
706
    /* Convert the type given to us into a character */
707
    if( param->type < 5 && param->type > 0 ) {
708
        frame_type = frame_types[param->type];
709
    } else {
710
        return XVID_ERR_FAIL;
711
    }
712

    
713
    snprintf(BUFFER_CAT(log), BUFFER_REMAINING(log),
714
        "%c %d %d %d %d %d %d\n",
715
        frame_type, param->stats.quant, param->stats.kblks, param->stats.mblks,
716
        param->stats.ublks, param->stats.length, param->stats.hlength);
717

    
718
    return 0;
719
}
720

    
721
/**
722
 * Dispatch function for our custom plugin.
723
 * This handles the dispatch for the XviD plugin. It passes data
724
 * on to other functions for actual processing.
725
 *
726
 * @param ref Context pointer for the plugin
727
 * @param cmd The task given for us to complete
728
 * @param p1 First parameter (varies)
729
 * @param p2 Second parameter (varies)
730
 * @return Returns XVID_ERR_xxxx on failure, or 0 on success
731
 */
732
int xvid_ff_2pass(void *ref, int cmd, void *p1, void *p2) {
733
    switch( cmd ) {
734
        case XVID_PLG_INFO:
735
        case XVID_PLG_FRAME:
736
            return 0;
737

    
738
        case XVID_PLG_BEFORE:
739
            return xvid_ff_2pass_before(ref, p1);
740

    
741
        case XVID_PLG_CREATE:
742
            return xvid_ff_2pass_create(p1, p2);
743

    
744
        case XVID_PLG_AFTER:
745
            return xvid_ff_2pass_after(ref, p1);
746

    
747
        case XVID_PLG_DESTROY:
748
            return xvid_ff_2pass_destroy(ref, p1);
749

    
750
        default:
751
            return XVID_ERR_FAIL;
752
    }
753
}
754

    
755
/**
756
 * XviD codec definition for libavcodec.
757
 */
758
AVCodec xvid_encoder = {
759
    "xvid",
760
    CODEC_TYPE_VIDEO,
761
    CODEC_ID_XVID,
762
    sizeof(xvid_context_t),
763
    ff_xvid_encode_init,
764
    ff_xvid_encode_frame,
765
    ff_xvid_encode_close,
766
    .pix_fmts= (enum PixelFormat[]){PIX_FMT_YUV420P, -1},
767
};