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