2 * Interface to xvidcore for mpeg4 encoding
3 * Copyright (c) 2004 Adam Thayer <krevnik@comcast.net>
5 * This file is part of Libav.
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.
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.
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
24 * Interface to xvidcore for MPEG-4 compliant encoding.
25 * @author Adam Thayer (krevnik@comcast.net)
31 #include "libavutil/cpu.h"
32 #include "libavutil/intreadwrite.h"
33 #include "libavutil/mathematics.h"
34 #include "libxvid_internal.h"
35 #include "mpegvideo.h"
41 * Buffer management macros.
43 #define BUFFER_SIZE 1024
44 #define BUFFER_REMAINING(x) (BUFFER_SIZE - strlen(x))
45 #define BUFFER_CAT(x) (&((x)[strlen(x)]))
48 * Structure for the private Xvid context.
49 * This stores all the private context for the codec.
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 */
69 * Structure for the private first-pass plugin.
71 struct xvid_ff_pass1 {
72 int version; /**< Xvid version */
73 struct xvid_context *context; /**< Pointer to private context */
77 * Xvid 2-Pass Kludge Section
79 * Xvid's default 2-pass doesn't allow us to create data as we need to, so
80 * this section spends time replacing the first pass plugin so we can write
81 * statistic information as libavcodec requests in. We have another kludge
82 * that allows us to pass data to the second pass in Xvid without a custom
83 * rate-control plugin.
86 /* Wrapper to work around the lack of mkstemp() on mingw.
87 * Also, tries to create file in /tmp first, if possible.
88 * *prefix can be a character constant; *filename will be allocated internally.
89 * @return file descriptor of opened file (or -1 on error)
90 * and opened file name in **filename. */
91 int ff_tempfile(const char *prefix, char **filename) {
94 *filename = tempnam(".", prefix);
96 size_t len = strlen(prefix) + 12; /* room for "/tmp/" and "XXXXXX\0" */
97 *filename = av_malloc(len);
99 /* -----common section-----*/
100 if (*filename == NULL) {
101 av_log(NULL, AV_LOG_ERROR, "ff_tempfile: Cannot allocate file name\n");
105 fd = open(*filename, O_RDWR | O_BINARY | O_CREAT, 0444);
107 snprintf(*filename, len, "/tmp/%sXXXXXX", prefix);
108 fd = mkstemp(*filename);
110 snprintf(*filename, len, "./%sXXXXXX", prefix);
111 fd = mkstemp(*filename);
114 /* -----common section-----*/
116 av_log(NULL, AV_LOG_ERROR, "ff_tempfile: Cannot open temporary file %s\n", *filename);
119 return fd; /* success */
123 * Initialize the two-pass plugin and context.
125 * @param param Input construction parameter structure
126 * @param handle Private context handle
127 * @return Returns XVID_ERR_xxxx on failure, or 0 on success.
129 static int xvid_ff_2pass_create(xvid_plg_create_t * param,
131 struct xvid_ff_pass1 *x = (struct xvid_ff_pass1 *)param->param;
132 char *log = x->context->twopassbuffer;
134 /* Do a quick bounds check */
136 return XVID_ERR_FAIL;
138 /* We use snprintf() */
139 /* This is because we can safely prevent a buffer overflow */
141 snprintf(log, BUFFER_REMAINING(log),
142 "# avconv 2-pass log file, using xvid codec\n");
143 snprintf(BUFFER_CAT(log), BUFFER_REMAINING(log),
144 "# Do not modify. libxvidcore version: %d.%d.%d\n\n",
145 XVID_VERSION_MAJOR(XVID_VERSION),
146 XVID_VERSION_MINOR(XVID_VERSION),
147 XVID_VERSION_PATCH(XVID_VERSION));
149 *handle = x->context;
154 * Destroy the two-pass plugin context.
156 * @param ref Context pointer for the plugin
157 * @param param Destrooy context
158 * @return Returns 0, success guaranteed
160 static int xvid_ff_2pass_destroy(struct xvid_context *ref,
161 xvid_plg_destroy_t *param) {
162 /* Currently cannot think of anything to do on destruction */
163 /* Still, the framework should be here for reference/use */
164 if( ref->twopassbuffer != NULL )
165 ref->twopassbuffer[0] = 0;
170 * Enable fast encode mode during the first pass.
172 * @param ref Context pointer for the plugin
173 * @param param Frame data
174 * @return Returns 0, success guaranteed
176 static int xvid_ff_2pass_before(struct xvid_context *ref,
177 xvid_plg_data_t *param) {
179 int motion_replacements;
182 /* Nothing to do here, result is changed too much */
183 if( param->zone && param->zone->mode == XVID_ZONE_QUANT )
186 /* We can implement a 'turbo' first pass mode here */
190 motion_remove = ~XVID_ME_CHROMA_PVOP &
191 ~XVID_ME_CHROMA_BVOP &
192 ~XVID_ME_EXTSEARCH16 &
193 ~XVID_ME_ADVANCEDDIAMOND16;
194 motion_replacements = XVID_ME_FAST_MODEINTERPOLATE |
195 XVID_ME_SKIP_DELTASEARCH |
196 XVID_ME_FASTREFINE16 |
197 XVID_ME_BFRAME_EARLYSTOP;
198 vop_remove = ~XVID_VOP_MODEDECISION_RD &
199 ~XVID_VOP_FAST_MODEDECISION_RD &
200 ~XVID_VOP_TRELLISQUANT &
204 param->vol_flags &= ~XVID_VOL_GMC;
205 param->vop_flags &= vop_remove;
206 param->motion_flags &= motion_remove;
207 param->motion_flags |= motion_replacements;
213 * Capture statistic data and write it during first pass.
215 * @param ref Context pointer for the plugin
216 * @param param Statistic data
217 * @return Returns XVID_ERR_xxxx on failure, or 0 on success
219 static int xvid_ff_2pass_after(struct xvid_context *ref,
220 xvid_plg_data_t *param) {
221 char *log = ref->twopassbuffer;
222 const char *frame_types = " ipbs";
225 /* Quick bounds check */
227 return XVID_ERR_FAIL;
229 /* Convert the type given to us into a character */
230 if( param->type < 5 && param->type > 0 ) {
231 frame_type = frame_types[param->type];
233 return XVID_ERR_FAIL;
236 snprintf(BUFFER_CAT(log), BUFFER_REMAINING(log),
237 "%c %d %d %d %d %d %d\n",
238 frame_type, param->stats.quant, param->stats.kblks, param->stats.mblks,
239 param->stats.ublks, param->stats.length, param->stats.hlength);
245 * Dispatch function for our custom plugin.
246 * This handles the dispatch for the Xvid plugin. It passes data
247 * on to other functions for actual processing.
249 * @param ref Context pointer for the plugin
250 * @param cmd The task given for us to complete
251 * @param p1 First parameter (varies)
252 * @param p2 Second parameter (varies)
253 * @return Returns XVID_ERR_xxxx on failure, or 0 on success
255 static int xvid_ff_2pass(void *ref, int cmd, void *p1, void *p2)
262 case XVID_PLG_BEFORE:
263 return xvid_ff_2pass_before(ref, p1);
265 case XVID_PLG_CREATE:
266 return xvid_ff_2pass_create(p1, p2);
269 return xvid_ff_2pass_after(ref, p1);
271 case XVID_PLG_DESTROY:
272 return xvid_ff_2pass_destroy(ref, p1);
275 return XVID_ERR_FAIL;
280 * Routine to create a global VO/VOL header for MP4 container.
281 * What we do here is extract the header from the Xvid bitstream
282 * as it is encoded. We also strip the repeated headers from the
283 * bitstream when a global header is requested for MPEG-4 ISO
286 * @param avctx AVCodecContext pointer to context
287 * @param frame Pointer to encoded frame data
288 * @param header_len Length of header to search
289 * @param frame_len Length of encoded frame data
290 * @return Returns new length of frame data
292 static int xvid_strip_vol_header(AVCodecContext *avctx,
294 unsigned int header_len,
295 unsigned int frame_len) {
298 for( i = 0; i < header_len - 3; i++ ) {
299 if( pkt->data[i] == 0x00 &&
300 pkt->data[i+1] == 0x00 &&
301 pkt->data[i+2] == 0x01 &&
302 pkt->data[i+3] == 0xB6 ) {
309 /* We need to store the header, so extract it */
310 if( avctx->extradata == NULL ) {
311 avctx->extradata = av_malloc(vo_len);
312 memcpy(avctx->extradata, pkt->data, vo_len);
313 avctx->extradata_size = vo_len;
315 /* Less dangerous now, memmove properly copies the two
316 chunks of overlapping data */
317 memmove(pkt->data, &pkt->data[vo_len], frame_len - vo_len);
318 pkt->size = frame_len - vo_len;
324 * Routine to correct a possibly erroneous framerate being fed to us.
325 * Xvid currently chokes on framerates where the ticks per frame is
326 * extremely large. This function works to correct problems in this area
327 * by estimating a new framerate and taking the simpler fraction of
330 * @param avctx Context that contains the framerate to correct.
332 static void xvid_correct_framerate(AVCodecContext *avctx)
335 int est_frate, est_fbase;
339 frate = avctx->time_base.den;
340 fbase = avctx->time_base.num;
342 gcd = av_gcd(frate, fbase);
348 if( frate <= 65000 && fbase <= 65000 ) {
349 avctx->time_base.den = frate;
350 avctx->time_base.num = fbase;
354 fps = (float)frate / (float)fbase;
355 est_fps = roundf(fps * 1000.0) / 1000.0;
357 est_frate = (int)est_fps;
358 if( est_fps > (int)est_fps ) {
359 est_frate = (est_frate + 1) * 1000;
360 est_fbase = (int)roundf((float)est_frate / est_fps);
364 gcd = av_gcd(est_frate, est_fbase);
370 if( fbase > est_fbase ) {
371 avctx->time_base.den = est_frate;
372 avctx->time_base.num = est_fbase;
373 av_log(avctx, AV_LOG_DEBUG,
374 "Xvid: framerate re-estimated: %.2f, %.3f%% correction\n",
375 est_fps, (((est_fps - fps)/fps) * 100.0));
377 avctx->time_base.den = frate;
378 avctx->time_base.num = fbase;
383 * Create the private context for the encoder.
384 * All buffers are allocated, settings are loaded from the user,
385 * and the encoder context created.
387 * @param avctx AVCodecContext pointer to context
388 * @return Returns 0 on success, -1 on failure
390 static av_cold int xvid_encode_init(AVCodecContext *avctx) {
392 int xvid_flags = avctx->flags;
393 struct xvid_context *x = avctx->priv_data;
394 uint16_t *intra, *inter;
397 xvid_plugin_single_t single = { 0 };
398 struct xvid_ff_pass1 rc2pass1 = { 0 };
399 xvid_plugin_2pass2_t rc2pass2 = { 0 };
400 xvid_gbl_init_t xvid_gbl_init = { 0 };
401 xvid_enc_create_t xvid_enc_create = { 0 };
402 xvid_enc_plugin_t plugins[7];
404 /* Bring in VOP flags from avconv command-line */
405 x->vop_flags = XVID_VOP_HALFPEL; /* Bare minimum quality */
406 if( xvid_flags & CODEC_FLAG_4MV )
407 x->vop_flags |= XVID_VOP_INTER4V; /* Level 3 */
410 x->vop_flags |= XVID_VOP_TRELLISQUANT; /* Level 5 */
411 if( xvid_flags & CODEC_FLAG_AC_PRED )
412 x->vop_flags |= XVID_VOP_HQACPRED; /* Level 6 */
413 if( xvid_flags & CODEC_FLAG_GRAY )
414 x->vop_flags |= XVID_VOP_GREYSCALE;
416 /* Decide which ME quality setting to use */
418 switch( avctx->me_method ) {
419 case ME_FULL: /* Quality 6 */
420 x->me_flags |= XVID_ME_EXTSEARCH16
421 | XVID_ME_EXTSEARCH8;
423 case ME_EPZS: /* Quality 4 */
424 x->me_flags |= XVID_ME_ADVANCEDDIAMOND8
425 | XVID_ME_HALFPELREFINE8
426 | XVID_ME_CHROMA_PVOP
427 | XVID_ME_CHROMA_BVOP;
429 case ME_LOG: /* Quality 2 */
432 x->me_flags |= XVID_ME_ADVANCEDDIAMOND16
433 | XVID_ME_HALFPELREFINE16;
435 case ME_ZERO: /* Quality 0 */
440 /* Decide how we should decide blocks */
441 switch( avctx->mb_decision ) {
443 x->vop_flags |= XVID_VOP_MODEDECISION_RD;
444 x->me_flags |= XVID_ME_HALFPELREFINE8_RD
445 | XVID_ME_QUARTERPELREFINE8_RD
446 | XVID_ME_EXTSEARCH_RD
447 | XVID_ME_CHECKPREDICTION_RD;
449 if( !(x->vop_flags & XVID_VOP_MODEDECISION_RD) )
450 x->vop_flags |= XVID_VOP_FAST_MODEDECISION_RD;
451 x->me_flags |= XVID_ME_HALFPELREFINE16_RD
452 | XVID_ME_QUARTERPELREFINE16_RD;
458 /* Bring in VOL flags from avconv command-line */
460 if( xvid_flags & CODEC_FLAG_GMC ) {
461 x->vol_flags |= XVID_VOL_GMC;
462 x->me_flags |= XVID_ME_GME_REFINE;
464 if( xvid_flags & CODEC_FLAG_QPEL ) {
465 x->vol_flags |= XVID_VOL_QUARTERPEL;
466 x->me_flags |= XVID_ME_QUARTERPELREFINE16;
467 if( x->vop_flags & XVID_VOP_INTER4V )
468 x->me_flags |= XVID_ME_QUARTERPELREFINE8;
471 xvid_gbl_init.version = XVID_VERSION;
472 xvid_gbl_init.debug = 0;
475 /* Xvid's PPC support is borked, use libavcodec to detect */
477 if (av_get_cpu_flags() & AV_CPU_FLAG_ALTIVEC) {
478 xvid_gbl_init.cpu_flags = XVID_CPU_FORCE | XVID_CPU_ALTIVEC;
481 xvid_gbl_init.cpu_flags = XVID_CPU_FORCE;
483 /* Xvid can detect on x86 */
484 xvid_gbl_init.cpu_flags = 0;
488 xvid_global(NULL, XVID_GBL_INIT, &xvid_gbl_init, NULL);
490 /* Create the encoder reference */
491 xvid_enc_create.version = XVID_VERSION;
493 /* Store the desired frame size */
494 xvid_enc_create.width = x->xsize = avctx->width;
495 xvid_enc_create.height = x->ysize = avctx->height;
497 /* Xvid can determine the proper profile to use */
498 /* xvid_enc_create.profile = XVID_PROFILE_S_L3; */
500 /* We don't use zones */
501 xvid_enc_create.zones = NULL;
502 xvid_enc_create.num_zones = 0;
504 xvid_enc_create.num_threads = avctx->thread_count;
506 xvid_enc_create.plugins = plugins;
507 xvid_enc_create.num_plugins = 0;
509 /* Initialize Buffers */
510 x->twopassbuffer = NULL;
511 x->old_twopassbuffer = NULL;
512 x->twopassfile = NULL;
514 if( xvid_flags & CODEC_FLAG_PASS1 ) {
515 rc2pass1.version = XVID_VERSION;
516 rc2pass1.context = x;
517 x->twopassbuffer = av_malloc(BUFFER_SIZE);
518 x->old_twopassbuffer = av_malloc(BUFFER_SIZE);
519 if( x->twopassbuffer == NULL || x->old_twopassbuffer == NULL ) {
520 av_log(avctx, AV_LOG_ERROR,
521 "Xvid: Cannot allocate 2-pass log buffers\n");
524 x->twopassbuffer[0] = x->old_twopassbuffer[0] = 0;
526 plugins[xvid_enc_create.num_plugins].func = xvid_ff_2pass;
527 plugins[xvid_enc_create.num_plugins].param = &rc2pass1;
528 xvid_enc_create.num_plugins++;
529 } else if( xvid_flags & CODEC_FLAG_PASS2 ) {
530 rc2pass2.version = XVID_VERSION;
531 rc2pass2.bitrate = avctx->bit_rate;
533 fd = ff_tempfile("xvidff.", &x->twopassfile);
535 av_log(avctx, AV_LOG_ERROR,
536 "Xvid: Cannot write 2-pass pipe\n");
540 if( avctx->stats_in == NULL ) {
541 av_log(avctx, AV_LOG_ERROR,
542 "Xvid: No 2-pass information loaded for second pass\n");
546 if( strlen(avctx->stats_in) >
547 write(fd, avctx->stats_in, strlen(avctx->stats_in)) ) {
549 av_log(avctx, AV_LOG_ERROR,
550 "Xvid: Cannot write to 2-pass pipe\n");
555 rc2pass2.filename = x->twopassfile;
556 plugins[xvid_enc_create.num_plugins].func = xvid_plugin_2pass2;
557 plugins[xvid_enc_create.num_plugins].param = &rc2pass2;
558 xvid_enc_create.num_plugins++;
559 } else if( !(xvid_flags & CODEC_FLAG_QSCALE) ) {
560 /* Single Pass Bitrate Control! */
561 single.version = XVID_VERSION;
562 single.bitrate = avctx->bit_rate;
564 plugins[xvid_enc_create.num_plugins].func = xvid_plugin_single;
565 plugins[xvid_enc_create.num_plugins].param = &single;
566 xvid_enc_create.num_plugins++;
569 /* Luminance Masking */
570 if( 0.0 != avctx->lumi_masking ) {
571 plugins[xvid_enc_create.num_plugins].func = xvid_plugin_lumimasking;
572 plugins[xvid_enc_create.num_plugins].param = NULL;
573 xvid_enc_create.num_plugins++;
576 /* Frame Rate and Key Frames */
577 xvid_correct_framerate(avctx);
578 xvid_enc_create.fincr = avctx->time_base.num;
579 xvid_enc_create.fbase = avctx->time_base.den;
580 if( avctx->gop_size > 0 )
581 xvid_enc_create.max_key_interval = avctx->gop_size;
583 xvid_enc_create.max_key_interval = 240; /* Xvid's best default */
586 if( xvid_flags & CODEC_FLAG_QSCALE ) x->qscale = 1;
589 xvid_enc_create.min_quant[0] = avctx->qmin;
590 xvid_enc_create.min_quant[1] = avctx->qmin;
591 xvid_enc_create.min_quant[2] = avctx->qmin;
592 xvid_enc_create.max_quant[0] = avctx->qmax;
593 xvid_enc_create.max_quant[1] = avctx->qmax;
594 xvid_enc_create.max_quant[2] = avctx->qmax;
597 x->intra_matrix = x->inter_matrix = NULL;
598 if( avctx->mpeg_quant )
599 x->vol_flags |= XVID_VOL_MPEGQUANT;
600 if( (avctx->intra_matrix || avctx->inter_matrix) ) {
601 x->vol_flags |= XVID_VOL_MPEGQUANT;
603 if( avctx->intra_matrix ) {
604 intra = avctx->intra_matrix;
605 x->intra_matrix = av_malloc(sizeof(unsigned char) * 64);
608 if( avctx->inter_matrix ) {
609 inter = avctx->inter_matrix;
610 x->inter_matrix = av_malloc(sizeof(unsigned char) * 64);
614 for( i = 0; i < 64; i++ ) {
616 x->intra_matrix[i] = (unsigned char)intra[i];
618 x->inter_matrix[i] = (unsigned char)inter[i];
623 xvid_enc_create.frame_drop_ratio = 0;
624 xvid_enc_create.global = 0;
625 if( xvid_flags & CODEC_FLAG_CLOSED_GOP )
626 xvid_enc_create.global |= XVID_GLOBAL_CLOSED_GOP;
628 /* Determines which codec mode we are operating in */
629 avctx->extradata = NULL;
630 avctx->extradata_size = 0;
631 if( xvid_flags & CODEC_FLAG_GLOBAL_HEADER ) {
632 /* In this case, we are claiming to be MPEG4 */
633 x->quicktime_format = 1;
634 avctx->codec_id = CODEC_ID_MPEG4;
636 /* We are claiming to be Xvid */
637 x->quicktime_format = 0;
638 if(!avctx->codec_tag)
639 avctx->codec_tag = AV_RL32("xvid");
643 xvid_enc_create.max_bframes = avctx->max_b_frames;
644 xvid_enc_create.bquant_offset = 100 * avctx->b_quant_offset;
645 xvid_enc_create.bquant_ratio = 100 * avctx->b_quant_factor;
646 if( avctx->max_b_frames > 0 && !x->quicktime_format ) xvid_enc_create.global |= XVID_GLOBAL_PACKED;
648 /* Create encoder context */
649 xerr = xvid_encore(NULL, XVID_ENC_CREATE, &xvid_enc_create, NULL);
651 av_log(avctx, AV_LOG_ERROR, "Xvid: Could not create encoder reference\n");
655 x->encoder_handle = xvid_enc_create.handle;
656 avctx->coded_frame = &x->encoded_picture;
662 * Encode a single frame.
664 * @param avctx AVCodecContext pointer to context
665 * @param frame Pointer to encoded frame buffer
666 * @param buf_size Size of encoded frame buffer
667 * @param data Pointer to AVFrame of unencoded frame
668 * @return Returns 0 on success, -1 on failure
670 static int xvid_encode_frame(AVCodecContext *avctx, AVPacket *pkt,
671 const AVFrame *picture, int *got_packet)
673 int xerr, i, ret, user_packet = !!pkt->data;
675 struct xvid_context *x = avctx->priv_data;
676 AVFrame *p = &x->encoded_picture;
677 int mb_width = (avctx->width + 15) / 16;
678 int mb_height = (avctx->height + 15) / 16;
680 xvid_enc_frame_t xvid_enc_frame = { 0 };
681 xvid_enc_stats_t xvid_enc_stats = { 0 };
684 (ret = av_new_packet(pkt, mb_width*mb_height*MAX_MB_BYTES + FF_MIN_BUFFER_SIZE)) < 0) {
685 av_log(avctx, AV_LOG_ERROR, "Error getting output packet.\n");
689 /* Start setting up the frame */
690 xvid_enc_frame.version = XVID_VERSION;
691 xvid_enc_stats.version = XVID_VERSION;
694 /* Let Xvid know where to put the frame. */
695 xvid_enc_frame.bitstream = pkt->data;
696 xvid_enc_frame.length = pkt->size;
698 /* Initialize input image fields */
699 if( avctx->pix_fmt != PIX_FMT_YUV420P ) {
700 av_log(avctx, AV_LOG_ERROR, "Xvid: Color spaces other than 420p not supported\n");
704 xvid_enc_frame.input.csp = XVID_CSP_PLANAR; /* YUV420P */
706 for( i = 0; i < 4; i++ ) {
707 xvid_enc_frame.input.plane[i] = picture->data[i];
708 xvid_enc_frame.input.stride[i] = picture->linesize[i];
712 xvid_enc_frame.vop_flags = x->vop_flags;
713 xvid_enc_frame.vol_flags = x->vol_flags;
714 xvid_enc_frame.motion = x->me_flags;
715 xvid_enc_frame.type =
716 picture->pict_type == AV_PICTURE_TYPE_I ? XVID_TYPE_IVOP :
717 picture->pict_type == AV_PICTURE_TYPE_P ? XVID_TYPE_PVOP :
718 picture->pict_type == AV_PICTURE_TYPE_B ? XVID_TYPE_BVOP :
721 /* Pixel aspect ratio setting */
722 if (avctx->sample_aspect_ratio.num < 1 || avctx->sample_aspect_ratio.num > 255 ||
723 avctx->sample_aspect_ratio.den < 1 || avctx->sample_aspect_ratio.den > 255) {
724 av_log(avctx, AV_LOG_ERROR, "Invalid pixel aspect ratio %i/%i\n",
725 avctx->sample_aspect_ratio.num, avctx->sample_aspect_ratio.den);
728 xvid_enc_frame.par = XVID_PAR_EXT;
729 xvid_enc_frame.par_width = avctx->sample_aspect_ratio.num;
730 xvid_enc_frame.par_height = avctx->sample_aspect_ratio.den;
733 if( x->qscale ) xvid_enc_frame.quant = picture->quality / FF_QP2LAMBDA;
734 else xvid_enc_frame.quant = 0;
737 xvid_enc_frame.quant_intra_matrix = x->intra_matrix;
738 xvid_enc_frame.quant_inter_matrix = x->inter_matrix;
741 xerr = xvid_encore(x->encoder_handle, XVID_ENC_ENCODE,
742 &xvid_enc_frame, &xvid_enc_stats);
744 /* Two-pass log buffer swapping */
745 avctx->stats_out = NULL;
746 if( x->twopassbuffer ) {
747 tmp = x->old_twopassbuffer;
748 x->old_twopassbuffer = x->twopassbuffer;
749 x->twopassbuffer = tmp;
750 x->twopassbuffer[0] = 0;
751 if( x->old_twopassbuffer[0] != 0 ) {
752 avctx->stats_out = x->old_twopassbuffer;
759 p->quality = xvid_enc_stats.quant * FF_QP2LAMBDA;
760 if( xvid_enc_stats.type == XVID_TYPE_PVOP )
761 p->pict_type = AV_PICTURE_TYPE_P;
762 else if( xvid_enc_stats.type == XVID_TYPE_BVOP )
763 p->pict_type = AV_PICTURE_TYPE_B;
764 else if( xvid_enc_stats.type == XVID_TYPE_SVOP )
765 p->pict_type = AV_PICTURE_TYPE_S;
767 p->pict_type = AV_PICTURE_TYPE_I;
768 if( xvid_enc_frame.out_flags & XVID_KEYFRAME ) {
770 pkt->flags |= AV_PKT_FLAG_KEY;
771 if( x->quicktime_format )
772 return xvid_strip_vol_header(avctx, pkt,
773 xvid_enc_stats.hlength, xerr);
785 av_log(avctx, AV_LOG_ERROR, "Xvid: Encoding Error Occurred: %i\n", xerr);
791 * Destroy the private context for the encoder.
792 * All buffers are freed, and the Xvid encoder context is destroyed.
794 * @param avctx AVCodecContext pointer to context
795 * @return Returns 0, success guaranteed
797 static av_cold int xvid_encode_close(AVCodecContext *avctx) {
798 struct xvid_context *x = avctx->priv_data;
800 xvid_encore(x->encoder_handle, XVID_ENC_DESTROY, NULL, NULL);
802 av_freep(&avctx->extradata);
803 if( x->twopassbuffer != NULL ) {
804 av_free(x->twopassbuffer);
805 av_free(x->old_twopassbuffer);
807 av_free(x->twopassfile);
808 av_free(x->intra_matrix);
809 av_free(x->inter_matrix);
815 * Xvid codec definition for libavcodec.
817 AVCodec ff_libxvid_encoder = {
819 .type = AVMEDIA_TYPE_VIDEO,
820 .id = CODEC_ID_MPEG4,
821 .priv_data_size = sizeof(struct xvid_context),
822 .init = xvid_encode_init,
823 .encode2 = xvid_encode_frame,
824 .close = xvid_encode_close,
825 .pix_fmts = (const enum PixelFormat[]){ PIX_FMT_YUV420P, PIX_FMT_NONE },
826 .long_name = NULL_IF_CONFIG_SMALL("libxvidcore MPEG-4 part 2"),