[svn] / trunk / xvidcore / src / encoder.c Repository:
ViewVC logotype

Diff of /trunk/xvidcore/src/encoder.c

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

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

Legend:
Removed from v.158  
changed lines
  Added in v.1684

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