]> git.sesse.net Git - ffmpeg/blob - libavcodec/libxvid.c
avcodec/ass: fix doxygen typo
[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 FFmpeg.
6  *
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.
11  *
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.
16  *
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
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 <xvid.h>
31
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"
39
40 #include "avcodec.h"
41 #include "internal.h"
42 #include "libxvid.h"
43 #include "mpegutils.h"
44
45 #if HAVE_UNISTD_H
46 #include <unistd.h>
47 #endif
48
49 #if HAVE_IO_H
50 #include <io.h>
51 #endif
52
53 /**
54  * Buffer management macros.
55  */
56 #define BUFFER_SIZE         1024
57 #define BUFFER_REMAINING(x) (BUFFER_SIZE - strlen(x))
58 #define BUFFER_CAT(x)       (&((x)[strlen(x)]))
59
60 /**
61  * Structure for the private Xvid context.
62  * This stores all the private context for the codec.
63  */
64 struct xvid_context {
65     AVClass *class;
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 */
77     int twopassfd;
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. */
84     int gmc;
85     int me_quality;                /**< Motion estimation quality. 0: fast 6: best. */
86 };
87
88 /**
89  * Structure for the private first-pass plugin.
90  */
91 struct xvid_ff_pass1 {
92     int version;                    /**< Xvid version */
93     struct xvid_context *context;   /**< Pointer to private context */
94 };
95
96 static int xvid_encode_close(AVCodecContext *avctx);
97
98 /*
99  * Xvid 2-Pass Kludge Section
100  *
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.
106  */
107
108 /**
109  * Initialize the two-pass plugin and context.
110  *
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.
114  */
115 static int xvid_ff_2pass_create(xvid_plg_create_t *param, void **handle)
116 {
117     struct xvid_ff_pass1 *x = (struct xvid_ff_pass1 *) param->param;
118     char *log = x->context->twopassbuffer;
119
120     /* Do a quick bounds check */
121     if (!log)
122         return XVID_ERR_FAIL;
123
124     /* We use snprintf() */
125     /* This is because we can safely prevent a buffer overflow */
126     log[0] = 0;
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));
134
135     *handle = x->context;
136     return 0;
137 }
138
139 /**
140  * Destroy the two-pass plugin context.
141  *
142  * @param ref Context pointer for the plugin
143  * @param param Destrooy context
144  * @return Returns 0, success guaranteed
145  */
146 static int xvid_ff_2pass_destroy(struct xvid_context *ref,
147                                  xvid_plg_destroy_t *param)
148 {
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;
153     return 0;
154 }
155
156 /**
157  * Enable fast encode mode during the first pass.
158  *
159  * @param ref Context pointer for the plugin
160  * @param param Frame data
161  * @return Returns 0, success guaranteed
162  */
163 static int xvid_ff_2pass_before(struct xvid_context *ref,
164                                 xvid_plg_data_t *param)
165 {
166     int motion_remove;
167     int motion_replacements;
168     int vop_remove;
169
170     /* Nothing to do here, result is changed too much */
171     if (param->zone && param->zone->mode == XVID_ZONE_QUANT)
172         return 0;
173
174     /* We can implement a 'turbo' first pass mode here */
175     param->quant = 2;
176
177     /* Init values */
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         &
189                           ~XVID_VOP_INTER4V              &
190                           ~XVID_VOP_HQACPRED;
191
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;
196
197     return 0;
198 }
199
200 /**
201  * Capture statistic data and write it during first pass.
202  *
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
206  */
207 static int xvid_ff_2pass_after(struct xvid_context *ref,
208                                xvid_plg_data_t *param)
209 {
210     char *log = ref->twopassbuffer;
211     const char *frame_types = " ipbs";
212     char frame_type;
213
214     /* Quick bounds check */
215     if (!log)
216         return XVID_ERR_FAIL;
217
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];
221     else
222         return XVID_ERR_FAIL;
223
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);
229
230     return 0;
231 }
232
233 /**
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.
237  *
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
243  */
244 static int xvid_ff_2pass(void *ref, int cmd, void *p1, void *p2)
245 {
246     switch (cmd) {
247     case XVID_PLG_INFO:
248     case XVID_PLG_FRAME:
249         return 0;
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);
254     case XVID_PLG_AFTER:
255         return xvid_ff_2pass_after(ref, p1);
256     case XVID_PLG_DESTROY:
257         return xvid_ff_2pass_destroy(ref, p1);
258     default:
259         return XVID_ERR_FAIL;
260     }
261 }
262
263 /**
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
268  * compliance.
269  *
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
275  */
276 static int xvid_strip_vol_header(AVCodecContext *avctx, AVPacket *pkt,
277                                  unsigned int header_len,
278                                  unsigned int frame_len)
279 {
280     int vo_len = 0, i;
281
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) {
287             vo_len = i;
288             break;
289         }
290     }
291
292     if (vo_len > 0) {
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;
300         }
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;
305     }
306     return 0;
307 }
308
309 /**
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
314  * the two presented.
315  *
316  * @param avctx Context that contains the framerate to correct.
317  */
318 static void xvid_correct_framerate(AVCodecContext *avctx)
319 {
320     int frate, fbase;
321     int est_frate, est_fbase;
322     int gcd;
323     float est_fps, fps;
324
325     frate = avctx->time_base.den;
326     fbase = avctx->time_base.num;
327
328     gcd = av_gcd(frate, fbase);
329     if (gcd > 1) {
330         frate /= gcd;
331         fbase /= gcd;
332     }
333
334     if (frate <= 65000 && fbase <= 65000) {
335         avctx->time_base.den = frate;
336         avctx->time_base.num = fbase;
337         return;
338     }
339
340     fps     = (float) frate / (float) fbase;
341     est_fps = roundf(fps * 1000.0) / 1000.0;
342
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);
347     } else
348         est_fbase = 1;
349
350     gcd = av_gcd(est_frate, est_fbase);
351     if (gcd > 1) {
352         est_frate /= gcd;
353         est_fbase /= gcd;
354     }
355
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));
362     } else {
363         avctx->time_base.den = frate;
364         avctx->time_base.num = fbase;
365     }
366 }
367
368 static av_cold int xvid_encode_init(AVCodecContext *avctx)
369 {
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;
374     int fd;
375
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];
385
386     x->twopassfd = -1;
387
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 */
392     if (avctx->trellis)
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;
398
399     /* Decide which ME quality setting to use */
400     x->me_flags = 0;
401     switch (x->me_quality) {
402     case 6:
403     case 5:
404         x->me_flags |= XVID_ME_EXTSEARCH16 |
405                        XVID_ME_EXTSEARCH8;
406     case 4:
407     case 3:
408         x->me_flags |= XVID_ME_ADVANCEDDIAMOND8 |
409                        XVID_ME_HALFPELREFINE8   |
410                        XVID_ME_CHROMA_PVOP      |
411                        XVID_ME_CHROMA_BVOP;
412     case 2:
413     case 1:
414         x->me_flags |= XVID_ME_ADVANCEDDIAMOND16 |
415                        XVID_ME_HALFPELREFINE16;
416 #if FF_API_MOTION_EST
417 FF_DISABLE_DEPRECATION_WARNINGS
418         break;
419     default:
420         switch (avctx->me_method) {
421         case ME_FULL:   /* Quality 6 */
422              x->me_flags |= XVID_ME_EXTSEARCH16 |
423                             XVID_ME_EXTSEARCH8;
424         case ME_EPZS:   /* Quality 4 */
425              x->me_flags |= XVID_ME_ADVANCEDDIAMOND8 |
426                             XVID_ME_HALFPELREFINE8   |
427                             XVID_ME_CHROMA_PVOP      |
428                             XVID_ME_CHROMA_BVOP;
429         case ME_LOG:    /* Quality 2 */
430         case ME_PHODS:
431         case ME_X1:
432              x->me_flags |= XVID_ME_ADVANCEDDIAMOND16 |
433                             XVID_ME_HALFPELREFINE16;
434         case ME_ZERO:   /* Quality 0 */
435         default:
436             break;
437         }
438 FF_ENABLE_DEPRECATION_WARNINGS
439 #endif
440     }
441
442     /* Decide how we should decide blocks */
443     switch (avctx->mb_decision) {
444     case 2:
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;
450     case 1:
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;
455     default:
456         break;
457     }
458
459     /* Bring in VOL flags from ffmpeg command-line */
460 #if FF_API_GMC
461     if (avctx->flags & CODEC_FLAG_GMC)
462         x->gmc = 1;
463 #endif
464
465     x->vol_flags = 0;
466     if (x->gmc) {
467         x->vol_flags |= XVID_VOL_GMC;
468         x->me_flags  |= XVID_ME_GME_REFINE;
469     }
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;
475     }
476
477     xvid_gbl_init.version   = XVID_VERSION;
478     xvid_gbl_init.debug     = 0;
479     xvid_gbl_init.cpu_flags = 0;
480
481     /* Initialize */
482     xvid_global(NULL, XVID_GBL_INIT, &xvid_gbl_init, NULL);
483
484     /* Create the encoder reference */
485     xvid_enc_create.version = XVID_VERSION;
486
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;
492
493     /* Xvid can determine the proper profile to use */
494     /* xvid_enc_create.profile = XVID_PROFILE_S_L3; */
495
496     /* We don't use zones */
497     xvid_enc_create.zones     = NULL;
498     xvid_enc_create.num_zones = 0;
499
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;
506         } else {
507             av_log(avctx, AV_LOG_ERROR,
508                    "Too small height for threads > 1.");
509             return AVERROR(EINVAL);
510         }
511     }
512 #endif
513
514     xvid_enc_create.plugins     = plugins;
515     xvid_enc_create.num_plugins = 0;
516
517     /* Initialize Buffers */
518     x->twopassbuffer     = NULL;
519     x->old_twopassbuffer = NULL;
520     x->twopassfile       = NULL;
521
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);
531         }
532         x->twopassbuffer[0]     =
533         x->old_twopassbuffer[0] = 0;
534
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;
541
542         fd = av_tempfile("xvidff.", &x->twopassfile, 0, avctx);
543         if (fd < 0) {
544             av_log(avctx, AV_LOG_ERROR, "Xvid: Cannot write 2-pass pipe\n");
545             return fd;
546         }
547         x->twopassfd = fd;
548
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);
553         }
554
555         ret = write(fd, avctx->stats_in, strlen(avctx->stats_in));
556         if (ret == -1)
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");
560             ret = AVERROR(EIO);
561         }
562         if (ret < 0)
563             return ret;
564
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;
573
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++;
577     }
578
579     if (avctx->lumi_masking != 0.0)
580         x->lumi_aq = 1;
581
582     /* Luminance Masking */
583     if (x->lumi_aq) {
584         masking_l.method                          = 0;
585         plugins[xvid_enc_create.num_plugins].func = xvid_plugin_lumimasking;
586
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++;
592     }
593
594     /* Variance AQ */
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++;
600     }
601
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");
606
607     /* SSIM */
608     if (x->ssim) {
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++;
616     }
617
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;
624     else
625         xvid_enc_create.max_key_interval = 240; /* Xvid's best default */
626
627     /* Quants */
628     if (xvid_flags & AV_CODEC_FLAG_QSCALE)
629         x->qscale = 1;
630     else
631         x->qscale = 0;
632
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;
639
640     /* Quant Matrices */
641     x->intra_matrix =
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;
647
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);
653         } else
654             intra = NULL;
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);
660         } else
661             inter = NULL;
662
663         for (i = 0; i < 64; i++) {
664             if (intra)
665                 x->intra_matrix[i] = (unsigned char) intra[i];
666             if (inter)
667                 x->inter_matrix[i] = (unsigned char) inter[i];
668         }
669     }
670
671     /* Misc Settings */
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;
676
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;
684     } else {
685         /* We are claiming to be Xvid */
686         x->quicktime_format = 0;
687         if (!avctx->codec_tag)
688             avctx->codec_tag = AV_RL32("xvid");
689     }
690
691     /* Bframes */
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;
697
698     av_assert0(xvid_enc_create.num_plugins + (!!x->ssim) + (!!x->variance_aq) + (!!x->lumi_aq) <= FF_ARRAY_ELEMS(plugins));
699
700     /* Create encoder context */
701     xerr = xvid_encore(NULL, XVID_ENC_CREATE, &xvid_enc_create, NULL);
702     if (xerr) {
703         av_log(avctx, AV_LOG_ERROR, "Xvid: Could not create encoder reference\n");
704         return AVERROR_EXTERNAL;
705     }
706
707     x->encoder_handle  = xvid_enc_create.handle;
708
709     return 0;
710 }
711
712 static int xvid_encode_frame(AVCodecContext *avctx, AVPacket *pkt,
713                              const AVFrame *picture, int *got_packet)
714 {
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;
719     char *tmp;
720
721     xvid_enc_frame_t xvid_enc_frame = { 0 };
722     xvid_enc_stats_t xvid_enc_stats = { 0 };
723
724     if ((ret = ff_alloc_packet2(avctx, pkt, mb_width*(int64_t)mb_height*MAX_MB_BYTES + AV_INPUT_BUFFER_MIN_SIZE, 0)) < 0)
725         return ret;
726
727     /* Start setting up the frame */
728     xvid_enc_frame.version = XVID_VERSION;
729     xvid_enc_stats.version = XVID_VERSION;
730
731     /* Let Xvid know where to put the frame. */
732     xvid_enc_frame.bitstream = pkt->data;
733     xvid_enc_frame.length    = pkt->size;
734
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);
740     }
741
742     xvid_enc_frame.input.csp = XVID_CSP_PLANAR; /* YUV420P */
743
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];
747     }
748
749     /* Encoder Flags */
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 :
757                                                   XVID_TYPE_AUTO;
758
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);
767     }
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;
771
772     /* Quant Setting */
773     if (x->qscale)
774         xvid_enc_frame.quant = picture->quality / FF_QP2LAMBDA;
775     else
776         xvid_enc_frame.quant = 0;
777
778     /* Matrices */
779     xvid_enc_frame.quant_intra_matrix = x->intra_matrix;
780     xvid_enc_frame.quant_inter_matrix = x->inter_matrix;
781
782     /* Encode */
783     xerr = xvid_encore(x->encoder_handle, XVID_ENC_ENCODE,
784                        &xvid_enc_frame, &xvid_enc_stats);
785
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;
795         }
796     }
797
798     if (xerr > 0) {
799         int pict_type;
800
801         *got_packet = 1;
802
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;
809         else
810             pict_type = AV_PICTURE_TYPE_I;
811
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
817 #endif
818
819         ff_side_data_set_encoder_stats(pkt, xvid_enc_stats.quant * FF_QP2LAMBDA, NULL, 0, pict_type);
820
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
826 #endif
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);
831         } else {
832 #if FF_API_CODED_FRAME
833 FF_DISABLE_DEPRECATION_WARNINGS
834             avctx->coded_frame->key_frame = 0;
835 FF_ENABLE_DEPRECATION_WARNINGS
836 #endif
837         }
838
839         pkt->size = xerr;
840
841         return 0;
842     } else {
843         if (!user_packet)
844             av_free_packet(pkt);
845         if (!xerr)
846             return 0;
847         av_log(avctx, AV_LOG_ERROR,
848                "Xvid: Encoding Error Occurred: %i\n", xerr);
849         return AVERROR_EXTERNAL;
850     }
851 }
852
853 static av_cold int xvid_encode_close(AVCodecContext *avctx)
854 {
855     struct xvid_context *x = avctx->priv_data;
856
857     if (x->encoder_handle) {
858         xvid_encore(x->encoder_handle, XVID_ENC_DESTROY, NULL, NULL);
859         x->encoder_handle = NULL;
860     }
861
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;
867     }
868     if (x->twopassfd>=0) {
869         unlink(x->twopassfile);
870         close(x->twopassfd);
871         x->twopassfd = -1;
872     }
873     av_freep(&x->twopassfile);
874     av_freep(&x->intra_matrix);
875     av_freep(&x->inter_matrix);
876
877     return 0;
878 }
879
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         },
892     { NULL },
893 };
894
895 static const AVClass xvid_class = {
896     .class_name = "libxvid",
897     .item_name  = av_default_item_name,
898     .option     = options,
899     .version    = LIBAVUTIL_VERSION_INT,
900 };
901
902 AVCodec ff_libxvid_encoder = {
903     .name           = "libxvid",
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,
915 };