[svn] / branches / dev-api-4 / xvidcore / src / encoder.c Repository:
ViewVC logotype

Diff of /branches/dev-api-4/xvidcore/src/encoder.c

Parent Directory Parent Directory | Revision Log Revision Log | View Patch Patch

trunk/xvidcore/src/encoder.c revision 41, Wed Mar 20 00:28:02 2002 UTC branches/dev-api-4/xvidcore/src/encoder.c revision 1014, Mon May 12 12:33:16 2003 UTC
# Line 1  Line 1 
1    /*****************************************************************************
2     *
3     *  XVID MPEG-4 VIDEO CODEC
4     *  -  Encoder main module  -
5     *
6     *  This program is an implementation of a part of one or more MPEG-4
7     *  Video tools as specified in ISO/IEC 14496-2 standard.  Those intending
8     *  to use this software module in hardware or software products are
9     *  advised that its use may infringe existing patents or copyrights, and
10     *  any such use would be at such party's own risk.  The original
11     *  developer of this software module and his/her company, and subsequent
12     *  editors and their companies, will have no liability for use of this
13     *  software or modifications or derivatives thereof.
14     *
15     *  This program is free software; you can redistribute it and/or modify
16     *  it under the terms of the GNU General Public License as published by
17     *  the Free Software Foundation; either version 2 of the License, or
18     *  (at your option) any later version.
19     *
20     *  This program is distributed in the hope that it will be useful,
21     *  but WITHOUT ANY WARRANTY; without even the implied warranty of
22     *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
23     *  GNU General Public License for more details.
24     *
25     *  You should have received a copy of the GNU General Public License
26     *  along with this program; if not, write to the Free Software
27     *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
28     *
29     *  $Id: encoder.c,v 1.95.2.21 2003-05-12 12:27:32 suxen_drol Exp $
30     *
31     ****************************************************************************/
32    
33  #include <stdlib.h>  #include <stdlib.h>
34  #include <stdio.h>  #include <stdio.h>
35  #include <math.h>  #include <math.h>
36    #include <string.h>
37    
38  #include "encoder.h"  #include "encoder.h"
39  #include "prediction/mbprediction.h"  #include "prediction/mbprediction.h"
40  #include "global.h"  #include "global.h"
41  #include "utils/timer.h"  #include "utils/timer.h"
42  #include "image/image.h"  #include "image/image.h"
43    #include "image/font.h"
44    #include "motion/sad.h"
45    #include "motion/motion.h"
46  #include "bitstream/cbp.h"  #include "bitstream/cbp.h"
47  #include "utils/mbfunctions.h"  #include "utils/mbfunctions.h"
48  #include "bitstream/bitstream.h"  #include "bitstream/bitstream.h"
49  #include "bitstream/mbcoding.h"  #include "bitstream/mbcoding.h"
 #include "utils/ratecontrol.h"  
50  #include "utils/emms.h"  #include "utils/emms.h"
51  #include "bitstream/mbcoding.h"  #include "bitstream/mbcoding.h"
52  #include "quant/adapt_quant.h"  #include "quant/adapt_quant.h"
53  #include "quant/quant_matrix.h"  #include "quant/quant_matrix.h"
54  #include "utils/mem_align.h"  #include "utils/mem_align.h"
55    
56  #define ENC_CHECK(X) if(!(X)) return XVID_ERR_FORMAT  /*****************************************************************************
57     * Local function prototypes
58     ****************************************************************************/
59    
60    static int FrameCodeI(Encoder * pEnc,
61                                              Bitstream * bs);
62    
63    static int FrameCodeP(Encoder * pEnc,
64                                              Bitstream * bs,
65                                              bool force_inter,
66                                              bool vol_header);
67    
68    static void FrameCodeB(Encoder * pEnc,
69                                               FRAMEINFO * frame,
70                                               Bitstream * bs);
71    
72    
73    /*****************************************************************************
74     * Encoder creation
75     *
76     * This function creates an Encoder instance, it allocates all necessary
77     * image buffers (reference, current and bframes) and initialize the internal
78     * xvid encoder paremeters according to the XVID_ENC_PARAM input parameter.
79     *
80     * The code seems to be very long but is very basic, mainly memory allocation
81     * and cleaning code.
82     *
83     * Returned values :
84     *    - 0                - no errors
85     *    - XVID_ERR_MEMORY - the libc could not allocate memory, the function
86     *                        cleans the structure before exiting.
87     *                        pParam->handle is also set to NULL.
88     *
89     ****************************************************************************/
90    
91    /*
92     * Simplify the "fincr/fbase" fraction
93    */
94    static void
95    simplify_time(int *inc, int *base)
96    {
97            /* common factor */
98            int i = *inc;
99            while (i > 1) {
100                    if (*inc % i == 0 && *base % i == 0) {
101                            *inc /= i;
102                            *base /= i;
103                            i = *inc;
104                            continue;
105                    }
106                    i--;
107            }
108    
109            /* if neccessary, round to 65535 accuracy */
110            if (*base > 65535) {
111                    float div = (float) *base / 65535;
112                    *base = (int) (*base / div);
113                    *inc = (int) (*inc / div);
114            }
115    }
116    
 static int FrameCodeI(Encoder * pEnc, Bitstream * bs, uint32_t *pBits);  
 static int FrameCodeP(Encoder * pEnc, Bitstream * bs, uint32_t *pBits, bool force_inter, bool vol_header);  
117    
118  static int DQtab[4] =  int
119    enc_create(xvid_enc_create_t * create)
120  {  {
121          -1, -2, 1, 2          Encoder *pEnc;
122  };      int n;
123    
124  static int iDQtab[5] =          if (XVID_MAJOR(create->version) != 1)   /* v1.x.x */
125  {                  return XVID_ERR_VERSION;
         1, 0, NO_CHANGE, 2, 3  
 };  
126    
127            if (create->width%2 || create->height%2)
128                    return XVID_ERR_FAIL;
129    
130  int encoder_create(XVID_ENC_PARAM * pParam)          /* allocate encoder struct */
 {  
         Encoder *pEnc;  
         uint32_t i;  
131    
132          pParam->handle = NULL;          pEnc = (Encoder *) xvid_malloc(sizeof(Encoder), CACHE_LINE);
133            if (pEnc == NULL)
134                    return XVID_ERR_MEMORY;
135            memset(pEnc, 0, sizeof(Encoder));
136    
137          ENC_CHECK(pParam);      pEnc->mbParam.profile = create->profile;
138    
139          ENC_CHECK(pParam->width > 0 && pParam->width <= 1920);          /* global flags */
140          ENC_CHECK(pParam->height > 0 && pParam->height <= 1280);      pEnc->mbParam.global_flags = create->global;
         ENC_CHECK(!(pParam->width % 2));  
         ENC_CHECK(!(pParam->height % 2));  
141    
142          if (pParam->fincr <= 0 || pParam->fbase <= 0)      /* width, height */
143          {          pEnc->mbParam.width = create->width;
144                  pParam->fincr = 1;          pEnc->mbParam.height = create->height;
145                  pParam->fbase = 25;          pEnc->mbParam.mb_width = (pEnc->mbParam.width + 15) / 16;
146            pEnc->mbParam.mb_height = (pEnc->mbParam.height + 15) / 16;
147            pEnc->mbParam.edged_width = 16 * pEnc->mbParam.mb_width + 2 * EDGE_SIZE;
148            pEnc->mbParam.edged_height = 16 * pEnc->mbParam.mb_height + 2 * EDGE_SIZE;
149    
150        /* framerate */
151        pEnc->mbParam.fincr = MAX(create->fincr, 0);
152            pEnc->mbParam.fbase = create->fincr <= 0 ? 25 : create->fbase;
153        if (pEnc->mbParam.fincr>0)
154                simplify_time(&pEnc->mbParam.fincr, &pEnc->mbParam.fbase);
155    
156        /* zones */
157        if(create->num_zones > 0) {
158                    pEnc->num_zones = create->num_zones;
159                    pEnc->zones = xvid_malloc(sizeof(xvid_enc_zone_t) * pEnc->num_zones, CACHE_LINE);
160                    if (pEnc->zones == NULL)
161                            goto xvid_err_memory0;
162            memcpy(pEnc->zones, create->zones, sizeof(xvid_enc_zone_t) * pEnc->num_zones);
163            } else {
164                    pEnc->num_zones = 0;
165                    pEnc->zones = NULL;
166            }
167    
168        /* plugins */
169        if(create->num_plugins > 0) {
170                    pEnc->num_plugins = create->num_plugins;
171                    pEnc->plugins = xvid_malloc(sizeof(xvid_enc_plugin_t) * pEnc->num_plugins, CACHE_LINE);
172                    if (pEnc->plugins == NULL)
173                            goto xvid_err_memory0;
174            } else {
175                    pEnc->num_plugins = 0;
176                    pEnc->plugins = NULL;
177          }          }
178    
179          // simplify the "fincr/fbase" fraction      for (n=0; n<pEnc->num_plugins;n++) {
180          // (neccessary, since windows supplies us with huge numbers)          xvid_plg_create_t pcreate;
181            xvid_plg_info_t pinfo;
182    
183          i = pParam->fincr;          memset(&pinfo, 0, sizeof(xvid_plg_info_t));
184          while (i > 1)          pinfo.version = XVID_VERSION;
185          {          if (create->plugins[n].func(0, XVID_PLG_INFO, &pinfo, 0) >= 0) {
186                  if (pParam->fincr % i == 0 && pParam->fbase % i == 0)              pEnc->mbParam.plugin_flags |= pinfo.flags;
187                  {          }
188                          pParam->fincr /= i;  
189                          pParam->fbase /= i;          memset(&pcreate, 0, sizeof(xvid_plg_create_t));
190                          i = pParam->fincr;          pcreate.version = XVID_VERSION;
191                          continue;          pcreate.num_zones = pEnc->num_zones;
192            pcreate.zones = pEnc->zones;
193            pcreate.width = pEnc->mbParam.width;
194            pcreate.height = pEnc->mbParam.height;
195            pcreate.fincr = pEnc->mbParam.fincr;
196            pcreate.fbase = pEnc->mbParam.fbase;
197            pcreate.param = create->plugins[n].param;
198    
199            pEnc->plugins[n].func = NULL;   /* disable plugins that fail */
200            if (create->plugins[n].func(0, XVID_PLG_CREATE, &pcreate, &pEnc->plugins[n].param) >= 0) {
201                pEnc->plugins[n].func = create->plugins[n].func;
202                  }                  }
                 i--;  
203          }          }
204    
205          if (pParam->fbase > 65535)      if ((pEnc->mbParam.global_flags & XVID_GLOBAL_EXTRASTATS_ENABLE) ||
206          {          (pEnc->mbParam.plugin_flags & XVID_REQPSNR)) {
207                  float div = (float)pParam->fbase / 65535;          pEnc->mbParam.plugin_flags |= XVID_REQORIGINAL; /* psnr calculation requires the original */
                 pParam->fbase = (int)(pParam->fbase / div);  
                 pParam->fincr = (int)(pParam->fincr / div);  
208          }          }
209    
210          if (pParam->bitrate <= 0)      /* temp dquants */
211                  pParam->bitrate = 900000;      if ((pEnc->mbParam.plugin_flags & XVID_REQDQUANTS)) {
212                pEnc->temp_dquants = (int *) xvid_malloc(pEnc->mbParam.mb_width *
213                                                pEnc->mbParam.mb_height * sizeof(int), CACHE_LINE);
214        }
215        /* XXX: error checking */
216    
217          if (pParam->rc_buffersize <= 0)          /* bframes */
218                  pParam->rc_buffersize = pParam->bitrate * pParam->fbase;          pEnc->mbParam.max_bframes = MAX(create->max_bframes, 0);
219            pEnc->mbParam.bquant_ratio = MAX(create->bquant_ratio, 0);
220            pEnc->mbParam.bquant_offset = create->bquant_offset;
221    
222          if ((pParam->min_quantizer <= 0) || (pParam->min_quantizer > 31))      /* min/max quant */
223                  pParam->min_quantizer = 1;      for (n=0; n<3; n++) {
224            pEnc->mbParam.min_quant[n] = create->min_quant[n] > 0 ? create->min_quant[n] : 2;
225            pEnc->mbParam.max_quant[n] = create->max_quant[n] > 0 ? create->max_quant[n] : 31;
226        }
227    
228          if ((pParam->max_quantizer <= 0) || (pParam->max_quantizer > 31))          /* frame drop ratio */
229                  pParam->max_quantizer = 31;          pEnc->mbParam.frame_drop_ratio = MAX(create->frame_drop_ratio, 0);
230    
231          if (pParam->max_key_interval == 0)              /* 1 keyframe each 10 seconds */      /* max keyframe interval */
232                  pParam->max_key_interval = 10 * pParam->fincr / pParam->fbase;      pEnc->mbParam.iMaxKeyInterval = create->max_key_interval <= 0 ?
233                    10 * pEnc->mbParam.fbase / pEnc->mbParam.fincr : create->max_key_interval;
234    
235          if (pParam->max_quantizer < pParam->min_quantizer)          /* Bitrate allocator defaults
                 pParam->max_quantizer = pParam->min_quantizer;  
236    
237          if ((pEnc = (Encoder *) xvid_malloc(sizeof(Encoder), 16)) == NULL)          if ((create->min_quantizer <= 0) || (create->min_quantizer > 31))
238                  return XVID_ERR_MEMORY;                  create->min_quantizer = 1;
239    
240          /* Fill members of Encoder structure */          if ((create->max_quantizer <= 0) || (create->max_quantizer > 31))
241                    create->max_quantizer = 31;
242    
243          pEnc->mbParam.width = pParam->width;          if (create->max_quantizer < create->min_quantizer)
244          pEnc->mbParam.height = pParam->height;                  create->max_quantizer = create->min_quantizer; */
245    
         pEnc->mbParam.mb_width = (pEnc->mbParam.width + 15) / 16;  
         pEnc->mbParam.mb_height = (pEnc->mbParam.height + 15) / 16;  
246    
247          pEnc->mbParam.edged_width = 16 * pEnc->mbParam.mb_width + 2 * EDGE_SIZE;      /* allocate working frame-image memory */
         pEnc->mbParam.edged_height = 16 * pEnc->mbParam.mb_height + 2 * EDGE_SIZE;  
248    
249          pEnc->sStat.fMvPrevSigma = -1;          pEnc->current = xvid_malloc(sizeof(FRAMEINFO), CACHE_LINE);
250            pEnc->reference = xvid_malloc(sizeof(FRAMEINFO), CACHE_LINE);
251    
252          /* Fill rate control parameters */          if (pEnc->current == NULL || pEnc->reference == NULL)
253                    goto xvid_err_memory1;
254    
255          pEnc->mbParam.quant = 4;          /* allocate macroblock memory */
256    
257          pEnc->bitrate = pParam->bitrate;          pEnc->current->mbs =
258                    xvid_malloc(sizeof(MACROBLOCK) * pEnc->mbParam.mb_width *
259                                            pEnc->mbParam.mb_height, CACHE_LINE);
260            pEnc->reference->mbs =
261                    xvid_malloc(sizeof(MACROBLOCK) * pEnc->mbParam.mb_width *
262                                            pEnc->mbParam.mb_height, CACHE_LINE);
263    
264          pEnc->iFrameNum = 0;          if (pEnc->current->mbs == NULL || pEnc->reference->mbs == NULL)
265          pEnc->iMaxKeyInterval = pParam->max_key_interval;                  goto xvid_err_memory2;
266    
267          if (image_create(&pEnc->sCurrent, pEnc->mbParam.edged_width, pEnc->mbParam.edged_height) < 0)          /* allocate interpolation image memory */
         {  
                 xvid_free(pEnc);  
                 return XVID_ERR_MEMORY;  
         }  
268    
269          if (image_create(&pEnc->sReference, pEnc->mbParam.edged_width, pEnc->mbParam.edged_height) < 0)      if ((pEnc->mbParam.plugin_flags & XVID_REQORIGINAL)) {
270          {          image_null(&pEnc->sOriginal);
271                  image_destroy(&pEnc->sCurrent, pEnc->mbParam.edged_width, pEnc->mbParam.edged_height);          image_null(&pEnc->sOriginal2);
                 xvid_free(pEnc);  
                 return XVID_ERR_MEMORY;  
272          }          }
273    
274          if (image_create(&pEnc->vInterH, pEnc->mbParam.edged_width, pEnc->mbParam.edged_height) < 0)          image_null(&pEnc->f_refh);
275          {          image_null(&pEnc->f_refv);
276                  image_destroy(&pEnc->sCurrent, pEnc->mbParam.edged_width, pEnc->mbParam.edged_height);          image_null(&pEnc->f_refhv);
                 image_destroy(&pEnc->sReference, pEnc->mbParam.edged_width, pEnc->mbParam.edged_height);  
                 xvid_free(pEnc);  
                 return XVID_ERR_MEMORY;  
         }  
277    
278          if (image_create(&pEnc->vInterV, pEnc->mbParam.edged_width, pEnc->mbParam.edged_height) < 0)          image_null(&pEnc->current->image);
279          {          image_null(&pEnc->reference->image);
280                  image_destroy(&pEnc->sCurrent, pEnc->mbParam.edged_width, pEnc->mbParam.edged_height);          image_null(&pEnc->vInterH);
281                  image_destroy(&pEnc->sReference, pEnc->mbParam.edged_width, pEnc->mbParam.edged_height);          image_null(&pEnc->vInterV);
282                  image_destroy(&pEnc->vInterH, pEnc->mbParam.edged_width, pEnc->mbParam.edged_height);          image_null(&pEnc->vInterVf);
283                  xvid_free(pEnc);          image_null(&pEnc->vInterHV);
284                  return XVID_ERR_MEMORY;          image_null(&pEnc->vInterHVf);
         }  
285    
286          if (image_create(&pEnc->vInterHV, pEnc->mbParam.edged_width, pEnc->mbParam.edged_height) < 0)          if ((pEnc->mbParam.plugin_flags & XVID_REQORIGINAL)) {
287          {          if (image_create
288                  image_destroy(&pEnc->sCurrent, pEnc->mbParam.edged_width, pEnc->mbParam.edged_height);                          (&pEnc->sOriginal, pEnc->mbParam.edged_width,
289                  image_destroy(&pEnc->sReference, pEnc->mbParam.edged_width, pEnc->mbParam.edged_height);                           pEnc->mbParam.edged_height) < 0)
290                  image_destroy(&pEnc->vInterH, pEnc->mbParam.edged_width, pEnc->mbParam.edged_height);                          goto xvid_err_memory3;
                 image_destroy(&pEnc->vInterV, pEnc->mbParam.edged_width, pEnc->mbParam.edged_height);  
                 xvid_free(pEnc);  
                 return XVID_ERR_MEMORY;  
         }  
291    
292          pEnc->pMBs = xvid_malloc(sizeof(MACROBLOCK) * pEnc->mbParam.mb_width * pEnc->mbParam.mb_height, 16);          if (image_create
293          if (pEnc->pMBs == NULL)                          (&pEnc->sOriginal2, pEnc->mbParam.edged_width,
294          {                           pEnc->mbParam.edged_height) < 0)
295                  image_destroy(&pEnc->sCurrent, pEnc->mbParam.edged_width, pEnc->mbParam.edged_height);                          goto xvid_err_memory3;
                 image_destroy(&pEnc->sReference, pEnc->mbParam.edged_width, pEnc->mbParam.edged_height);  
                 image_destroy(&pEnc->vInterH, pEnc->mbParam.edged_width, pEnc->mbParam.edged_height);  
                 image_destroy(&pEnc->vInterV, pEnc->mbParam.edged_width, pEnc->mbParam.edged_height);  
                 image_destroy(&pEnc->vInterHV, pEnc->mbParam.edged_width, pEnc->mbParam.edged_height);  
                 xvid_free(pEnc);  
                 return XVID_ERR_MEMORY;  
296          }          }
297    
298          // init macroblock array          if (image_create
299          for (i = 0; i < pEnc->mbParam.mb_width * pEnc->mbParam.mb_height; i++)                  (&pEnc->f_refh, pEnc->mbParam.edged_width,
300          {                   pEnc->mbParam.edged_height) < 0)
301                  pEnc->pMBs[i].dquant = NO_CHANGE;                  goto xvid_err_memory3;
302          }          if (image_create
303                    (&pEnc->f_refv, pEnc->mbParam.edged_width,
304                     pEnc->mbParam.edged_height) < 0)
305                    goto xvid_err_memory3;
306            if (image_create
307                    (&pEnc->f_refhv, pEnc->mbParam.edged_width,
308                     pEnc->mbParam.edged_height) < 0)
309                    goto xvid_err_memory3;
310    
311          pParam->handle = (void *)pEnc;          if (image_create
312                    (&pEnc->current->image, pEnc->mbParam.edged_width,
313                     pEnc->mbParam.edged_height) < 0)
314                    goto xvid_err_memory3;
315            if (image_create
316                    (&pEnc->reference->image, pEnc->mbParam.edged_width,
317                     pEnc->mbParam.edged_height) < 0)
318                    goto xvid_err_memory3;
319            if (image_create
320                    (&pEnc->vInterH, pEnc->mbParam.edged_width,
321                     pEnc->mbParam.edged_height) < 0)
322                    goto xvid_err_memory3;
323            if (image_create
324                    (&pEnc->vInterV, pEnc->mbParam.edged_width,
325                     pEnc->mbParam.edged_height) < 0)
326                    goto xvid_err_memory3;
327            if (image_create
328                    (&pEnc->vInterVf, pEnc->mbParam.edged_width,
329                     pEnc->mbParam.edged_height) < 0)
330                    goto xvid_err_memory3;
331            if (image_create
332                    (&pEnc->vInterHV, pEnc->mbParam.edged_width,
333                     pEnc->mbParam.edged_height) < 0)
334                    goto xvid_err_memory3;
335            if (image_create
336                    (&pEnc->vInterHVf, pEnc->mbParam.edged_width,
337                     pEnc->mbParam.edged_height) < 0)
338                    goto xvid_err_memory3;
339    
340          if (pParam->bitrate)  /* Create full bitplane for GMC, this might be wasteful */
341          {          if (image_create
342                  RateControlInit(pParam->bitrate, pParam->rc_buffersize, pParam->fbase, pParam->width,                  (&pEnc->vGMC, pEnc->mbParam.edged_width,
343                                  pParam->height, pParam->max_quantizer, pParam->min_quantizer);                   pEnc->mbParam.edged_height) < 0)
344          }                  goto xvid_err_memory3;
345    
346          create_vlc_tables();          /* init bframe image buffers */
         init_timer();  
