OSDN Git Service

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