]> git.sesse.net Git - ffmpeg/blob - libavcodec/libxvid.c
avpacket: Replace av_free_packet with av_packet_unref
[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/opt.h"
38
39 #include "avcodec.h"
40 #include "internal.h"
41 #include "libxvid.h"
42 #include "mpegutils.h"
43
44 /**
45  * Buffer management macros.
46  */
47 #define BUFFER_SIZE         1024
48 #define BUFFER_REMAINING(x) (BUFFER_SIZE - strlen(x))
49 #define BUFFER_CAT(x)       (&((x)[strlen(x)]))
50
51 /**
52  * Structure for the private Xvid context.
53  * This stores all the private context for the codec.
54  */
55 struct xvid_context {
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. */
74     int gmc;
75     int me_quality;                /**< Motion estimation quality. 0: fast 6: best. */
76 };
77
78 /**
79  * Structure for the private first-pass plugin.
80  */
81 struct xvid_ff_pass1 {
82     int version;                    /**< Xvid version */
83     struct xvid_context *context;   /**< Pointer to private context */
84 };
85
86 /*
87  * Xvid 2-Pass Kludge Section
88  *
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.
94  */
95
96 /**
97  * Initialize the two-pass plugin and context.
98  *
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.
102  */
103 static int xvid_ff_2pass_create(xvid_plg_create_t *param, void **handle)
104 {
105     struct xvid_ff_pass1 *x = (struct xvid_ff_pass1 *) param->param;
106     char *log = x->context->twopassbuffer;
107
108     /* Do a quick bounds check */
109     if (!log)
110         return XVID_ERR_FAIL;
111
112     /* We use snprintf() */
113     /* This is because we can safely prevent a buffer overflow */
114     log[0] = 0;
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));
122
123     *handle = x->context;
124     return 0;
125 }
126
127 /**
128  * Destroy the two-pass plugin context.
129  *
130  * @param ref Context pointer for the plugin
131  * @param param Destrooy context
132  * @return Returns 0, success guaranteed
133  */
134 static int xvid_ff_2pass_destroy(struct xvid_context *ref,
135                                  xvid_plg_destroy_t *param)
136 {
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;
141     return 0;
142 }
143
144 /**
145  * Enable fast encode mode during the first pass.
146  *
147  * @param ref Context pointer for the plugin
148  * @param param Frame data
149  * @return Returns 0, success guaranteed
150  */
151 static int xvid_ff_2pass_before(struct xvid_context *ref,
152                                 xvid_plg_data_t *param)
153 {
154     int motion_remove;
155     int motion_replacements;
156     int vop_remove;
157
158     /* Nothing to do here, result is changed too much */
159     if (param->zone && param->zone->mode == XVID_ZONE_QUANT)
160         return 0;
161
162     /* We can implement a 'turbo' first pass mode here */
163     param->quant = 2;
164
165     /* Init values */
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         &
177                           ~XVID_VOP_INTER4V              &
178                           ~XVID_VOP_HQACPRED;
179
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;
184
185     return 0;
186 }
187
188 /**
189  * Capture statistic data and write it during first pass.
190  *
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
194  */
195 static int xvid_ff_2pass_after(struct xvid_context *ref,
196                                xvid_plg_data_t *param)
197 {
198     char *log = ref->twopassbuffer;
199     const char *frame_types = " ipbs";
200     char frame_type;
201
202     /* Quick bounds check */
203     if (!log)
204         return XVID_ERR_FAIL;
205
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];
209     else
210         return XVID_ERR_FAIL;
211
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);
217
218     return 0;
219 }
220
221 /**
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.
225  *
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
231  */
232 static int xvid_ff_2pass(void *ref, int cmd, void *p1, void *p2)
233 {
234     switch (cmd) {
235     case XVID_PLG_INFO:
236     case XVID_PLG_FRAME:
237         return 0;
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);
242     case XVID_PLG_AFTER:
243         return xvid_ff_2pass_after(ref, p1);
244     case XVID_PLG_DESTROY:
245         return xvid_ff_2pass_destroy(ref, p1);
246     default:
247         return XVID_ERR_FAIL;
248     }
249 }
250
251 /**
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
256  * compliance.
257  *
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
263  */
264 static int xvid_strip_vol_header(AVCodecContext *avctx, AVPacket *pkt,
265                                  unsigned int header_len,
266                                  unsigned int frame_len)
267 {
268     int vo_len = 0, i;
269
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) {
275             vo_len = i;
276             break;
277         }
278     }
279
280     if (vo_len > 0) {
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;
288         }
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;
293     }
294     return 0;
295 }
296
297 /**
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
302  * the two presented.
303  *
304  * @param avctx Context that contains the framerate to correct.
305  */
306 static void xvid_correct_framerate(AVCodecContext *avctx)
307 {
308     int frate, fbase;
309     int est_frate, est_fbase;
310     int gcd;
311     float est_fps, fps;
312
313     frate = avctx->time_base.den;
314     fbase = avctx->time_base.num;
315
316     gcd = av_gcd(frate, fbase);
317     if (gcd > 1) {
318         frate /= gcd;
319         fbase /= gcd;
320     }
321
322     if (frate <= 65000 && fbase <= 65000) {
323         avctx->time_base.den = frate;
324         avctx->time_base.num = fbase;
325         return;
326     }
327
328     fps     = (float) frate / (float) fbase;
329     est_fps = roundf(fps * 1000.0) / 1000.0;
330
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);
335     } else
336         est_fbase = 1;
337
338     gcd = av_gcd(est_frate, est_fbase);
339     if (gcd > 1) {
340         est_frate /= gcd;
341         est_fbase /= gcd;
342     }
343
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));
350     } else {
351         avctx->time_base.den = frate;
352         avctx->time_base.num = fbase;
353     }
354 }
355
356 static av_cold int xvid_encode_init(AVCodecContext *avctx)
357 {
358     int xerr, i;
359     int xvid_flags = avctx->flags;
360     struct xvid_context *x = avctx->priv_data;
361     uint16_t *intra, *inter;
362     int fd;
363
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];
373
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 */
378     if (avctx->trellis)
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;
384
385     /* Decide which ME quality setting to use */
386     x->me_flags = 0;
387     switch (x->me_quality) {
388     case 6:
389     case 5:
390         x->me_flags |= XVID_ME_EXTSEARCH16 |
391                        XVID_ME_EXTSEARCH8;
392     case 4:
393     case 3:
394         x->me_flags |= XVID_ME_ADVANCEDDIAMOND8 |
395                        XVID_ME_HALFPELREFINE8   |
396                        XVID_ME_CHROMA_PVOP      |
397                        XVID_ME_CHROMA_BVOP;
398     case 2:
399     case 1:
400         x->me_flags |= XVID_ME_ADVANCEDDIAMOND16 |
401                        XVID_ME_HALFPELREFINE16;
402 #if FF_API_MOTION_EST
403 FF_DISABLE_DEPRECATION_WARNINGS
404         break;
405     default:
406         switch (avctx->me_method) {
407         case ME_FULL:   /* Quality 6 */
408              x->me_flags |= XVID_ME_EXTSEARCH16 |
409                             XVID_ME_EXTSEARCH8;
410         case ME_EPZS:   /* Quality 4 */
411              x->me_flags |= XVID_ME_ADVANCEDDIAMOND8 |
412                             XVID_ME_HALFPELREFINE8   |
413                             XVID_ME_CHROMA_PVOP      |
414                             XVID_ME_CHROMA_BVOP;
415         case ME_LOG:    /* Quality 2 */
416         case ME_PHODS:
417         case ME_X1:
418              x->me_flags |= XVID_ME_ADVANCEDDIAMOND16 |
419                             XVID_ME_HALFPELREFINE16;
420         case ME_ZERO:   /* Quality 0 */
421         default:
422             break;
423         }
424 FF_ENABLE_DEPRECATION_WARNINGS
425 #endif
426     }
427
428     /* Decide how we should decide blocks */
429     switch (avctx->mb_decision) {
430     case 2:
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;
436     case 1:
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;
441     default:
442         break;
443     }
444
445     /* Bring in VOL flags from avconv command-line */
446 #if FF_API_GMC
447     if (avctx->flags & CODEC_FLAG_GMC)
448         x->gmc = 1;
449 #endif
450
451     x->vol_flags = 0;
452     if (x->gmc) {
453         x->vol_flags |= XVID_VOL_GMC;
454         x->me_flags  |= XVID_ME_GME_REFINE;
455     }
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;
461     }
462
463     xvid_gbl_init.version   = XVID_VERSION;
464     xvid_gbl_init.debug     = 0;
465     xvid_gbl_init.cpu_flags = 0;
466
467     /* Initialize */
468     xvid_global(NULL, XVID_GBL_INIT, &xvid_gbl_init, NULL);
469
470     /* Create the encoder reference */
471     xvid_enc_create.version = XVID_VERSION;
472
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;
478
479     /* Xvid can determine the proper profile to use */
480     /* xvid_enc_create.profile = XVID_PROFILE_S_L3; */
481
482     /* We don't use zones */
483     xvid_enc_create.zones     = NULL;
484     xvid_enc_create.num_zones = 0;
485
486     xvid_enc_create.num_threads = avctx->thread_count;
487
488     xvid_enc_create.plugins     = plugins;
489     xvid_enc_create.num_plugins = 0;
490
491     /* Initialize Buffers */
492     x->twopassbuffer     = NULL;
493     x->old_twopassbuffer = NULL;
494     x->twopassfile       = NULL;
495
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);
505         }
506         x->twopassbuffer[0]     =
507         x->old_twopassbuffer[0] = 0;
508
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;
515
516         fd = ff_tempfile("xvidff.", &x->twopassfile);
517         if (fd < 0) {
518             av_log(avctx, AV_LOG_ERROR, "Xvid: Cannot write 2-pass pipe\n");
519             return fd;
520         }
521
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;
526         }
527
528         if (strlen(avctx->stats_in) >
529             write(fd, avctx->stats_in, strlen(avctx->stats_in))) {
530             close(fd);
531             av_log(avctx, AV_LOG_ERROR, "Xvid: Cannot write to 2-pass pipe\n");
532             return AVERROR(EIO);
533         }
534
535         close(fd);
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;
544
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++;
548     }
549
550     if (avctx->lumi_masking != 0.0)
551         x->lumi_aq = 1;
552
553     if (x->lumi_aq && x->variance_aq) {
554         x->variance_aq = 0;
555         av_log(avctx, AV_LOG_WARNING,
556                "variance_aq is ignored when lumi_aq is set.\n");
557     }
558
559     /* Luminance Masking */
560     if (x->lumi_aq) {
561         masking_l.method                          = 0;
562         plugins[xvid_enc_create.num_plugins].func = xvid_plugin_lumimasking;
563
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++;
569     }
570
571     /* Variance AQ */
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++;
577     }
578
579     /* SSIM */
580     if (x->ssim) {
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++;
588     }
589
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;
596     else
597         xvid_enc_create.max_key_interval = 240; /* Xvid's best default */
598
599     /* Quants */
600     if (xvid_flags & AV_CODEC_FLAG_QSCALE)
601         x->qscale = 1;
602     else
603         x->qscale = 0;
604
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;
611
612     /* Quant Matrices */
613     x->intra_matrix =
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;
619
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);
625         } else
626             intra = NULL;
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);
632         } else
633             inter = NULL;
634
635         for (i = 0; i < 64; i++) {
636             if (intra)
637                 x->intra_matrix[i] = (unsigned char) intra[i];
638             if (inter)
639                 x->inter_matrix[i] = (unsigned char) inter[i];
640         }
641     }
642
643     /* Misc Settings */
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;
648
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;
656     } else {
657         /* We are claiming to be Xvid */
658         x->quicktime_format = 0;
659         if (!avctx->codec_tag)
660             avctx->codec_tag = AV_RL32("xvid");
661     }
662
663     /* Bframes */
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;
669
670     /* Create encoder context */
671     xerr = xvid_encore(NULL, XVID_ENC_CREATE, &xvid_enc_create, NULL);
672     if (xerr) {
673         av_log(avctx, AV_LOG_ERROR, "Xvid: Could not create encoder reference\n");
674         return -1;
675     }
676
677     x->encoder_handle  = xvid_enc_create.handle;
678
679     return 0;
680 }
681
682 static int xvid_encode_frame(AVCodecContext *avctx, AVPacket *pkt,
683                              const AVFrame *picture, int *got_packet)
684 {
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;
689     char *tmp;
690
691     xvid_enc_frame_t xvid_enc_frame = { 0 };
692     xvid_enc_stats_t xvid_enc_stats = { 0 };
693
694     if (!user_packet &&
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");
697         return ret;
698     }
699
700     /* Start setting up the frame */
701     xvid_enc_frame.version = XVID_VERSION;
702     xvid_enc_stats.version = XVID_VERSION;
703
704     /* Let Xvid know where to put the frame. */
705     xvid_enc_frame.bitstream = pkt->data;
706     xvid_enc_frame.length    = pkt->size;
707
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");
712         return -1;
713     }
714
715     xvid_enc_frame.input.csp = XVID_CSP_PLANAR; /* YUV420P */
716
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];
720     }
721
722     /* Encoder Flags */
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 :
730                                                   XVID_TYPE_AUTO;
731
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);
737         return -1;
738     }
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;
742
743     /* Quant Setting */
744     if (x->qscale)
745         xvid_enc_frame.quant = picture->quality / FF_QP2LAMBDA;
746     else
747         xvid_enc_frame.quant = 0;
748
749     /* Matrices */
750     xvid_enc_frame.quant_intra_matrix = x->intra_matrix;
751     xvid_enc_frame.quant_inter_matrix = x->inter_matrix;
752
753     /* Encode */
754     xerr = xvid_encore(x->encoder_handle, XVID_ENC_ENCODE,
755                        &xvid_enc_frame, &xvid_enc_stats);
756
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;
766         }
767     }
768
769     if (xerr > 0) {
770         uint8_t *sd = av_packet_new_side_data(pkt, AV_PKT_DATA_QUALITY_FACTOR,
771                                               sizeof(int));
772         if (!sd)
773             return AVERROR(ENOMEM);
774         *(int *)sd = xvid_enc_stats.quant * FF_QP2LAMBDA;
775
776         *got_packet = 1;
777
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;
787         else
788             avctx->coded_frame->pict_type = AV_PICTURE_TYPE_I;
789 FF_ENABLE_DEPRECATION_WARNINGS
790 #endif
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
796 #endif
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);
801         } else {
802 #if FF_API_CODED_FRAME
803 FF_DISABLE_DEPRECATION_WARNINGS
804             avctx->coded_frame->key_frame = 0;
805 FF_ENABLE_DEPRECATION_WARNINGS
806 #endif
807         }
808
809         pkt->size = xerr;
810
811         return 0;
812     } else {
813         if (!user_packet)
814             av_packet_unref(pkt);
815         if (!xerr)
816             return 0;
817         av_log(avctx, AV_LOG_ERROR,
818                "Xvid: Encoding Error Occurred: %i\n", xerr);
819         return xerr;
820     }
821 }
822
823 static av_cold int xvid_encode_close(AVCodecContext *avctx)
824 {
825     struct xvid_context *x = avctx->priv_data;
826
827     if (x->encoder_handle) {
828         xvid_encore(x->encoder_handle, XVID_ENC_DESTROY, NULL, NULL);
829         x->encoder_handle = NULL;
830     }
831
832     av_freep(&avctx->extradata);
833     if (x->twopassbuffer) {
834         av_free(x->twopassbuffer);
835         av_free(x->old_twopassbuffer);
836     }
837     av_free(x->twopassfile);
838     av_free(x->intra_matrix);
839     av_free(x->inter_matrix);
840
841     return 0;
842 }
843
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         },
856     { NULL },
857 };
858
859 static const AVClass xvid_class = {
860     .class_name = "libxvid",
861     .item_name  = av_default_item_name,
862     .option     = options,
863     .version    = LIBAVUTIL_VERSION_INT,
864 };
865
866 AVCodec ff_libxvid_encoder = {
867     .name           = "libxvid",
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,
879 };