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
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 "libavutil/intreadwrite.h"
32#include "libxvid_internal.h"
33
34/**
35 * Buffer management macros.
36 */
37#define BUFFER_SIZE                 1024
38#define BUFFER_REMAINING(x)         (BUFFER_SIZE - strlen(x))
39#define BUFFER_CAT(x)               (&((x)[strlen(x)]))
40
41/* For PPC Use */
42int has_altivec(void);
43
44/**
45 * Structure for the private Xvid context.
46 * This stores all the private context for the codec.
47 */
48struct xvid_context {
49    void *encoder_handle;          /** Handle for Xvid encoder */
50    int xsize, ysize;              /** Frame size */
51    int vop_flags;                 /** VOP flags for Xvid encoder */
52    int vol_flags;                 /** VOL flags for Xvid encoder */
53    int me_flags;                  /** Motion Estimation flags */
54    int qscale;                    /** Do we use constant scale? */
55    int quicktime_format;          /** Are we in a QT-based format? */
56    AVFrame encoded_picture;       /** Encoded frame information */
57    char *twopassbuffer;           /** Character buffer for two-pass */
58    char *old_twopassbuffer;       /** Old character buffer (two-pass) */
59    char *twopassfile;             /** second pass temp file name */
60    unsigned char *intra_matrix;   /** P-Frame Quant Matrix */
61    unsigned char *inter_matrix;   /** I-Frame Quant Matrix */
62};
63
64/**
65 * Structure for the private first-pass plugin.
66 */
67struct xvid_ff_pass1 {
68    int     version;                /** Xvid version */
69    struct xvid_context *context;        /** Pointer to private context */
70};
71
72/* Prototypes - See function implementation for details */
73int xvid_strip_vol_header(AVCodecContext *avctx, unsigned char *frame, unsigned int header_len, unsigned int frame_len);
74int xvid_ff_2pass(void *ref, int opt, void *p1, void *p2);
75void xvid_correct_framerate(AVCodecContext *avctx);
76
77/**
78 * Creates the private context for the encoder.
79 * All buffers are allocated, settings are loaded from the user,
80 * and the encoder context created.
81 *
82 * @param avctx AVCodecContext pointer to context
83 * @return Returns 0 on success, -1 on failure
84 */
85static av_cold int xvid_encode_init(AVCodecContext *avctx)  {
86    int xerr, i;
87    int xvid_flags = avctx->flags;
88    struct xvid_context *x = avctx->priv_data;
89    uint16_t *intra, *inter;
90    int fd;
91
92    xvid_plugin_single_t single;
93    struct xvid_ff_pass1 rc2pass1;
94    xvid_plugin_2pass2_t rc2pass2;
95    xvid_gbl_init_t xvid_gbl_init;
96    xvid_enc_create_t xvid_enc_create;
97    xvid_enc_plugin_t plugins[7];
98
99    /* Bring in VOP flags from ffmpeg command-line */
100    x->vop_flags = XVID_VOP_HALFPEL; /* Bare minimum quality */
101    if( xvid_flags & CODEC_FLAG_4MV )
102        x->vop_flags |= XVID_VOP_INTER4V; /* Level 3 */
103    if( avctx->trellis
104        )
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#if ARCH_PPC
171    /* Xvid's PPC support is borked, use libavcodec to detect */
172#if HAVE_ALTIVEC
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 */
198    xvid_enc_create.zones = NULL;
199    xvid_enc_create.num_zones = 0;
200
201    xvid_enc_create.num_threads = avctx->thread_count;
202
203    xvid_enc_create.plugins = plugins;
204    xvid_enc_create.num_plugins = 0;
205
206    /* Initialize Buffers */
207    x->twopassbuffer = NULL;
208    x->old_twopassbuffer = NULL;
209    x->twopassfile = NULL;
210
211    if( xvid_flags & CODEC_FLAG_PASS1 ) {
212        memset(&rc2pass1, 0, sizeof(struct xvid_ff_pass1));
213        rc2pass1.version = XVID_VERSION;
214        rc2pass1.context = x;
215        x->twopassbuffer = av_malloc(BUFFER_SIZE);
216        x->old_twopassbuffer = av_malloc(BUFFER_SIZE);
217        if( x->twopassbuffer == NULL || x->old_twopassbuffer == NULL ) {
218            av_log(avctx, AV_LOG_ERROR,
219                "Xvid: Cannot allocate 2-pass log buffers\n");
220            return -1;
221        }
222        x->twopassbuffer[0] = x->old_twopassbuffer[0] = 0;
223
224        plugins[xvid_enc_create.num_plugins].func = xvid_ff_2pass;
225        plugins[xvid_enc_create.num_plugins].param = &rc2pass1;
226        xvid_enc_create.num_plugins++;
227    } else if( xvid_flags & CODEC_FLAG_PASS2 ) {
228        memset(&rc2pass2, 0, sizeof(xvid_plugin_2pass2_t));
229        rc2pass2.version = XVID_VERSION;
230        rc2pass2.bitrate = avctx->bit_rate;
231
232        fd = av_tempfile("xvidff.", &(x->twopassfile));
233        if( fd == -1 ) {
234            av_log(avctx, AV_LOG_ERROR,
235                "Xvid: Cannot write 2-pass pipe\n");
236            return -1;
237        }
238
239        if( avctx->stats_in == NULL ) {
240            av_log(avctx, AV_LOG_ERROR,
241                "Xvid: No 2-pass information loaded for second pass\n");
242            return -1;
243        }
244
245        if( strlen(avctx->stats_in) >
246              write(fd, avctx->stats_in, strlen(avctx->stats_in)) ) {
247            close(fd);
248            av_log(avctx, AV_LOG_ERROR,
249                "Xvid: Cannot write to 2-pass pipe\n");
250            return -1;
251        }
252
253        close(fd);
254        rc2pass2.filename = x->twopassfile;
255        plugins[xvid_enc_create.num_plugins].func = xvid_plugin_2pass2;
256        plugins[xvid_enc_create.num_plugins].param = &rc2pass2;
257        xvid_enc_create.num_plugins++;
258    } else if( !(xvid_flags & CODEC_FLAG_QSCALE) ) {
259        /* Single Pass Bitrate Control! */
260        memset(&single, 0, sizeof(xvid_plugin_single_t));
261        single.version = XVID_VERSION;
262        single.bitrate = avctx->bit_rate;
263
264        plugins[xvid_enc_create.num_plugins].func = xvid_plugin_single;
265        plugins[xvid_enc_create.num_plugins].param = &single;
266        xvid_enc_create.num_plugins++;
267    }
268
269    /* Luminance Masking */
270    if( 0.0 != avctx->lumi_masking ) {
271        plugins[xvid_enc_create.num_plugins].func = xvid_plugin_lumimasking;
272        plugins[xvid_enc_create.num_plugins].param = NULL;
273        xvid_enc_create.num_plugins++;
274    }
275
276    /* Frame Rate and Key Frames */
277    xvid_correct_framerate(avctx);
278    xvid_enc_create.fincr = avctx->time_base.num;
279    xvid_enc_create.fbase = avctx->time_base.den;
280    if( avctx->gop_size > 0 )
281        xvid_enc_create.max_key_interval = avctx->gop_size;
282    else
283        xvid_enc_create.max_key_interval = 240; /* Xvid's best default */
284
285    /* Quants */
286    if( xvid_flags & CODEC_FLAG_QSCALE ) x->qscale = 1;
287    else x->qscale = 0;
288
289    xvid_enc_create.min_quant[0] = avctx->qmin;
290    xvid_enc_create.min_quant[1] = avctx->qmin;
291    xvid_enc_create.min_quant[2] = avctx->qmin;
292    xvid_enc_create.max_quant[0] = avctx->qmax;
293    xvid_enc_create.max_quant[1] = avctx->qmax;
294    xvid_enc_create.max_quant[2] = avctx->qmax;
295
296    /* Quant Matrices */
297    x->intra_matrix = x->inter_matrix = NULL;
298    if( avctx->mpeg_quant )
299       x->vol_flags |= XVID_VOL_MPEGQUANT;
300    if( (avctx->intra_matrix || avctx->inter_matrix) ) {
301       x->vol_flags |= XVID_VOL_MPEGQUANT;
302
303       if( avctx->intra_matrix ) {
304           intra = avctx->intra_matrix;
305           x->intra_matrix = av_malloc(sizeof(unsigned char) * 64);
306       } else
307           intra = NULL;
308       if( avctx->inter_matrix ) {
309           inter = avctx->inter_matrix;
310           x->inter_matrix = av_malloc(sizeof(unsigned char) * 64);
311       } else
312           inter = NULL;
313
314       for( i = 0; i < 64; i++ ) {
315           if( intra )
316               x->intra_matrix[i] = (unsigned char)intra[i];
317           if( inter )
318               x->inter_matrix[i] = (unsigned char)inter[i];
319       }
320    }
321
322    /* Misc Settings */
323    xvid_enc_create.frame_drop_ratio = 0;
324    xvid_enc_create.global = 0;
325    if( xvid_flags & CODEC_FLAG_CLOSED_GOP )
326        xvid_enc_create.global |= XVID_GLOBAL_CLOSED_GOP;
327
328    /* Determines which codec mode we are operating in */
329    avctx->extradata = NULL;
330    avctx->extradata_size = 0;
331    if( xvid_flags & CODEC_FLAG_GLOBAL_HEADER ) {
332        /* In this case, we are claiming to be MPEG4 */
333        x->quicktime_format = 1;
334        avctx->codec_id = CODEC_ID_MPEG4;
335    } else {
336        /* We are claiming to be Xvid */
337        x->quicktime_format = 0;
338        if(!avctx->codec_tag)
339            avctx->codec_tag = AV_RL32("xvid");
340    }
341
342    /* Bframes */
343    xvid_enc_create.max_bframes = avctx->max_b_frames;
344    xvid_enc_create.bquant_offset = 100 * avctx->b_quant_offset;
345    xvid_enc_create.bquant_ratio = 100 * avctx->b_quant_factor;
346    if( avctx->max_b_frames > 0  && !x->quicktime_format ) xvid_enc_create.global |= XVID_GLOBAL_PACKED;
347
348    /* Create encoder context */
349    xerr = xvid_encore(NULL, XVID_ENC_CREATE, &xvid_enc_create, NULL);
350    if( xerr ) {
351        av_log(avctx, AV_LOG_ERROR, "Xvid: Could not create encoder reference\n");
352        return -1;
353    }
354
355    x->encoder_handle = xvid_enc_create.handle;
356    avctx->coded_frame = &x->encoded_picture;
357
358    return 0;
359}
360
361/**
362 * Encodes a single frame.
363 *
364 * @param avctx AVCodecContext pointer to context
365 * @param frame Pointer to encoded frame buffer
366 * @param buf_size Size of encoded frame buffer
367 * @param data Pointer to AVFrame of unencoded frame
368 * @return Returns 0 on success, -1 on failure
369 */
370static int xvid_encode_frame(AVCodecContext *avctx,
371                         unsigned char *frame, int buf_size, void *data) {
372    int xerr, i;
373    char *tmp;
374    struct xvid_context *x = avctx->priv_data;
375    AVFrame *picture = data;
376    AVFrame *p = &(x->encoded_picture);
377
378    xvid_enc_frame_t xvid_enc_frame;
379    xvid_enc_stats_t xvid_enc_stats;
380
381    /* Start setting up the frame */
382    memset(&xvid_enc_frame, 0, sizeof(xvid_enc_frame));
383    xvid_enc_frame.version = XVID_VERSION;
384    memset(&xvid_enc_stats, 0, sizeof(xvid_enc_stats));
385    xvid_enc_stats.version = XVID_VERSION;
386    *p = *picture;
387
388    /* Let Xvid know where to put the frame. */
389    xvid_enc_frame.bitstream = frame;
390    xvid_enc_frame.length = buf_size;
391
392    /* Initialize input image fields */
393    if( avctx->pix_fmt != PIX_FMT_YUV420P ) {
394        av_log(avctx, AV_LOG_ERROR, "Xvid: Color spaces other than 420p not supported\n");
395        return -1;
396    }
397
398    xvid_enc_frame.input.csp = XVID_CSP_PLANAR; /* YUV420P */
399
400    for( i = 0; i < 4; i++ ) {
401        xvid_enc_frame.input.plane[i] = picture->data[i];
402        xvid_enc_frame.input.stride[i] = picture->linesize[i];
403    }
404
405    /* Encoder Flags */
406    xvid_enc_frame.vop_flags = x->vop_flags;
407    xvid_enc_frame.vol_flags = x->vol_flags;
408    xvid_enc_frame.motion = x->me_flags;
409    xvid_enc_frame.type = XVID_TYPE_AUTO;
410
411    /* Pixel aspect ratio setting */
412    if (avctx->sample_aspect_ratio.num < 1 || avctx->sample_aspect_ratio.num > 255 ||
413        avctx->sample_aspect_ratio.den < 1 || avctx->sample_aspect_ratio.den > 255) {
414        av_log(avctx, AV_LOG_ERROR, "Invalid pixel aspect ratio %i/%i\n",
415               avctx->sample_aspect_ratio.num, avctx->sample_aspect_ratio.den);
416        return -1;
417    }
418    xvid_enc_frame.par = XVID_PAR_EXT;
419    xvid_enc_frame.par_width  = avctx->sample_aspect_ratio.num;
420    xvid_enc_frame.par_height = avctx->sample_aspect_ratio.den;
421
422    /* Quant Setting */
423    if( x->qscale ) xvid_enc_frame.quant = picture->quality / FF_QP2LAMBDA;
424    else xvid_enc_frame.quant = 0;
425
426    /* Matrices */
427    xvid_enc_frame.quant_intra_matrix = x->intra_matrix;
428    xvid_enc_frame.quant_inter_matrix = x->inter_matrix;
429
430    /* Encode */
431    xerr = xvid_encore(x->encoder_handle, XVID_ENC_ENCODE,
432        &xvid_enc_frame, &xvid_enc_stats);
433
434    /* Two-pass log buffer swapping */
435    avctx->stats_out = NULL;
436    if( x->twopassbuffer ) {
437        tmp = x->old_twopassbuffer;
438        x->old_twopassbuffer = x->twopassbuffer;
439        x->twopassbuffer = tmp;
440        x->twopassbuffer[0] = 0;
441        if( x->old_twopassbuffer[0] != 0 ) {
442            avctx->stats_out = x->old_twopassbuffer;
443        }
444    }
445
446    if( 0 <= xerr ) {
447        p->quality = xvid_enc_stats.quant * FF_QP2LAMBDA;
448        if( xvid_enc_stats.type == XVID_TYPE_PVOP )
449            p->pict_type = FF_P_TYPE;
450        else if( xvid_enc_stats.type == XVID_TYPE_BVOP )
451            p->pict_type = FF_B_TYPE;
452        else if( xvid_enc_stats.type == XVID_TYPE_SVOP )
453            p->pict_type = FF_S_TYPE;
454        else
455            p->pict_type = FF_I_TYPE;
456        if( xvid_enc_frame.out_flags & XVID_KEYFRAME ) {
457            p->key_frame = 1;
458            if( x->quicktime_format )
459                return xvid_strip_vol_header(avctx, frame,
460                    xvid_enc_stats.hlength, xerr);
461         } else
462            p->key_frame = 0;
463
464        return xerr;
465    } else {
466        av_log(avctx, AV_LOG_ERROR, "Xvid: Encoding Error Occurred: %i\n", xerr);
467        return -1;
468    }
469}
470
471/**
472 * Destroys the private context for the encoder.
473 * All buffers are freed, and the Xvid encoder context is destroyed.
474 *
475 * @param avctx AVCodecContext pointer to context
476 * @return Returns 0, success guaranteed
477 */
478static av_cold int xvid_encode_close(AVCodecContext *avctx) {
479    struct xvid_context *x = avctx->priv_data;
480
481    xvid_encore(x->encoder_handle, XVID_ENC_DESTROY, NULL, NULL);
482
483    if( avctx->extradata != NULL )
484        av_freep(&avctx->extradata);
485    if( x->twopassbuffer != NULL ) {
486        av_free(x->twopassbuffer);
487        av_free(x->old_twopassbuffer);
488    }
489    if( x->twopassfile != NULL )
490        av_free(x->twopassfile);
491    if( x->intra_matrix != NULL )
492        av_free(x->intra_matrix);
493    if( x->inter_matrix != NULL )
494        av_free(x->inter_matrix);
495
496    return 0;
497}
498
499/**
500 * Routine to create a global VO/VOL header for MP4 container.
501 * What we do here is extract the header from the Xvid bitstream
502 * as it is encoded. We also strip the repeated headers from the
503 * bitstream when a global header is requested for MPEG-4 ISO
504 * compliance.
505 *
506 * @param avctx AVCodecContext pointer to context
507 * @param frame Pointer to encoded frame data
508 * @param header_len Length of header to search
509 * @param frame_len Length of encoded frame data
510 * @return Returns new length of frame data
511 */
512int xvid_strip_vol_header(AVCodecContext *avctx,
513                  unsigned char *frame,
514                  unsigned int header_len,
515                  unsigned int frame_len) {
516    int vo_len = 0, i;
517
518    for( i = 0; i < header_len - 3; i++ ) {
519        if( frame[i] == 0x00 &&
520            frame[i+1] == 0x00 &&
521            frame[i+2] == 0x01 &&
522            frame[i+3] == 0xB6 ) {
523            vo_len = i;
524            break;
525        }
526    }
527
528    if( vo_len > 0 ) {
529        /* We need to store the header, so extract it */
530        if( avctx->extradata == NULL ) {
531            avctx->extradata = av_malloc(vo_len);
532            memcpy(avctx->extradata, frame, vo_len);
533            avctx->extradata_size = vo_len;
534        }
535        /* Less dangerous now, memmove properly copies the two
536           chunks of overlapping data */
537        memmove(frame, &(frame[vo_len]), frame_len - vo_len);
538        return frame_len - vo_len;
539    } else
540        return frame_len;
541}
542
543/**
544 * Routine to correct a possibly erroneous framerate being fed to us.
545 * Xvid currently chokes on framerates where the ticks per frame is
546 * extremely large. This function works to correct problems in this area
547 * by estimating a new framerate and taking the simpler fraction of
548 * the two presented.
549 *
550 * @param avctx Context that contains the framerate to correct.
551 */
552void xvid_correct_framerate(AVCodecContext *avctx) {
553    int frate, fbase;
554    int est_frate, est_fbase;
555    int gcd;
556    float est_fps, fps;
557
558    frate = avctx->time_base.den;
559    fbase = avctx->time_base.num;
560
561    gcd = av_gcd(frate, fbase);
562    if( gcd > 1 ) {
563        frate /= gcd;
564        fbase /= gcd;
565    }
566
567    if( frate <= 65000 && fbase <= 65000 ) {
568        avctx->time_base.den = frate;
569        avctx->time_base.num = fbase;
570        return;
571    }
572
573    fps = (float)frate / (float)fbase;
574    est_fps = roundf(fps * 1000.0) / 1000.0;
575
576    est_frate = (int)est_fps;
577    if( est_fps > (int)est_fps ) {
578        est_frate = (est_frate + 1) * 1000;
579        est_fbase = (int)roundf((float)est_frate / est_fps);
580    } else
581        est_fbase = 1;
582
583    gcd = av_gcd(est_frate, est_fbase);
584    if( gcd > 1 ) {
585        est_frate /= gcd;
586        est_fbase /= gcd;
587    }
588
589    if( fbase > est_fbase ) {
590        avctx->time_base.den = est_frate;
591        avctx->time_base.num = est_fbase;
592        av_log(avctx, AV_LOG_DEBUG,
593            "Xvid: framerate re-estimated: %.2f, %.3f%% correction\n",
594            est_fps, (((est_fps - fps)/fps) * 100.0));
595    } else {
596        avctx->time_base.den = frate;
597        avctx->time_base.num = fbase;
598    }
599}
600
601/*
602 * Xvid 2-Pass Kludge Section
603 *
604 * Xvid's default 2-pass doesn't allow us to create data as we need to, so
605 * this section spends time replacing the first pass plugin so we can write
606 * statistic information as libavcodec requests in. We have another kludge
607 * that allows us to pass data to the second pass in Xvid without a custom
608 * rate-control plugin.
609 */
610
611/**
612 * Initializes the two-pass plugin and context.
613 *
614 * @param param Input construction parameter structure
615 * @param handle Private context handle
616 * @return Returns XVID_ERR_xxxx on failure, or 0 on success.
617 */
618static int xvid_ff_2pass_create(xvid_plg_create_t * param,
619                                void ** handle) {
620    struct xvid_ff_pass1 *x = (struct xvid_ff_pass1 *)param->param;
621    char *log = x->context->twopassbuffer;
622
623    /* Do a quick bounds check */
624    if( log == NULL )
625        return XVID_ERR_FAIL;
626
627    /* We use snprintf() */
628    /* This is because we can safely prevent a buffer overflow */
629    log[0] = 0;
630    snprintf(log, BUFFER_REMAINING(log),
631        "# ffmpeg 2-pass log file, using xvid codec\n");
632    snprintf(BUFFER_CAT(log), BUFFER_REMAINING(log),
633        "# Do not modify. libxvidcore version: %d.%d.%d\n\n",
634        XVID_VERSION_MAJOR(XVID_VERSION),
635        XVID_VERSION_MINOR(XVID_VERSION),
636        XVID_VERSION_PATCH(XVID_VERSION));
637
638    *handle = x->context;
639    return 0;
640}
641
642/**
643 * Destroys the two-pass plugin context.
644 *
645 * @param ref Context pointer for the plugin
646 * @param param Destrooy context
647 * @return Returns 0, success guaranteed
648 */
649static int xvid_ff_2pass_destroy(struct xvid_context *ref,
650                                xvid_plg_destroy_t *param) {
651    /* Currently cannot think of anything to do on destruction */
652    /* Still, the framework should be here for reference/use */
653    if( ref->twopassbuffer != NULL )
654        ref->twopassbuffer[0] = 0;
655    return 0;
656}
657
658/**
659 * Enables fast encode mode during the first pass.
660 *
661 * @param ref Context pointer for the plugin
662 * @param param Frame data
663 * @return Returns 0, success guaranteed
664 */
665static int xvid_ff_2pass_before(struct xvid_context *ref,
666                                xvid_plg_data_t *param) {
667    int motion_remove;
668    int motion_replacements;
669    int vop_remove;
670
671    /* Nothing to do here, result is changed too much */
672    if( param->zone && param->zone->mode == XVID_ZONE_QUANT )
673        return 0;
674
675    /* We can implement a 'turbo' first pass mode here */
676    param->quant = 2;
677
678    /* Init values */
679    motion_remove = ~XVID_ME_CHROMA_PVOP &
680                    ~XVID_ME_CHROMA_BVOP &
681                    ~XVID_ME_EXTSEARCH16 &
682                    ~XVID_ME_ADVANCEDDIAMOND16;
683    motion_replacements = XVID_ME_FAST_MODEINTERPOLATE |
684                          XVID_ME_SKIP_DELTASEARCH |
685                          XVID_ME_FASTREFINE16 |
686                          XVID_ME_BFRAME_EARLYSTOP;
687    vop_remove = ~XVID_VOP_MODEDECISION_RD &
688                 ~XVID_VOP_FAST_MODEDECISION_RD &
689                 ~XVID_VOP_TRELLISQUANT &
690                 ~XVID_VOP_INTER4V &
691                 ~XVID_VOP_HQACPRED;
692
693    param->vol_flags &= ~XVID_VOL_GMC;
694    param->vop_flags &= vop_remove;
695    param->motion_flags &= motion_remove;
696    param->motion_flags |= motion_replacements;
697
698    return 0;
699}
700
701/**
702 * Captures statistic data and writes it during first pass.
703 *
704 * @param ref Context pointer for the plugin
705 * @param param Statistic data
706 * @return Returns XVID_ERR_xxxx on failure, or 0 on success
707 */
708static int xvid_ff_2pass_after(struct xvid_context *ref,
709                                xvid_plg_data_t *param) {
710    char *log = ref->twopassbuffer;
711    char *frame_types = " ipbs";
712    char frame_type;
713
714    /* Quick bounds check */
715    if( log == NULL )
716        return XVID_ERR_FAIL;
717
718    /* Convert the type given to us into a character */
719    if( param->type < 5 && param->type > 0 ) {
720        frame_type = frame_types[param->type];
721    } else {
722        return XVID_ERR_FAIL;
723    }
724
725    snprintf(BUFFER_CAT(log), BUFFER_REMAINING(log),
726        "%c %d %d %d %d %d %d\n",
727        frame_type, param->stats.quant, param->stats.kblks, param->stats.mblks,
728        param->stats.ublks, param->stats.length, param->stats.hlength);
729
730    return 0;
731}
732
733/**
734 * Dispatch function for our custom plugin.
735 * This handles the dispatch for the Xvid plugin. It passes data
736 * on to other functions for actual processing.
737 *
738 * @param ref Context pointer for the plugin
739 * @param cmd The task given for us to complete
740 * @param p1 First parameter (varies)
741 * @param p2 Second parameter (varies)
742 * @return Returns XVID_ERR_xxxx on failure, or 0 on success
743 */
744int xvid_ff_2pass(void *ref, int cmd, void *p1, void *p2) {
745    switch( cmd ) {
746        case XVID_PLG_INFO:
747        case XVID_PLG_FRAME:
748            return 0;
749
750        case XVID_PLG_BEFORE:
751            return xvid_ff_2pass_before(ref, p1);
752
753        case XVID_PLG_CREATE:
754            return xvid_ff_2pass_create(p1, p2);
755
756        case XVID_PLG_AFTER:
757            return xvid_ff_2pass_after(ref, p1);
758
759        case XVID_PLG_DESTROY:
760            return xvid_ff_2pass_destroy(ref, p1);
761
762        default:
763            return XVID_ERR_FAIL;
764    }
765}
766
767/**
768 * Xvid codec definition for libavcodec.
769 */
770AVCodec libxvid_encoder = {
771    "libxvid",
772    AVMEDIA_TYPE_VIDEO,
773    CODEC_ID_MPEG4,
774    sizeof(struct xvid_context),
775    xvid_encode_init,
776    xvid_encode_frame,
777    xvid_encode_close,
778    .pix_fmts= (const enum PixelFormat[]){PIX_FMT_YUV420P, PIX_FMT_NONE},
779    .long_name= NULL_IF_CONFIG_SMALL("libxvidcore MPEG-4 part 2"),
780};
781