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/mem.h"
38 #include "libavutil/opt.h"
43 #include "mpegutils.h"
46 * Buffer management macros.
48 #define BUFFER_SIZE 1024
49 #define BUFFER_REMAINING(x) (BUFFER_SIZE - strlen(x))
50 #define BUFFER_CAT(x) (&((x)[strlen(x)]))
53 * Structure for the private Xvid context.
54 * This stores all the private context for the codec.
57 AVClass *class; /**< Handle for Xvid encoder */
58 void *encoder_handle; /**< Handle for Xvid encoder */
59 int xsize; /**< Frame x size */
60 int ysize; /**< Frame y size */
61 int vop_flags; /**< VOP flags for Xvid encoder */
62 int vol_flags; /**< VOL flags for Xvid encoder */
63 int me_flags; /**< Motion Estimation flags */
64 int qscale; /**< Do we use constant scale? */
65 int quicktime_format; /**< Are we in a QT-based format? */
66 char *twopassbuffer; /**< Character buffer for two-pass */
67 char *old_twopassbuffer; /**< Old character buffer (two-pass) */
68 char *twopassfile; /**< second pass temp file name */
69 unsigned char *intra_matrix; /**< P-Frame Quant Matrix */
70 unsigned char *inter_matrix; /**< I-Frame Quant Matrix */
71 int lumi_aq; /**< Lumi masking as an aq method */
72 int variance_aq; /**< Variance adaptive quantization */
73 int ssim; /**< SSIM information display mode */
74 int ssim_acc; /**< SSIM accuracy. 0: accurate. 4: fast. */
76 int me_quality; /**< Motion estimation quality. 0: fast 6: best. */
77 int mpeg_quant; /**< Quantization type. 0: H263, 1: MPEG */
81 * Structure for the private first-pass plugin.
83 struct xvid_ff_pass1 {
84 int version; /**< Xvid version */
85 struct xvid_context *context; /**< Pointer to private context */
89 * Xvid 2-Pass Kludge Section
91 * Xvid's default 2-pass doesn't allow us to create data as we need to, so
92 * this section spends time replacing the first pass plugin so we can write
93 * statistic information as libavcodec requests in. We have another kludge
94 * that allows us to pass data to the second pass in Xvid without a custom
95 * rate-control plugin.
99 * Initialize the two-pass plugin and context.
101 * @param param Input construction parameter structure
102 * @param handle Private context handle
103 * @return Returns XVID_ERR_xxxx on failure, or 0 on success.
105 static int xvid_ff_2pass_create(xvid_plg_create_t *param, void **handle)
107 struct xvid_ff_pass1 *x = (struct xvid_ff_pass1 *) param->param;
108 char *log = x->context->twopassbuffer;
110 /* Do a quick bounds check */
112 return XVID_ERR_FAIL;
114 /* We use snprintf() */
115 /* This is because we can safely prevent a buffer overflow */
117 snprintf(log, BUFFER_REMAINING(log),
118 "# avconv 2-pass log file, using xvid codec\n");
119 snprintf(BUFFER_CAT(log), BUFFER_REMAINING(log),
120 "# Do not modify. libxvidcore version: %d.%d.%d\n\n",
121 XVID_VERSION_MAJOR(XVID_VERSION),
122 XVID_VERSION_MINOR(XVID_VERSION),
123 XVID_VERSION_PATCH(XVID_VERSION));
125 *handle = x->context;
130 * Destroy the two-pass plugin context.
132 * @param ref Context pointer for the plugin
133 * @param param Destrooy context
134 * @return Returns 0, success guaranteed
136 static int xvid_ff_2pass_destroy(struct xvid_context *ref,
137 xvid_plg_destroy_t *param)
139 /* Currently cannot think of anything to do on destruction */
140 /* Still, the framework should be here for reference/use */
141 if (ref->twopassbuffer)
142 ref->twopassbuffer[0] = 0;
147 * Enable fast encode mode during the first pass.
149 * @param ref Context pointer for the plugin
150 * @param param Frame data
151 * @return Returns 0, success guaranteed
153 static int xvid_ff_2pass_before(struct xvid_context *ref,
154 xvid_plg_data_t *param)
157 int motion_replacements;
160 /* Nothing to do here, result is changed too much */
161 if (param->zone && param->zone->mode == XVID_ZONE_QUANT)
164 /* We can implement a 'turbo' first pass mode here */
168 motion_remove = ~XVID_ME_CHROMA_PVOP &
169 ~XVID_ME_CHROMA_BVOP &
170 ~XVID_ME_EXTSEARCH16 &
171 ~XVID_ME_ADVANCEDDIAMOND16;
172 motion_replacements = XVID_ME_FAST_MODEINTERPOLATE |
173 XVID_ME_SKIP_DELTASEARCH |
174 XVID_ME_FASTREFINE16 |
175 XVID_ME_BFRAME_EARLYSTOP;
176 vop_remove = ~XVID_VOP_MODEDECISION_RD &
177 ~XVID_VOP_FAST_MODEDECISION_RD &
178 ~XVID_VOP_TRELLISQUANT &
182 param->vol_flags &= ~XVID_VOL_GMC;
183 param->vop_flags &= vop_remove;
184 param->motion_flags &= motion_remove;
185 param->motion_flags |= motion_replacements;
191 * Capture statistic data and write it during first pass.
193 * @param ref Context pointer for the plugin
194 * @param param Statistic data
195 * @return Returns XVID_ERR_xxxx on failure, or 0 on success
197 static int xvid_ff_2pass_after(struct xvid_context *ref,
198 xvid_plg_data_t *param)
200 char *log = ref->twopassbuffer;
201 const char *frame_types = " ipbs";
204 /* Quick bounds check */
206 return XVID_ERR_FAIL;
208 /* Convert the type given to us into a character */
209 if (param->type < 5 && param->type > 0)
210 frame_type = frame_types[param->type];
212 return XVID_ERR_FAIL;
214 snprintf(BUFFER_CAT(log), BUFFER_REMAINING(log),
215 "%c %d %d %d %d %d %d\n",
216 frame_type, param->stats.quant, param->stats.kblks,
217 param->stats.mblks, param->stats.ublks,
218 param->stats.length, param->stats.hlength);
224 * Dispatch function for our custom plugin.
225 * This handles the dispatch for the Xvid plugin. It passes data
226 * on to other functions for actual processing.
228 * @param ref Context pointer for the plugin
229 * @param cmd The task given for us to complete
230 * @param p1 First parameter (varies)
231 * @param p2 Second parameter (varies)
232 * @return Returns XVID_ERR_xxxx on failure, or 0 on success
234 static int xvid_ff_2pass(void *ref, int cmd, void *p1, void *p2)
240 case XVID_PLG_BEFORE:
241 return xvid_ff_2pass_before(ref, p1);
242 case XVID_PLG_CREATE:
243 return xvid_ff_2pass_create(p1, p2);
245 return xvid_ff_2pass_after(ref, p1);
246 case XVID_PLG_DESTROY:
247 return xvid_ff_2pass_destroy(ref, p1);
249 return XVID_ERR_FAIL;
254 * Routine to create a global VO/VOL header for MP4 container.
255 * What we do here is extract the header from the Xvid bitstream
256 * as it is encoded. We also strip the repeated headers from the
257 * bitstream when a global header is requested for MPEG-4 ISO
260 * @param avctx AVCodecContext pointer to context
261 * @param frame Pointer to encoded frame data
262 * @param header_len Length of header to search
263 * @param frame_len Length of encoded frame data
264 * @return Returns new length of frame data
266 static int xvid_strip_vol_header(AVCodecContext *avctx, AVPacket *pkt,
267 unsigned int header_len,
268 unsigned int frame_len)
272 for (i = 0; i < header_len - 3; i++) {
273 if (pkt->data[i] == 0x00 &&
274 pkt->data[i + 1] == 0x00 &&
275 pkt->data[i + 2] == 0x01 &&
276 pkt->data[i + 3] == 0xB6) {
283 /* We need to store the header, so extract it */
284 if (!avctx->extradata) {
285 avctx->extradata = av_malloc(vo_len);
286 if (!avctx->extradata)
287 return AVERROR(ENOMEM);
288 memcpy(avctx->extradata, pkt->data, vo_len);
289 avctx->extradata_size = vo_len;
291 /* Less dangerous now, memmove properly copies the two
292 * chunks of overlapping data */
293 memmove(pkt->data, &pkt->data[vo_len], frame_len - vo_len);
294 pkt->size = frame_len - vo_len;
300 * Routine to correct a possibly erroneous framerate being fed to us.
301 * Xvid currently chokes on framerates where the ticks per frame is
302 * extremely large. This function works to correct problems in this area
303 * by estimating a new framerate and taking the simpler fraction of
306 * @param avctx Context that contains the framerate to correct.
308 static void xvid_correct_framerate(AVCodecContext *avctx)
311 int est_frate, est_fbase;
315 frate = avctx->time_base.den;
316 fbase = avctx->time_base.num;
318 gcd = av_gcd(frate, fbase);
324 if (frate <= 65000 && fbase <= 65000) {
325 avctx->time_base.den = frate;
326 avctx->time_base.num = fbase;
330 fps = (float) frate / (float) fbase;
331 est_fps = roundf(fps * 1000.0) / 1000.0;
333 est_frate = (int) est_fps;
334 if (est_fps > (int) est_fps) {
335 est_frate = (est_frate + 1) * 1000;
336 est_fbase = (int) roundf((float) est_frate / est_fps);
340 gcd = av_gcd(est_frate, est_fbase);
346 if (fbase > est_fbase) {
347 avctx->time_base.den = est_frate;
348 avctx->time_base.num = est_fbase;
349 av_log(avctx, AV_LOG_DEBUG,
350 "Xvid: framerate re-estimated: %.2f, %.3f%% correction\n",
351 est_fps, (((est_fps - fps) / fps) * 100.0));
353 avctx->time_base.den = frate;
354 avctx->time_base.num = fbase;
358 static av_cold int xvid_encode_init(AVCodecContext *avctx)
361 int xvid_flags = avctx->flags;
362 struct xvid_context *x = avctx->priv_data;
363 uint16_t *intra, *inter;
366 xvid_plugin_single_t single = { 0 };
367 struct xvid_ff_pass1 rc2pass1 = { 0 };
368 xvid_plugin_2pass2_t rc2pass2 = { 0 };
369 xvid_plugin_lumimasking_t masking_l = { 0 }; /* For lumi masking */
370 xvid_plugin_lumimasking_t masking_v = { 0 }; /* For variance AQ */
371 xvid_plugin_ssim_t ssim = { 0 };
372 xvid_gbl_init_t xvid_gbl_init = { 0 };
373 xvid_enc_create_t xvid_enc_create = { 0 };
374 xvid_enc_plugin_t plugins[7];
376 /* Bring in VOP flags from avconv command-line */
377 x->vop_flags = XVID_VOP_HALFPEL; /* Bare minimum quality */
378 if (xvid_flags & AV_CODEC_FLAG_4MV)
379 x->vop_flags |= XVID_VOP_INTER4V; /* Level 3 */
381 x->vop_flags |= XVID_VOP_TRELLISQUANT; /* Level 5 */
382 if (xvid_flags & AV_CODEC_FLAG_AC_PRED)
383 x->vop_flags |= XVID_VOP_HQACPRED; /* Level 6 */
384 if (xvid_flags & AV_CODEC_FLAG_GRAY)
385 x->vop_flags |= XVID_VOP_GREYSCALE;
387 /* Decide which ME quality setting to use */
389 switch (x->me_quality) {
392 x->me_flags |= XVID_ME_EXTSEARCH16 |
396 x->me_flags |= XVID_ME_ADVANCEDDIAMOND8 |
397 XVID_ME_HALFPELREFINE8 |
398 XVID_ME_CHROMA_PVOP |
402 x->me_flags |= XVID_ME_ADVANCEDDIAMOND16 |
403 XVID_ME_HALFPELREFINE16;
404 #if FF_API_MOTION_EST
405 FF_DISABLE_DEPRECATION_WARNINGS
408 switch (avctx->me_method) {
409 case ME_FULL: /* Quality 6 */
410 x->me_flags |= XVID_ME_EXTSEARCH16 |
412 case ME_EPZS: /* Quality 4 */
413 x->me_flags |= XVID_ME_ADVANCEDDIAMOND8 |
414 XVID_ME_HALFPELREFINE8 |
415 XVID_ME_CHROMA_PVOP |
417 case ME_LOG: /* Quality 2 */
420 x->me_flags |= XVID_ME_ADVANCEDDIAMOND16 |
421 XVID_ME_HALFPELREFINE16;
422 case ME_ZERO: /* Quality 0 */
426 FF_ENABLE_DEPRECATION_WARNINGS
430 /* Decide how we should decide blocks */
431 switch (avctx->mb_decision) {
433 x->vop_flags |= XVID_VOP_MODEDECISION_RD;
434 x->me_flags |= XVID_ME_HALFPELREFINE8_RD |
435 XVID_ME_QUARTERPELREFINE8_RD |
436 XVID_ME_EXTSEARCH_RD |
437 XVID_ME_CHECKPREDICTION_RD;
439 if (!(x->vop_flags & XVID_VOP_MODEDECISION_RD))
440 x->vop_flags |= XVID_VOP_FAST_MODEDECISION_RD;
441 x->me_flags |= XVID_ME_HALFPELREFINE16_RD |
442 XVID_ME_QUARTERPELREFINE16_RD;
447 /* Bring in VOL flags from avconv command-line */
449 if (avctx->flags & CODEC_FLAG_GMC)
455 x->vol_flags |= XVID_VOL_GMC;
456 x->me_flags |= XVID_ME_GME_REFINE;
458 if (xvid_flags & AV_CODEC_FLAG_QPEL) {
459 x->vol_flags |= XVID_VOL_QUARTERPEL;
460 x->me_flags |= XVID_ME_QUARTERPELREFINE16;
461 if (x->vop_flags & XVID_VOP_INTER4V)
462 x->me_flags |= XVID_ME_QUARTERPELREFINE8;
465 xvid_gbl_init.version = XVID_VERSION;
466 xvid_gbl_init.debug = 0;
467 xvid_gbl_init.cpu_flags = 0;
470 xvid_global(NULL, XVID_GBL_INIT, &xvid_gbl_init, NULL);
472 /* Create the encoder reference */
473 xvid_enc_create.version = XVID_VERSION;
475 /* Store the desired frame size */
476 xvid_enc_create.width =
477 x->xsize = avctx->width;
478 xvid_enc_create.height =
479 x->ysize = avctx->height;
481 /* Xvid can determine the proper profile to use */
482 /* xvid_enc_create.profile = XVID_PROFILE_S_L3; */
484 /* We don't use zones */
485 xvid_enc_create.zones = NULL;
486 xvid_enc_create.num_zones = 0;
488 xvid_enc_create.num_threads = avctx->thread_count;
490 xvid_enc_create.plugins = plugins;
491 xvid_enc_create.num_plugins = 0;
493 /* Initialize Buffers */
494 x->twopassbuffer = NULL;
495 x->old_twopassbuffer = NULL;
496 x->twopassfile = NULL;
498 if (xvid_flags & AV_CODEC_FLAG_PASS1) {
499 rc2pass1.version = XVID_VERSION;
500 rc2pass1.context = x;
501 x->twopassbuffer = av_malloc(BUFFER_SIZE);
502 x->old_twopassbuffer = av_malloc(BUFFER_SIZE);
503 if (!x->twopassbuffer || !x->old_twopassbuffer) {
504 av_log(avctx, AV_LOG_ERROR,
505 "Xvid: Cannot allocate 2-pass log buffers\n");
506 return AVERROR(ENOMEM);
508 x->twopassbuffer[0] =
509 x->old_twopassbuffer[0] = 0;
511 plugins[xvid_enc_create.num_plugins].func = xvid_ff_2pass;
512 plugins[xvid_enc_create.num_plugins].param = &rc2pass1;
513 xvid_enc_create.num_plugins++;
514 } else if (xvid_flags & AV_CODEC_FLAG_PASS2) {
515 rc2pass2.version = XVID_VERSION;
516 rc2pass2.bitrate = avctx->bit_rate;
518 fd = ff_tempfile("xvidff.", &x->twopassfile);
520 av_log(avctx, AV_LOG_ERROR, "Xvid: Cannot write 2-pass pipe\n");
524 if (!avctx->stats_in) {
525 av_log(avctx, AV_LOG_ERROR,
526 "Xvid: No 2-pass information loaded for second pass\n");
527 return AVERROR_INVALIDDATA;
530 if (strlen(avctx->stats_in) >
531 write(fd, avctx->stats_in, strlen(avctx->stats_in))) {
533 av_log(avctx, AV_LOG_ERROR, "Xvid: Cannot write to 2-pass pipe\n");
538 rc2pass2.filename = x->twopassfile;
539 plugins[xvid_enc_create.num_plugins].func = xvid_plugin_2pass2;
540 plugins[xvid_enc_create.num_plugins].param = &rc2pass2;
541 xvid_enc_create.num_plugins++;
542 } else if (!(xvid_flags & AV_CODEC_FLAG_QSCALE)) {
543 /* Single Pass Bitrate Control! */
544 single.version = XVID_VERSION;
545 single.bitrate = avctx->bit_rate;
547 plugins[xvid_enc_create.num_plugins].func = xvid_plugin_single;
548 plugins[xvid_enc_create.num_plugins].param = &single;
549 xvid_enc_create.num_plugins++;
552 if (avctx->lumi_masking != 0.0)
555 if (x->lumi_aq && x->variance_aq) {
557 av_log(avctx, AV_LOG_WARNING,
558 "variance_aq is ignored when lumi_aq is set.\n");
561 /* Luminance Masking */
563 masking_l.method = 0;
564 plugins[xvid_enc_create.num_plugins].func = xvid_plugin_lumimasking;
566 /* The old behavior is that when avctx->lumi_masking is specified,
567 * plugins[...].param = NULL. Trying to keep the old behavior here. */
568 plugins[xvid_enc_create.num_plugins].param =
569 avctx->lumi_masking ? NULL : &masking_l;
570 xvid_enc_create.num_plugins++;
574 if (x->variance_aq) {
575 masking_v.method = 1;
576 plugins[xvid_enc_create.num_plugins].func = xvid_plugin_lumimasking;
577 plugins[xvid_enc_create.num_plugins].param = &masking_v;
578 xvid_enc_create.num_plugins++;
583 plugins[xvid_enc_create.num_plugins].func = xvid_plugin_ssim;
584 ssim.b_printstat = x->ssim == 2;
585 ssim.acc = x->ssim_acc;
586 ssim.cpu_flags = xvid_gbl_init.cpu_flags;
587 ssim.b_visualize = 0;
588 plugins[xvid_enc_create.num_plugins].param = &ssim;
589 xvid_enc_create.num_plugins++;
592 /* Frame Rate and Key Frames */
593 xvid_correct_framerate(avctx);
594 xvid_enc_create.fincr = avctx->time_base.num;
595 xvid_enc_create.fbase = avctx->time_base.den;
596 if (avctx->gop_size > 0)
597 xvid_enc_create.max_key_interval = avctx->gop_size;
599 xvid_enc_create.max_key_interval = 240; /* Xvid's best default */
602 if (xvid_flags & AV_CODEC_FLAG_QSCALE)
607 xvid_enc_create.min_quant[0] = avctx->qmin;
608 xvid_enc_create.min_quant[1] = avctx->qmin;
609 xvid_enc_create.min_quant[2] = avctx->qmin;
610 xvid_enc_create.max_quant[0] = avctx->qmax;
611 xvid_enc_create.max_quant[1] = avctx->qmax;
612 xvid_enc_create.max_quant[2] = avctx->qmax;
616 x->inter_matrix = NULL;
618 #if FF_API_PRIVATE_OPT
619 FF_DISABLE_DEPRECATION_WARNINGS
620 if (avctx->mpeg_quant)
621 x->mpeg_quant = avctx->mpeg_quant;
622 FF_ENABLE_DEPRECATION_WARNINGS
626 x->vol_flags |= XVID_VOL_MPEGQUANT;
627 if ((avctx->intra_matrix || avctx->inter_matrix)) {
628 x->vol_flags |= XVID_VOL_MPEGQUANT;
630 if (avctx->intra_matrix) {
631 intra = avctx->intra_matrix;
632 x->intra_matrix = av_malloc(sizeof(unsigned char) * 64);
633 if (!x->intra_matrix)
634 return AVERROR(ENOMEM);
637 if (avctx->inter_matrix) {
638 inter = avctx->inter_matrix;
639 x->inter_matrix = av_malloc(sizeof(unsigned char) * 64);
640 if (!x->inter_matrix)
641 return AVERROR(ENOMEM);
645 for (i = 0; i < 64; i++) {
647 x->intra_matrix[i] = (unsigned char) intra[i];
649 x->inter_matrix[i] = (unsigned char) inter[i];
654 xvid_enc_create.frame_drop_ratio = 0;
655 xvid_enc_create.global = 0;
656 if (xvid_flags & AV_CODEC_FLAG_CLOSED_GOP)
657 xvid_enc_create.global |= XVID_GLOBAL_CLOSED_GOP;
659 /* Determines which codec mode we are operating in */
660 avctx->extradata = NULL;
661 avctx->extradata_size = 0;
662 if (xvid_flags & AV_CODEC_FLAG_GLOBAL_HEADER) {
663 /* In this case, we are claiming to be MPEG4 */
664 x->quicktime_format = 1;
665 avctx->codec_id = AV_CODEC_ID_MPEG4;
667 /* We are claiming to be Xvid */
668 x->quicktime_format = 0;
669 if (!avctx->codec_tag)
670 avctx->codec_tag = AV_RL32("xvid");
674 xvid_enc_create.max_bframes = avctx->max_b_frames;
675 xvid_enc_create.bquant_offset = 100 * avctx->b_quant_offset;
676 xvid_enc_create.bquant_ratio = 100 * avctx->b_quant_factor;
677 if (avctx->max_b_frames > 0 && !x->quicktime_format)
678 xvid_enc_create.global |= XVID_GLOBAL_PACKED;
680 /* Create encoder context */
681 xerr = xvid_encore(NULL, XVID_ENC_CREATE, &xvid_enc_create, NULL);
683 av_log(avctx, AV_LOG_ERROR, "Xvid: Could not create encoder reference\n");
687 x->encoder_handle = xvid_enc_create.handle;
692 static int xvid_encode_frame(AVCodecContext *avctx, AVPacket *pkt,
693 const AVFrame *picture, int *got_packet)
695 int xerr, i, ret, user_packet = !!pkt->data;
696 struct xvid_context *x = avctx->priv_data;
697 int mb_width = (avctx->width + 15) / 16;
698 int mb_height = (avctx->height + 15) / 16;
701 xvid_enc_frame_t xvid_enc_frame = { 0 };
702 xvid_enc_stats_t xvid_enc_stats = { 0 };
705 (ret = av_new_packet(pkt, mb_width * mb_height * MAX_MB_BYTES + AV_INPUT_BUFFER_MIN_SIZE)) < 0) {
706 av_log(avctx, AV_LOG_ERROR, "Error getting output packet.\n");
710 /* Start setting up the frame */
711 xvid_enc_frame.version = XVID_VERSION;
712 xvid_enc_stats.version = XVID_VERSION;
714 /* Let Xvid know where to put the frame. */
715 xvid_enc_frame.bitstream = pkt->data;
716 xvid_enc_frame.length = pkt->size;
718 /* Initialize input image fields */
719 if (avctx->pix_fmt != AV_PIX_FMT_YUV420P) {
720 av_log(avctx, AV_LOG_ERROR,
721 "Xvid: Color spaces other than 420P not supported\n");
725 xvid_enc_frame.input.csp = XVID_CSP_PLANAR; /* YUV420P */
727 for (i = 0; i < 4; i++) {
728 xvid_enc_frame.input.plane[i] = picture->data[i];
729 xvid_enc_frame.input.stride[i] = picture->linesize[i];
733 xvid_enc_frame.vop_flags = x->vop_flags;
734 xvid_enc_frame.vol_flags = x->vol_flags;
735 xvid_enc_frame.motion = x->me_flags;
736 xvid_enc_frame.type =
737 picture->pict_type == AV_PICTURE_TYPE_I ? XVID_TYPE_IVOP :
738 picture->pict_type == AV_PICTURE_TYPE_P ? XVID_TYPE_PVOP :
739 picture->pict_type == AV_PICTURE_TYPE_B ? XVID_TYPE_BVOP :
742 /* Pixel aspect ratio setting */
743 if (avctx->sample_aspect_ratio.num < 1 || avctx->sample_aspect_ratio.num > 255 ||
744 avctx->sample_aspect_ratio.den < 1 || avctx->sample_aspect_ratio.den > 255) {
745 av_log(avctx, AV_LOG_ERROR, "Invalid pixel aspect ratio %i/%i\n",
746 avctx->sample_aspect_ratio.num, avctx->sample_aspect_ratio.den);
749 xvid_enc_frame.par = XVID_PAR_EXT;
750 xvid_enc_frame.par_width = avctx->sample_aspect_ratio.num;
751 xvid_enc_frame.par_height = avctx->sample_aspect_ratio.den;
755 xvid_enc_frame.quant = picture->quality / FF_QP2LAMBDA;
757 xvid_enc_frame.quant = 0;
760 xvid_enc_frame.quant_intra_matrix = x->intra_matrix;
761 xvid_enc_frame.quant_inter_matrix = x->inter_matrix;
764 xerr = xvid_encore(x->encoder_handle, XVID_ENC_ENCODE,
765 &xvid_enc_frame, &xvid_enc_stats);
767 /* Two-pass log buffer swapping */
768 avctx->stats_out = NULL;
769 if (x->twopassbuffer) {
770 tmp = x->old_twopassbuffer;
771 x->old_twopassbuffer = x->twopassbuffer;
772 x->twopassbuffer = tmp;
773 x->twopassbuffer[0] = 0;
774 if (x->old_twopassbuffer[0] != 0) {
775 avctx->stats_out = x->old_twopassbuffer;
780 uint8_t *sd = av_packet_new_side_data(pkt, AV_PKT_DATA_QUALITY_FACTOR,
783 return AVERROR(ENOMEM);
784 *(int *)sd = xvid_enc_stats.quant * FF_QP2LAMBDA;
788 #if FF_API_CODED_FRAME
789 FF_DISABLE_DEPRECATION_WARNINGS
790 avctx->coded_frame->quality = xvid_enc_stats.quant * FF_QP2LAMBDA;
791 if (xvid_enc_stats.type == XVID_TYPE_PVOP)
792 avctx->coded_frame->pict_type = AV_PICTURE_TYPE_P;
793 else if (xvid_enc_stats.type == XVID_TYPE_BVOP)
794 avctx->coded_frame->pict_type = AV_PICTURE_TYPE_B;
795 else if (xvid_enc_stats.type == XVID_TYPE_SVOP)
796 avctx->coded_frame->pict_type = AV_PICTURE_TYPE_S;
798 avctx->coded_frame->pict_type = AV_PICTURE_TYPE_I;
799 FF_ENABLE_DEPRECATION_WARNINGS
801 if (xvid_enc_frame.out_flags & XVID_KEYFRAME) {
802 #if FF_API_CODED_FRAME
803 FF_DISABLE_DEPRECATION_WARNINGS
804 avctx->coded_frame->key_frame = 1;
805 FF_ENABLE_DEPRECATION_WARNINGS
807 pkt->flags |= AV_PKT_FLAG_KEY;
808 if (x->quicktime_format)
809 return xvid_strip_vol_header(avctx, pkt,
810 xvid_enc_stats.hlength, xerr);
812 #if FF_API_CODED_FRAME
813 FF_DISABLE_DEPRECATION_WARNINGS
814 avctx->coded_frame->key_frame = 0;
815 FF_ENABLE_DEPRECATION_WARNINGS
824 av_packet_unref(pkt);
827 av_log(avctx, AV_LOG_ERROR,
828 "Xvid: Encoding Error Occurred: %i\n", xerr);
833 static av_cold int xvid_encode_close(AVCodecContext *avctx)
835 struct xvid_context *x = avctx->priv_data;
837 if (x->encoder_handle) {
838 xvid_encore(x->encoder_handle, XVID_ENC_DESTROY, NULL, NULL);
839 x->encoder_handle = NULL;
842 av_freep(&avctx->extradata);
843 if (x->twopassbuffer) {
844 av_free(x->twopassbuffer);
845 av_free(x->old_twopassbuffer);
847 av_free(x->twopassfile);
848 av_free(x->intra_matrix);
849 av_free(x->inter_matrix);
854 #define OFFSET(x) offsetof(struct xvid_context, x)
855 #define VE AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_ENCODING_PARAM
856 static const AVOption options[] = {
857 { "lumi_aq", "Luminance masking AQ", OFFSET(lumi_aq), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 1, VE },
858 { "variance_aq", "Variance AQ", OFFSET(variance_aq), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 1, VE },
859 { "ssim", "Show SSIM information to stdout", OFFSET(ssim), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 2, VE, "ssim" },
860 { "off", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = 0 }, INT_MIN, INT_MAX, VE, "ssim" },
861 { "avg", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = 1 }, INT_MIN, INT_MAX, VE, "ssim" },
862 { "frame", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = 2 }, INT_MIN, INT_MAX, VE, "ssim" },
863 { "ssim_acc", "SSIM accuracy", OFFSET(ssim_acc), AV_OPT_TYPE_INT, { .i64 = 2 }, 0, 4, VE },
864 { "gmc", "use GMC", OFFSET(gmc), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 1, VE },
865 { "me_quality", "Motion estimation quality", OFFSET(me_quality), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 6, VE },
866 { "mpeg_quant", "Use MPEG quantizers instead of H.263", OFFSET(mpeg_quant), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 1, VE },
870 static const AVClass xvid_class = {
871 .class_name = "libxvid",
872 .item_name = av_default_item_name,
874 .version = LIBAVUTIL_VERSION_INT,
877 AVCodec ff_libxvid_encoder = {
879 .long_name = NULL_IF_CONFIG_SMALL("libxvidcore MPEG-4 part 2"),
880 .type = AVMEDIA_TYPE_VIDEO,
881 .id = AV_CODEC_ID_MPEG4,
882 .priv_data_size = sizeof(struct xvid_context),
883 .init = xvid_encode_init,
884 .encode2 = xvid_encode_frame,
885 .close = xvid_encode_close,
886 .pix_fmts = (const enum AVPixelFormat[]) { AV_PIX_FMT_YUV420P, AV_PIX_FMT_NONE },
887 .priv_class = &xvid_class,
888 .caps_internal = FF_CODEC_CAP_INIT_THREADSAFE |
889 FF_CODEC_CAP_INIT_CLEANUP,