347    
348          return XVID_ERR_OK;          pEnc->bframenum_head = 0;
349  }          pEnc->bframenum_tail = 0;
350            pEnc->flush_bframes = 0;
351            pEnc->closed_bframenum = -1;
352    
353            /* B Frames specific init */
354            pEnc->bframes = NULL;
355    
356  int encoder_destroy(Encoder * pEnc)          if (pEnc->mbParam.max_bframes > 0) {
 {  
         ENC_CHECK(pEnc);  
         ENC_CHECK(pEnc->sCurrent.y);  
         ENC_CHECK(pEnc->sReference.y);  
357    
358          xvid_free(pEnc->pMBs);                  pEnc->bframes =
359          image_destroy(&pEnc->sCurrent, pEnc->mbParam.edged_width, pEnc->mbParam.edged_height);                          xvid_malloc(pEnc->mbParam.max_bframes * sizeof(FRAMEINFO *),
360          image_destroy(&pEnc->sReference, pEnc->mbParam.edged_width, pEnc->mbParam.edged_height);                                                  CACHE_LINE);
361          image_destroy(&pEnc->vInterH, pEnc->mbParam.edged_width, pEnc->mbParam.edged_height);  
362          image_destroy(&pEnc->vInterV, pEnc->mbParam.edged_width, pEnc->mbParam.edged_height);                  if (pEnc->bframes == NULL)
363          image_destroy(&pEnc->vInterHV, pEnc->mbParam.edged_width, pEnc->mbParam.edged_height);                          goto xvid_err_memory3;
364          xvid_free(pEnc);  
365                    for (n = 0; n < pEnc->mbParam.max_bframes; n++)
366                            pEnc->bframes[n] = NULL;
367    
368    
369                    for (n = 0; n < pEnc->mbParam.max_bframes; n++) {
370                            pEnc->bframes[n] = xvid_malloc(sizeof(FRAMEINFO), CACHE_LINE);
371    
372                            if (pEnc->bframes[n] == NULL)
373                                    goto xvid_err_memory4;
374    
375          destroy_vlc_tables();                          pEnc->bframes[n]->mbs =
376                                    xvid_malloc(sizeof(MACROBLOCK) * pEnc->mbParam.mb_width *
377                                                            pEnc->mbParam.mb_height, CACHE_LINE);
378    
379          return XVID_ERR_OK;                          if (pEnc->bframes[n]->mbs == NULL)
380                                    goto xvid_err_memory4;
381    
382                            image_null(&pEnc->bframes[n]->image);
383    
384                            if (image_create
385                                    (&pEnc->bframes[n]->image, pEnc->mbParam.edged_width,
386                                     pEnc->mbParam.edged_height) < 0)
387                                    goto xvid_err_memory4;
388    
389                    }
390  }  }
391    
392  int encoder_encode(Encoder * pEnc, XVID_ENC_FRAME * pFrame, XVID_ENC_STATS * pResult)      /* init incoming frame queue */
393  {          pEnc->queue_head = 0;
394          uint16_t x, y;          pEnc->queue_tail = 0;
395          Bitstream bs;          pEnc->queue_size = 0;
         uint32_t bits;  
         uint16_t write_vol_header = 0;  
396    
397          start_global_timer();          pEnc->queue =
398                    xvid_malloc((pEnc->mbParam.max_bframes+1) * sizeof(QUEUEINFO),
399                                            CACHE_LINE);
400    
401          ENC_CHECK(pEnc);          if (pEnc->queue == NULL)
402          ENC_CHECK(pFrame);                  goto xvid_err_memory4;
         ENC_CHECK(pFrame->bitstream);  
         ENC_CHECK(pFrame->image);  
403    
404          pEnc->mbParam.global_flags = pFrame->general;          for (n = 0; n < pEnc->mbParam.max_bframes+1; n++)
405          pEnc->mbParam.motion_flags = pFrame->motion;                  image_null(&pEnc->queue[n].image);
406    
407          start_timer();  
408          if (image_input(&pEnc->sCurrent, pEnc->mbParam.width, pEnc->mbParam.height, pEnc->mbParam.edged_width,          for (n = 0; n < pEnc->mbParam.max_bframes+1; n++)
                         pFrame->image, pFrame->colorspace))  
409          {          {
410                  return XVID_ERR_FORMAT;                  if (image_create
411                            (&pEnc->queue[n].image, pEnc->mbParam.edged_width,
412                             pEnc->mbParam.edged_height) < 0)
413                            goto xvid_err_memory5;
414    
415          }          }
         stop_conv_timer();  
416    
         EMMS();  
417    
418          BitstreamInit(&bs, pFrame->bitstream, 0);          /* timestamp stuff */
419    
420          if (pFrame->quant == 0)          pEnc->mbParam.m_stamp = 0;
421          {          pEnc->m_framenum = 0;
422                  pEnc->mbParam.quant = RateControlGetQ(0);          pEnc->current->stamp = 0;
423            pEnc->reference->stamp = 0;
424    
425            /* other stuff */
426    
427            pEnc->iFrameNum = 0;
428            pEnc->fMvPrevSigma = -1;
429    
430        create->handle = (void *) pEnc;
431    
432            init_timer();
433    
434        return 0;   /* ok */
435    
436            /*
437             * We handle all XVID_ERR_MEMORY here, this makes the code lighter
438             */
439    
440      xvid_err_memory5:
441    
442            if (pEnc->mbParam.max_bframes > 0) {
443            int i;
444    
445                    for (i = 0; i < pEnc->mbParam.max_bframes+1; i++) {
446                            image_destroy(&pEnc->queue[i].image, pEnc->mbParam.edged_width,
447                                                      pEnc->mbParam.edged_height);
448          }          }
449          else                  xvid_free(pEnc->queue);
         {  
                 pEnc->mbParam.quant = pFrame->quant;  
450          }          }
451    
452          if ((pEnc->mbParam.global_flags & XVID_LUMIMASKING) > 0)    xvid_err_memory4:
         {  
                 int * temp_dquants = (int *) xvid_malloc(pEnc->mbParam.mb_width * pEnc->mbParam.mb_height * sizeof(int), 16);  
453    
454                  pEnc->mbParam.quant = adaptive_quantization(pEnc->sCurrent.y, pEnc->mbParam.width,          if (pEnc->mbParam.max_bframes > 0) {
455                                                              temp_dquants, pFrame->quant, pFrame->quant,          int i;
456                                                              2*pFrame->quant, pEnc->mbParam.mb_width, pEnc->mbParam.mb_height);  
457                    for (i = 0; i < pEnc->mbParam.max_bframes; i++) {
458    
459                            if (pEnc->bframes[i] == NULL)
460                                    continue;
461    
462                            image_destroy(&pEnc->bframes[i]->image, pEnc->mbParam.edged_width,
463                                                      pEnc->mbParam.edged_height);
464    
465                            xvid_free(pEnc->bframes[i]->mbs);
466    
467                            xvid_free(pEnc->bframes[i]);
468    
                 for (y = 0; y < pEnc->mbParam.mb_height; y++)  
                         for (x = 0; x < pEnc->mbParam.mb_width; x++)  
                         {  
                                 MACROBLOCK *pMB = &pEnc->pMBs[x + y * pEnc->mbParam.mb_width];  
                                 pMB->dquant = iDQtab[(temp_dquants[y * pEnc->mbParam.mb_width + x] + 2)];  
469                          }                          }
470                  xvid_free(temp_dquants);  
471                    xvid_free(pEnc->bframes);
472          }          }
473    
474          if(pEnc->mbParam.global_flags & XVID_H263QUANT) {    xvid_err_memory3:
475                  if(pEnc->mbParam.quant_type != H263_QUANT)  
476                          write_vol_header = 1;          if ((pEnc->mbParam.plugin_flags & XVID_REQORIGINAL)) {
477                  pEnc->mbParam.quant_type = H263_QUANT;                  image_destroy(&pEnc->sOriginal, pEnc->mbParam.edged_width,
478                                              pEnc->mbParam.edged_height);
479                    image_destroy(&pEnc->sOriginal2, pEnc->mbParam.edged_width,
480                                              pEnc->mbParam.edged_height);
481          }          }
         else if(pEnc->mbParam.global_flags & XVID_MPEGQUANT) {  
                 int ret1, ret2;  
482    
483                  if(pEnc->mbParam.quant_type != MPEG4_QUANT)          image_destroy(&pEnc->f_refh, pEnc->mbParam.edged_width,
484                          write_vol_header = 1;                                    pEnc->mbParam.edged_height);
485            image_destroy(&pEnc->f_refv, pEnc->mbParam.edged_width,
486                                      pEnc->mbParam.edged_height);
487            image_destroy(&pEnc->f_refhv, pEnc->mbParam.edged_width,
488                                      pEnc->mbParam.edged_height);
489    
490            image_destroy(&pEnc->current->image, pEnc->mbParam.edged_width,
491                                      pEnc->mbParam.edged_height);
492            image_destroy(&pEnc->reference->image, pEnc->mbParam.edged_width,
493                                      pEnc->mbParam.edged_height);
494            image_destroy(&pEnc->vInterH, pEnc->mbParam.edged_width,
495                                      pEnc->mbParam.edged_height);
496            image_destroy(&pEnc->vInterV, pEnc->mbParam.edged_width,
497                                      pEnc->mbParam.edged_height);
498            image_destroy(&pEnc->vInterVf, pEnc->mbParam.edged_width,
499                                      pEnc->mbParam.edged_height);
500            image_destroy(&pEnc->vInterHV, pEnc->mbParam.edged_width,
501                                      pEnc->mbParam.edged_height);
502            image_destroy(&pEnc->vInterHVf, pEnc->mbParam.edged_width,
503                                      pEnc->mbParam.edged_height);
504    
505    /* destroy GMC image */
506            image_destroy(&pEnc->vGMC, pEnc->mbParam.edged_width,
507                                      pEnc->mbParam.edged_height);
508    
509    
510                  pEnc->mbParam.quant_type = MPEG4_QUANT;    xvid_err_memory2:
511            xvid_free(pEnc->current->mbs);
512            xvid_free(pEnc->reference->mbs);
513    
514                  if ((pEnc->mbParam.global_flags & XVID_CUSTOM_QMATRIX) > 0) {    xvid_err_memory1:
515                          if(pFrame->quant_intra_matrix != NULL)          xvid_free(pEnc->current);
516                                  ret1 = set_intra_matrix(pFrame->quant_intra_matrix);          xvid_free(pEnc->reference);
517                          if(pFrame->quant_inter_matrix != NULL)  
518                                  ret2 = set_inter_matrix(pFrame->quant_inter_matrix);      if ((pEnc->mbParam.plugin_flags & XVID_REQDQUANTS)) {
519                xvid_free(pEnc->temp_dquants);
520                  }                  }
521                  else {  
522                          ret1 = set_intra_matrix(get_default_intra_matrix());    xvid_err_memory0:
523                          ret2 = set_inter_matrix(get_default_inter_matrix());      for (n=0; n<pEnc->num_plugins;n++) {
524            if (pEnc->plugins[n].func) {
525                pEnc->plugins[n].func(pEnc->plugins[n].param, XVID_PLG_DESTROY, 0, 0);
526                  }                  }
                 if(write_vol_header == 0)  
                         write_vol_header = ret1 | ret2;  
527          }          }
528        xvid_free(pEnc->plugins);
529    
530          if (pFrame->intra < 0)      xvid_free(pEnc->zones);
         {  
                 if ((pEnc->iFrameNum == 0) || ((pEnc->iMaxKeyInterval > 0)  
                                                && (pEnc->iFrameNum >= pEnc->iMaxKeyInterval)))  
531    
532                          pFrame->intra = FrameCodeI(pEnc, &bs, &bits);          xvid_free(pEnc);
                 else  
                         pFrame->intra = FrameCodeP(pEnc, &bs, &bits, 0, write_vol_header);  
         }  
         else  
         {  
                 if (pFrame->intra == 1)  
                         pFrame->intra = FrameCodeI(pEnc, &bs, &bits);  
                 else  
                         pFrame->intra = FrameCodeP(pEnc, &bs, &bits, 1, write_vol_header);  
         }  
533    
534          BitstreamPutBits(&bs, 0xFFFF, 16);          create->handle = NULL;
         BitstreamPutBits(&bs, 0xFFFF, 16);  
         BitstreamPad(&bs);  
         pFrame->length = BitstreamLength(&bs);  
535    
536          if (pResult)          return XVID_ERR_MEMORY;
         {  
                 pResult->quant = pEnc->mbParam.quant;  
                 pResult->hlength = pFrame->length - (pEnc->sStat.iTextBits / 8);  
                 pResult->kblks = pEnc->sStat.kblks;  
                 pResult->mblks = pEnc->sStat.mblks;  
                 pResult->ublks = pEnc->sStat.ublks;  
537          }          }
538    
539          EMMS();  /*****************************************************************************
540     * Encoder destruction
541     *
542     * This function destroy the entire encoder structure created by a previous
543     * successful enc_create call.
544     *
545     * Returned values (for now only one returned value) :
546     *    - 0     - no errors
547     *
548     ****************************************************************************/
549    
550          if (pFrame->quant == 0)  int
551    enc_destroy(Encoder * pEnc)
552          {          {
553                  RateControlUpdate(pEnc->mbParam.quant, pFrame->length, pFrame->intra);          int i;
         }  
554    
555          pEnc->iFrameNum++;          /* B Frames specific */
556          image_swap(&pEnc->sCurrent, &pEnc->sReference);          if (pEnc->mbParam.max_bframes > 0) {
557    
558          stop_global_timer();                  for (i = 0; i < pEnc->mbParam.max_bframes+1; i++) {
         write_timer();  
559    
560          return XVID_ERR_OK;                          image_destroy(&pEnc->queue[i].image, pEnc->mbParam.edged_width,
561                                              pEnc->mbParam.edged_height);
562                    }
563                    xvid_free(pEnc->queue);
564  }  }
565    
566    
567  static __inline void CodeIntraMB(Encoder *pEnc, MACROBLOCK *pMB) {          if (pEnc->mbParam.max_bframes > 0) {
568    
569          pMB->mode = MODE_INTRA;                  for (i = 0; i < pEnc->mbParam.max_bframes; i++) {
570    
571          if ((pEnc->mbParam.global_flags & XVID_LUMIMASKING) > 0) {                          if (pEnc->bframes[i] == NULL)
572                  if(pMB->dquant != NO_CHANGE)                                  continue;
                 {  
                         pMB->mode = MODE_INTRA_Q;  
                         pEnc->mbParam.quant += DQtab[pMB->dquant];  
573    
574                          if (pEnc->mbParam.quant > 31) pEnc->mbParam.quant = 31;                          image_destroy(&pEnc->bframes[i]->image, pEnc->mbParam.edged_width,
575                          if (pEnc->mbParam.quant < 1) pEnc->mbParam.quant = 1;                                            pEnc->mbParam.edged_height);
576                  }  
577                            xvid_free(pEnc->bframes[i]->mbs);
578    
579                            xvid_free(pEnc->bframes[i]);
580          }          }
581    
582          pMB->quant = pEnc->mbParam.quant;                  xvid_free(pEnc->bframes);
583    
584  }  }
585    
586            /* All images, reference, current etc ... */
587    
588  static int FrameCodeI(Encoder * pEnc, Bitstream * bs, uint32_t *pBits)          image_destroy(&pEnc->current->image, pEnc->mbParam.edged_width,
589  {                                    pEnc->mbParam.edged_height);
590          int16_t dct_codes[6][64];          image_destroy(&pEnc->reference->image, pEnc->mbParam.edged_width,
591          int16_t qcoeff[6][64];                                    pEnc->mbParam.edged_height);
592          uint16_t x, y;          image_destroy(&pEnc->vInterH, pEnc->mbParam.edged_width,
593                                      pEnc->mbParam.edged_height);
594            image_destroy(&pEnc->vInterV, pEnc->mbParam.edged_width,
595                                      pEnc->mbParam.edged_height);
596            image_destroy(&pEnc->vInterVf, pEnc->mbParam.edged_width,
597                                      pEnc->mbParam.edged_height);
598            image_destroy(&pEnc->vInterHV, pEnc->mbParam.edged_width,
599                                      pEnc->mbParam.edged_height);
600            image_destroy(&pEnc->vInterHVf, pEnc->mbParam.edged_width,
601                                      pEnc->mbParam.edged_height);
602    
603          pEnc->iFrameNum = 0;          image_destroy(&pEnc->f_refh, pEnc->mbParam.edged_width,
604          pEnc->mbParam.rounding_type = 1;                                    pEnc->mbParam.edged_height);
605          pEnc->mbParam.coding_type = I_VOP;          image_destroy(&pEnc->f_refv, pEnc->mbParam.edged_width,
606                                      pEnc->mbParam.edged_height);
607            image_destroy(&pEnc->f_refhv, pEnc->mbParam.edged_width,
608                                      pEnc->mbParam.edged_height);
609            image_destroy(&pEnc->vGMC, pEnc->mbParam.edged_width,
610                                      pEnc->mbParam.edged_height);
611    
612          BitstreamWriteVolHeader(bs, pEnc->mbParam.width, pEnc->mbParam.height, pEnc->mbParam.quant_type);          if ((pEnc->mbParam.plugin_flags & XVID_REQORIGINAL)) {
613          BitstreamWriteVopHeader(bs, I_VOP, pEnc->mbParam.rounding_type,                  image_destroy(&pEnc->sOriginal, pEnc->mbParam.edged_width,
614                                  pEnc->mbParam.quant,                                            pEnc->mbParam.edged_height);
615                                  pEnc->mbParam.fixed_code);                  image_destroy(&pEnc->sOriginal2, pEnc->mbParam.edged_width,
616                                              pEnc->mbParam.edged_height);
617            }
618    
619          *pBits = BitstreamPos(bs);          /* Encoder structure */
620    
621          pEnc->sStat.iTextBits = 0;          xvid_free(pEnc->current->mbs);
622          pEnc->sStat.kblks = pEnc->mbParam.mb_width * pEnc->mbParam.mb_height;          xvid_free(pEnc->current);
         pEnc->sStat.mblks = pEnc->sStat.ublks = 0;  
623    
624          for (y = 0; y < pEnc->mbParam.mb_height; y++)          xvid_free(pEnc->reference->mbs);
625                  for (x = 0; x < pEnc->mbParam.mb_width; x++)          xvid_free(pEnc->reference);
                 {  
                         MACROBLOCK *pMB = &pEnc->pMBs[x + y * pEnc->mbParam.mb_width];  
626    
627                          CodeIntraMB(pEnc, pMB);      if ((pEnc->mbParam.plugin_flags & XVID_REQDQUANTS)) {
628            xvid_free(pEnc->temp_dquants);
629        }
630    
                         MBTransQuantIntra(&pEnc->mbParam, x, y, dct_codes, qcoeff, &pEnc->sCurrent);  
631    
632                          start_timer();      if (pEnc->num_plugins>0) {
633                          MBPrediction(&pEnc->mbParam, x, y, pEnc->mbParam.mb_width, qcoeff, pEnc->pMBs);          xvid_plg_destroy_t pdestroy;
634                          stop_prediction_timer();          memset(&pdestroy, 0, sizeof(xvid_plg_destroy_t));
635    
636                          start_timer();          pdestroy.version = XVID_VERSION;
637                          MBCoding(&pEnc->mbParam, pMB, qcoeff, bs, &pEnc->sStat);          pdestroy.num_frames = pEnc->m_framenum;
638                          stop_coding_timer();  
639            for (i=0; i<pEnc->num_plugins;i++) {
640                if (pEnc->plugins[i].func) {
641                    pEnc->plugins[i].func(pEnc->plugins[i].param, XVID_PLG_DESTROY, &pdestroy, 0);
642                }
643            }
644            xvid_free(pEnc->plugins);
645                  }                  }
646    
647          emms();      if (pEnc->num_plugins>0)
648            xvid_free(pEnc->zones);
649    
650          *pBits = BitstreamPos(bs) - *pBits;          xvid_free(pEnc);
         pEnc->sStat.fMvPrevSigma = -1;  
         pEnc->sStat.iMvSum = 0;  
         pEnc->sStat.iMvCount = 0;  
         pEnc->mbParam.fixed_code = 2;  
651    
652          return 1;                                        // intra          return 0;  /* ok */
653  }  }
654    
655    
656  #define INTRA_THRESHOLD 0.5  /*
657      call the plugins
658      */
659    
660  static int FrameCodeP(Encoder * pEnc, Bitstream * bs, uint32_t *pBits, bool force_inter, bool vol_header)  static void call_plugins(Encoder * pEnc, FRAMEINFO * frame, IMAGE * original,
661                             int opt, int * type, int * quant, xvid_enc_stats_t * stats)
662  {  {
663          float fSigma;      unsigned int i, j;
664          int16_t dct_codes[6][64];      xvid_plg_data_t data;
         int16_t qcoeff[6][64];  
         int iLimit;  
         uint32_t x, y;  
         int iSearchRange;  
         bool bIntra;  
665    
666          IMAGE *pCurrent = &pEnc->sCurrent;      /* set data struct */
         IMAGE *pRef = &pEnc->sReference;  
667    
668          image_setedges(pRef,pEnc->mbParam.edged_width, pEnc->mbParam.edged_height, pEnc->mbParam.width, pEnc->mbParam.height);      memset(&data, 0, sizeof(xvid_plg_data_t));
669        data.version = XVID_VERSION;
670    
671          pEnc->mbParam.rounding_type = 1 - pEnc->mbParam.rounding_type;      /* find zone */
672        for(i=0; i<pEnc->num_zones && pEnc->zones[i].frame<=frame->frame_num; i++) ;
673        data.zone = i>0 ? &pEnc->zones[i-1] : NULL;
674    
675          if (!force_inter)      data.width = pEnc->mbParam.width;
676                  iLimit = (int)(pEnc->mbParam.mb_width * pEnc->mbParam.mb_height * INTRA_THRESHOLD);      data.height = pEnc->mbParam.height;
677          else      data.mb_width = pEnc->mbParam.mb_width;
678                  iLimit = pEnc->mbParam.mb_width * pEnc->mbParam.mb_height + 1;      data.mb_height = pEnc->mbParam.mb_height;
679        data.fincr = frame->fincr;
680        data.fbase = pEnc->mbParam.fbase;
681    
682          if ((pEnc->mbParam.global_flags & XVID_HALFPEL) > 0) {      data.reference.csp = XVID_CSP_USER;
683                  start_timer();      data.reference.plane[0] = pEnc->reference->image.y;
684                  image_interpolate(pRef, &pEnc->vInterH, &pEnc->vInterV, &pEnc->vInterHV,      data.reference.plane[1] = pEnc->reference->image.u;
685                                    pEnc->mbParam.edged_width, pEnc->mbParam.edged_height,      data.reference.plane[2] = pEnc->reference->image.v;
686                                    pEnc->mbParam.rounding_type);      data.reference.stride[0] = pEnc->mbParam.edged_width;
687                  stop_inter_timer();      data.reference.stride[1] = pEnc->mbParam.edged_width/2;
688        data.reference.stride[2] = pEnc->mbParam.edged_width/2;
689    
690        data.current.csp = XVID_CSP_USER;
691        data.current.plane[0] = frame->image.y;
692        data.current.plane[1] = frame->image.u;
693        data.current.plane[2] = frame->image.v;
694        data.current.stride[0] = pEnc->mbParam.edged_width;
695        data.current.stride[1] = pEnc->mbParam.edged_width/2;
696        data.current.stride[2] = pEnc->mbParam.edged_width/2;
697    
698        data.frame_num = frame->frame_num;
699    
700        if (opt == XVID_PLG_BEFORE) {
701            data.type = XVID_TYPE_AUTO;
702            data.quant = 0;
703    
704                    if ((pEnc->mbParam.plugin_flags & XVID_REQDQUANTS)) {
705                data.dquant = pEnc->temp_dquants;
706                data.dquant_stride = pEnc->mbParam.mb_width;
707                            memset(data.dquant, 0, data.mb_width*data.mb_height);
708          }          }
709    
710          start_timer();          /* todo: [vol,vop,motion]_flags*/
         bIntra = MotionEstimation(pEnc->pMBs, &pEnc->mbParam, &pEnc->sReference,  
                                   &pEnc->vInterH, &pEnc->vInterV,  
                                   &pEnc->vInterHV, &pEnc->sCurrent, iLimit);  
         stop_motion_timer();  
711    
712          if (bIntra == 1)      } else { // XVID_PLG_AFTER
713                  return FrameCodeI(pEnc, bs, pBits);          if ((pEnc->mbParam.plugin_flags & XVID_REQORIGINAL)) {
714                data.original.csp = XVID_CSP_USER;
715                data.original.plane[0] = original->y;
716                data.original.plane[1] = original->u;
717                data.original.plane[2] = original->v;
718                data.original.stride[0] = pEnc->mbParam.edged_width;
719                data.original.stride[1] = pEnc->mbParam.edged_width/2;
720                data.original.stride[2] = pEnc->mbParam.edged_width/2;
721            }
722    
723          pEnc->mbParam.coding_type = P_VOP;          if ((frame->vol_flags & XVID_VOL_EXTRASTATS) ||
724                (pEnc->mbParam.plugin_flags & XVID_REQPSNR)) {
725    
726          if(vol_header)                          data.sse_y =
727                  BitstreamWriteVolHeader(bs, pEnc->mbParam.width, pEnc->mbParam.height, pEnc->mbParam.quant_type);                              plane_sse( original->y, frame->image.y,
728                                                   pEnc->mbParam.edged_width, pEnc->mbParam.width,
729                                                   pEnc->mbParam.height);
730    
731          BitstreamWriteVopHeader(bs, P_VOP, pEnc->mbParam.rounding_type,              data.sse_u =
732                                  pEnc->mbParam.quant,                  plane_sse( original->u, frame->image.u,
733                                  pEnc->mbParam.fixed_code);                                             pEnc->mbParam.edged_width/2, pEnc->mbParam.width/2,
734                                                   pEnc->mbParam.height/2);
735    
736          *pBits = BitstreamPos(bs);                          data.sse_v =
737                    plane_sse( original->v, frame->image.v,
738                                               pEnc->mbParam.edged_width/2, pEnc->mbParam.width/2,
739                                                   pEnc->mbParam.height/2);
740            }
741    
742          pEnc->sStat.iTextBits = 0;          data.type = coding2type(frame->coding_type);
743          pEnc->sStat.iMvSum = 0;          data.quant = frame->quant;
         pEnc->sStat.iMvCount = 0;  
         pEnc->sStat.kblks = pEnc->sStat.mblks = pEnc->sStat.ublks = 0;  
744    
745          for(y = 0; y < pEnc->mbParam.mb_height; y++)          if ((pEnc->mbParam.plugin_flags & XVID_REQDQUANTS)) {
746          {              data.dquant = pEnc->temp_dquants;
747                  for(x = 0; x < pEnc->mbParam.mb_width; x++)              data.dquant_stride = pEnc->mbParam.mb_width;
                 {  
                         MACROBLOCK * pMB = &pEnc->pMBs[x + y * pEnc->mbParam.mb_width];  
748    
749                          bIntra = (pMB->mode == MODE_INTRA) || (pMB->mode == MODE_INTRA_Q);              for (j=0; j<pEnc->mbParam.mb_height; j++)
750                for (i=0; i<pEnc->mbParam.mb_width; i++) {
751                    data.dquant[j*data.dquant_stride + i] = frame->mbs[j*pEnc->mbParam.mb_width + i].dquant;;
752                }
753            }
754    
755                          if (!bIntra)          data.vol_flags = frame->vol_flags;
756                          {          data.vop_flags = frame->vop_flags;
757                                  start_timer();          data.motion_flags = frame->motion_flags;
                                 MBMotionCompensation(pMB, x, y, &pEnc->sReference,  
                                                      &pEnc->vInterH, &pEnc->vInterV,  
                                                      &pEnc->vInterHV, &pEnc->sCurrent, dct_codes,  
                                                      pEnc->mbParam.width,  
                                                      pEnc->mbParam.height,  
                                                      pEnc->mbParam.edged_width,  
                                                      pEnc->mbParam.rounding_type);  
                                 stop_comp_timer();  
758    
759                                  if ((pEnc->mbParam.global_flags & XVID_LUMIMASKING) > 0) {          data.length = frame->length;
760                                          if(pMB->dquant != NO_CHANGE) {          data.kblks = frame->sStat.kblks;
761                                                  pMB->mode = MODE_INTER_Q;          data.mblks = frame->sStat.mblks;
762                                                  pEnc->mbParam.quant += DQtab[pMB->dquant];          data.ublks = frame->sStat.ublks;
763                                                  if (pEnc->mbParam.quant > 31) pEnc->mbParam.quant = 31;  
764                                                  else if(pEnc->mbParam.quant < 1) pEnc->mbParam.quant = 1;          if (stats) {
765                    stats->type = coding2type(frame->coding_type);
766                    stats->quant = frame->quant;
767                    stats->vol_flags = frame->vol_flags;
768                    stats->vop_flags = frame->vop_flags;
769                    stats->length = frame->length;
770                    stats->hlength = frame->length - (frame->sStat.iTextBits / 8);
771                    stats->kblks = frame->sStat.kblks;
772                    stats->mblks = frame->sStat.mblks;
773                    stats->ublks = frame->sStat.ublks;
774                stats->sse_y = data.sse_y;
775                stats->sse_u = data.sse_u;
776                stats->sse_v = data.sse_v;
777            }
778        }
779    
780        /* call plugins */
781        for (i=0; i<pEnc->num_plugins;i++) {
782            emms();
783            if (pEnc->plugins[i].func) {
784                if (pEnc->plugins[i].func(pEnc->plugins[i].param, opt, &data, 0) < 0) {
785                    continue;
786                }
787                                          }                                          }
788                                  }                                  }
789                                  pMB->quant = pEnc->mbParam.quant;      emms();
790    
791        /* copy modified values back into frame*/
792        if (opt == XVID_PLG_BEFORE) {
793            *type = data.type;
794            *quant = data.quant > 0 ? data.quant : 2;   /* default */
795    
796                                  pMB->cbp = MBTransQuantInter(&pEnc->mbParam, x, y, dct_codes, qcoeff, pCurrent);          if ((pEnc->mbParam.plugin_flags & XVID_REQDQUANTS)) {
797                for (j=0; j<pEnc->mbParam.mb_height; j++)
798                for (i=0; i<pEnc->mbParam.mb_width; i++) {
799                    frame->mbs[j*pEnc->mbParam.mb_width + i].dquant = data.dquant[j*data.mb_width + i];
800                }
801            }else{
802                for (j=0; j<pEnc->mbParam.mb_height; j++)
803                for (i=0; i<pEnc->mbParam.mb_width; i++) {
804                    frame->mbs[j*pEnc->mbParam.mb_width + i].dquant = 0;
805                }
806            }
807            /* todo: [vol,vop,motion]_flags*/
808                          }                          }
                         else  
                         {  
                                 CodeIntraMB(pEnc, pMB);  
                                 MBTransQuantIntra(&pEnc->mbParam, x, y, dct_codes, qcoeff, pCurrent);  
809                          }                          }
810    
                         start_timer();  
                         MBPrediction(&pEnc->mbParam, x, y, pEnc->mbParam.mb_width, qcoeff, pEnc->pMBs);  
                         stop_prediction_timer();  
811    
812                          if (pMB->mode == MODE_INTRA || pMB->mode == MODE_INTRA_Q)  
813    
814    static __inline void inc_frame_num(Encoder * pEnc)
815                          {                          {
816                                  pEnc->sStat.kblks++;      pEnc->current->frame_num = pEnc->m_framenum;
817            pEnc->current->stamp = pEnc->mbParam.m_stamp;   /* first frame is zero */
818    
819        pEnc->mbParam.m_stamp += pEnc->current->fincr;
820        pEnc->m_framenum++; /* debug ticker */
821                          }                          }
822                          else if (pMB->cbp ||  
823                                   pMB->mvs[0].x || pMB->mvs[0].y ||  static __inline void dec_frame_num(Encoder * pEnc)
                                  pMB->mvs[1].x || pMB->mvs[1].y ||  
                                  pMB->mvs[2].x || pMB->mvs[2].y ||  
                                  pMB->mvs[3].x || pMB->mvs[3].y)  
824                          {                          {
825                                  pEnc->sStat.mblks++;      pEnc->mbParam.m_stamp -= pEnc->mbParam.fincr;
826        pEnc->m_framenum--; /* debug ticker */
827                          }                          }
828                          else  
829    
830    
831    static __inline void
832    set_timecodes(FRAMEINFO* pCur,FRAMEINFO *pRef, int32_t time_base)
833                          {                          {
834                                  pEnc->sStat.ublks++;  
835        pCur->ticks = (int32_t)pCur->stamp % time_base;
836                    pCur->seconds =  ((int32_t)pCur->stamp / time_base)     - ((int32_t)pRef->stamp / time_base) ;
837    
838                    /* HEAVY DEBUG OUTPUT remove when timecodes prove to be stable */
839    
840    /*              fprintf(stderr,"WriteVop:   %d - %d \n",
841                            ((int32_t)pCur->stamp / time_base), ((int32_t)pRef->stamp / time_base));
842                    fprintf(stderr,"set_timecodes: VOP %1d   stamp=%lld ref_stamp=%lld  base=%d\n",
843                            pCur->coding_type, pCur->stamp, pRef->stamp, time_base);
844                    fprintf(stderr,"set_timecodes: VOP %1d   seconds=%d   ticks=%d   (ref-sec=%d  ref-tick=%d)\n",
845                            pCur->coding_type, pCur->seconds, pCur->ticks, pRef->seconds, pRef->ticks);
846    
847    */
848                          }                          }
849    
850    
851    
852    /*****************************************************************************
853     * IPB frame encoder entry point
854     *
855     * Returned values :
856     *    - >0               - output bytes
857     *    - 0                - no output
858     *    - XVID_ERR_VERSION - wrong version passed to core
859     *    - XVID_ERR_END     - End of stream reached before end of coding
860     *    - XVID_ERR_FORMAT  - the image subsystem reported the image had a wrong
861     *                         format
862     ****************************************************************************/
863    
864    
865    int
866    enc_encode(Encoder * pEnc,
867                               xvid_enc_frame_t * xFrame,
868                               xvid_enc_stats_t * stats)
869    {
870            xvid_enc_frame_t * frame;
871            int type;
872            Bitstream bs;
873    
874            if (XVID_MAJOR(xFrame->version) != 1 || (stats && XVID_MAJOR(stats->version) != 1))     /* v1.x.x */
875                    return XVID_ERR_VERSION;
876    
877            xFrame->out_flags = 0;
878    
879            start_global_timer();
880            BitstreamInit(&bs, xFrame->bitstream, 0);
881    
882    
883            /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
884             * enqueue image to the encoding-queue
885             * %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% */
886    
887            if (xFrame->input.csp != XVID_CSP_NULL)
888            {
889                    QUEUEINFO * q = &pEnc->queue[pEnc->queue_tail];
890    
891                          start_timer();                          start_timer();
892                          MBCoding(&pEnc->mbParam, pMB, qcoeff, bs, &pEnc->sStat);                  if (image_input
893                          stop_coding_timer();                          (&q->image, pEnc->mbParam.width, pEnc->mbParam.height,
894                            pEnc->mbParam.edged_width, (uint8_t**)xFrame->input.plane, xFrame->input.stride,
895                            xFrame->input.csp, xFrame->vol_flags & XVID_VOL_INTERLACING))
896                    {
897                            emms();
898                            return XVID_ERR_FORMAT;
899                  }                  }
900                    stop_conv_timer();
901    
902                    if ((xFrame->vop_flags & XVID_VOP_CHROMAOPT)) {
903                            image_chroma_optimize(&q->image,
904                                    pEnc->mbParam.width, pEnc->mbParam.height, pEnc->mbParam.edged_width);
905          }          }
906    
907          emms();                  q->frame = *xFrame;
908    
909          if (pEnc->sStat.iMvCount == 0)                  if (xFrame->quant_intra_matrix)
910                  pEnc->sStat.iMvCount = 1;                  {
911                            memcpy(q->quant_intra_matrix, xFrame->quant_intra_matrix, sizeof(xFrame->quant_intra_matrix));
912                            q->frame.quant_intra_matrix = q->quant_intra_matrix;
913                    }
914    
915                    if (xFrame->quant_inter_matrix)
916                    {
917                            memcpy(q->quant_inter_matrix, xFrame->quant_inter_matrix, sizeof(xFrame->quant_inter_matrix));
918                            q->frame.quant_inter_matrix = q->quant_inter_matrix;
919                    }
920    
921                    pEnc->queue_tail = (pEnc->queue_tail + 1) % (pEnc->mbParam.max_bframes+1);
922                    pEnc->queue_size++;
923            }
924    
         fSigma = (float)sqrt((float) pEnc->sStat.iMvSum / pEnc->sStat.iMvCount);  
925    
926          iSearchRange = 1 << (3 + pEnc->mbParam.fixed_code);          /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
927             * bframe flush code
928             * %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% */
929    
930          if ((fSigma > iSearchRange / 3)  repeat:
931              && (pEnc->mbParam.fixed_code <= 3)) // maximum search range 128  
932            if (pEnc->flush_bframes)
933          {          {
934                  pEnc->mbParam.fixed_code++;                  if (pEnc->bframenum_head < pEnc->bframenum_tail) {
935                  iSearchRange *= 2;  
936                            DPRINTF(DPRINTF_DEBUG,"*** BFRAME (flush) bf: head=%i tail=%i   queue: head=%i tail=%i size=%i",
937                                            pEnc->bframenum_head, pEnc->bframenum_tail,
938                                            pEnc->queue_head, pEnc->queue_tail, pEnc->queue_size);
939    
940                if ((pEnc->mbParam.plugin_flags & XVID_REQORIGINAL)) {
941                                    image_copy(&pEnc->sOriginal2, &pEnc->bframes[pEnc->bframenum_head]->image,
942                                                       pEnc->mbParam.edged_width, pEnc->mbParam.height);
943          }          }
944          else if ((fSigma < iSearchRange / 6)  
945                   && (pEnc->sStat.fMvPrevSigma >= 0)                          FrameCodeB(pEnc, pEnc->bframes[pEnc->bframenum_head], &bs);
946                   && (pEnc->sStat.fMvPrevSigma < iSearchRange / 6)              call_plugins(pEnc, pEnc->bframes[pEnc->bframenum_head], &pEnc->sOriginal2, XVID_PLG_AFTER, 0, 0, stats);
947                   && (pEnc->mbParam.fixed_code >= 2))    // minimum search range 16                          pEnc->bframenum_head++;
948          {  
949                  pEnc->mbParam.fixed_code--;                          goto done;
                 iSearchRange /= 2;  
950          }          }
951    
952          pEnc->sStat.fMvPrevSigma = fSigma;                  /* write an empty marker to the bitstream.
953    
954          *pBits = BitstreamPos(bs) - *pBits;                     for divx5 decoder compatibility, this marker must consist
955                       of a not-coded p-vop, with a time_base of zero, and time_increment
956                       indentical to the future-referece frame.
957                    */
958    
959          return 0;                                        // inter                  if ((pEnc->mbParam.global_flags & XVID_GLOBAL_PACKED && pEnc->bframenum_tail > 0)) {
960                            int tmp;
961                            int bits;
962    
963                            DPRINTF(DPRINTF_DEBUG,"*** EMPTY bf: head=%i tail=%i   queue: head=%i tail=%i size=%i",
964                                    pEnc->bframenum_head, pEnc->bframenum_tail,
965                                    pEnc->queue_head, pEnc->queue_tail, pEnc->queue_size);
966    
967                            bits = BitstreamPos(&bs);
968    
969                            tmp = pEnc->current->seconds;
970                            pEnc->current->seconds = 0; /* force time_base = 0 */
971    
972                            BitstreamWriteVopHeader(&bs, &pEnc->mbParam, pEnc->current, 0);
973                            BitstreamPad(&bs);
974                            pEnc->current->seconds = tmp;
975    
976                            /* add the not-coded length to the reference frame size */
977                            pEnc->current->length += (BitstreamPos(&bs) - bits) / 8;
978                call_plugins(pEnc, pEnc->current, &pEnc->sOriginal, XVID_PLG_AFTER, 0, 0, stats);
979    
980                /* flush complete: reset counters */
981                    pEnc->flush_bframes = 0;
982                        pEnc->bframenum_head = pEnc->bframenum_tail = 0;
983                            goto done;
984    
985                    }
986    
987            /* flush complete: reset counters */
988                    pEnc->flush_bframes = 0;
989                    pEnc->bframenum_head = pEnc->bframenum_tail = 0;
990            }
991    
992            /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
993             * dequeue frame from the encoding queue
994             * %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% */
995    
996            if (pEnc->queue_size == 0)              /* empty */
997            {
998                    if (xFrame->input.csp == XVID_CSP_NULL) /* no futher input */
999                    {
1000    
1001                if (!(pEnc->mbParam.global_flags & XVID_GLOBAL_PACKED) && pEnc->mbParam.max_bframes > 0) {
1002                    call_plugins(pEnc, pEnc->current, &pEnc->sOriginal, XVID_PLG_AFTER, 0, 0, stats);
1003                }
1004    
1005                /* if the very last frame is to be b-vop, we must change it to a p-vop */
1006                if (pEnc->bframenum_tail > 0)
1007                            {
1008    
1009                                    SWAP(FRAMEINFO*, pEnc->current, pEnc->reference);
1010                                    pEnc->bframenum_tail--;
1011                                    SWAP(FRAMEINFO*, pEnc->current, pEnc->bframes[pEnc->bframenum_tail]);
1012    
1013                                    /* convert B-VOP to P-VOP */
1014                    pEnc->current->quant = ((pEnc->current->quant*100) - pEnc->mbParam.bquant_offset) / pEnc->mbParam.bquant_ratio;
1015    
1016                    if ((pEnc->mbParam.plugin_flags & XVID_REQORIGINAL)) {
1017                                image_copy(&pEnc->sOriginal, &pEnc->current->image,
1018                                       pEnc->mbParam.edged_width, pEnc->mbParam.height);
1019                    }
1020    
1021                                    FrameCodeP(pEnc, &bs, 1, 0);
1022    
1023                                    goto done_flush;
1024                            }
1025    
1026                            emms();
1027                            return XVID_ERR_END;    /* end of stream reached */
1028                    }
1029                    goto done;      /* nothing to encode yet; encoder lag */
1030            }
1031    
1032            // the current FRAME becomes the reference
1033            SWAP(FRAMEINFO*, pEnc->current, pEnc->reference);
1034    
1035            // remove frame from encoding-queue (head), and move it into the current
1036            image_swap(&pEnc->current->image, &pEnc->queue[pEnc->queue_head].image);
1037            frame = &pEnc->queue[pEnc->queue_head].frame;
1038            pEnc->queue_head = (pEnc->queue_head + 1) % (pEnc->mbParam.max_bframes+1);
1039            pEnc->queue_size--;
1040    
1041    
1042            /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1043             * init pEnc->current fields
1044             * %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% */
1045    
1046        pEnc->current->fincr = pEnc->mbParam.fincr>0 ? pEnc->mbParam.fincr : frame->fincr;
1047        inc_frame_num(pEnc);
1048        pEnc->current->vol_flags = pEnc->mbParam.vol_flags;
1049        pEnc->current->vop_flags = frame->vop_flags;
1050            pEnc->current->motion_flags = frame->motion;
1051            pEnc->current->fcode = pEnc->mbParam.m_fcode;
1052            pEnc->current->bcode = pEnc->mbParam.m_fcode;
1053    
1054    
1055        if ((xFrame->vop_flags & XVID_VOP_CHROMAOPT)) {
1056                image_chroma_optimize(&pEnc->current->image,
1057                        pEnc->mbParam.width, pEnc->mbParam.height, pEnc->mbParam.edged_width);
1058        }
1059    
1060            /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1061             * frame type & quant selection
1062             * %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% */
1063    
1064        call_plugins(pEnc, pEnc->current, NULL, XVID_PLG_BEFORE, &type, &pEnc->current->quant, stats);
1065    
1066        if (frame->type > 0)
1067                    type = frame->type;
1068    
1069        if (frame->quant > 0)
1070                    pEnc->current->quant = frame->quant;
1071    
1072        if (type > 0){      /* XVID_TYPE_?VOP */
1073                    type = type2coding(type);       /* convert XVID_TYPE_?VOP to bitstream coding type */
1074        } else{             /* XVID_TYPE_AUTO */
1075                    if (pEnc->iFrameNum == 0 || (pEnc->mbParam.iMaxKeyInterval > 0 && pEnc->iFrameNum >= pEnc->mbParam.iMaxKeyInterval)){
1076                            pEnc->iFrameNum = 0;
1077                            type = I_VOP;
1078                    }else{
1079                            type = MEanalysis(&pEnc->reference->image, pEnc->current,
1080                                            &pEnc->mbParam, pEnc->mbParam.iMaxKeyInterval,
1081                                            pEnc->iFrameNum, pEnc->bframenum_tail, xFrame->bframe_threshold);
1082    
1083                if (type == B_VOP && !(pEnc->current->vop_flags & XVID_VOP_DYNAMIC_BFRAMES)) {
1084                    type = P_VOP;   /* disable dynamic bframes */
1085                }
1086                    }
1087            }
1088    
1089        /* bframes buffer overflow check */
1090        if (type != I_VOP) {
1091            if (pEnc->bframenum_tail >= pEnc->mbParam.max_bframes) {
1092                type = P_VOP;
1093            }else{
1094                type = B_VOP;
1095            }
1096        }
1097    
1098            pEnc->iFrameNum++;
1099    
1100            if ((pEnc->current->vop_flags & XVID_VOP_DEBUG)) {
1101                    image_printf(&pEnc->current->image, pEnc->mbParam.edged_width, pEnc->mbParam.height, 5, 5,
1102                            "%i  st:%i  if:%i", pEnc->current->frame_num, pEnc->current->stamp, pEnc->iFrameNum);
1103            }
1104    
1105            /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1106             * encode this frame as a b-vop
1107         * (we dont encode here, rather we store the frame in the bframes queue, to be encoded later)
1108             * %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% */
1109            if (type == B_VOP) {
1110                    if ((pEnc->current->vop_flags & XVID_VOP_DEBUG)) {
1111                            image_printf(&pEnc->current->image, pEnc->mbParam.edged_width, pEnc->mbParam.height, 5, 200, "BVOP");
1112                    }
1113    
1114                    if (frame->quant < 1) {
1115                            pEnc->current->quant = ((((pEnc->reference->quant + pEnc->current->quant) *
1116                                    pEnc->mbParam.bquant_ratio) / 2) + pEnc->mbParam.bquant_offset)/100;
1117    
1118                    } else {
1119                            pEnc->current->quant = frame->quant;
1120                    }
1121    
1122                    if (pEnc->current->quant < 1)
1123                            pEnc->current->quant = 1;
1124                    else if (pEnc->current->quant > 31)
1125                pEnc->current->quant = 31;
1126    
1127                    DPRINTF(DPRINTF_DEBUG,"*** BFRAME (store) bf: head=%i tail=%i   queue: head=%i tail=%i size=%i  quant=%i",
1128                                    pEnc->bframenum_head, pEnc->bframenum_tail,
1129                                    pEnc->queue_head, pEnc->queue_tail, pEnc->queue_size,pEnc->current->quant);
1130    
1131                    /* store frame into bframe buffer & swap ref back to current */
1132                    SWAP(FRAMEINFO*, pEnc->current, pEnc->bframes[pEnc->bframenum_tail]);
1133                    SWAP(FRAMEINFO*, pEnc->current, pEnc->reference);
1134    
1135                    pEnc->bframenum_tail++;
1136    
1137                    goto repeat;
1138        }
1139    
1140        /* for unpacked bframes, output the stats for the last encoded frame */
1141        if (!(pEnc->mbParam.global_flags & XVID_GLOBAL_PACKED) && pEnc->bframenum_tail > 0)
1142        {
1143            if (pEnc->current->stamp > 0) {
1144                call_plugins(pEnc, pEnc->reference, &pEnc->sOriginal, XVID_PLG_AFTER, 0, 0, stats);
1145            }
1146                    else
1147                            stats->type = XVID_TYPE_NOTHING;
1148        }
1149    
1150            /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1151             * closed-gop
1152         * if the frame prior to an iframe is scheduled as a bframe, we must change it to a pframe
1153         * %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% */
1154    
1155        if (type == I_VOP && (pEnc->mbParam.global_flags & XVID_GLOBAL_CLOSED_GOP) && pEnc->bframenum_tail > 0) {
1156    
1157                    // place this frame back on the encoding-queue (head)
1158                    // we will deal with it next time
1159            dec_frame_num(pEnc);
1160            pEnc->iFrameNum--;
1161    
1162            pEnc->queue_head = (pEnc->queue_head + (pEnc->mbParam.max_bframes+1) - 1) % (pEnc->mbParam.max_bframes+1);
1163            pEnc->queue_size++;
1164                    image_swap(&pEnc->current->image, &pEnc->queue[pEnc->queue_head].image);
1165    
1166                    // grab the last frame from the bframe-queue
1167    
1168                    pEnc->bframenum_tail--;
1169                    SWAP(FRAMEINFO*, pEnc->current, pEnc->bframes[pEnc->bframenum_tail]);
1170    
1171                    if ((pEnc->current->vop_flags & XVID_VOP_DEBUG)) {
1172                            image_printf(&pEnc->current->image, pEnc->mbParam.edged_width, pEnc->mbParam.height, 5, 100, "DX50 BVOP->PVOP");
1173                    }
1174    
1175                    /* convert B-VOP quant to P-VOP */
1176                    pEnc->current->quant = ((pEnc->current->quant*100) - pEnc->mbParam.bquant_offset) / pEnc->mbParam.bquant_ratio;
1177            type = P_VOP;
1178        }
1179    
1180    
1181            /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1182             * encode this frame as an i-vop
1183         * %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% */
1184    
1185            if (type == I_VOP) {
1186    
1187                    DPRINTF(DPRINTF_DEBUG,"*** IFRAME bf: head=%i tail=%i   queue: head=%i tail=%i size=%i",
1188                                    pEnc->bframenum_head, pEnc->bframenum_tail,
1189                                    pEnc->queue_head, pEnc->queue_tail, pEnc->queue_size);
1190    
1191                    if ((pEnc->current->vop_flags & XVID_VOP_DEBUG)) {
1192                            image_printf(&pEnc->current->image, pEnc->mbParam.edged_width, pEnc->mbParam.height, 5, 200, "IVOP");
1193                    }
1194    
1195    
1196                    /* ---- update vol flags at IVOP ----------- */
1197                    pEnc->current->vol_flags = pEnc->mbParam.vol_flags = frame->vol_flags;
1198    
1199            if ((pEnc->mbParam.vol_flags & XVID_VOL_MPEGQUANT)) {
1200                            if (frame->quant_intra_matrix != NULL)
1201                                    set_intra_matrix(frame->quant_intra_matrix);
1202                            if (frame->quant_inter_matrix != NULL)
1203                                    set_inter_matrix(frame->quant_inter_matrix);
1204                    }
1205    
1206            /* prevent vol/vop misuse */
1207    
1208            if (!(pEnc->current->vol_flags & XVID_VOL_REDUCED_ENABLE))
1209                pEnc->current->vop_flags &= ~XVID_VOP_REDUCED;
1210    
1211            if (!(pEnc->current->vol_flags & XVID_VOL_INTERLACING))
1212                pEnc->current->vop_flags &= ~(XVID_VOP_TOPFIELDFIRST|XVID_VOP_ALTERNATESCAN);
1213    
1214                    /* ^^^------------------------ */
1215    
1216            if ((pEnc->mbParam.plugin_flags & XVID_REQORIGINAL)) {
1217                        image_copy(&pEnc->sOriginal, &pEnc->current->image,
1218                               pEnc->mbParam.edged_width, pEnc->mbParam.height);
1219            }
1220    
1221                    FrameCodeI(pEnc, &bs);
1222                    xFrame->out_flags |= XVID_KEYFRAME;
1223    
1224            /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1225             * encode this frame as an p-vop
1226         * %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% */
1227    
1228        } else { // (type == P_VOP || type == S_VOP)
1229    
1230                    DPRINTF(DPRINTF_DEBUG,"*** PFRAME bf: head=%i tail=%i   queue: head=%i tail=%i size=%i",
1231                                    pEnc->bframenum_head, pEnc->bframenum_tail,
1232                                    pEnc->queue_head, pEnc->queue_tail, pEnc->queue_size);
1233    
1234                    if ((pEnc->current->vop_flags & XVID_VOP_DEBUG)) {
1235                            image_printf(&pEnc->current->image, pEnc->mbParam.edged_width, pEnc->mbParam.height, 5, 200, "PVOP");
1236                    }
1237    
1238            if ((pEnc->mbParam.plugin_flags & XVID_REQORIGINAL)) {
1239                        image_copy(&pEnc->sOriginal, &pEnc->current->image,
1240                               pEnc->mbParam.edged_width, pEnc->mbParam.height);
1241            }
1242    
1243                    FrameCodeP(pEnc, &bs, 1, 0);
1244        }
1245    
1246    
1247        /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1248             * on next enc_encode call we must flush bframes
1249             * %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% */
1250    
1251    done_flush:
1252    
1253        pEnc->flush_bframes = 1;
1254    
1255            /* packed & queued_bframes: dont bother outputting stats, we do so after the flush */
1256            if ((pEnc->mbParam.global_flags & XVID_GLOBAL_PACKED) && pEnc->bframenum_tail > 0) {
1257                    goto repeat;
1258            }
1259    
1260        /* packed or no-bframes: output stats */
1261        if ((pEnc->mbParam.global_flags & XVID_GLOBAL_PACKED) || pEnc->mbParam.max_bframes == 0) {
1262            call_plugins(pEnc, pEnc->current, &pEnc->sOriginal, XVID_PLG_AFTER, 0, 0, stats);
1263            }
1264    
1265            /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1266             * done; return number of bytes consumed
1267             * %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% */
1268    
1269    done:
1270    
1271            stop_global_timer();
1272            write_timer();
1273    
1274            emms();
1275            return BitstreamLength(&bs);
1276    }
1277    
1278    
1279    static void SetMacroblockQuants(MBParam * const pParam, FRAMEINFO * frame)
1280    {
1281        unsigned int i,j;
1282        int quant = frame->quant;
1283    
1284        for (j=0; j<pParam->mb_height; j++)
1285        for (i=0; i<pParam->mb_width; i++) {
1286            MACROBLOCK * pMB = &frame->mbs[j*pParam->mb_width + i];
1287            quant += pMB->dquant;
1288            if (quant > 31)
1289                            quant = 31;
1290                    if (quant < 1)
1291                            quant = 1;
1292            pMB->quant = quant;
1293        }
1294    }
1295    
1296    
1297    static __inline void
1298    CodeIntraMB(Encoder * pEnc,
1299                            MACROBLOCK * pMB)
1300    {
1301    
1302            pMB->mode = MODE_INTRA;
1303    
1304            /* zero mv statistics */
1305            pMB->mvs[0].x = pMB->mvs[1].x = pMB->mvs[2].x = pMB->mvs[3].x = 0;
1306            pMB->mvs[0].y = pMB->mvs[1].y = pMB->mvs[2].y = pMB->mvs[3].y = 0;
1307            pMB->sad8[0] = pMB->sad8[1] = pMB->sad8[2] = pMB->sad8[3] = 0;
1308            pMB->sad16 = 0;
1309    
1310            if (pMB->dquant != 0) {
1311                    pMB->mode = MODE_INTRA_Q;
1312        }
1313    }
1314    
1315    
1316    
1317    static int
1318    FrameCodeI(Encoder * pEnc,
1319                       Bitstream * bs)
1320    {
1321        int bits = BitstreamPos(bs);
1322            int mb_width = pEnc->mbParam.mb_width;
1323            int mb_height = pEnc->mbParam.mb_height;
1324    
1325            DECLARE_ALIGNED_MATRIX(dct_codes, 6, 64, int16_t, CACHE_LINE);
1326            DECLARE_ALIGNED_MATRIX(qcoeff, 6, 64, int16_t, CACHE_LINE);
1327    
1328            uint16_t x, y;
1329    
1330            if ((pEnc->current->vol_flags & XVID_VOL_REDUCED_ENABLE))
1331            {
1332                    mb_width = (pEnc->mbParam.width + 31) / 32;
1333                    mb_height = (pEnc->mbParam.height + 31) / 32;
1334    
1335                    /* 16x16->8x8 downsample requires 1 additional edge pixel*/
1336                    /* XXX: setedges is overkill */
1337                    start_timer();
1338                    image_setedges(&pEnc->current->image,
1339                            pEnc->mbParam.edged_width, pEnc->mbParam.edged_height,
1340                            pEnc->mbParam.width, pEnc->mbParam.height);
1341                    stop_edges_timer();
1342            }
1343    
1344            pEnc->mbParam.m_rounding_type = 1;
1345            pEnc->current->rounding_type = pEnc->mbParam.m_rounding_type;
1346            pEnc->current->coding_type = I_VOP;
1347    
1348        SetMacroblockQuants(&pEnc->mbParam, pEnc->current);
1349    
1350            BitstreamWriteVolHeader(bs, &pEnc->mbParam);
1351    
1352            set_timecodes(pEnc->current,pEnc->reference,pEnc->mbParam.fbase);
1353    
1354            BitstreamPadAlways(bs);
1355            BitstreamWriteVopHeader(bs, &pEnc->mbParam, pEnc->current, 1);
1356    
1357            pEnc->current->sStat.iTextBits = 0;
1358            pEnc->current->sStat.kblks = mb_width * mb_height;
1359            pEnc->current->sStat.mblks = pEnc->current->sStat.ublks = 0;
1360    
1361            for (y = 0; y < mb_height; y++)
1362                    for (x = 0; x < mb_width; x++) {
1363                            MACROBLOCK *pMB =
1364                                    &pEnc->current->mbs[x + y * pEnc->mbParam.mb_width];
1365    
1366                            CodeIntraMB(pEnc, pMB);
1367    
1368                            MBTransQuantIntra(&pEnc->mbParam, pEnc->current, pMB, x, y,
1369                                                              dct_codes, qcoeff);
1370    
1371                            start_timer();
1372                            MBPrediction(pEnc->current, x, y, pEnc->mbParam.mb_width, qcoeff);
1373                            stop_prediction_timer();
1374    
1375                            start_timer();
1376                            if (pEnc->current->vop_flags & XVID_VOP_GREYSCALE)
1377                            {       pMB->cbp &= 0x3C;               /* keep only bits 5-2 */
1378                                    qcoeff[4*64+0]=0;               /* zero, because for INTRA MBs DC value is saved */
1379                                    qcoeff[5*64+0]=0;
1380                            }
1381                            MBCoding(pEnc->current, pMB, qcoeff, bs, &pEnc->current->sStat);
1382                            stop_coding_timer();
1383                    }
1384    
1385            if ((pEnc->current->vop_flags & XVID_VOP_REDUCED))
1386            {
1387                    image_deblock_rrv(&pEnc->current->image, pEnc->mbParam.edged_width,
1388                            pEnc->current->mbs, mb_width, mb_height, pEnc->mbParam.mb_width,
1389                            16, 0);
1390            }
1391            emms();
1392    
1393    /* XXX: Remove the two #if 0 blocks when we are sure we must always pad the stream */
1394    #if 0
1395            /* for divx5 compatibility, we must always pad between the packed p and b frames */
1396            if ((pEnc->mbParam.global_flags & XVID_GLOBAL_PACKED) && pEnc->bframenum_tail > 0)
1397    #endif
1398                    BitstreamPadAlways(bs);
1399    #if 0
1400            else
1401                    BitstreamPad(bs);
1402    #endif
1403        pEnc->current->length = (BitstreamPos(bs) - bits) / 8;
1404    
1405            pEnc->fMvPrevSigma = -1;
1406            pEnc->mbParam.m_fcode = 2;
1407    
1408        /* XXX: hinted me
1409            if (pEnc->current->global_flags & XVID_HINTEDME_GET) {
1410                    HintedMEGet(pEnc, 1);
1411            }*/
1412    
1413            return 1;                                       /* intra */
1414    }
1415    
1416    
1417    #define INTRA_THRESHOLD 0.5
1418    #define BFRAME_SKIP_THRESHHOLD 30
1419    
1420    
1421    /* FrameCodeP also handles S(GMC)-VOPs */
1422    static int
1423    FrameCodeP(Encoder * pEnc,
1424                       Bitstream * bs,
1425                       bool force_inter,
1426                       bool vol_header)
1427    {
1428            float fSigma;
1429        int bits = BitstreamPos(bs);
1430    
1431            DECLARE_ALIGNED_MATRIX(dct_codes, 6, 64, int16_t, CACHE_LINE);
1432            DECLARE_ALIGNED_MATRIX(qcoeff, 6, 64, int16_t, CACHE_LINE);
1433    
1434            int mb_width = pEnc->mbParam.mb_width;
1435            int mb_height = pEnc->mbParam.mb_height;
1436    
1437            int iLimit;
1438            int x, y, k;
1439            int iSearchRange;
1440            int bIntra, skip_possible;
1441    
1442            /* IMAGE *pCurrent = &pEnc->current->image; */
1443            IMAGE *pRef = &pEnc->reference->image;
1444    
1445            if ((pEnc->current->vop_flags & XVID_VOP_REDUCED))
1446            {
1447                    mb_width = (pEnc->mbParam.width + 31) / 32;
1448                    mb_height = (pEnc->mbParam.height + 31) / 32;
1449            }
1450    
1451    
1452            start_timer();
1453            image_setedges(pRef, pEnc->mbParam.edged_width, pEnc->mbParam.edged_height,
1454                                       pEnc->mbParam.width, pEnc->mbParam.height);
1455            stop_edges_timer();
1456    
1457            pEnc->mbParam.m_rounding_type = 1 - pEnc->mbParam.m_rounding_type;
1458            pEnc->current->rounding_type = pEnc->mbParam.m_rounding_type;
1459            //pEnc->current->quarterpel =  pEnc->mbParam.m_quarterpel;
1460            pEnc->current->fcode = pEnc->mbParam.m_fcode;
1461    
1462            if (!force_inter)
1463                    iLimit = (int)(mb_width * mb_height *  INTRA_THRESHOLD);
1464            else
1465                    iLimit = mb_width * mb_height + 1;
1466    
1467            if ((pEnc->current->vop_flags & XVID_VOP_HALFPEL)) {
1468                    start_timer();
1469                    image_interpolate(pRef, &pEnc->vInterH, &pEnc->vInterV,
1470                                                      &pEnc->vInterHV, pEnc->mbParam.edged_width,
1471                                                      pEnc->mbParam.edged_height,
1472                                                      (pEnc->mbParam.vol_flags & XVID_VOL_QUARTERPEL),
1473                                                      pEnc->current->rounding_type);
1474                    stop_inter_timer();
1475            }
1476    
1477            pEnc->current->coding_type = P_VOP;
1478    
1479    
1480        SetMacroblockQuants(&pEnc->mbParam, pEnc->current);
1481    
1482            start_timer();
1483            /*if (pEnc->current->global_flags & XVID_HINTEDME_SET)
1484                    HintedMESet(pEnc, &bIntra);
1485            else*/
1486                    bIntra =
1487                            MotionEstimation(&pEnc->mbParam, pEnc->current, pEnc->reference,
1488                             &pEnc->vInterH, &pEnc->vInterV, &pEnc->vInterHV,
1489                             iLimit);
1490    
1491            stop_motion_timer();
1492    
1493            if (bIntra == 1) return FrameCodeI(pEnc, bs);
1494    
1495            if ( ( pEnc->current->vol_flags & XVID_VOL_GMC )
1496                    && ( (pEnc->current->warp.duv[1].x != 0) || (pEnc->current->warp.duv[1].y != 0) ) )
1497            {
1498                    pEnc->current->coding_type = S_VOP;
1499    
1500                    generate_GMCparameters( 2, 16, &pEnc->current->warp,
1501                                            pEnc->mbParam.width, pEnc->mbParam.height,
1502                                            &pEnc->current->gmc_data);
1503    
1504                    generate_GMCimage(&pEnc->current->gmc_data, &pEnc->reference->image,
1505                                    pEnc->mbParam.mb_width, pEnc->mbParam.mb_height,
1506                                    pEnc->mbParam.edged_width, pEnc->mbParam.edged_width/2,
1507                                    pEnc->mbParam.m_fcode, (pEnc->mbParam.vol_flags & XVID_VOL_QUARTERPEL), 0,
1508                                    pEnc->current->rounding_type, pEnc->current->mbs, &pEnc->vGMC);
1509    
1510            }
1511    
1512            set_timecodes(pEnc->current,pEnc->reference,pEnc->mbParam.fbase);
1513            if (vol_header)
1514            {       BitstreamWriteVolHeader(bs, &pEnc->mbParam);
1515                    BitstreamPadAlways(bs);
1516            }
1517    
1518            BitstreamWriteVopHeader(bs, &pEnc->mbParam, pEnc->current, 1);
1519    
1520            pEnc->current->sStat.iTextBits = pEnc->current->sStat.iMvSum = pEnc->current->sStat.iMvCount =
1521                    pEnc->current->sStat.kblks = pEnc->current->sStat.mblks = pEnc->current->sStat.ublks = 0;
1522    
1523    
1524            for (y = 0; y < mb_height; y++) {
1525                    for (x = 0; x < mb_width; x++) {
1526                            MACROBLOCK *pMB =
1527                                    &pEnc->current->mbs[x + y * pEnc->mbParam.mb_width];
1528    
1529    /* Mode decision: Check, if the block should be INTRA / INTER or GMC-coded */
1530    /* For a start, leave INTRA decision as is, only choose only between INTER/GMC  - gruel, 9.1.2002 */
1531    
1532                            bIntra = (pMB->mode == MODE_INTRA) || (pMB->mode == MODE_INTRA_Q);
1533    
1534                            if (bIntra) {
1535                                    CodeIntraMB(pEnc, pMB);
1536                                    MBTransQuantIntra(&pEnc->mbParam, pEnc->current, pMB, x, y,
1537                                                                      dct_codes, qcoeff);
1538    
1539                                    start_timer();
1540                                    MBPrediction(pEnc->current, x, y, pEnc->mbParam.mb_width, qcoeff);
1541                                    stop_prediction_timer();
1542    
1543                                    pEnc->current->sStat.kblks++;
1544    
1545                                    MBCoding(pEnc->current, pMB, qcoeff, bs, &pEnc->current->sStat);
1546                                    stop_coding_timer();
1547                                    continue;
1548                            }
1549    
1550                            if (pEnc->current->coding_type == S_VOP) {
1551    
1552                                    int32_t iSAD = sad16(pEnc->current->image.y + 16*y*pEnc->mbParam.edged_width + 16*x,
1553                                            pEnc->vGMC.y + 16*y*pEnc->mbParam.edged_width + 16*x,
1554                                            pEnc->mbParam.edged_width, 65536);
1555    
1556                                    if (pEnc->current->motion_flags & XVID_ME_CHROMA16) {
1557                                            iSAD += sad8(pEnc->current->image.u + 8*y*(pEnc->mbParam.edged_width/2) + 8*x,
1558                                            pEnc->vGMC.u + 8*y*(pEnc->mbParam.edged_width/2) + 8*x, pEnc->mbParam.edged_width/2);
1559    
1560                                            iSAD += sad8(pEnc->current->image.v + 8*y*(pEnc->mbParam.edged_width/2) + 8*x,
1561                                            pEnc->vGMC.v + 8*y*(pEnc->mbParam.edged_width/2) + 8*x, pEnc->mbParam.edged_width/2);
1562                                    }
1563    
1564                                    if (iSAD <= pMB->sad16) {               /* mode decision GMC */
1565    
1566                                            if ((pEnc->mbParam.vol_flags & XVID_VOL_QUARTERPEL))
1567                                                    pMB->qmvs[0] = pMB->qmvs[1] = pMB->qmvs[2] = pMB->qmvs[3] = pMB->amv;
1568                                            else
1569                                                    pMB->mvs[0] = pMB->mvs[1] = pMB->mvs[2] = pMB->mvs[3] = pMB->amv;
1570    
1571                                            pMB->mode = MODE_INTER;
1572                                            pMB->mcsel = 1;
1573                                            pMB->sad16 = iSAD;
1574                                    } else {
1575                                            pMB->mcsel = 0;
1576                                    }
1577                            } else {
1578                                    pMB->mcsel = 0; /* just a precaution */
1579                            }
1580    
1581                            start_timer();
1582                            MBMotionCompensation(pMB, x, y, &pEnc->reference->image,
1583                                                                     &pEnc->vInterH, &pEnc->vInterV,
1584                                                                     &pEnc->vInterHV, &pEnc->vGMC,
1585                                                                     &pEnc->current->image,
1586                                                                     dct_codes, pEnc->mbParam.width,
1587                                                                     pEnc->mbParam.height,
1588                                                                     pEnc->mbParam.edged_width,
1589                                                                     (pEnc->current->vol_flags & XVID_VOL_QUARTERPEL),
1590                                                                     (pEnc->current->vop_flags & XVID_VOP_REDUCED),
1591                                                                     pEnc->current->rounding_type);
1592    
1593                            stop_comp_timer();
1594    
1595                            if (pMB->dquant != 0) {
1596                    pMB->mode = MODE_INTER_Q;
1597                            }
1598    
1599                            pMB->field_pred = 0;
1600    
1601                            if (pMB->mode != MODE_NOT_CODED)
1602                            {       pMB->cbp =
1603                                            MBTransQuantInter(&pEnc->mbParam, pEnc->current, pMB, x, y,
1604                                                                              dct_codes, qcoeff);
1605                            }
1606    
1607                            if (pMB->cbp || pMB->mvs[0].x || pMB->mvs[0].y ||
1608                                       pMB->mvs[1].x || pMB->mvs[1].y || pMB->mvs[2].x ||
1609                                       pMB->mvs[2].y || pMB->mvs[3].x || pMB->mvs[3].y) {
1610                                    pEnc->current->sStat.mblks++;
1611                            }  else {
1612                                    pEnc->current->sStat.ublks++;
1613                            }
1614    
1615                            start_timer();
1616    
1617                            /* Finished processing the MB, now check if to CODE or SKIP */
1618    
1619                            skip_possible = (pMB->cbp == 0) && (pMB->mode == MODE_INTER) &&
1620                                                            (pMB->dquant == 0);
1621    
1622                            if (pEnc->current->coding_type == S_VOP)
1623                                    skip_possible &= (pMB->mcsel == 1);
1624                            else if (pEnc->current->coding_type == P_VOP) {
1625                                    if ((pEnc->mbParam.vol_flags & XVID_VOL_QUARTERPEL))
1626                                            skip_possible &= ( (pMB->qmvs[0].x == 0) && (pMB->qmvs[0].y == 0) );
1627                                    else
1628                                            skip_possible &= ( (pMB->mvs[0].x == 0) && (pMB->mvs[0].y == 0) );
1629                            }
1630    
1631                            if ( (pMB->mode == MODE_NOT_CODED) || (skip_possible)) {
1632    
1633    /* This is a candidate for SKIPping, but for P-VOPs check intermediate B-frames first */
1634    
1635                                    if (pEnc->current->coding_type == P_VOP)        /* special rule for P-VOP's SKIP */
1636                                    {
1637                                            int bSkip = 1;
1638    
1639                                            for (k=pEnc->bframenum_head; k< pEnc->bframenum_tail; k++)
1640                                            {
1641                                                    int iSAD;
1642                                                    iSAD = sad16(pEnc->reference->image.y + 16*y*pEnc->mbParam.edged_width + 16*x,
1643                                                                            pEnc->bframes[k]->image.y + 16*y*pEnc->mbParam.edged_width + 16*x,
1644                                                                    pEnc->mbParam.edged_width,BFRAME_SKIP_THRESHHOLD);
1645                                                    if (iSAD >= BFRAME_SKIP_THRESHHOLD * pMB->quant)
1646                                                    {       bSkip = 0;
1647                                                            break;
1648                                                    }
1649                                            }
1650    
1651                                            if (!bSkip) {   /* no SKIP, but trivial block */
1652                                                    if((pEnc->mbParam.vol_flags & XVID_VOL_QUARTERPEL)) {
1653                                                            VECTOR predMV = get_qpmv2(pEnc->current->mbs, pEnc->mbParam.mb_width, 0, x, y, 0);
1654                                                            pMB->pmvs[0].x = - predMV.x;
1655                                                            pMB->pmvs[0].y = - predMV.y;
1656                                                    }
1657                                                    else {
1658                                                            VECTOR predMV = get_pmv2(pEnc->current->mbs, pEnc->mbParam.mb_width, 0, x, y, 0);
1659                                                            pMB->pmvs[0].x = - predMV.x;
1660                                                            pMB->pmvs[0].y = - predMV.y;
1661                                                    }
1662                                                    pMB->mode = MODE_INTER;
1663                                                    pMB->cbp = 0;
1664                                                    MBCoding(pEnc->current, pMB, qcoeff, bs, &pEnc->current->sStat);
1665                                                    stop_coding_timer();
1666    
1667                                                    continue;       /* next MB */
1668                                            }
1669                                    }
1670                                    /* do SKIP */
1671    
1672                                    pMB->mode = MODE_NOT_CODED;
1673                                    MBSkip(bs);
1674                                    stop_coding_timer();
1675                                    continue;       /* next MB */
1676                            }
1677                            /* ordinary case: normal coded INTER/INTER4V block */
1678    
1679                            if ((pEnc->current->vop_flags & XVID_VOP_GREYSCALE))
1680                            {       pMB->cbp &= 0x3C;               /* keep only bits 5-2 */
1681                                    qcoeff[4*64+0]=0;               /* zero, because DC for INTRA MBs DC value is saved */
1682                                    qcoeff[5*64+0]=0;
1683                            }
1684    
1685                            if((pEnc->mbParam.vol_flags & XVID_VOL_QUARTERPEL)) {
1686                                    VECTOR predMV = get_qpmv2(pEnc->current->mbs, pEnc->mbParam.mb_width, 0, x, y, 0);
1687                                    pMB->pmvs[0].x = pMB->qmvs[0].x - predMV.x;
1688                                    pMB->pmvs[0].y = pMB->qmvs[0].y - predMV.y;
1689                                    DPRINTF(DPRINTF_MV,"mv_diff (%i,%i) pred (%i,%i) result (%i,%i)", pMB->pmvs[0].x, pMB->pmvs[0].y, predMV.x, predMV.y, pMB->mvs[0].x, pMB->mvs[0].y);
1690                            } else {
1691                                    VECTOR predMV = get_pmv2(pEnc->current->mbs, pEnc->mbParam.mb_width, 0, x, y, 0);
1692                                    pMB->pmvs[0].x = pMB->mvs[0].x - predMV.x;
1693                                    pMB->pmvs[0].y = pMB->mvs[0].y - predMV.y;
1694                                    DPRINTF(DPRINTF_MV,"mv_diff (%i,%i) pred (%i,%i) result (%i,%i)", pMB->pmvs[0].x, pMB->pmvs[0].y, predMV.x, predMV.y, pMB->mvs[0].x, pMB->mvs[0].y);
1695                            }
1696    
1697    
1698                            if (pMB->mode == MODE_INTER4V)
1699                            {       int k;
1700                                    for (k=1;k<4;k++)
1701                                    {
1702                                            if((pEnc->mbParam.vol_flags & XVID_VOL_QUARTERPEL)) {
1703                                                    VECTOR predMV = get_qpmv2(pEnc->current->mbs, pEnc->mbParam.mb_width, 0, x, y, k);
1704                                                    pMB->pmvs[k].x = pMB->qmvs[k].x - predMV.x;
1705                                                    pMB->pmvs[k].y = pMB->qmvs[k].y - predMV.y;
1706                                    DPRINTF(DPRINTF_MV,"mv_diff (%i,%i) pred (%i,%i) result (%i,%i)", pMB->pmvs[k].x, pMB->pmvs[k].y, predMV.x, predMV.y, pMB->mvs[k].x, pMB->mvs[k].y);
1707                                            } else {
1708                                                    VECTOR predMV = get_pmv2(pEnc->current->mbs, pEnc->mbParam.mb_width, 0, x, y, k);
1709                                                    pMB->pmvs[k].x = pMB->mvs[k].x - predMV.x;
1710                                                    pMB->pmvs[k].y = pMB->mvs[k].y - predMV.y;
1711                                    DPRINTF(DPRINTF_MV,"mv_diff (%i,%i) pred (%i,%i) result (%i,%i)", pMB->pmvs[k].x, pMB->pmvs[k].y, predMV.x, predMV.y, pMB->mvs[k].x, pMB->mvs[k].y);
1712                                            }
1713    
1714                                    }
1715                            }
1716    
1717                            MBCoding(pEnc->current, pMB, qcoeff, bs, &pEnc->current->sStat);
1718                            stop_coding_timer();
1719    
1720                    }
1721            }
1722    
1723            if ((pEnc->current->vop_flags & XVID_VOP_REDUCED))
1724            {
1725                    image_deblock_rrv(&pEnc->current->image, pEnc->mbParam.edged_width,
1726                            pEnc->current->mbs, mb_width, mb_height, pEnc->mbParam.mb_width,
1727                            16, 0);
1728            }
1729    
1730            emms();
1731    
1732        /* XXX: hinted me
1733            if (pEnc->current->global_flags & XVID_HINTEDME_GET) {
1734                    HintedMEGet(pEnc, 0);
1735            }*/
1736    
1737            if (pEnc->current->sStat.iMvCount == 0)
1738                    pEnc->current->sStat.iMvCount = 1;
1739    
1740            fSigma = (float) sqrt((float) pEnc->current->sStat.iMvSum / pEnc->current->sStat.iMvCount);
1741    
1742            iSearchRange = 1 << (3 + pEnc->mbParam.m_fcode);
1743    
1744            if ((fSigma > iSearchRange / 3)
1745            && (pEnc->mbParam.m_fcode <= (3 +  (pEnc->mbParam.vol_flags & XVID_VOL_QUARTERPEL?1:0)  )))     /* maximum search range 128 */
1746            {
1747                    pEnc->mbParam.m_fcode++;
1748                    iSearchRange *= 2;
1749            } else if ((fSigma < iSearchRange / 6)
1750                               && (pEnc->fMvPrevSigma >= 0)
1751                               && (pEnc->fMvPrevSigma < iSearchRange / 6)
1752                               && (pEnc->mbParam.m_fcode >= (2 + (pEnc->mbParam.vol_flags & XVID_VOL_QUARTERPEL?1:0) )))    /* minimum search range 16 */
1753            {
1754                    pEnc->mbParam.m_fcode--;
1755                    iSearchRange /= 2;
1756            }
1757    
1758            pEnc->fMvPrevSigma = fSigma;
1759    
1760            /* frame drop code */
1761            DPRINTF(DPRINTF_DEBUG, "kmu %i %i %i", pEnc->current->sStat.kblks, pEnc->current->sStat.mblks, pEnc->current->sStat.ublks);
1762            if (pEnc->current->sStat.kblks + pEnc->current->sStat.mblks <
1763                    (pEnc->mbParam.frame_drop_ratio * mb_width * mb_height) / 100)
1764            {
1765                    pEnc->current->sStat.kblks = pEnc->current->sStat.mblks = 0;
1766                    pEnc->current->sStat.ublks = mb_width * mb_height;
1767    
1768                    BitstreamReset(bs);
1769    
1770                    set_timecodes(pEnc->current,pEnc->reference,pEnc->mbParam.fbase);
1771                    BitstreamWriteVopHeader(bs, &pEnc->mbParam, pEnc->current, 0);
1772    
1773                    /* copy reference frame details into the current frame */
1774                    pEnc->current->quant = pEnc->reference->quant;
1775                    pEnc->current->motion_flags = pEnc->reference->motion_flags;
1776                    pEnc->current->rounding_type = pEnc->reference->rounding_type;
1777                    //pEnc->current->quarterpel =  pEnc->reference->quarterpel;
1778                    pEnc->current->fcode = pEnc->reference->fcode;
1779                    pEnc->current->bcode = pEnc->reference->bcode;
1780                    image_copy(&pEnc->current->image, &pEnc->reference->image, pEnc->mbParam.edged_width, pEnc->mbParam.height);
1781                    memcpy(pEnc->current->mbs, pEnc->reference->mbs, sizeof(MACROBLOCK) * mb_width * mb_height);
1782            }
1783    
1784            /* XXX: debug
1785            {
1786                    char s[100];
1787                    sprintf(s, "\\%05i_cur.pgm", pEnc->m_framenum);
1788                    image_dump_yuvpgm(&pEnc->current->image,
1789                            pEnc->mbParam.edged_width,
1790                            pEnc->mbParam.width, pEnc->mbParam.height, s);
1791    
1792                    sprintf(s, "\\%05i_ref.pgm", pEnc->m_framenum);
1793                    image_dump_yuvpgm(&pEnc->reference->image,
1794                            pEnc->mbParam.edged_width,
1795                            pEnc->mbParam.width, pEnc->mbParam.height, s);
1796            }
1797            */
1798    
1799    /* XXX: Remove the two #if 0 blocks when we are sure we must always pad the stream */
1800    #if 0
1801            /* for divx5 compatibility, we must always pad between the packed p and b frames */
1802            if ((pEnc->mbParam.global_flags & XVID_GLOBAL_PACKED) && pEnc->bframenum_tail > 0)
1803    #endif
1804                    BitstreamPadAlways(bs);
1805    #if 0
1806            else
1807                    BitstreamPad(bs);
1808    #endif
1809    
1810        pEnc->current->length = (BitstreamPos(bs) - bits) / 8;
1811    
1812            return 0;                                       /* inter */
1813    }
1814    
1815    
1816    static void
1817    FrameCodeB(Encoder * pEnc,
1818                       FRAMEINFO * frame,
1819                       Bitstream * bs)
1820    {
1821        int bits = BitstreamPos(bs);
1822            DECLARE_ALIGNED_MATRIX(dct_codes, 6, 64, int16_t, CACHE_LINE);
1823            DECLARE_ALIGNED_MATRIX(qcoeff, 6, 64, int16_t, CACHE_LINE);
1824            uint32_t x, y;
1825    
1826            IMAGE *f_ref = &pEnc->reference->image;
1827            IMAGE *b_ref = &pEnc->current->image;
1828    
1829        #ifdef BFRAMES_DEC_DEBUG
1830            FILE *fp;
1831            static char first=0;
1832    #define BFRAME_DEBUG    if (!first && fp){ \
1833                    fprintf(fp,"Y=%3d   X=%3d   MB=%2d   CBP=%02X\n",y,x,mb->mode,mb->cbp); \
1834            }
1835    
1836            /* XXX: pEnc->current->global_flags &= ~XVID_VOP_REDUCED;  reduced resoltion not yet supported */
1837    
1838            if (!first){
1839                    fp=fopen("C:\\XVIDDBGE.TXT","w");
1840            }
1841    #endif
1842    
1843            //frame->quarterpel =  pEnc->mbParam.m_quarterpel;
1844    
1845            /* forward  */
1846            image_setedges(f_ref, pEnc->mbParam.edged_width,
1847                                       pEnc->mbParam.edged_height, pEnc->mbParam.width,
1848                                       pEnc->mbParam.height);
1849            start_timer();
1850            image_interpolate(f_ref, &pEnc->f_refh, &pEnc->f_refv, &pEnc->f_refhv,
1851                                              pEnc->mbParam.edged_width, pEnc->mbParam.edged_height,
1852                                              (pEnc->mbParam.vol_flags & XVID_VOL_QUARTERPEL), 0);
1853            stop_inter_timer();
1854    
1855            /* backward */
1856            image_setedges(b_ref, pEnc->mbParam.edged_width,
1857                                       pEnc->mbParam.edged_height, pEnc->mbParam.width,
1858                                       pEnc->mbParam.height);
1859            start_timer();
1860            image_interpolate(b_ref, &pEnc->vInterH, &pEnc->vInterV, &pEnc->vInterHV,
1861                                              pEnc->mbParam.edged_width, pEnc->mbParam.edged_height,
1862                                              (pEnc->mbParam.vol_flags & XVID_VOL_QUARTERPEL), 0);
1863            stop_inter_timer();
1864    
1865            start_timer();
1866    
1867            MotionEstimationBVOP(&pEnc->mbParam, frame,
1868                                                     ((int32_t)(pEnc->current->stamp - frame->stamp)),                              /* time_bp */
1869                                                     ((int32_t)(pEnc->current->stamp - pEnc->reference->stamp)),    /* time_pp */
1870                                                     pEnc->reference->mbs, f_ref,
1871                                                     &pEnc->f_refh, &pEnc->f_refv, &pEnc->f_refhv,
1872                                                     pEnc->current, b_ref, &pEnc->vInterH,
1873                                                     &pEnc->vInterV, &pEnc->vInterHV);
1874    
1875    
1876            stop_motion_timer();
1877    
1878            /*
1879            if (test_quant_type(&pEnc->mbParam, pEnc->current)) {
1880                    BitstreamWriteVolHeader(bs, pEnc->mbParam.width, pEnc->mbParam.height, pEnc->mbParam.quant_type);
1881            }
1882            */
1883    
1884            frame->coding_type = B_VOP;
1885    
1886            set_timecodes(frame, pEnc->reference,pEnc->mbParam.fbase);
1887            BitstreamWriteVopHeader(bs, &pEnc->mbParam, frame, 1);
1888    
1889            frame->sStat.iTextBits = 0;
1890            frame->sStat.iMvSum = 0;
1891            frame->sStat.iMvCount = 0;
1892            frame->sStat.kblks = frame->sStat.mblks = frame->sStat.ublks = 0;
1893            frame->sStat.mblks = pEnc->mbParam.mb_width * pEnc->mbParam.mb_height;
1894            frame->sStat.kblks = frame->sStat.ublks = 0;
1895    
1896            for (y = 0; y < pEnc->mbParam.mb_height; y++) {
1897                    for (x = 0; x < pEnc->mbParam.mb_width; x++) {
1898                            MACROBLOCK * const mb = &frame->mbs[x + y * pEnc->mbParam.mb_width];
1899                            int direction = frame->vop_flags & XVID_VOP_ALTERNATESCAN ? 2 : 0;
1900    
1901                            /* decoder ignores mb when refence block is INTER(0,0), CBP=0 */
1902                            if (mb->mode == MODE_NOT_CODED) {
1903                                    /* mb->mvs[0].x = mb->mvs[0].y = mb->cbp = 0; */
1904                                    continue;
1905                            }
1906    
1907                            if (mb->mode != MODE_DIRECT_NONE_MV || pEnc->mbParam.plugin_flags & XVID_REQORIGINAL) {
1908                                    MBMotionCompensationBVOP(&pEnc->mbParam, mb, x, y, &frame->image,
1909                                                                             f_ref, &pEnc->f_refh, &pEnc->f_refv,
1910                                                                             &pEnc->f_refhv, b_ref, &pEnc->vInterH,
1911                                                                             &pEnc->vInterV, &pEnc->vInterHV,
1912                                                                             dct_codes);
1913    
1914                                    if (mb->mode == MODE_DIRECT_NO4V) mb->mode = MODE_DIRECT;
1915                                    mb->quant = frame->quant;
1916    
1917                                    if (mb->mode != MODE_DIRECT_NONE_MV)
1918                                            mb->cbp = MBTransQuantInterBVOP(&pEnc->mbParam, frame, mb, x, y,  dct_codes, qcoeff);
1919    
1920                                    if ( (mb->mode == MODE_DIRECT) && (mb->cbp == 0)
1921                                            && (mb->pmvs[3].x == 0) && (mb->pmvs[3].y == 0) ) {
1922                                            mb->mode = MODE_DIRECT_NONE_MV; /* skipped */
1923                                    }
1924                            }
1925    
1926    #ifdef BFRAMES_DEC_DEBUG
1927            BFRAME_DEBUG
1928    #endif
1929                            start_timer();
1930                            MBCodingBVOP(mb, qcoeff, frame->fcode, frame->bcode, bs,
1931                                                     &frame->sStat, direction);
1932                            stop_coding_timer();
1933                    }
1934            }
1935    
1936            emms();
1937    
1938            /* TODO: dynamic fcode/bcode ??? */
1939    
1940        BitstreamPadAlways(bs);
1941            frame->length = (BitstreamPos(bs) - bits) / 8;
1942    
1943    #ifdef BFRAMES_DEC_DEBUG
1944            if (!first){
1945                    first=1;
1946                    if (fp)
1947                            fclose(fp);
1948            }
1949    #endif
1950  }  }

Legend:
Removed from v.41  
changed lines
  Added in v.1014

No admin address has been configured
ViewVC Help
Powered by ViewVC 1.0.4