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