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)
33 #include "libavutil/cpu.h"
34 #include "libavutil/internal.h"
35 #include "libavutil/intreadwrite.h"
36 #include "libavutil/mathematics.h"
37 #include "libavutil/opt.h"
42 #include "mpegutils.h"
45 * Buffer management macros.
47 #define BUFFER_SIZE 1024
48 #define BUFFER_REMAINING(x) (BUFFER_SIZE - strlen(x))
49 #define BUFFER_CAT(x) (&((x)[strlen(x)]))
52 * Structure for the private Xvid context.
53 * This stores all the private context for the codec.
56 AVClass *class; /**< Handle for Xvid encoder */
57 void *encoder_handle; /**< Handle for Xvid encoder */
58 int xsize; /**< Frame x size */
59 int ysize; /**< Frame y size */
60 int vop_flags; /**< VOP flags for Xvid encoder */
61 int vol_flags; /**< VOL flags for Xvid encoder */
62 int me_flags; /**< Motion Estimation flags */
63 int qscale; /**< Do we use constant scale? */
64 int quicktime_format; /**< Are we in a QT-based format? */
65 char *twopassbuffer; /**< Character buffer for two-pass */
66 char *old_twopassbuffer; /**< Old character buffer (two-pass) */
67 char *twopassfile; /**< second pass temp file name */
68 unsigned char *intra_matrix; /**< P-Frame Quant Matrix */
69 unsigned char *inter_matrix; /**< I-Frame Quant Matrix */
70 int lumi_aq; /**< Lumi masking as an aq method */
71 int variance_aq; /**< Variance adaptive quantization */
72 int ssim; /**< SSIM information display mode */
73 int ssim_acc; /**< SSIM accuracy. 0: accurate. 4: fast. */
75 int me_quality; /**< Motion estimation quality. 0: fast 6: best. */
79 * Structure for the private first-pass plugin.
81 struct xvid_ff_pass1 {
82 int version; /**< Xvid version */
83 struct xvid_context *context; /**< Pointer to private context */
87 * Xvid 2-Pass Kludge Section
89 * Xvid's default 2-pass doesn't allow us to create data as we need to, so
90 * this section spends time replacing the first pass plugin so we can write
91 * statistic information as libavcodec requests in. We have another kludge
92 * that allows us to pass data to the second pass in Xvid without a custom
93 * rate-control plugin.
97 * Initialize the two-pass plugin and context.
99 * @param param Input construction parameter structure
100 * @param handle Private context handle
101 * @return Returns XVID_ERR_xxxx on failure, or 0 on success.
103 static int xvid_ff_2pass_create(xvid_plg_create_t *param, void **handle)
105 struct xvid_ff_pass1 *x = (struct xvid_ff_pass1 *) param->param;
106 char *log = x->context->twopassbuffer;
108 /* Do a quick bounds check */
110 return XVID_ERR_FAIL;
112 /* We use snprintf() */
113 /* This is because we can safely prevent a buffer overflow */
115 snprintf(log, BUFFER_REMAINING(log),
116 "# avconv 2-pass log file, using xvid codec\n");
117 snprintf(BUFFER_CAT(log), BUFFER_REMAINING(log),
118 "# Do not modify. libxvidcore version: %d.%d.%d\n\n",
119 XVID_VERSION_MAJOR(XVID_VERSION),
120 XVID_VERSION_MINOR(XVID_VERSION),
121 XVID_VERSION_PATCH(XVID_VERSION));
123 *handle = x->context;
128 * Destroy the two-pass plugin context.
130 * @param ref Context pointer for the plugin
131 * @param param Destrooy context
132 * @return Returns 0, success guaranteed
134 static int xvid_ff_2pass_destroy(struct xvid_context *ref,
135 xvid_plg_destroy_t *param)
137 /* Currently cannot think of anything to do on destruction */
138 /* Still, the framework should be here for reference/use */
139 if (ref->twopassbuffer)
140 ref->twopassbuffer[0] = 0;
145 * Enable fast encode mode during the first pass.
147 * @param ref Context pointer for the plugin
148 * @param param Frame data
149 * @return Returns 0, success guaranteed
151 static int xvid_ff_2pass_before(struct xvid_context *ref,
152 xvid_plg_data_t *param)
155 int motion_replacements;
158 /* Nothing to do here, result is changed too much */
159 if (param->zone && param->zone->mode == XVID_ZONE_QUANT)
162 /* We can implement a 'turbo' first pass mode here */
166 motion_remove = ~XVID_ME_CHROMA_PVOP &
167 ~XVID_ME_CHROMA_BVOP &
168 ~XVID_ME_EXTSEARCH16 &
169 ~XVID_ME_ADVANCEDDIAMOND16;
170 motion_replacements = XVID_ME_FAST_MODEINTERPOLATE |
171 XVID_ME_SKIP_DELTASEARCH |
172 XVID_ME_FASTREFINE16 |
173 XVID_ME_BFRAME_EARLYSTOP;
174 vop_remove = ~XVID_VOP_MODEDECISION_RD &
175 ~XVID_VOP_FAST_MODEDECISION_RD &
176 ~XVID_VOP_TRELLISQUANT &
180 param->vol_flags &= ~XVID_VOL_GMC;
181 param->vop_flags &= vop_remove;
182 param->motion_flags &= motion_remove;
183 param->motion_flags |= motion_replacements;
189 * Capture statistic data and write it during first pass.
191 * @param ref Context pointer for the plugin
192 * @param param Statistic data
193 * @return Returns XVID_ERR_xxxx on failure, or 0 on success
195 static int xvid_ff_2pass_after(struct xvid_context *ref,
196 xvid_plg_data_t *param)
198 char *log = ref->twopassbuffer;
199 const char *frame_types = " ipbs";
202 /* Quick bounds check */
204 return XVID_ERR_FAIL;
206 /* Convert the type given to us into a character */
207 if (param->type < 5 && param->type > 0)
208 frame_type = frame_types[param->type];
210 return XVID_ERR_FAIL;
212 snprintf(BUFFER_CAT(log), BUFFER_REMAINING(log),
213 "%c %d %d %d %d %d %d\n",
214 frame_type, param->stats.quant, param->stats.kblks,
215 param->stats.mblks, param->stats.ublks,
216 param->stats.length, param->stats.hlength);
222 * Dispatch function for our custom plugin.
223 * This handles the dispatch for the Xvid plugin. It passes data
224 * on to other functions for actual processing.
226 * @param ref Context pointer for the plugin
227 * @param cmd The task given for us to complete
228 * @param p1 First parameter (varies)
229 * @param p2 Second parameter (varies)
230 * @return Returns XVID_ERR_xxxx on failure, or 0 on success
232 static int xvid_ff_2pass(void *ref, int cmd, void *p1, void *p2)
238 case XVID_PLG_BEFORE:
239 return xvid_ff_2pass_before(ref, p1);
240 case XVID_PLG_CREATE:
241 return xvid_ff_2pass_create(p1, p2);
243 return xvid_ff_2pass_after(ref, p1);
244 case XVID_PLG_DESTROY:
245 return xvid_ff_2pass_destroy(ref, p1);
247 return XVID_ERR_FAIL;
252 * Routine to create a global VO/VOL header for MP4 container.
253 * What we do here is extract the header from the Xvid bitstream
254 * as it is encoded. We also strip the repeated headers from the
255 * bitstream when a global header is requested for MPEG-4 ISO
258 * @param avctx AVCodecContext pointer to context
259 * @param frame Pointer to encoded frame data
260 * @param header_len Length of header to search
261 * @param frame_len Length of encoded frame data
262 * @return Returns new length of frame data
264 static int xvid_strip_vol_header(AVCodecContext *avctx, AVPacket *pkt,
265 unsigned int header_len,
266 unsigned int frame_len)
270 for (i = 0; i < header_len - 3; i++) {
271 if (pkt->data[i] == 0x00 &&
272 pkt->data[i + 1] == 0x00 &&
273 pkt->data[i + 2] == 0x01 &&
274 pkt->data[i + 3] == 0xB6) {
281 /* We need to store the header, so extract it */
282 if (!avctx->extradata) {
283 avctx->extradata = av_malloc(vo_len);
284 if (!avctx->extradata)
285 return AVERROR(ENOMEM);
286 memcpy(avctx->extradata, pkt->data, vo_len);
287 avctx->extradata_size = vo_len;
289 /* Less dangerous now, memmove properly copies the two
290 * chunks of overlapping data */
291 memmove(pkt->data, &pkt->data[vo_len], frame_len - vo_len);
292 pkt->size = frame_len - vo_len;
298 * Routine to correct a possibly erroneous framerate being fed to us.
299 * Xvid currently chokes on framerates where the ticks per frame is
300 * extremely large. This function works to correct problems in this area
301 * by estimating a new framerate and taking the simpler fraction of
304 * @param avctx Context that contains the framerate to correct.
306 static void xvid_correct_framerate(AVCodecContext *avctx)
309 int est_frate, est_fbase;
313 frate = avctx->time_base.den;
314 fbase = avctx->time_base.num;
316 gcd = av_gcd(frate, fbase);
322 if (frate <= 65000 && fbase <= 65000) {
323 avctx->time_base.den = frate;
324 avctx->time_base.num = fbase;
328 fps = (float) frate / (float) fbase;
329 est_fps = roundf(fps * 1000.0) / 1000.0;
331 est_frate = (int) est_fps;
332 if (est_fps > (int) est_fps) {
333 est_frate = (est_frate + 1) * 1000;
334 est_fbase = (int) roundf((float) est_frate / est_fps);
338 gcd = av_gcd(est_frate, est_fbase);
344 if (fbase > est_fbase) {
345 avctx->time_base.den = est_frate;
346 avctx->time_base.num = est_fbase;
347 av_log(avctx, AV_LOG_DEBUG,
348 "Xvid: framerate re-estimated: %.2f, %.3f%% correction\n",
349 est_fps, (((est_fps - fps) / fps) * 100.0));
351 avctx->time_base.den = frate;
352 avctx->time_base.num = fbase;
356 static av_cold int xvid_encode_init(AVCodecContext *avctx)
359 int xvid_flags = avctx->flags;
360 struct xvid_context *x = avctx->priv_data;
361 uint16_t *intra, *inter;
364 xvid_plugin_single_t single = { 0 };
365 struct xvid_ff_pass1 rc2pass1 = { 0 };
366 xvid_plugin_2pass2_t rc2pass2 = { 0 };
367 xvid_plugin_lumimasking_t masking_l = { 0 }; /* For lumi masking */
368 xvid_plugin_lumimasking_t masking_v = { 0 }; /* For variance AQ */
369 xvid_plugin_ssim_t ssim = { 0 };
370 xvid_gbl_init_t xvid_gbl_init = { 0 };
371 xvid_enc_create_t xvid_enc_create = { 0 };
372 xvid_enc_plugin_t plugins[7];
374 /* Bring in VOP flags from avconv command-line */
375 x->vop_flags = XVID_VOP_HALFPEL; /* Bare minimum quality */
376 if (xvid_flags & AV_CODEC_FLAG_4MV)
377 x->vop_flags |= XVID_VOP_INTER4V; /* Level 3 */
379 x->vop_flags |= XVID_VOP_TRELLISQUANT; /* Level 5 */
380 if (xvid_flags & AV_CODEC_FLAG_AC_PRED)
381 x->vop_flags |= XVID_VOP_HQACPRED; /* Level 6 */
382 if (xvid_flags & AV_CODEC_FLAG_GRAY)
383 x->vop_flags |= XVID_VOP_GREYSCALE;
385 /* Decide which ME quality setting to use */
387 switch (x->me_quality) {
390 x->me_flags |= XVID_ME_EXTSEARCH16 |
394 x->me_flags |= XVID_ME_ADVANCEDDIAMOND8 |
395 XVID_ME_HALFPELREFINE8 |
396 XVID_ME_CHROMA_PVOP |
400 x->me_flags |= XVID_ME_ADVANCEDDIAMOND16 |
401 XVID_ME_HALFPELREFINE16;
402 #if FF_API_MOTION_EST
403 FF_DISABLE_DEPRECATION_WARNINGS
406 switch (avctx->me_method) {
407 case ME_FULL: /* Quality 6 */
408 x->me_flags |= XVID_ME_EXTSEARCH16 |
410 case ME_EPZS: /* Quality 4 */
411 x->me_flags |= XVID_ME_ADVANCEDDIAMOND8 |
412 XVID_ME_HALFPELREFINE8 |
413 XVID_ME_CHROMA_PVOP |
415 case ME_LOG: /* Quality 2 */
418 x->me_flags |= XVID_ME_ADVANCEDDIAMOND16 |
419 XVID_ME_HALFPELREFINE16;
420 case ME_ZERO: /* Quality 0 */
424 FF_ENABLE_DEPRECATION_WARNINGS
428 /* Decide how we should decide blocks */
429 switch (avctx->mb_decision) {
431 x->vop_flags |= XVID_VOP_MODEDECISION_RD;
432 x->me_flags |= XVID_ME_HALFPELREFINE8_RD |
433 XVID_ME_QUARTERPELREFINE8_RD |
434 XVID_ME_EXTSEARCH_RD |
435 XVID_ME_CHECKPREDICTION_RD;
437 if (!(x->vop_flags & XVID_VOP_MODEDECISION_RD))
438 x->vop_flags |= XVID_VOP_FAST_MODEDECISION_RD;
439 x->me_flags |= XVID_ME_HALFPELREFINE16_RD |
440 XVID_ME_QUARTERPELREFINE16_RD;
445 /* Bring in VOL flags from avconv command-line */
447 if (avctx->flags & CODEC_FLAG_GMC)
453 x->vol_flags |= XVID_VOL_GMC;
454 x->me_flags |= XVID_ME_GME_REFINE;
456 if (xvid_flags & AV_CODEC_FLAG_QPEL) {
457 x->vol_flags |= XVID_VOL_QUARTERPEL;
458 x->me_flags |= XVID_ME_QUARTERPELREFINE16;
459 if (x->vop_flags & XVID_VOP_INTER4V)
460 x->me_flags |= XVID_ME_QUARTERPELREFINE8;
463 xvid_gbl_init.version = XVID_VERSION;
464 xvid_gbl_init.debug = 0;
465 xvid_gbl_init.cpu_flags = 0;
468 xvid_global(NULL, XVID_GBL_INIT, &xvid_gbl_init, NULL);
470 /* Create the encoder reference */
471 xvid_enc_create.version = XVID_VERSION;
473 /* Store the desired frame size */
474 xvid_enc_create.width =
475 x->xsize = avctx->width;
476 xvid_enc_create.height =
477 x->ysize = avctx->height;
479 /* Xvid can determine the proper profile to use */
480 /* xvid_enc_create.profile = XVID_PROFILE_S_L3; */
482 /* We don't use zones */
483 xvid_enc_create.zones = NULL;
484 xvid_enc_create.num_zones = 0;
486 xvid_enc_create.num_threads = avctx->thread_count;
488 xvid_enc_create.plugins = plugins;
489 xvid_enc_create.num_plugins = 0;
491 /* Initialize Buffers */
492 x->twopassbuffer = NULL;
493 x->old_twopassbuffer = NULL;
494 x->twopassfile = NULL;
496 if (xvid_flags & AV_CODEC_FLAG_PASS1) {
497 rc2pass1.version = XVID_VERSION;
498 rc2pass1.context = x;
499 x->twopassbuffer = av_malloc(BUFFER_SIZE);
500 x->old_twopassbuffer = av_malloc(BUFFER_SIZE);
501 if (!x->twopassbuffer || !x->old_twopassbuffer) {
502 av_log(avctx, AV_LOG_ERROR,
503 "Xvid: Cannot allocate 2-pass log buffers\n");
504 return AVERROR(ENOMEM);
506 x->twopassbuffer[0] =
507 x->old_twopassbuffer[0] = 0;
509 plugins[xvid_enc_create.num_plugins].func = xvid_ff_2pass;
510 plugins[xvid_enc_create.num_plugins].param = &rc2pass1;
511 xvid_enc_create.num_plugins++;
512 } else if (xvid_flags & AV_CODEC_FLAG_PASS2) {
513 rc2pass2.version = XVID_VERSION;
514 rc2pass2.bitrate = avctx->bit_rate;
516 fd = ff_tempfile("xvidff.", &x->twopassfile);
518 av_log(avctx, AV_LOG_ERROR, "Xvid: Cannot write 2-pass pipe\n");
522 if (!avctx->stats_in) {
523 av_log(avctx, AV_LOG_ERROR,
524 "Xvid: No 2-pass information loaded for second pass\n");
525 return AVERROR_INVALIDDATA;
528 if (strlen(avctx->stats_in) >
529 write(fd, avctx->stats_in, strlen(avctx->stats_in))) {
531 av_log(avctx, AV_LOG_ERROR, "Xvid: Cannot write to 2-pass pipe\n");
536 rc2pass2.filename = x->twopassfile;
537 plugins[xvid_enc_create.num_plugins].func = xvid_plugin_2pass2;
538 plugins[xvid_enc_create.num_plugins].param = &rc2pass2;
539 xvid_enc_create.num_plugins++;
540 } else if (!(xvid_flags & AV_CODEC_FLAG_QSCALE)) {
541 /* Single Pass Bitrate Control! */
542 single.version = XVID_VERSION;
543 single.bitrate = avctx->bit_rate;
545 plugins[xvid_enc_create.num_plugins].func = xvid_plugin_single;
546 plugins[xvid_enc_create.num_plugins].param = &single;
547 xvid_enc_create.num_plugins++;
550 if (avctx->lumi_masking != 0.0)
553 if (x->lumi_aq && x->variance_aq) {
555 av_log(avctx, AV_LOG_WARNING,
556 "variance_aq is ignored when lumi_aq is set.\n");
559 /* Luminance Masking */
561 masking_l.method = 0;
562 plugins[xvid_enc_create.num_plugins].func = xvid_plugin_lumimasking;
564 /* The old behavior is that when avctx->lumi_masking is specified,
565 * plugins[...].param = NULL. Trying to keep the old behavior here. */
566 plugins[xvid_enc_create.num_plugins].param =
567 avctx->lumi_masking ? NULL : &masking_l;
568 xvid_enc_create.num_plugins++;
572 if (x->variance_aq) {
573 masking_v.method = 1;
574 plugins[xvid_enc_create.num_plugins].func = xvid_plugin_lumimasking;
575 plugins[xvid_enc_create.num_plugins].param = &masking_v;
576 xvid_enc_create.num_plugins++;
581 plugins[xvid_enc_create.num_plugins].func = xvid_plugin_ssim;
582 ssim.b_printstat = x->ssim == 2;
583 ssim.acc = x->ssim_acc;
584 ssim.cpu_flags = xvid_gbl_init.cpu_flags;
585 ssim.b_visualize = 0;
586 plugins[xvid_enc_create.num_plugins].param = &ssim;
587 xvid_enc_create.num_plugins++;
590 /* Frame Rate and Key Frames */
591 xvid_correct_framerate(avctx);
592 xvid_enc_create.fincr = avctx->time_base.num;
593 xvid_enc_create.fbase = avctx->time_base.den;
594 if (avctx->gop_size > 0)
595 xvid_enc_create.max_key_interval = avctx->gop_size;
597 xvid_enc_create.max_key_interval = 240; /* Xvid's best default */
600 if (xvid_flags & AV_CODEC_FLAG_QSCALE)
605 xvid_enc_create.min_quant[0] = avctx->qmin;
606 xvid_enc_create.min_quant[1] = avctx->qmin;
607 xvid_enc_create.min_quant[2] = avctx->qmin;
608 xvid_enc_create.max_quant[0] = avctx->qmax;
609 xvid_enc_create.max_quant[1] = avctx->qmax;
610 xvid_enc_create.max_quant[2] = avctx->qmax;
614 x->inter_matrix = NULL;
615 if (avctx->mpeg_quant)
616 x->vol_flags |= XVID_VOL_MPEGQUANT;
617 if ((avctx->intra_matrix || avctx->inter_matrix)) {
618 x->vol_flags |= XVID_VOL_MPEGQUANT;
620 if (avctx->intra_matrix) {
621 intra = avctx->intra_matrix;
622 x->intra_matrix = av_malloc(sizeof(unsigned char) * 64);
623 if (!x->intra_matrix)
624 return AVERROR(ENOMEM);
627 if (avctx->inter_matrix) {
628 inter = avctx->inter_matrix;
629 x->inter_matrix = av_malloc(sizeof(unsigned char) * 64);
630 if (!x->inter_matrix)
631 return AVERROR(ENOMEM);
635 for (i = 0; i < 64; i++) {
637 x->intra_matrix[i] = (unsigned char) intra[i];
639 x->inter_matrix[i] = (unsigned char) inter[i];
644 xvid_enc_create.frame_drop_ratio = 0;
645 xvid_enc_create.global = 0;
646 if (xvid_flags & AV_CODEC_FLAG_CLOSED_GOP)
647 xvid_enc_create.global |= XVID_GLOBAL_CLOSED_GOP;
649 /* Determines which codec mode we are operating in */
650 avctx->extradata = NULL;
651 avctx->extradata_size = 0;
652 if (xvid_flags & AV_CODEC_FLAG_GLOBAL_HEADER) {
653 /* In this case, we are claiming to be MPEG4 */
654 x->quicktime_format = 1;
655 avctx->codec_id = AV_CODEC_ID_MPEG4;
657 /* We are claiming to be Xvid */
658 x->quicktime_format = 0;
659 if (!avctx->codec_tag)
660 avctx->codec_tag = AV_RL32("xvid");
664 xvid_enc_create.max_bframes = avctx->max_b_frames;
665 xvid_enc_create.bquant_offset = 100 * avctx->b_quant_offset;
666 xvid_enc_create.bquant_ratio = 100 * avctx->b_quant_factor;
667 if (avctx->max_b_frames > 0 && !x->quicktime_format)
668 xvid_enc_create.global |= XVID_GLOBAL_PACKED;
670 /* Create encoder context */
671 xerr = xvid_encore(NULL, XVID_ENC_CREATE, &xvid_enc_create, NULL);
673 av_log(avctx, AV_LOG_ERROR, "Xvid: Could not create encoder reference\n");
677 x->encoder_handle = xvid_enc_create.handle;
682 static int xvid_encode_frame(AVCodecContext *avctx, AVPacket *pkt,
683 const AVFrame *picture, int *got_packet)
685 int xerr, i, ret, user_packet = !!pkt->data;
686 struct xvid_context *x = avctx->priv_data;
687 int mb_width = (avctx->width + 15) / 16;
688 int mb_height = (avctx->height + 15) / 16;
691 xvid_enc_frame_t xvid_enc_frame = { 0 };
692 xvid_enc_stats_t xvid_enc_stats = { 0 };
695 (ret = av_new_packet(pkt, mb_width * mb_height * MAX_MB_BYTES + AV_INPUT_BUFFER_MIN_SIZE)) < 0) {
696 av_log(avctx, AV_LOG_ERROR, "Error getting output packet.\n");
700 /* Start setting up the frame */
701 xvid_enc_frame.version = XVID_VERSION;
702 xvid_enc_stats.version = XVID_VERSION;
704 /* Let Xvid know where to put the frame. */
705 xvid_enc_frame.bitstream = pkt->data;
706 xvid_enc_frame.length = pkt->size;
708 /* Initialize input image fields */
709 if (avctx->pix_fmt != AV_PIX_FMT_YUV420P) {
710 av_log(avctx, AV_LOG_ERROR,
711 "Xvid: Color spaces other than 420P not supported\n");
715 xvid_enc_frame.input.csp = XVID_CSP_PLANAR; /* YUV420P */
717 for (i = 0; i < 4; i++) {
718 xvid_enc_frame.input.plane[i] = picture->data[i];
719 xvid_enc_frame.input.stride[i] = picture->linesize[i];
723 xvid_enc_frame.vop_flags = x->vop_flags;
724 xvid_enc_frame.vol_flags = x->vol_flags;
725 xvid_enc_frame.motion = x->me_flags;
726 xvid_enc_frame.type =
727 picture->pict_type == AV_PICTURE_TYPE_I ? XVID_TYPE_IVOP :
728 picture->pict_type == AV_PICTURE_TYPE_P ? XVID_TYPE_PVOP :
729 picture->pict_type == AV_PICTURE_TYPE_B ? XVID_TYPE_BVOP :
732 /* Pixel aspect ratio setting */
733 if (avctx->sample_aspect_ratio.num < 1 || avctx->sample_aspect_ratio.num > 255 ||
734 avctx->sample_aspect_ratio.den < 1 || avctx->sample_aspect_ratio.den > 255) {
735 av_log(avctx, AV_LOG_ERROR, "Invalid pixel aspect ratio %i/%i\n",
736 avctx->sample_aspect_ratio.num, avctx->sample_aspect_ratio.den);
739 xvid_enc_frame.par = XVID_PAR_EXT;
740 xvid_enc_frame.par_width = avctx->sample_aspect_ratio.num;
741 xvid_enc_frame.par_height = avctx->sample_aspect_ratio.den;
745 xvid_enc_frame.quant = picture->quality / FF_QP2LAMBDA;
747 xvid_enc_frame.quant = 0;
750 xvid_enc_frame.quant_intra_matrix = x->intra_matrix;
751 xvid_enc_frame.quant_inter_matrix = x->inter_matrix;
754 xerr = xvid_encore(x->encoder_handle, XVID_ENC_ENCODE,
755 &xvid_enc_frame, &xvid_enc_stats);
757 /* Two-pass log buffer swapping */
758 avctx->stats_out = NULL;
759 if (x->twopassbuffer) {
760 tmp = x->old_twopassbuffer;
761 x->old_twopassbuffer = x->twopassbuffer;
762 x->twopassbuffer = tmp;
763 x->twopassbuffer[0] = 0;
764 if (x->old_twopassbuffer[0] != 0) {
765 avctx->stats_out = x->old_twopassbuffer;
770 uint8_t *sd = av_packet_new_side_data(pkt, AV_PKT_DATA_QUALITY_FACTOR,
773 return AVERROR(ENOMEM);
774 *(int *)sd = xvid_enc_stats.quant * FF_QP2LAMBDA;
778 #if FF_API_CODED_FRAME
779 FF_DISABLE_DEPRECATION_WARNINGS
780 avctx->coded_frame->quality = xvid_enc_stats.quant * FF_QP2LAMBDA;
781 if (xvid_enc_stats.type == XVID_TYPE_PVOP)
782 avctx->coded_frame->pict_type = AV_PICTURE_TYPE_P;
783 else if (xvid_enc_stats.type == XVID_TYPE_BVOP)
784 avctx->coded_frame->pict_type = AV_PICTURE_TYPE_B;
785 else if (xvid_enc_stats.type == XVID_TYPE_SVOP)
786 avctx->coded_frame->pict_type = AV_PICTURE_TYPE_S;
788 avctx->coded_frame->pict_type = AV_PICTURE_TYPE_I;
789 FF_ENABLE_DEPRECATION_WARNINGS
791 if (xvid_enc_frame.out_flags & XVID_KEYFRAME) {
792 #if FF_API_CODED_FRAME
793 FF_DISABLE_DEPRECATION_WARNINGS
794 avctx->coded_frame->key_frame = 1;
795 FF_ENABLE_DEPRECATION_WARNINGS
797 pkt->flags |= AV_PKT_FLAG_KEY;
798 if (x->quicktime_format)
799 return xvid_strip_vol_header(avctx, pkt,
800 xvid_enc_stats.hlength, xerr);
802 #if FF_API_CODED_FRAME
803 FF_DISABLE_DEPRECATION_WARNINGS
804 avctx->coded_frame->key_frame = 0;
805 FF_ENABLE_DEPRECATION_WARNINGS
814 av_packet_unref(pkt);
817 av_log(avctx, AV_LOG_ERROR,
818 "Xvid: Encoding Error Occurred: %i\n", xerr);
823 static av_cold int xvid_encode_close(AVCodecContext *avctx)
825 struct xvid_context *x = avctx->priv_data;
827 if (x->encoder_handle) {
828 xvid_encore(x->encoder_handle, XVID_ENC_DESTROY, NULL, NULL);
829 x->encoder_handle = NULL;
832 av_freep(&avctx->extradata);
833 if (x->twopassbuffer) {
834 av_free(x->twopassbuffer);
835 av_free(x->old_twopassbuffer);
837 av_free(x->twopassfile);
838 av_free(x->intra_matrix);
839 av_free(x->inter_matrix);
844 #define OFFSET(x) offsetof(struct xvid_context, x)
845 #define VE AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_ENCODING_PARAM
846 static const AVOption options[] = {
847 { "lumi_aq", "Luminance masking AQ", OFFSET(lumi_aq), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 1, VE },
848 { "variance_aq", "Variance AQ", OFFSET(variance_aq), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 1, VE },
849 { "ssim", "Show SSIM information to stdout", OFFSET(ssim), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 2, VE, "ssim" },
850 { "off", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = 0 }, INT_MIN, INT_MAX, VE, "ssim" },
851 { "avg", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = 1 }, INT_MIN, INT_MAX, VE, "ssim" },
852 { "frame", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = 2 }, INT_MIN, INT_MAX, VE, "ssim" },
853 { "ssim_acc", "SSIM accuracy", OFFSET(ssim_acc), AV_OPT_TYPE_INT, { .i64 = 2 }, 0, 4, VE },
854 { "gmc", "use GMC", OFFSET(gmc), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 1, VE },
855 { "me_quality", "Motion estimation quality", OFFSET(me_quality), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 6, VE },
859 static const AVClass xvid_class = {
860 .class_name = "libxvid",
861 .item_name = av_default_item_name,
863 .version = LIBAVUTIL_VERSION_INT,
866 AVCodec ff_libxvid_encoder = {
868 .long_name = NULL_IF_CONFIG_SMALL("libxvidcore MPEG-4 part 2"),
869 .type = AVMEDIA_TYPE_VIDEO,
870 .id = AV_CODEC_ID_MPEG4,
871 .priv_data_size = sizeof(struct xvid_context),
872 .init = xvid_encode_init,
873 .encode2 = xvid_encode_frame,
874 .close = xvid_encode_close,
875 .pix_fmts = (const enum AVPixelFormat[]) { AV_PIX_FMT_YUV420P, AV_PIX_FMT_NONE },
876 .priv_class = &xvid_class,
877 .caps_internal = FF_CODEC_CAP_INIT_THREADSAFE |
878 FF_CODEC_CAP_INIT_CLEANUP,