2 * Interface to xvidcore for mpeg4 encoding
3 * Copyright (c) 2004 Adam Thayer <krevnik@comcast.net>
5 * This file is part of FFmpeg.
7 * FFmpeg is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU Lesser General Public
9 * License as published by the Free Software Foundation; either
10 * version 2.1 of the License, or (at your option) any later version.
12 * FFmpeg is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 * Lesser General Public License for more details.
17 * You should have received a copy of the GNU Lesser General Public
18 * License along with FFmpeg; if not, write to the Free Software
19 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
24 * Interface to xvidcore for MPEG-4 compliant encoding.
25 * @author Adam Thayer (krevnik@comcast.net)
32 #include "libavutil/avassert.h"
33 #include "libavutil/cpu.h"
34 #include "libavutil/file.h"
35 #include "libavutil/internal.h"
36 #include "libavutil/intreadwrite.h"
37 #include "libavutil/mathematics.h"
38 #include "libavutil/opt.h"
43 #include "mpegutils.h"
54 * Buffer management macros.
56 #define BUFFER_SIZE 1024
57 #define BUFFER_REMAINING(x) (BUFFER_SIZE - strlen(x))
58 #define BUFFER_CAT(x) (&((x)[strlen(x)]))
61 * Structure for the private Xvid context.
62 * This stores all the private context for the codec.
66 void *encoder_handle; /**< Handle for Xvid encoder */
67 int xsize; /**< Frame x size */
68 int ysize; /**< Frame y size */
69 int vop_flags; /**< VOP flags for Xvid encoder */
70 int vol_flags; /**< VOL flags for Xvid encoder */
71 int me_flags; /**< Motion Estimation flags */
72 int qscale; /**< Do we use constant scale? */
73 int quicktime_format; /**< Are we in a QT-based format? */
74 char *twopassbuffer; /**< Character buffer for two-pass */
75 char *old_twopassbuffer; /**< Old character buffer (two-pass) */
76 char *twopassfile; /**< second pass temp file name */
78 unsigned char *intra_matrix; /**< P-Frame Quant Matrix */
79 unsigned char *inter_matrix; /**< I-Frame Quant Matrix */
80 int lumi_aq; /**< Lumi masking as an aq method */
81 int variance_aq; /**< Variance adaptive quantization */
82 int ssim; /**< SSIM information display mode */
83 int ssim_acc; /**< SSIM accuracy. 0: accurate. 4: fast. */
85 int me_quality; /**< Motion estimation quality. 0: fast 6: best. */
89 * Structure for the private first-pass plugin.
91 struct xvid_ff_pass1 {
92 int version; /**< Xvid version */
93 struct xvid_context *context; /**< Pointer to private context */
96 static int xvid_encode_close(AVCodecContext *avctx);
99 * Xvid 2-Pass Kludge Section
101 * Xvid's default 2-pass doesn't allow us to create data as we need to, so
102 * this section spends time replacing the first pass plugin so we can write
103 * statistic information as libavcodec requests in. We have another kludge
104 * that allows us to pass data to the second pass in Xvid without a custom
105 * rate-control plugin.
109 * Initialize the two-pass plugin and context.
111 * @param param Input construction parameter structure
112 * @param handle Private context handle
113 * @return Returns XVID_ERR_xxxx on failure, or 0 on success.
115 static int xvid_ff_2pass_create(xvid_plg_create_t *param, void **handle)
117 struct xvid_ff_pass1 *x = (struct xvid_ff_pass1 *) param->param;
118 char *log = x->context->twopassbuffer;
120 /* Do a quick bounds check */
122 return XVID_ERR_FAIL;
124 /* We use snprintf() */
125 /* This is because we can safely prevent a buffer overflow */
127 snprintf(log, BUFFER_REMAINING(log),
128 "# ffmpeg 2-pass log file, using xvid codec\n");
129 snprintf(BUFFER_CAT(log), BUFFER_REMAINING(log),
130 "# Do not modify. libxvidcore version: %d.%d.%d\n\n",
131 XVID_VERSION_MAJOR(XVID_VERSION),
132 XVID_VERSION_MINOR(XVID_VERSION),
133 XVID_VERSION_PATCH(XVID_VERSION));
135 *handle = x->context;
140 * Destroy the two-pass plugin context.
142 * @param ref Context pointer for the plugin
143 * @param param Destrooy context
144 * @return Returns 0, success guaranteed
146 static int xvid_ff_2pass_destroy(struct xvid_context *ref,
147 xvid_plg_destroy_t *param)
149 /* Currently cannot think of anything to do on destruction */
150 /* Still, the framework should be here for reference/use */
151 if (ref->twopassbuffer)
152 ref->twopassbuffer[0] = 0;
157 * Enable fast encode mode during the first pass.
159 * @param ref Context pointer for the plugin
160 * @param param Frame data
161 * @return Returns 0, success guaranteed
163 static int xvid_ff_2pass_before(struct xvid_context *ref,
164 xvid_plg_data_t *param)
167 int motion_replacements;
170 /* Nothing to do here, result is changed too much */
171 if (param->zone && param->zone->mode == XVID_ZONE_QUANT)
174 /* We can implement a 'turbo' first pass mode here */
178 motion_remove = ~XVID_ME_CHROMA_PVOP &
179 ~XVID_ME_CHROMA_BVOP &
180 ~XVID_ME_EXTSEARCH16 &
181 ~XVID_ME_ADVANCEDDIAMOND16;
182 motion_replacements = XVID_ME_FAST_MODEINTERPOLATE |
183 XVID_ME_SKIP_DELTASEARCH |
184 XVID_ME_FASTREFINE16 |
185 XVID_ME_BFRAME_EARLYSTOP;
186 vop_remove = ~XVID_VOP_MODEDECISION_RD &
187 ~XVID_VOP_FAST_MODEDECISION_RD &
188 ~XVID_VOP_TRELLISQUANT &
192 param->vol_flags &= ~XVID_VOL_GMC;
193 param->vop_flags &= vop_remove;
194 param->motion_flags &= motion_remove;
195 param->motion_flags |= motion_replacements;
201 * Capture statistic data and write it during first pass.
203 * @param ref Context pointer for the plugin
204 * @param param Statistic data
205 * @return Returns XVID_ERR_xxxx on failure, or 0 on success
207 static int xvid_ff_2pass_after(struct xvid_context *ref,
208 xvid_plg_data_t *param)
210 char *log = ref->twopassbuffer;
211 const char *frame_types = " ipbs";
214 /* Quick bounds check */
216 return XVID_ERR_FAIL;
218 /* Convert the type given to us into a character */
219 if (param->type < 5 && param->type > 0)
220 frame_type = frame_types[param->type];
222 return XVID_ERR_FAIL;
224 snprintf(BUFFER_CAT(log), BUFFER_REMAINING(log),
225 "%c %d %d %d %d %d %d\n",
226 frame_type, param->stats.quant, param->stats.kblks,
227 param->stats.mblks, param->stats.ublks,
228 param->stats.length, param->stats.hlength);
234 * Dispatch function for our custom plugin.
235 * This handles the dispatch for the Xvid plugin. It passes data
236 * on to other functions for actual processing.
238 * @param ref Context pointer for the plugin
239 * @param cmd The task given for us to complete
240 * @param p1 First parameter (varies)
241 * @param p2 Second parameter (varies)
242 * @return Returns XVID_ERR_xxxx on failure, or 0 on success
244 static int xvid_ff_2pass(void *ref, int cmd, void *p1, void *p2)
250 case XVID_PLG_BEFORE:
251 return xvid_ff_2pass_before(ref, p1);
252 case XVID_PLG_CREATE:
253 return xvid_ff_2pass_create(p1, p2);
255 return xvid_ff_2pass_after(ref, p1);
256 case XVID_PLG_DESTROY:
257 return xvid_ff_2pass_destroy(ref, p1);
259 return XVID_ERR_FAIL;
264 * Routine to create a global VO/VOL header for MP4 container.
265 * What we do here is extract the header from the Xvid bitstream
266 * as it is encoded. We also strip the repeated headers from the
267 * bitstream when a global header is requested for MPEG-4 ISO
270 * @param avctx AVCodecContext pointer to context
271 * @param frame Pointer to encoded frame data
272 * @param header_len Length of header to search
273 * @param frame_len Length of encoded frame data
274 * @return Returns new length of frame data
276 static int xvid_strip_vol_header(AVCodecContext *avctx, AVPacket *pkt,
277 unsigned int header_len,
278 unsigned int frame_len)
282 for (i = 0; i < header_len - 3; i++) {
283 if (pkt->data[i] == 0x00 &&
284 pkt->data[i + 1] == 0x00 &&
285 pkt->data[i + 2] == 0x01 &&
286 pkt->data[i + 3] == 0xB6) {
293 /* We need to store the header, so extract it */
294 if (!avctx->extradata) {
295 avctx->extradata = av_malloc(vo_len);
296 if (!avctx->extradata)
297 return AVERROR(ENOMEM);
298 memcpy(avctx->extradata, pkt->data, vo_len);
299 avctx->extradata_size = vo_len;
301 /* Less dangerous now, memmove properly copies the two
302 * chunks of overlapping data */
303 memmove(pkt->data, &pkt->data[vo_len], frame_len - vo_len);
304 pkt->size = frame_len - vo_len;
310 * Routine to correct a possibly erroneous framerate being fed to us.
311 * Xvid currently chokes on framerates where the ticks per frame is
312 * extremely large. This function works to correct problems in this area
313 * by estimating a new framerate and taking the simpler fraction of
316 * @param avctx Context that contains the framerate to correct.
318 static void xvid_correct_framerate(AVCodecContext *avctx)
321 int est_frate, est_fbase;
325 frate = avctx->time_base.den;
326 fbase = avctx->time_base.num;
328 gcd = av_gcd(frate, fbase);
334 if (frate <= 65000 && fbase <= 65000) {
335 avctx->time_base.den = frate;
336 avctx->time_base.num = fbase;
340 fps = (float) frate / (float) fbase;
341 est_fps = roundf(fps * 1000.0) / 1000.0;
343 est_frate = (int) est_fps;
344 if (est_fps > (int) est_fps) {
345 est_frate = (est_frate + 1) * 1000;
346 est_fbase = (int) roundf((float) est_frate / est_fps);
350 gcd = av_gcd(est_frate, est_fbase);
356 if (fbase > est_fbase) {
357 avctx->time_base.den = est_frate;
358 avctx->time_base.num = est_fbase;
359 av_log(avctx, AV_LOG_DEBUG,
360 "Xvid: framerate re-estimated: %.2f, %.3f%% correction\n",
361 est_fps, (((est_fps - fps) / fps) * 100.0));
363 avctx->time_base.den = frate;
364 avctx->time_base.num = fbase;
368 static av_cold int xvid_encode_init(AVCodecContext *avctx)
370 int xerr, i, ret = -1;
371 int xvid_flags = avctx->flags;
372 struct xvid_context *x = avctx->priv_data;
373 uint16_t *intra, *inter;
376 xvid_plugin_single_t single = { 0 };
377 struct xvid_ff_pass1 rc2pass1 = { 0 };
378 xvid_plugin_2pass2_t rc2pass2 = { 0 };
379 xvid_plugin_lumimasking_t masking_l = { 0 }; /* For lumi masking */
380 xvid_plugin_lumimasking_t masking_v = { 0 }; /* For variance AQ */
381 xvid_plugin_ssim_t ssim = { 0 };
382 xvid_gbl_init_t xvid_gbl_init = { 0 };
383 xvid_enc_create_t xvid_enc_create = { 0 };
384 xvid_enc_plugin_t plugins[4];
388 /* Bring in VOP flags from ffmpeg command-line */
389 x->vop_flags = XVID_VOP_HALFPEL; /* Bare minimum quality */
390 if (xvid_flags & AV_CODEC_FLAG_4MV)
391 x->vop_flags |= XVID_VOP_INTER4V; /* Level 3 */
393 x->vop_flags |= XVID_VOP_TRELLISQUANT; /* Level 5 */
394 if (xvid_flags & AV_CODEC_FLAG_AC_PRED)
395 x->vop_flags |= XVID_VOP_HQACPRED; /* Level 6 */
396 if (xvid_flags & AV_CODEC_FLAG_GRAY)
397 x->vop_flags |= XVID_VOP_GREYSCALE;
399 /* Decide which ME quality setting to use */
401 switch (x->me_quality) {
404 x->me_flags |= XVID_ME_EXTSEARCH16 |
408 x->me_flags |= XVID_ME_ADVANCEDDIAMOND8 |
409 XVID_ME_HALFPELREFINE8 |
410 XVID_ME_CHROMA_PVOP |
414 x->me_flags |= XVID_ME_ADVANCEDDIAMOND16 |
415 XVID_ME_HALFPELREFINE16;
416 #if FF_API_MOTION_EST
417 FF_DISABLE_DEPRECATION_WARNINGS
420 switch (avctx->me_method) {
421 case ME_FULL: /* Quality 6 */
422 x->me_flags |= XVID_ME_EXTSEARCH16 |
424 case ME_EPZS: /* Quality 4 */
425 x->me_flags |= XVID_ME_ADVANCEDDIAMOND8 |
426 XVID_ME_HALFPELREFINE8 |
427 XVID_ME_CHROMA_PVOP |
429 case ME_LOG: /* Quality 2 */
432 x->me_flags |= XVID_ME_ADVANCEDDIAMOND16 |
433 XVID_ME_HALFPELREFINE16;
434 case ME_ZERO: /* Quality 0 */
438 FF_ENABLE_DEPRECATION_WARNINGS
442 /* Decide how we should decide blocks */
443 switch (avctx->mb_decision) {
445 x->vop_flags |= XVID_VOP_MODEDECISION_RD;
446 x->me_flags |= XVID_ME_HALFPELREFINE8_RD |
447 XVID_ME_QUARTERPELREFINE8_RD |
448 XVID_ME_EXTSEARCH_RD |
449 XVID_ME_CHECKPREDICTION_RD;
451 if (!(x->vop_flags & XVID_VOP_MODEDECISION_RD))
452 x->vop_flags |= XVID_VOP_FAST_MODEDECISION_RD;
453 x->me_flags |= XVID_ME_HALFPELREFINE16_RD |
454 XVID_ME_QUARTERPELREFINE16_RD;
459 /* Bring in VOL flags from ffmpeg command-line */
461 if (avctx->flags & CODEC_FLAG_GMC)
467 x->vol_flags |= XVID_VOL_GMC;
468 x->me_flags |= XVID_ME_GME_REFINE;
470 if (xvid_flags & AV_CODEC_FLAG_QPEL) {
471 x->vol_flags |= XVID_VOL_QUARTERPEL;
472 x->me_flags |= XVID_ME_QUARTERPELREFINE16;
473 if (x->vop_flags & XVID_VOP_INTER4V)
474 x->me_flags |= XVID_ME_QUARTERPELREFINE8;
477 xvid_gbl_init.version = XVID_VERSION;
478 xvid_gbl_init.debug = 0;
479 xvid_gbl_init.cpu_flags = 0;
482 xvid_global(NULL, XVID_GBL_INIT, &xvid_gbl_init, NULL);
484 /* Create the encoder reference */
485 xvid_enc_create.version = XVID_VERSION;
487 /* Store the desired frame size */
488 xvid_enc_create.width =
489 x->xsize = avctx->width;
490 xvid_enc_create.height =
491 x->ysize = avctx->height;
493 /* Xvid can determine the proper profile to use */
494 /* xvid_enc_create.profile = XVID_PROFILE_S_L3; */
496 /* We don't use zones */
497 xvid_enc_create.zones = NULL;
498 xvid_enc_create.num_zones = 0;
500 xvid_enc_create.num_threads = avctx->thread_count;
501 #if (XVID_VERSION <= 0x010303) && (XVID_VERSION >= 0x010300)
502 /* workaround for a bug in libxvidcore */
503 if (avctx->height <= 16) {
504 if (avctx->thread_count < 2) {
505 xvid_enc_create.num_threads = 0;
507 av_log(avctx, AV_LOG_ERROR,
508 "Too small height for threads > 1.");
509 return AVERROR(EINVAL);
514 xvid_enc_create.plugins = plugins;
515 xvid_enc_create.num_plugins = 0;
517 /* Initialize Buffers */
518 x->twopassbuffer = NULL;
519 x->old_twopassbuffer = NULL;
520 x->twopassfile = NULL;
522 if (xvid_flags & AV_CODEC_FLAG_PASS1) {
523 rc2pass1.version = XVID_VERSION;
524 rc2pass1.context = x;
525 x->twopassbuffer = av_malloc(BUFFER_SIZE);
526 x->old_twopassbuffer = av_malloc(BUFFER_SIZE);
527 if (!x->twopassbuffer || !x->old_twopassbuffer) {
528 av_log(avctx, AV_LOG_ERROR,
529 "Xvid: Cannot allocate 2-pass log buffers\n");
530 return AVERROR(ENOMEM);
532 x->twopassbuffer[0] =
533 x->old_twopassbuffer[0] = 0;
535 plugins[xvid_enc_create.num_plugins].func = xvid_ff_2pass;
536 plugins[xvid_enc_create.num_plugins].param = &rc2pass1;
537 xvid_enc_create.num_plugins++;
538 } else if (xvid_flags & AV_CODEC_FLAG_PASS2) {
539 rc2pass2.version = XVID_VERSION;
540 rc2pass2.bitrate = avctx->bit_rate;
542 fd = av_tempfile("xvidff.", &x->twopassfile, 0, avctx);
544 av_log(avctx, AV_LOG_ERROR, "Xvid: Cannot write 2-pass pipe\n");
549 if (!avctx->stats_in) {
550 av_log(avctx, AV_LOG_ERROR,
551 "Xvid: No 2-pass information loaded for second pass\n");
552 return AVERROR(EINVAL);
555 ret = write(fd, avctx->stats_in, strlen(avctx->stats_in));
557 ret = AVERROR(errno);
558 else if (strlen(avctx->stats_in) > ret) {
559 av_log(avctx, AV_LOG_ERROR, "Xvid: Cannot write to 2-pass pipe\n");
565 rc2pass2.filename = x->twopassfile;
566 plugins[xvid_enc_create.num_plugins].func = xvid_plugin_2pass2;
567 plugins[xvid_enc_create.num_plugins].param = &rc2pass2;
568 xvid_enc_create.num_plugins++;
569 } else if (!(xvid_flags & AV_CODEC_FLAG_QSCALE)) {
570 /* Single Pass Bitrate Control! */
571 single.version = XVID_VERSION;
572 single.bitrate = avctx->bit_rate;
574 plugins[xvid_enc_create.num_plugins].func = xvid_plugin_single;
575 plugins[xvid_enc_create.num_plugins].param = &single;
576 xvid_enc_create.num_plugins++;
579 if (avctx->lumi_masking != 0.0)
582 /* Luminance Masking */
584 masking_l.method = 0;
585 plugins[xvid_enc_create.num_plugins].func = xvid_plugin_lumimasking;
587 /* The old behavior is that when avctx->lumi_masking is specified,
588 * plugins[...].param = NULL. Trying to keep the old behavior here. */
589 plugins[xvid_enc_create.num_plugins].param =
590 avctx->lumi_masking ? NULL : &masking_l;
591 xvid_enc_create.num_plugins++;
595 if (x->variance_aq) {
596 masking_v.method = 1;
597 plugins[xvid_enc_create.num_plugins].func = xvid_plugin_lumimasking;
598 plugins[xvid_enc_create.num_plugins].param = &masking_v;
599 xvid_enc_create.num_plugins++;
602 if (x->lumi_aq && x->variance_aq )
603 av_log(avctx, AV_LOG_INFO,
604 "Both lumi_aq and variance_aq are enabled. The resulting quality"
605 "will be the worse one of the two effects made by the AQ.\n");
609 plugins[xvid_enc_create.num_plugins].func = xvid_plugin_ssim;
610 ssim.b_printstat = x->ssim == 2;
611 ssim.acc = x->ssim_acc;
612 ssim.cpu_flags = xvid_gbl_init.cpu_flags;
613 ssim.b_visualize = 0;
614 plugins[xvid_enc_create.num_plugins].param = &ssim;
615 xvid_enc_create.num_plugins++;
618 /* Frame Rate and Key Frames */
619 xvid_correct_framerate(avctx);
620 xvid_enc_create.fincr = avctx->time_base.num;
621 xvid_enc_create.fbase = avctx->time_base.den;
622 if (avctx->gop_size > 0)
623 xvid_enc_create.max_key_interval = avctx->gop_size;
625 xvid_enc_create.max_key_interval = 240; /* Xvid's best default */
628 if (xvid_flags & AV_CODEC_FLAG_QSCALE)
633 xvid_enc_create.min_quant[0] = avctx->qmin;
634 xvid_enc_create.min_quant[1] = avctx->qmin;
635 xvid_enc_create.min_quant[2] = avctx->qmin;
636 xvid_enc_create.max_quant[0] = avctx->qmax;
637 xvid_enc_create.max_quant[1] = avctx->qmax;
638 xvid_enc_create.max_quant[2] = avctx->qmax;
642 x->inter_matrix = NULL;
643 if (avctx->mpeg_quant)
644 x->vol_flags |= XVID_VOL_MPEGQUANT;
645 if ((avctx->intra_matrix || avctx->inter_matrix)) {
646 x->vol_flags |= XVID_VOL_MPEGQUANT;
648 if (avctx->intra_matrix) {
649 intra = avctx->intra_matrix;
650 x->intra_matrix = av_malloc(sizeof(unsigned char) * 64);
651 if (!x->intra_matrix)
652 return AVERROR(ENOMEM);
655 if (avctx->inter_matrix) {
656 inter = avctx->inter_matrix;
657 x->inter_matrix = av_malloc(sizeof(unsigned char) * 64);
658 if (!x->inter_matrix)
659 return AVERROR(ENOMEM);
663 for (i = 0; i < 64; i++) {
665 x->intra_matrix[i] = (unsigned char) intra[i];
667 x->inter_matrix[i] = (unsigned char) inter[i];
672 xvid_enc_create.frame_drop_ratio = 0;
673 xvid_enc_create.global = 0;
674 if (xvid_flags & AV_CODEC_FLAG_CLOSED_GOP)
675 xvid_enc_create.global |= XVID_GLOBAL_CLOSED_GOP;
677 /* Determines which codec mode we are operating in */
678 avctx->extradata = NULL;
679 avctx->extradata_size = 0;
680 if (xvid_flags & AV_CODEC_FLAG_GLOBAL_HEADER) {
681 /* In this case, we are claiming to be MPEG4 */
682 x->quicktime_format = 1;
683 avctx->codec_id = AV_CODEC_ID_MPEG4;
685 /* We are claiming to be Xvid */
686 x->quicktime_format = 0;
687 if (!avctx->codec_tag)
688 avctx->codec_tag = AV_RL32("xvid");
692 xvid_enc_create.max_bframes = avctx->max_b_frames;
693 xvid_enc_create.bquant_offset = 100 * avctx->b_quant_offset;
694 xvid_enc_create.bquant_ratio = 100 * avctx->b_quant_factor;
695 if (avctx->max_b_frames > 0 && !x->quicktime_format)
696 xvid_enc_create.global |= XVID_GLOBAL_PACKED;
698 av_assert0(xvid_enc_create.num_plugins + (!!x->ssim) + (!!x->variance_aq) + (!!x->lumi_aq) <= FF_ARRAY_ELEMS(plugins));
700 /* Create encoder context */
701 xerr = xvid_encore(NULL, XVID_ENC_CREATE, &xvid_enc_create, NULL);
703 av_log(avctx, AV_LOG_ERROR, "Xvid: Could not create encoder reference\n");
704 return AVERROR_EXTERNAL;
707 x->encoder_handle = xvid_enc_create.handle;
712 static int xvid_encode_frame(AVCodecContext *avctx, AVPacket *pkt,
713 const AVFrame *picture, int *got_packet)
715 int xerr, i, ret, user_packet = !!pkt->data;
716 struct xvid_context *x = avctx->priv_data;
717 int mb_width = (avctx->width + 15) / 16;
718 int mb_height = (avctx->height + 15) / 16;
721 xvid_enc_frame_t xvid_enc_frame = { 0 };
722 xvid_enc_stats_t xvid_enc_stats = { 0 };
724 if ((ret = ff_alloc_packet2(avctx, pkt, mb_width*(int64_t)mb_height*MAX_MB_BYTES + AV_INPUT_BUFFER_MIN_SIZE, 0)) < 0)
727 /* Start setting up the frame */
728 xvid_enc_frame.version = XVID_VERSION;
729 xvid_enc_stats.version = XVID_VERSION;
731 /* Let Xvid know where to put the frame. */
732 xvid_enc_frame.bitstream = pkt->data;
733 xvid_enc_frame.length = pkt->size;
735 /* Initialize input image fields */
736 if (avctx->pix_fmt != AV_PIX_FMT_YUV420P) {
737 av_log(avctx, AV_LOG_ERROR,
738 "Xvid: Color spaces other than 420P not supported\n");
739 return AVERROR(EINVAL);
742 xvid_enc_frame.input.csp = XVID_CSP_PLANAR; /* YUV420P */
744 for (i = 0; i < 4; i++) {
745 xvid_enc_frame.input.plane[i] = picture->data[i];
746 xvid_enc_frame.input.stride[i] = picture->linesize[i];
750 xvid_enc_frame.vop_flags = x->vop_flags;
751 xvid_enc_frame.vol_flags = x->vol_flags;
752 xvid_enc_frame.motion = x->me_flags;
753 xvid_enc_frame.type =
754 picture->pict_type == AV_PICTURE_TYPE_I ? XVID_TYPE_IVOP :
755 picture->pict_type == AV_PICTURE_TYPE_P ? XVID_TYPE_PVOP :
756 picture->pict_type == AV_PICTURE_TYPE_B ? XVID_TYPE_BVOP :
759 /* Pixel aspect ratio setting */
760 if (avctx->sample_aspect_ratio.num < 0 || avctx->sample_aspect_ratio.num > 255 ||
761 avctx->sample_aspect_ratio.den < 0 || avctx->sample_aspect_ratio.den > 255) {
762 av_log(avctx, AV_LOG_WARNING,
763 "Invalid pixel aspect ratio %i/%i, limit is 255/255 reducing\n",
764 avctx->sample_aspect_ratio.num, avctx->sample_aspect_ratio.den);
765 av_reduce(&avctx->sample_aspect_ratio.num, &avctx->sample_aspect_ratio.den,
766 avctx->sample_aspect_ratio.num, avctx->sample_aspect_ratio.den, 255);
768 xvid_enc_frame.par = XVID_PAR_EXT;
769 xvid_enc_frame.par_width = avctx->sample_aspect_ratio.num;
770 xvid_enc_frame.par_height = avctx->sample_aspect_ratio.den;
774 xvid_enc_frame.quant = picture->quality / FF_QP2LAMBDA;
776 xvid_enc_frame.quant = 0;
779 xvid_enc_frame.quant_intra_matrix = x->intra_matrix;
780 xvid_enc_frame.quant_inter_matrix = x->inter_matrix;
783 xerr = xvid_encore(x->encoder_handle, XVID_ENC_ENCODE,
784 &xvid_enc_frame, &xvid_enc_stats);
786 /* Two-pass log buffer swapping */
787 avctx->stats_out = NULL;
788 if (x->twopassbuffer) {
789 tmp = x->old_twopassbuffer;
790 x->old_twopassbuffer = x->twopassbuffer;
791 x->twopassbuffer = tmp;
792 x->twopassbuffer[0] = 0;
793 if (x->old_twopassbuffer[0] != 0) {
794 avctx->stats_out = x->old_twopassbuffer;
803 if (xvid_enc_stats.type == XVID_TYPE_PVOP)
804 pict_type = AV_PICTURE_TYPE_P;
805 else if (xvid_enc_stats.type == XVID_TYPE_BVOP)
806 pict_type = AV_PICTURE_TYPE_B;
807 else if (xvid_enc_stats.type == XVID_TYPE_SVOP)
808 pict_type = AV_PICTURE_TYPE_S;
810 pict_type = AV_PICTURE_TYPE_I;
812 #if FF_API_CODED_FRAME
813 FF_DISABLE_DEPRECATION_WARNINGS
814 avctx->coded_frame->pict_type = pict_type;
815 avctx->coded_frame->quality = xvid_enc_stats.quant * FF_QP2LAMBDA;
816 FF_ENABLE_DEPRECATION_WARNINGS
819 ff_side_data_set_encoder_stats(pkt, xvid_enc_stats.quant * FF_QP2LAMBDA, NULL, 0, pict_type);
821 if (xvid_enc_frame.out_flags & XVID_KEYFRAME) {
822 #if FF_API_CODED_FRAME
823 FF_DISABLE_DEPRECATION_WARNINGS
824 avctx->coded_frame->key_frame = 1;
825 FF_ENABLE_DEPRECATION_WARNINGS
827 pkt->flags |= AV_PKT_FLAG_KEY;
828 if (x->quicktime_format)
829 return xvid_strip_vol_header(avctx, pkt,
830 xvid_enc_stats.hlength, xerr);
832 #if FF_API_CODED_FRAME
833 FF_DISABLE_DEPRECATION_WARNINGS
834 avctx->coded_frame->key_frame = 0;
835 FF_ENABLE_DEPRECATION_WARNINGS
847 av_log(avctx, AV_LOG_ERROR,
848 "Xvid: Encoding Error Occurred: %i\n", xerr);
849 return AVERROR_EXTERNAL;
853 static av_cold int xvid_encode_close(AVCodecContext *avctx)
855 struct xvid_context *x = avctx->priv_data;
857 if (x->encoder_handle) {
858 xvid_encore(x->encoder_handle, XVID_ENC_DESTROY, NULL, NULL);
859 x->encoder_handle = NULL;
862 av_freep(&avctx->extradata);
863 if (x->twopassbuffer) {
864 av_freep(&x->twopassbuffer);
865 av_freep(&x->old_twopassbuffer);
866 avctx->stats_out = NULL;
868 if (x->twopassfd>=0) {
869 unlink(x->twopassfile);
873 av_freep(&x->twopassfile);
874 av_freep(&x->intra_matrix);
875 av_freep(&x->inter_matrix);
880 #define OFFSET(x) offsetof(struct xvid_context, x)
881 #define VE AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_ENCODING_PARAM
882 static const AVOption options[] = {
883 { "lumi_aq", "Luminance masking AQ", OFFSET(lumi_aq), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 1, VE },
884 { "variance_aq", "Variance AQ", OFFSET(variance_aq), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 1, VE },
885 { "ssim", "Show SSIM information to stdout", OFFSET(ssim), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 2, VE, "ssim" },
886 { "off", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = 0 }, INT_MIN, INT_MAX, VE, "ssim" },
887 { "avg", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = 1 }, INT_MIN, INT_MAX, VE, "ssim" },
888 { "frame", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = 2 }, INT_MIN, INT_MAX, VE, "ssim" },
889 { "ssim_acc", "SSIM accuracy", OFFSET(ssim_acc), AV_OPT_TYPE_INT, { .i64 = 2 }, 0, 4, VE },
890 { "gmc", "use GMC", OFFSET(gmc), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 1, VE },
891 { "me_quality", "Motion estimation quality", OFFSET(me_quality), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 6, VE },
895 static const AVClass xvid_class = {
896 .class_name = "libxvid",
897 .item_name = av_default_item_name,
899 .version = LIBAVUTIL_VERSION_INT,
902 AVCodec ff_libxvid_encoder = {
904 .long_name = NULL_IF_CONFIG_SMALL("libxvidcore MPEG-4 part 2"),
905 .type = AVMEDIA_TYPE_VIDEO,
906 .id = AV_CODEC_ID_MPEG4,
907 .priv_data_size = sizeof(struct xvid_context),
908 .init = xvid_encode_init,
909 .encode2 = xvid_encode_frame,
910 .close = xvid_encode_close,
911 .pix_fmts = (const enum AVPixelFormat[]) { AV_PIX_FMT_YUV420P, AV_PIX_FMT_NONE },
912 .priv_class = &xvid_class,
913 .caps_internal = FF_CODEC_CAP_INIT_THREADSAFE |
914 FF_CODEC_CAP_INIT_CLEANUP,