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 <xvid.h>
29#include "avcodec.h"
30#include "internal.h"
31#include "libavutil/file.h"
32#include "libavutil/cpu.h"
33#include "libavutil/intreadwrite.h"
34#include "libavutil/mathematics.h"
35#include "libxvid.h"
36#include "mpegvideo.h"
37
38#if HAVE_UNISTD_H
39#include <unistd.h>
40#endif
41
42/**
43 * Buffer management macros.
44 */
45#define BUFFER_SIZE                 1024
46#define BUFFER_REMAINING(x)         (BUFFER_SIZE - strlen(x))
47#define BUFFER_CAT(x)               (&((x)[strlen(x)]))
48
49/**
50 * Structure for the private Xvid context.
51 * This stores all the private context for the codec.
52 */
53struct xvid_context {
54    AVClass *class;
55    void *encoder_handle;          /**< Handle for Xvid encoder */
56    int xsize;                     /**< Frame x size */
57    int ysize;                     /**< Frame y size */
58    int vop_flags;                 /**< VOP flags for Xvid encoder */
59    int vol_flags;                 /**< VOL flags for Xvid encoder */
60    int me_flags;                  /**< Motion Estimation flags */
61    int qscale;                    /**< Do we use constant scale? */
62    int quicktime_format;          /**< Are we in a QT-based format? */
63    char *twopassbuffer;           /**< Character buffer for two-pass */
64    char *old_twopassbuffer;       /**< Old character buffer (two-pass) */
65    char *twopassfile;             /**< second pass temp file name */
66    int twopassfd;
67    unsigned char *intra_matrix;   /**< P-Frame Quant Matrix */
68    unsigned char *inter_matrix;   /**< I-Frame Quant Matrix */
69    int lumi_aq;                   /**< Lumi masking as an aq method */
70    int variance_aq;               /**< Variance adaptive quantization */
71    int ssim;                      /**< SSIM information display mode */
72    int ssim_acc;                  /**< SSIM accuracy. 0: accurate. 4: fast. */
73    int gmc;
74};
75
76/**
77 * Structure for the private first-pass plugin.
78 */
79struct xvid_ff_pass1 {
80    int     version;                /**< Xvid version */
81    struct xvid_context *context;   /**< Pointer to private context */
82};
83
84static int xvid_encode_close(AVCodecContext *avctx);
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 */
103static int xvid_ff_2pass_create(xvid_plg_create_t * param,
104                                void ** handle) {
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 == NULL )
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        "# ffmpeg 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 */
134static int xvid_ff_2pass_destroy(struct xvid_context *ref,
135                                xvid_plg_destroy_t *param) {
136    /* Currently cannot think of anything to do on destruction */
137    /* Still, the framework should be here for reference/use */
138    if( ref->twopassbuffer != NULL )
139        ref->twopassbuffer[0] = 0;
140    return 0;
141}
142
143/**
144 * Enable fast encode mode during the first pass.
145 *
146 * @param ref Context pointer for the plugin
147 * @param param Frame data
148 * @return Returns 0, success guaranteed
149 */
150static int xvid_ff_2pass_before(struct xvid_context *ref,
151                                xvid_plg_data_t *param) {
152    int motion_remove;
153    int motion_replacements;
154    int vop_remove;
155
156    /* Nothing to do here, result is changed too much */
157    if( param->zone && param->zone->mode == XVID_ZONE_QUANT )
158        return 0;
159
160    /* We can implement a 'turbo' first pass mode here */
161    param->quant = 2;
162
163    /* Init values */
164    motion_remove = ~XVID_ME_CHROMA_PVOP &
165                    ~XVID_ME_CHROMA_BVOP &
166                    ~XVID_ME_EXTSEARCH16 &
167                    ~XVID_ME_ADVANCEDDIAMOND16;
168    motion_replacements = XVID_ME_FAST_MODEINTERPOLATE |
169                          XVID_ME_SKIP_DELTASEARCH |
170                          XVID_ME_FASTREFINE16 |
171                          XVID_ME_BFRAME_EARLYSTOP;
172    vop_remove = ~XVID_VOP_MODEDECISION_RD &
173                 ~XVID_VOP_FAST_MODEDECISION_RD &
174                 ~XVID_VOP_TRELLISQUANT &
175                 ~XVID_VOP_INTER4V &
176                 ~XVID_VOP_HQACPRED;
177
178    param->vol_flags &= ~XVID_VOL_GMC;
179    param->vop_flags &= vop_remove;
180    param->motion_flags &= motion_remove;
181    param->motion_flags |= motion_replacements;
182
183    return 0;
184}
185
186/**
187 * Capture statistic data and write it during first pass.
188 *
189 * @param ref Context pointer for the plugin
190 * @param param Statistic data
191 * @return Returns XVID_ERR_xxxx on failure, or 0 on success
192 */
193static int xvid_ff_2pass_after(struct xvid_context *ref,
194                                xvid_plg_data_t *param) {
195    char *log = ref->twopassbuffer;
196    const char *frame_types = " ipbs";
197    char frame_type;
198
199    /* Quick bounds check */
200    if( log == NULL )
201        return XVID_ERR_FAIL;
202
203    /* Convert the type given to us into a character */
204    if( param->type < 5 && param->type > 0 ) {
205        frame_type = frame_types[param->type];
206    } else {
207        return XVID_ERR_FAIL;
208    }
209
210    snprintf(BUFFER_CAT(log), BUFFER_REMAINING(log),
211        "%c %d %d %d %d %d %d\n",
212        frame_type, param->stats.quant, param->stats.kblks, param->stats.mblks,
213        param->stats.ublks, param->stats.length, param->stats.hlength);
214
215    return 0;
216}
217
218/**
219 * Dispatch function for our custom plugin.
220 * This handles the dispatch for the Xvid plugin. It passes data
221 * on to other functions for actual processing.
222 *
223 * @param ref Context pointer for the plugin
224 * @param cmd The task given for us to complete
225 * @param p1 First parameter (varies)
226 * @param p2 Second parameter (varies)
227 * @return Returns XVID_ERR_xxxx on failure, or 0 on success
228 */
229static int xvid_ff_2pass(void *ref, int cmd, void *p1, void *p2)
230{
231    switch( cmd ) {
232        case XVID_PLG_INFO:
233        case XVID_PLG_FRAME:
234            return 0;
235
236        case XVID_PLG_BEFORE:
237            return xvid_ff_2pass_before(ref, p1);
238
239        case XVID_PLG_CREATE:
240            return xvid_ff_2pass_create(p1, p2);
241
242        case XVID_PLG_AFTER:
243            return xvid_ff_2pass_after(ref, p1);
244
245        case XVID_PLG_DESTROY:
246            return xvid_ff_2pass_destroy(ref, p1);
247
248        default:
249            return XVID_ERR_FAIL;
250    }
251}
252
253/**
254 * Routine to create a global VO/VOL header for MP4 container.
255 * What we do here is extract the header from the Xvid bitstream
256 * as it is encoded. We also strip the repeated headers from the
257 * bitstream when a global header is requested for MPEG-4 ISO
258 * compliance.
259 *
260 * @param avctx AVCodecContext pointer to context
261 * @param frame Pointer to encoded frame data
262 * @param header_len Length of header to search
263 * @param frame_len Length of encoded frame data
264 * @return Returns new length of frame data
265 */
266static int xvid_strip_vol_header(AVCodecContext *avctx,
267                  AVPacket *pkt,
268                  unsigned int header_len,
269                  unsigned int frame_len) {
270    int vo_len = 0, i;
271
272    for( i = 0; i < header_len - 3; i++ ) {
273        if( pkt->data[i] == 0x00 &&
274            pkt->data[i+1] == 0x00 &&
275            pkt->data[i+2] == 0x01 &&
276            pkt->data[i+3] == 0xB6 ) {
277            vo_len = i;
278            break;
279        }
280    }
281
282    if( vo_len > 0 ) {
283        /* We need to store the header, so extract it */
284        if( avctx->extradata == NULL ) {
285            avctx->extradata = av_malloc(vo_len);
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 */
306static 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
356static av_cold int xvid_encode_init(AVCodecContext *avctx)  {
357    int xerr, i;
358    int xvid_flags = avctx->flags;
359    struct xvid_context *x = avctx->priv_data;
360    uint16_t *intra, *inter;
361    int fd;
362
363    xvid_plugin_single_t      single          = { 0 };
364    struct xvid_ff_pass1      rc2pass1        = { 0 };
365    xvid_plugin_2pass2_t      rc2pass2        = { 0 };
366    xvid_plugin_lumimasking_t masking_l       = { 0 }; /* For lumi masking */
367    xvid_plugin_lumimasking_t masking_v       = { 0 }; /* For variance AQ */
368    xvid_plugin_ssim_t        ssim            = { 0 };
369    xvid_gbl_init_t           xvid_gbl_init   = { 0 };
370    xvid_enc_create_t         xvid_enc_create = { 0 };
371    xvid_enc_plugin_t         plugins[4];
372
373    x->twopassfd = -1;
374
375    /* Bring in VOP flags from ffmpeg command-line */
376    x->vop_flags = XVID_VOP_HALFPEL;              /* Bare minimum quality */
377    if( xvid_flags & 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 & CODEC_FLAG_AC_PRED )
382        x->vop_flags    |= XVID_VOP_HQACPRED;     /* Level 6 */
383    if( xvid_flags & 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( avctx->me_method ) {
389       case ME_FULL:   /* Quality 6 */
390           x->me_flags  |=  XVID_ME_EXTSEARCH16
391                        |   XVID_ME_EXTSEARCH8;
392
393       case ME_EPZS:   /* Quality 4 */
394           x->me_flags  |=  XVID_ME_ADVANCEDDIAMOND8
395                        |   XVID_ME_HALFPELREFINE8
396                        |   XVID_ME_CHROMA_PVOP
397                        |   XVID_ME_CHROMA_BVOP;
398
399       case ME_LOG:    /* Quality 2 */
400       case ME_PHODS:
401       case ME_X1:
402           x->me_flags  |=  XVID_ME_ADVANCEDDIAMOND16
403                        |   XVID_ME_HALFPELREFINE16;
404
405       case ME_ZERO:   /* Quality 0 */
406       default:
407           break;
408    }
409
410    /* Decide how we should decide blocks */
411    switch( avctx->mb_decision ) {
412       case 2:
413           x->vop_flags |= XVID_VOP_MODEDECISION_RD;
414           x->me_flags  |=  XVID_ME_HALFPELREFINE8_RD
415                        |   XVID_ME_QUARTERPELREFINE8_RD
416                        |   XVID_ME_EXTSEARCH_RD
417                        |   XVID_ME_CHECKPREDICTION_RD;
418       case 1:
419           if( !(x->vop_flags & XVID_VOP_MODEDECISION_RD) )
420               x->vop_flags |= XVID_VOP_FAST_MODEDECISION_RD;
421           x->me_flags  |=  XVID_ME_HALFPELREFINE16_RD
422                        |   XVID_ME_QUARTERPELREFINE16_RD;
423
424       default:
425           break;
426    }
427
428    /* Bring in VOL flags from ffmpeg command-line */
429#if FF_API_GMC
430    if (avctx->flags & CODEC_FLAG_GMC)
431        x->gmc = 1;
432#endif
433
434    x->vol_flags = 0;
435    if (x->gmc) {
436        x->vol_flags    |= XVID_VOL_GMC;
437        x->me_flags     |= XVID_ME_GME_REFINE;
438    }
439    if( xvid_flags & CODEC_FLAG_QPEL ) {
440        x->vol_flags    |= XVID_VOL_QUARTERPEL;
441        x->me_flags     |= XVID_ME_QUARTERPELREFINE16;
442        if( x->vop_flags & XVID_VOP_INTER4V )
443            x->me_flags |= XVID_ME_QUARTERPELREFINE8;
444    }
445
446    xvid_gbl_init.version = XVID_VERSION;
447    xvid_gbl_init.debug = 0;
448
449#if ARCH_PPC
450    /* Xvid's PPC support is borked, use libavcodec to detect */
451#if HAVE_ALTIVEC
452    if (av_get_cpu_flags() & AV_CPU_FLAG_ALTIVEC) {
453        xvid_gbl_init.cpu_flags = XVID_CPU_FORCE | XVID_CPU_ALTIVEC;
454    } else
455#endif
456        xvid_gbl_init.cpu_flags = XVID_CPU_FORCE;
457#else
458    /* Xvid can detect on x86 */
459    xvid_gbl_init.cpu_flags = 0;
460#endif
461
462    /* Initialize */
463    xvid_global(NULL, XVID_GBL_INIT, &xvid_gbl_init, NULL);
464
465    /* Create the encoder reference */
466    xvid_enc_create.version = XVID_VERSION;
467
468    /* Store the desired frame size */
469    xvid_enc_create.width = x->xsize = avctx->width;
470    xvid_enc_create.height = x->ysize = avctx->height;
471
472    /* Xvid can determine the proper profile to use */
473    /* xvid_enc_create.profile = XVID_PROFILE_S_L3; */
474
475    /* We don't use zones */
476    xvid_enc_create.zones = NULL;
477    xvid_enc_create.num_zones = 0;
478
479    xvid_enc_create.num_threads = avctx->thread_count;
480
481    xvid_enc_create.plugins = plugins;
482    xvid_enc_create.num_plugins = 0;
483
484    /* Initialize Buffers */
485    x->twopassbuffer = NULL;
486    x->old_twopassbuffer = NULL;
487    x->twopassfile = NULL;
488
489    if( xvid_flags & CODEC_FLAG_PASS1 ) {
490        rc2pass1.version = XVID_VERSION;
491        rc2pass1.context = x;
492        x->twopassbuffer = av_malloc(BUFFER_SIZE);
493        x->old_twopassbuffer = av_malloc(BUFFER_SIZE);
494        if( x->twopassbuffer == NULL || x->old_twopassbuffer == NULL ) {
495            av_log(avctx, AV_LOG_ERROR,
496                "Xvid: Cannot allocate 2-pass log buffers\n");
497            goto fail;
498        }
499        x->twopassbuffer[0] = x->old_twopassbuffer[0] = 0;
500
501        plugins[xvid_enc_create.num_plugins].func = xvid_ff_2pass;
502        plugins[xvid_enc_create.num_plugins].param = &rc2pass1;
503        xvid_enc_create.num_plugins++;
504    } else if( xvid_flags & CODEC_FLAG_PASS2 ) {
505        rc2pass2.version = XVID_VERSION;
506        rc2pass2.bitrate = avctx->bit_rate;
507
508        fd = av_tempfile("xvidff.", &x->twopassfile, 0, avctx);
509        if( fd == -1 ) {
510            av_log(avctx, AV_LOG_ERROR,
511                "Xvid: Cannot write 2-pass pipe\n");
512            goto fail;
513        }
514        x->twopassfd = fd;
515
516        if( avctx->stats_in == NULL ) {
517            av_log(avctx, AV_LOG_ERROR,
518                "Xvid: No 2-pass information loaded for second pass\n");
519            goto fail;
520        }
521
522        if( strlen(avctx->stats_in) >
523              write(fd, avctx->stats_in, strlen(avctx->stats_in)) ) {
524            av_log(avctx, AV_LOG_ERROR,
525                "Xvid: Cannot write to 2-pass pipe\n");
526            goto fail;
527        }
528
529        rc2pass2.filename = x->twopassfile;
530        plugins[xvid_enc_create.num_plugins].func = xvid_plugin_2pass2;
531        plugins[xvid_enc_create.num_plugins].param = &rc2pass2;
532        xvid_enc_create.num_plugins++;
533    } else if( !(xvid_flags & CODEC_FLAG_QSCALE) ) {
534        /* Single Pass Bitrate Control! */
535        single.version = XVID_VERSION;
536        single.bitrate = avctx->bit_rate;
537
538        plugins[xvid_enc_create.num_plugins].func = xvid_plugin_single;
539        plugins[xvid_enc_create.num_plugins].param = &single;
540        xvid_enc_create.num_plugins++;
541    }
542
543    if (avctx->lumi_masking != 0.0)
544        x->lumi_aq = 1;
545
546    /* Luminance Masking */
547    if (x->lumi_aq) {
548        masking_l.method = 0;
549        plugins[xvid_enc_create.num_plugins].func = xvid_plugin_lumimasking;
550
551        /* The old behavior is that when avctx->lumi_masking is specified,
552         * plugins[...].param = NULL. Trying to keep the old behavior here. */
553        plugins[xvid_enc_create.num_plugins].param = avctx->lumi_masking ? NULL
554                                                                         : &masking_l;
555                xvid_enc_create.num_plugins++;
556    }
557
558    /* Variance AQ */
559    if (x->variance_aq) {
560        masking_v.method = 1;
561        plugins[xvid_enc_create.num_plugins].func  = xvid_plugin_lumimasking;
562        plugins[xvid_enc_create.num_plugins].param = &masking_v;
563        xvid_enc_create.num_plugins++;
564    }
565
566    if( x->lumi_aq && x->variance_aq )
567        av_log(avctx, AV_LOG_INFO,
568               "Both lumi_aq and variance_aq are enabled. The resulting quality"
569               "will be the worse one of the two effects made by the AQ.\n");
570
571    /* SSIM */
572    if (x->ssim) {
573        plugins[xvid_enc_create.num_plugins].func = xvid_plugin_ssim;
574        ssim.b_printstat = x->ssim == 2;
575        ssim.acc         = x->ssim_acc;
576        ssim.cpu_flags   = xvid_gbl_init.cpu_flags;
577        ssim.b_visualize = 0;
578        plugins[xvid_enc_create.num_plugins].param = &ssim;
579        xvid_enc_create.num_plugins++;
580    }
581
582    /* Frame Rate and Key Frames */
583    xvid_correct_framerate(avctx);
584    xvid_enc_create.fincr = avctx->time_base.num;
585    xvid_enc_create.fbase = avctx->time_base.den;
586    if( avctx->gop_size > 0 )
587        xvid_enc_create.max_key_interval = avctx->gop_size;
588    else
589        xvid_enc_create.max_key_interval = 240; /* Xvid's best default */
590
591    /* Quants */
592    if( xvid_flags & CODEC_FLAG_QSCALE ) x->qscale = 1;
593    else x->qscale = 0;
594
595    xvid_enc_create.min_quant[0] = avctx->qmin;
596    xvid_enc_create.min_quant[1] = avctx->qmin;
597    xvid_enc_create.min_quant[2] = avctx->qmin;
598    xvid_enc_create.max_quant[0] = avctx->qmax;
599    xvid_enc_create.max_quant[1] = avctx->qmax;
600    xvid_enc_create.max_quant[2] = avctx->qmax;
601
602    /* Quant Matrices */
603    x->intra_matrix = x->inter_matrix = NULL;
604    if( avctx->mpeg_quant )
605       x->vol_flags |= XVID_VOL_MPEGQUANT;
606    if( (avctx->intra_matrix || avctx->inter_matrix) ) {
607       x->vol_flags |= XVID_VOL_MPEGQUANT;
608
609       if( avctx->intra_matrix ) {
610           intra = avctx->intra_matrix;
611           x->intra_matrix = av_malloc(sizeof(unsigned char) * 64);
612       } else
613           intra = NULL;
614       if( avctx->inter_matrix ) {
615           inter = avctx->inter_matrix;
616           x->inter_matrix = av_malloc(sizeof(unsigned char) * 64);
617       } else
618           inter = NULL;
619
620       for( i = 0; i < 64; i++ ) {
621           if( intra )
622               x->intra_matrix[i] = (unsigned char)intra[i];
623           if( inter )
624               x->inter_matrix[i] = (unsigned char)inter[i];
625       }
626    }
627
628    /* Misc Settings */
629    xvid_enc_create.frame_drop_ratio = 0;
630    xvid_enc_create.global = 0;
631    if( xvid_flags & CODEC_FLAG_CLOSED_GOP )
632        xvid_enc_create.global |= XVID_GLOBAL_CLOSED_GOP;
633
634    /* Determines which codec mode we are operating in */
635    avctx->extradata = NULL;
636    avctx->extradata_size = 0;
637    if( xvid_flags & CODEC_FLAG_GLOBAL_HEADER ) {
638        /* In this case, we are claiming to be MPEG4 */
639        x->quicktime_format = 1;
640        avctx->codec_id = AV_CODEC_ID_MPEG4;
641    } else {
642        /* We are claiming to be Xvid */
643        x->quicktime_format = 0;
644        if(!avctx->codec_tag)
645            avctx->codec_tag = AV_RL32("xvid");
646    }
647
648    /* Bframes */
649    xvid_enc_create.max_bframes = avctx->max_b_frames;
650    xvid_enc_create.bquant_offset = 100 * avctx->b_quant_offset;
651    xvid_enc_create.bquant_ratio = 100 * avctx->b_quant_factor;
652    if( avctx->max_b_frames > 0  && !x->quicktime_format ) xvid_enc_create.global |= XVID_GLOBAL_PACKED;
653
654    av_assert0(xvid_enc_create.num_plugins + (!!x->ssim) + (!!x->variance_aq) + (!!x->lumi_aq) <= FF_ARRAY_ELEMS(plugins));
655
656    /* Create encoder context */
657    xerr = xvid_encore(NULL, XVID_ENC_CREATE, &xvid_enc_create, NULL);
658    if( xerr ) {
659        av_log(avctx, AV_LOG_ERROR, "Xvid: Could not create encoder reference\n");
660        goto fail;
661    }
662
663    x->encoder_handle = xvid_enc_create.handle;
664    avctx->coded_frame = av_frame_alloc();
665    if (!avctx->coded_frame)
666        return AVERROR(ENOMEM);
667
668    return 0;
669fail:
670    xvid_encode_close(avctx);
671    return -1;
672}
673
674static int xvid_encode_frame(AVCodecContext *avctx, AVPacket *pkt,
675                             const AVFrame *picture, int *got_packet)
676{
677    int xerr, i, ret, user_packet = !!pkt->data;
678    char *tmp;
679    struct xvid_context *x = avctx->priv_data;
680    AVFrame *p = avctx->coded_frame;
681    int mb_width   = (avctx->width  + 15) / 16;
682    int mb_height  = (avctx->height + 15) / 16;
683
684    xvid_enc_frame_t xvid_enc_frame = { 0 };
685    xvid_enc_stats_t xvid_enc_stats = { 0 };
686
687    if ((ret = ff_alloc_packet2(avctx, pkt, mb_width*mb_height*MAX_MB_BYTES + FF_MIN_BUFFER_SIZE)) < 0)
688        return ret;
689
690    /* Start setting up the frame */
691    xvid_enc_frame.version = XVID_VERSION;
692    xvid_enc_stats.version = XVID_VERSION;
693
694    /* Let Xvid know where to put the frame. */
695    xvid_enc_frame.bitstream = pkt->data;
696    xvid_enc_frame.length    = pkt->size;
697
698    /* Initialize input image fields */
699    if( avctx->pix_fmt != AV_PIX_FMT_YUV420P ) {
700        av_log(avctx, AV_LOG_ERROR, "Xvid: Color spaces other than 420p not supported\n");
701        return AVERROR(EINVAL);
702    }
703
704    xvid_enc_frame.input.csp = XVID_CSP_PLANAR; /* YUV420P */
705
706    for( i = 0; i < 4; i++ ) {
707        xvid_enc_frame.input.plane[i] = picture->data[i];
708        xvid_enc_frame.input.stride[i] = picture->linesize[i];
709    }
710
711    /* Encoder Flags */
712    xvid_enc_frame.vop_flags = x->vop_flags;
713    xvid_enc_frame.vol_flags = x->vol_flags;
714    xvid_enc_frame.motion = x->me_flags;
715    xvid_enc_frame.type =
716        picture->pict_type == AV_PICTURE_TYPE_I ? XVID_TYPE_IVOP :
717        picture->pict_type == AV_PICTURE_TYPE_P ? XVID_TYPE_PVOP :
718        picture->pict_type == AV_PICTURE_TYPE_B ? XVID_TYPE_BVOP :
719                                          XVID_TYPE_AUTO;
720
721    /* Pixel aspect ratio setting */
722    if (avctx->sample_aspect_ratio.num < 0 || avctx->sample_aspect_ratio.num > 255 ||
723        avctx->sample_aspect_ratio.den < 0 || avctx->sample_aspect_ratio.den > 255) {
724        av_log(avctx, AV_LOG_WARNING,
725               "Invalid pixel aspect ratio %i/%i, limit is 255/255 reducing\n",
726               avctx->sample_aspect_ratio.num, avctx->sample_aspect_ratio.den);
727        av_reduce(&avctx->sample_aspect_ratio.num, &avctx->sample_aspect_ratio.den,
728                   avctx->sample_aspect_ratio.num,  avctx->sample_aspect_ratio.den, 255);
729    }
730    xvid_enc_frame.par = XVID_PAR_EXT;
731    xvid_enc_frame.par_width  = avctx->sample_aspect_ratio.num;
732    xvid_enc_frame.par_height = avctx->sample_aspect_ratio.den;
733
734    /* Quant Setting */
735    if( x->qscale ) xvid_enc_frame.quant = picture->quality / FF_QP2LAMBDA;
736    else xvid_enc_frame.quant = 0;
737
738    /* Matrices */
739    xvid_enc_frame.quant_intra_matrix = x->intra_matrix;
740    xvid_enc_frame.quant_inter_matrix = x->inter_matrix;
741
742    /* Encode */
743    xerr = xvid_encore(x->encoder_handle, XVID_ENC_ENCODE,
744        &xvid_enc_frame, &xvid_enc_stats);
745
746    /* Two-pass log buffer swapping */
747    avctx->stats_out = NULL;
748    if( x->twopassbuffer ) {
749        tmp = x->old_twopassbuffer;
750        x->old_twopassbuffer = x->twopassbuffer;
751        x->twopassbuffer = tmp;
752        x->twopassbuffer[0] = 0;
753        if( x->old_twopassbuffer[0] != 0 ) {
754            avctx->stats_out = x->old_twopassbuffer;
755        }
756    }
757
758    if (xerr > 0) {
759        *got_packet = 1;
760
761        p->quality = xvid_enc_stats.quant * FF_QP2LAMBDA;
762        if( xvid_enc_stats.type == XVID_TYPE_PVOP )
763            p->pict_type = AV_PICTURE_TYPE_P;
764        else if( xvid_enc_stats.type == XVID_TYPE_BVOP )
765            p->pict_type = AV_PICTURE_TYPE_B;
766        else if( xvid_enc_stats.type == XVID_TYPE_SVOP )
767            p->pict_type = AV_PICTURE_TYPE_S;
768        else
769            p->pict_type = AV_PICTURE_TYPE_I;
770        if( xvid_enc_frame.out_flags & XVID_KEYFRAME ) {
771            p->key_frame = 1;
772            pkt->flags |= AV_PKT_FLAG_KEY;
773            if( x->quicktime_format )
774                return xvid_strip_vol_header(avctx, pkt,
775                    xvid_enc_stats.hlength, xerr);
776         } else
777            p->key_frame = 0;
778
779        pkt->size = xerr;
780
781        return 0;
782    } else {
783        if (!user_packet)
784            av_free_packet(pkt);
785        if (!xerr)
786            return 0;
787        av_log(avctx, AV_LOG_ERROR, "Xvid: Encoding Error Occurred: %i\n", xerr);
788        return AVERROR_EXTERNAL;
789    }
790}
791
792static av_cold int xvid_encode_close(AVCodecContext *avctx) {
793    struct xvid_context *x = avctx->priv_data;
794
795    if(x->encoder_handle)
796        xvid_encore(x->encoder_handle, XVID_ENC_DESTROY, NULL, NULL);
797    x->encoder_handle = NULL;
798
799    av_freep(&avctx->extradata);
800    if( x->twopassbuffer != NULL ) {
801        av_freep(&x->twopassbuffer);
802        av_freep(&x->old_twopassbuffer);
803        avctx->stats_out = NULL;
804    }
805    if (x->twopassfd>=0) {
806        unlink(x->twopassfile);
807        close(x->twopassfd);
808        x->twopassfd = -1;
809    }
810    av_freep(&x->twopassfile);
811    av_freep(&x->intra_matrix);
812    av_freep(&x->inter_matrix);
813
814    return 0;
815}
816
817#define OFFSET(x) offsetof(struct xvid_context, x)
818#define VE AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_ENCODING_PARAM
819static const AVOption options[] = {
820    { "lumi_aq",     "Luminance masking AQ", OFFSET(lumi_aq),     AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 1, VE },
821    { "variance_aq", "Variance AQ",          OFFSET(variance_aq), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 1, VE },
822    { "ssim",        "Show SSIM information to stdout",       OFFSET(ssim),              AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 2, VE, "ssim" },
823        { "off",     NULL, 0, AV_OPT_TYPE_CONST, { .i64 = 0 }, INT_MIN, INT_MAX, VE, "ssim" },
824        { "avg",     NULL, 0, AV_OPT_TYPE_CONST, { .i64 = 1 }, INT_MIN, INT_MAX, VE, "ssim" },
825        { "frame",   NULL, 0, AV_OPT_TYPE_CONST, { .i64 = 2 }, INT_MIN, INT_MAX, VE, "ssim" },
826    { "ssim_acc",    "SSIM accuracy",                         OFFSET(ssim_acc),          AV_OPT_TYPE_INT, { .i64 = 2 }, 0, 4, VE },
827    { "gmc",         "use GMC",              OFFSET(gmc),         AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 1, VE },
828    { NULL },
829};
830
831static const AVClass xvid_class = {
832    .class_name = "libxvid",
833    .item_name  = av_default_item_name,
834    .option     = options,
835    .version    = LIBAVUTIL_VERSION_INT,
836};
837
838AVCodec ff_libxvid_encoder = {
839    .name           = "libxvid",
840    .long_name      = NULL_IF_CONFIG_SMALL("libxvidcore MPEG-4 part 2"),
841    .type           = AVMEDIA_TYPE_VIDEO,
842    .id             = AV_CODEC_ID_MPEG4,
843    .priv_data_size = sizeof(struct xvid_context),
844    .init           = xvid_encode_init,
845    .encode2        = xvid_encode_frame,
846    .close          = xvid_encode_close,
847    .pix_fmts       = (const enum AVPixelFormat[]){ AV_PIX_FMT_YUV420P, AV_PIX_FMT_NONE },
848    .priv_class     = &xvid_class,
849};
850