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

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

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

revision 982, Thu Apr 10 13:05:54 2003 UTC revision 1129, Mon Aug 25 15:10:30 2003 UTC
# Line 1  Line 1 
1  /**************************************************************************  /*****************************************************************************
2   *   *
3   *      XVID MPEG-4 VIDEO CODEC   *      XVID MPEG-4 VIDEO CODEC
4   *      motion estimation   *  - Motion Estimation related code  -
5   *   *
6   *      This program is an implementation of a part of one or more MPEG-4   *  Copyright(C) 2002 Christoph Lampert <gruel@web.de>
7   *      Video tools as specified in ISO/IEC 14496-2 standard.  Those intending   *               2002 Michael Militzer <michael@xvid.org>
8   *      to use this software module in hardware or software products are   *               2002-2003 Radoslaw Czyz <xvid@syskin.cjb.net>
  *      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 24  Line 19 
19   *   *
20   *      You should have received a copy of the GNU General Public License   *      You should have received a copy of the GNU General Public License
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., 675 Mass Ave, Cambridge, MA 02139, USA.   *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
23     *
24     * $Id: motion_est.c,v 1.58.2.28 2003-08-25 15:10:13 syskin Exp $
25   *   *
26   *************************************************************************/   ****************************************************************************/
27    
28  #include <assert.h>  #include <assert.h>
29  #include <stdio.h>  #include <stdio.h>
30  #include <stdlib.h>  #include <stdlib.h>
31  #include <string.h>     // memcpy  #include <string.h>     /* memcpy */
32  #include <math.h>       // lrint  #include <math.h>       /* lrint */
33    
34  #include "../encoder.h"  #include "../encoder.h"
35  #include "../utils/mbfunctions.h"  #include "../utils/mbfunctions.h"
# Line 43  Line 40 
40  #include "motion_est.h"  #include "motion_est.h"
41  #include "motion.h"  #include "motion.h"
42  #include "sad.h"  #include "sad.h"
43    #include "gmc.h"
44  #include "../utils/emms.h"  #include "../utils/emms.h"
45  #include "../dct/fdct.h"  #include "../dct/fdct.h"
46    
# Line 74  Line 72 
72  #define CHECK_CANDIDATE(X,Y,D) { \  #define CHECK_CANDIDATE(X,Y,D) { \
73  CheckCandidate((X),(Y), (D), &iDirection, data ); }  CheckCandidate((X),(Y), (D), &iDirection, data ); }
74    
75    
76  /*****************************************************************************  /*****************************************************************************
77   * Code   * Code
78   ****************************************************************************/   ****************************************************************************/
# Line 110  Line 109 
109  {  {
110          int sad;          int sad;
111          const uint32_t stride = data->iEdgedWidth/2;          const uint32_t stride = data->iEdgedWidth/2;
112          uint8_t * f_refu = data->RefQ,          uint8_t *f_refu, *f_refv, *b_refu, *b_refv;
113                  * f_refv = data->RefQ + 8,  
114                  * b_refu = data->RefQ + 16,          const INTERPOLATE8X8_PTR interpolate8x8_halfpel[] = {
115                  * b_refv = data->RefQ + 24;                  NULL,
116                    interpolate8x8_halfpel_v,
117                    interpolate8x8_halfpel_h,
118                    interpolate8x8_halfpel_hv
119            };
120    
121          int offset = (fx>>1) + (fy>>1)*stride;          int offset = (fx>>1) + (fy>>1)*stride;
122            int filter = ((fx & 1) << 1) | (fy & 1);
123    
124          switch (((fx & 1) << 1) | (fy & 1))     {          if (filter != 0) {
125                  case 0:                  f_refu = data->RefQ;
126                    f_refv = data->RefQ + 8;
127                    interpolate8x8_halfpel[filter](f_refu, data->RefP[4] + offset, stride, data->rounding);
128                    interpolate8x8_halfpel[filter](f_refv, data->RefP[5] + offset, stride, data->rounding);
129            } else {
130                          f_refu = (uint8_t*)data->RefP[4] + offset;                          f_refu = (uint8_t*)data->RefP[4] + offset;
131                          f_refv = (uint8_t*)data->RefP[5] + offset;                          f_refv = (uint8_t*)data->RefP[5] + offset;
                         break;  
                 case 1:  
                         interpolate8x8_halfpel_v(f_refu, data->RefP[4] + offset, stride, data->rounding);  
                         interpolate8x8_halfpel_v(f_refv, data->RefP[5] + offset, stride, data->rounding);  
                         break;  
                 case 2:  
                         interpolate8x8_halfpel_h(f_refu, data->RefP[4] + offset, stride, data->rounding);  
                         interpolate8x8_halfpel_h(f_refv, data->RefP[5] + offset, stride, data->rounding);  
                         break;  
                 default:  
                         interpolate8x8_halfpel_hv(f_refu, data->RefP[4] + offset, stride, data->rounding);  
                         interpolate8x8_halfpel_hv(f_refv, data->RefP[5] + offset, stride, data->rounding);  
                         break;  
132          }          }
133    
134          offset = (bx>>1) + (by>>1)*stride;          offset = (bx>>1) + (by>>1)*stride;
135          switch (((bx & 1) << 1) | (by & 1))     {          filter = ((bx & 1) << 1) | (by & 1);
136                  case 0:  
137            if (filter != 0) {
138                    b_refu = data->RefQ + 16;
139                    b_refv = data->RefQ + 24;
140                    interpolate8x8_halfpel[filter](b_refu, data->b_RefP[4] + offset, stride, data->rounding);
141                    interpolate8x8_halfpel[filter](b_refv, data->b_RefP[5] + offset, stride, data->rounding);
142            } else {
143                          b_refu = (uint8_t*)data->b_RefP[4] + offset;                          b_refu = (uint8_t*)data->b_RefP[4] + offset;
144                          b_refv = (uint8_t*)data->b_RefP[5] + offset;                          b_refv = (uint8_t*)data->b_RefP[5] + offset;
                         break;  
                 case 1:  
                         interpolate8x8_halfpel_v(b_refu, data->b_RefP[4] + offset, stride, data->rounding);  
                         interpolate8x8_halfpel_v(b_refv, data->b_RefP[5] + offset, stride, data->rounding);  
                         break;  
                 case 2:  
                         interpolate8x8_halfpel_h(b_refu, data->b_RefP[4] + offset, stride, data->rounding);  
                         interpolate8x8_halfpel_h(b_refv, data->b_RefP[5] + offset, stride, data->rounding);  
                         break;  
                 default:  
                         interpolate8x8_halfpel_hv(b_refu, data->b_RefP[4] + offset, stride, data->rounding);  
                         interpolate8x8_halfpel_hv(b_refv, data->b_RefP[5] + offset, stride, data->rounding);  
                         break;  
145          }          }
146    
147          sad = sad8bi(data->CurU, b_refu, f_refu, stride);          sad = sad8bi(data->CurU, b_refu, f_refu, stride);
# Line 168  Line 157 
157          const uint32_t stride = data->iEdgedWidth/2;          const uint32_t stride = data->iEdgedWidth/2;
158          int offset = (dx>>1) + (dy>>1)*stride;          int offset = (dx>>1) + (dy>>1)*stride;
159    
160          if (dx == data->temp[5] && dy == data->temp[6]) return data->temp[7]; //it has been checked recently          if (dx == data->temp[5] && dy == data->temp[6]) return data->temp[7]; /* it has been checked recently */
161          data->temp[5] = dx; data->temp[6] = dy; // backup          data->temp[5] = dx; data->temp[6] = dy; /* backup */
162    
163          switch (((dx & 1) << 1) | (dy & 1))     {          switch (((dx & 1) << 1) | (dy & 1))     {
164                  case 0:                  case 0:
# Line 192  Line 181 
181                          sad += sad8(data->CurV, data->RefQ, stride);                          sad += sad8(data->CurV, data->RefQ, stride);
182                          break;                          break;
183          }          }
184          data->temp[7] = sad; //backup, part 2          data->temp[7] = sad; /* backup, part 2 */
185          return sad;          return sad;
186  }  }
187    
188  static __inline const uint8_t *  static __inline const uint8_t *
189  GetReferenceB(const int x, const int y, const uint32_t dir, const SearchData * const data)  GetReferenceB(const int x, const int y, const uint32_t dir, const SearchData * const data)
190  {  {
191  //      dir : 0 = forward, 1 = backward          /* dir : 0 = forward, 1 = backward */
192          const uint8_t* const *direction = ( dir == 0 ? data->RefP : data->b_RefP );          const uint8_t *const *const direction = ( dir == 0 ? data->RefP : data->b_RefP );
193          const int picture = ((x&1)<<1) | (y&1);          const int picture = ((x&1)<<1) | (y&1);
194          const int offset = (x>>1) + (y>>1)*data->iEdgedWidth;          const int offset = (x>>1) + (y>>1)*data->iEdgedWidth;
195          return direction[picture] + offset;          return direction[picture] + offset;
196  }  }
197    
198  // this is a simpler copy of GetReferenceB, but as it's __inline anyway, we can keep the two separate  /* this is a simpler copy of GetReferenceB, but as it's __inline anyway, we can keep the two separate */
199  static __inline const uint8_t *  static __inline const uint8_t *
200  GetReference(const int x, const int y, const SearchData * const data)  GetReference(const int x, const int y, const SearchData * const data)
201  {  {
# Line 218  Line 207 
207  static uint8_t *  static uint8_t *
208  Interpolate8x8qpel(const int x, const int y, const uint32_t block, const uint32_t dir, const SearchData * const data)  Interpolate8x8qpel(const int x, const int y, const uint32_t block, const uint32_t dir, const SearchData * const data)
209  {  {
210  // create or find a qpel-precision reference picture; return pointer to it          /* create or find a qpel-precision reference picture; return pointer to it */
211          uint8_t * Reference = data->RefQ + 16*dir;          uint8_t * Reference = data->RefQ + 16*dir;
212          const uint32_t iEdgedWidth = data->iEdgedWidth;          const uint32_t iEdgedWidth = data->iEdgedWidth;
213          const uint32_t rounding = data->rounding;          const uint32_t rounding = data->rounding;
# Line 229  Line 218 
218          ref1 = GetReferenceB(halfpel_x, halfpel_y, dir, data);          ref1 = GetReferenceB(halfpel_x, halfpel_y, dir, data);
219          ref1 += 8 * (block&1) + 8 * (block>>1) * iEdgedWidth;          ref1 += 8 * (block&1) + 8 * (block>>1) * iEdgedWidth;
220          switch( ((x&1)<<1) + (y&1) ) {          switch( ((x&1)<<1) + (y&1) ) {
221          case 3: // x and y in qpel resolution - the "corners" (top left/right and          case 3: /* x and y in qpel resolution - the "corners" (top left/right and */
222                          // bottom left/right) during qpel refinement                          /* bottom left/right) during qpel refinement */
223                  ref2 = GetReferenceB(halfpel_x, y - halfpel_y, dir, data);                  ref2 = GetReferenceB(halfpel_x, y - halfpel_y, dir, data);
224                  ref3 = GetReferenceB(x - halfpel_x, halfpel_y, dir, data);                  ref3 = GetReferenceB(x - halfpel_x, halfpel_y, dir, data);
225                  ref4 = GetReferenceB(x - halfpel_x, y - halfpel_y, dir, data);                  ref4 = GetReferenceB(x - halfpel_x, y - halfpel_y, dir, data);
# Line 240  Line 229 
229                  interpolate8x8_avg4(Reference, ref1, ref2, ref3, ref4, iEdgedWidth, rounding);                  interpolate8x8_avg4(Reference, ref1, ref2, ref3, ref4, iEdgedWidth, rounding);
230                  break;                  break;
231    
232          case 1: // x halfpel, y qpel - top or bottom during qpel refinement          case 1: /* x halfpel, y qpel - top or bottom during qpel refinement */
233                  ref2 = GetReferenceB(halfpel_x, y - halfpel_y, dir, data);                  ref2 = GetReferenceB(halfpel_x, y - halfpel_y, dir, data);
234                  ref2 += 8 * (block&1) + 8 * (block>>1) * iEdgedWidth;                  ref2 += 8 * (block&1) + 8 * (block>>1) * iEdgedWidth;
235                  interpolate8x8_avg2(Reference, ref1, ref2, iEdgedWidth, rounding, 8);                  interpolate8x8_avg2(Reference, ref1, ref2, iEdgedWidth, rounding, 8);
236                  break;                  break;
237    
238          case 2: // x qpel, y halfpel - left or right during qpel refinement          case 2: /* x qpel, y halfpel - left or right during qpel refinement */
239                  ref2 = GetReferenceB(x - halfpel_x, halfpel_y, dir, data);                  ref2 = GetReferenceB(x - halfpel_x, halfpel_y, dir, data);
240                  ref2 += 8 * (block&1) + 8 * (block>>1) * iEdgedWidth;                  ref2 += 8 * (block&1) + 8 * (block>>1) * iEdgedWidth;
241                  interpolate8x8_avg2(Reference, ref1, ref2, iEdgedWidth, rounding, 8);                  interpolate8x8_avg2(Reference, ref1, ref2, iEdgedWidth, rounding, 8);
242                  break;                  break;
243    
244          default: // pure halfpel position          default: /* pure halfpel position */
245                  return (uint8_t *) ref1;                  return (uint8_t *) ref1;
246    
247          }          }
# Line 262  Line 251 
251  static uint8_t *  static uint8_t *
252  Interpolate16x16qpel(const int x, const int y, const uint32_t dir, const SearchData * const data)  Interpolate16x16qpel(const int x, const int y, const uint32_t dir, const SearchData * const data)
253  {  {
254  // create or find a qpel-precision reference picture; return pointer to it          /* create or find a qpel-precision reference picture; return pointer to it */
255          uint8_t * Reference = data->RefQ + 16*dir;          uint8_t * Reference = data->RefQ + 16*dir;
256          const uint32_t iEdgedWidth = data->iEdgedWidth;          const uint32_t iEdgedWidth = data->iEdgedWidth;
257          const uint32_t rounding = data->rounding;          const uint32_t rounding = data->rounding;
# Line 272  Line 261 
261    
262          ref1 = GetReferenceB(halfpel_x, halfpel_y, dir, data);          ref1 = GetReferenceB(halfpel_x, halfpel_y, dir, data);
263          switch( ((x&1)<<1) + (y&1) ) {          switch( ((x&1)<<1) + (y&1) ) {
264          case 3: // x and y in qpel resolution - the "corners" (top left/right and          case 3:
265                          // bottom left/right) during qpel refinement                  /*
266                     * x and y in qpel resolution - the "corners" (top left/right and
267                     * bottom left/right) during qpel refinement
268                     */
269                  ref2 = GetReferenceB(halfpel_x, y - halfpel_y, dir, data);                  ref2 = GetReferenceB(halfpel_x, y - halfpel_y, dir, data);
270                  ref3 = GetReferenceB(x - halfpel_x, halfpel_y, dir, data);                  ref3 = GetReferenceB(x - halfpel_x, halfpel_y, dir, data);
271                  ref4 = GetReferenceB(x - halfpel_x, y - halfpel_y, dir, data);                  ref4 = GetReferenceB(x - halfpel_x, y - halfpel_y, dir, data);
# Line 283  Line 275 
275                  interpolate8x8_avg4(Reference+8*iEdgedWidth+8, ref1+8*iEdgedWidth+8, ref2+8*iEdgedWidth+8, ref3+8*iEdgedWidth+8, ref4+8*iEdgedWidth+8, iEdgedWidth, rounding);                  interpolate8x8_avg4(Reference+8*iEdgedWidth+8, ref1+8*iEdgedWidth+8, ref2+8*iEdgedWidth+8, ref3+8*iEdgedWidth+8, ref4+8*iEdgedWidth+8, iEdgedWidth, rounding);
276                  break;                  break;
277    
278          case 1: // x halfpel, y qpel - top or bottom during qpel refinement          case 1: /* x halfpel, y qpel - top or bottom during qpel refinement */
279                  ref2 = GetReferenceB(halfpel_x, y - halfpel_y, dir, data);                  ref2 = GetReferenceB(halfpel_x, y - halfpel_y, dir, data);
280                  interpolate8x8_avg2(Reference, ref1, ref2, iEdgedWidth, rounding, 8);                  interpolate8x8_avg2(Reference, ref1, ref2, iEdgedWidth, rounding, 8);
281                  interpolate8x8_avg2(Reference+8, ref1+8, ref2+8, iEdgedWidth, rounding, 8);                  interpolate8x8_avg2(Reference+8, ref1+8, ref2+8, iEdgedWidth, rounding, 8);
# Line 291  Line 283 
283                  interpolate8x8_avg2(Reference+8*iEdgedWidth+8, ref1+8*iEdgedWidth+8, ref2+8*iEdgedWidth+8, iEdgedWidth, rounding, 8);                  interpolate8x8_avg2(Reference+8*iEdgedWidth+8, ref1+8*iEdgedWidth+8, ref2+8*iEdgedWidth+8, iEdgedWidth, rounding, 8);
284                  break;                  break;
285    
286          case 2: // x qpel, y halfpel - left or right during qpel refinement          case 2: /* x qpel, y halfpel - left or right during qpel refinement */
287                  ref2 = GetReferenceB(x - halfpel_x, halfpel_y, dir, data);                  ref2 = GetReferenceB(x - halfpel_x, halfpel_y, dir, data);
288                  interpolate8x8_avg2(Reference, ref1, ref2, iEdgedWidth, rounding, 8);                  interpolate8x8_avg2(Reference, ref1, ref2, iEdgedWidth, rounding, 8);
289                  interpolate8x8_avg2(Reference+8, ref1+8, ref2+8, iEdgedWidth, rounding, 8);                  interpolate8x8_avg2(Reference+8, ref1+8, ref2+8, iEdgedWidth, rounding, 8);
# Line 299  Line 291 
291                  interpolate8x8_avg2(Reference+8*iEdgedWidth+8, ref1+8*iEdgedWidth+8, ref2+8*iEdgedWidth+8, iEdgedWidth, rounding, 8);                  interpolate8x8_avg2(Reference+8*iEdgedWidth+8, ref1+8*iEdgedWidth+8, ref2+8*iEdgedWidth+8, iEdgedWidth, rounding, 8);
292                  break;                  break;
293    
294          default: // pure halfpel position  
295            default: /* pure halfpel position */
296                  return (uint8_t *) ref1;                  return (uint8_t *) ref1;
297          }          }
298          return Reference;          return Reference;
# Line 322  Line 315 
315                  Reference = GetReference(x, y, data);                  Reference = GetReference(x, y, data);
316                  current = data->currentMV;                  current = data->currentMV;
317                  xc = x; yc = y;                  xc = x; yc = y;
318          } else { // x and y are in 1/4 precision          } else { /* x and y are in 1/4 precision */
319                  Reference = Interpolate16x16qpel(x, y, 0, data);                  Reference = Interpolate16x16qpel(x, y, 0, data);
320                  xc = x/2; yc = y/2; //for chroma sad                  xc = x/2; yc = y/2; /* for chroma sad */
321                  current = data->currentQMV;                  current = data->currentQMV;
322          }          }
323    
# Line 334  Line 327 
327          sad += (data->lambda16 * t * sad)>>10;          sad += (data->lambda16 * t * sad)>>10;
328          data->temp[1] += (data->lambda8 * t * (data->temp[1] + NEIGH_8X8_BIAS))>>10;          data->temp[1] += (data->lambda8 * t * (data->temp[1] + NEIGH_8X8_BIAS))>>10;
329    
330          if (data->chroma) sad += ChromaSAD((xc >> 1) + roundtab_79[xc & 0x3],          if (data->chroma && sad < data->iMinSAD[0])
331                    sad += ChromaSAD((xc >> 1) + roundtab_79[xc & 0x3],
332                                                                             (yc >> 1) + roundtab_79[yc & 0x3], data);                                                                             (yc >> 1) + roundtab_79[yc & 0x3], data);
333    
334          if (sad < data->iMinSAD[0]) {          if (sad < data->iMinSAD[0]) {
# Line 351  Line 345 
345                  data->iMinSAD[3] = data->temp[3]; current[3].x = x; current[3].y = y; }                  data->iMinSAD[3] = data->temp[3]; current[3].x = x; current[3].y = y; }
346          if (data->temp[4] < data->iMinSAD[4]) {          if (data->temp[4] < data->iMinSAD[4]) {
347                  data->iMinSAD[4] = data->temp[4]; current[4].x = x; current[4].y = y; }                  data->iMinSAD[4] = data->temp[4]; current[4].x = x; current[4].y = y; }
   
348  }  }
349    
350  static void  static void
# Line 367  Line 360 
360          if (!data->qpel_precision) {          if (!data->qpel_precision) {
361                  Reference = GetReference(x, y, data);                  Reference = GetReference(x, y, data);
362                  current = data->currentMV;                  current = data->currentMV;
363          } else { // x and y are in 1/4 precision          } else { /* x and y are in 1/4 precision */
364                  Reference = Interpolate8x8qpel(x, y, 0, 0, data);                  Reference = Interpolate8x8qpel(x, y, 0, 0, data);
365                  current = data->currentQMV;                  current = data->currentQMV;
366          }          }
# Line 384  Line 377 
377          }          }
378  }  }
379    
   
380  static void  static void
381  CheckCandidate32(const int x, const int y, const int Direction, int * const dir, const SearchData * const data)  CheckCandidate32(const int x, const int y, const int Direction, int * const dir, const SearchData * const data)
382  {  {
383          uint32_t t;          uint32_t t;
384          const uint8_t * Reference;          const uint8_t * Reference;
385    
386          if ( (!(x&1) && x !=0) || (!(y&1) && y !=0) || //non-zero even value          if ( (!(x&1) && x !=0) || (!(y&1) && y !=0) || /* non-zero even value */
387                  (x > data->max_dx) || (x < data->min_dx)                  (x > data->max_dx) || (x < data->min_dx)
388                  || (y > data->max_dy) || (y < data->min_dy) ) return;                  || (y > data->max_dy) || (y < data->min_dy) ) return;
389    
# Line 429  Line 421 
421          if ( (x > data->max_dx) || ( x < data->min_dx)          if ( (x > data->max_dx) || ( x < data->min_dx)
422                  || (y > data->max_dy) || (y < data->min_dy) ) return;                  || (y > data->max_dy) || (y < data->min_dy) ) return;
423    
424          if (data->rrv && (!(x&1) && x !=0) | (!(y&1) && y !=0) ) return; //non-zero even value          if (data->rrv && (!(x&1) && x !=0) | (!(y&1) && y !=0) ) return; /* non-zero even value */
425    
426          if (data->qpel_precision) { // x and y are in 1/4 precision          if (data->qpel_precision) { /* x and y are in 1/4 precision */
427                  Reference = Interpolate16x16qpel(x, y, 0, data);                  Reference = Interpolate16x16qpel(x, y, 0, data);
428                  current = data->currentQMV;                  current = data->currentQMV;
429                  xc = x/2; yc = y/2;                  xc = x/2; yc = y/2;
# Line 446  Line 438 
438          sad = sad16(data->Cur, Reference, data->iEdgedWidth, 256*4096);          sad = sad16(data->Cur, Reference, data->iEdgedWidth, 256*4096);
439          sad += (data->lambda16 * t * sad)>>10;          sad += (data->lambda16 * t * sad)>>10;
440    
441          if (data->chroma) sad += ChromaSAD((xc >> 1) + roundtab_79[xc & 0x3],          if (data->chroma && sad < *data->iMinSAD)
442                    sad += ChromaSAD((xc >> 1) + roundtab_79[xc & 0x3],
443                                                                                  (yc >> 1) + roundtab_79[yc & 0x3], data);                                                                                  (yc >> 1) + roundtab_79[yc & 0x3], data);
444    
445          if (sad < *(data->iMinSAD)) {          if (sad < *(data->iMinSAD)) {
# Line 457  Line 450 
450  }  }
451    
452  static void  static void
453    CheckCandidate16I(const int x, const int y, const int Direction, int * const dir, const SearchData * const data)
454    {
455            int sad;
456    //      int xc, yc;
457            const uint8_t * Reference;
458    //      VECTOR * current;
459    
460            if ( (x > data->max_dx) || ( x < data->min_dx)
461                    || (y > data->max_dy) || (y < data->min_dy) ) return;
462    
463            Reference = GetReference(x, y, data);
464    //      xc = x; yc = y;
465    
466            sad = sad16(data->Cur, Reference, data->iEdgedWidth, 256*4096);
467    //      sad += d_mv_bits(x, y, data->predMV, data->iFcode, 0, 0);
468    
469    /*      if (data->chroma) sad += ChromaSAD((xc >> 1) + roundtab_79[xc & 0x3],
470                                                                                    (yc >> 1) + roundtab_79[yc & 0x3], data);
471    */
472    
473            if (sad < data->iMinSAD[0]) {
474                    data->iMinSAD[0] = sad;
475                    data->currentMV[0].x = x; data->currentMV[0].y = y;
476                    *dir = Direction;
477            }
478    }
479    
480    static void
481  CheckCandidate32I(const int x, const int y, const int Direction, int * const dir, const SearchData * const data)  CheckCandidate32I(const int x, const int y, const int Direction, int * const dir, const SearchData * const data)
482  {  {
483  // maximum speed - for P/B/I decision          /* maximum speed - for P/B/I decision */
484          int32_t sad;          int32_t sad;
485    
486          if ( (x > data->max_dx) || (x < data->min_dx)          if ( (x > data->max_dx) || (x < data->min_dx)
487                  || (y > data->max_dy) || (y < data->min_dy) ) return;                  || (y > data->max_dy) || (y < data->min_dy) ) return;
488    
489          sad = sad32v_c(data->Cur, data->RefP[0] + x/2 + (y/2)*(data->iEdgedWidth),          sad = sad32v_c(data->Cur, data->RefP[0] + (x>>1) + (y>>1)*((int)data->iEdgedWidth),
490                                                          data->iEdgedWidth, data->temp+1);                                                          data->iEdgedWidth, data->temp+1);
491    
492          if (sad < *(data->iMinSAD)) {          if (sad < *(data->iMinSAD)) {
# Line 518  Line 539 
539          sad = sad16bi(data->Cur, ReferenceF, ReferenceB, data->iEdgedWidth);          sad = sad16bi(data->Cur, ReferenceF, ReferenceB, data->iEdgedWidth);
540          sad += (data->lambda16 * t * sad)>>10;          sad += (data->lambda16 * t * sad)>>10;
541    
542          if (data->chroma) sad += ChromaSAD2((xcf >> 1) + roundtab_79[xcf & 0x3],          if (data->chroma && sad < *data->iMinSAD)
543                    sad += ChromaSAD2((xcf >> 1) + roundtab_79[xcf & 0x3],
544                                                                                  (ycf >> 1) + roundtab_79[ycf & 0x3],                                                                                  (ycf >> 1) + roundtab_79[ycf & 0x3],
545                                                                                  (xcb >> 1) + roundtab_79[xcb & 0x3],                                                                                  (xcb >> 1) + roundtab_79[xcb & 0x3],
546                                                                                  (ycb >> 1) + roundtab_79[ycb & 0x3], data);                                                                                  (ycb >> 1) + roundtab_79[ycb & 0x3], data);
# Line 564  Line 586 
586                  } else {                  } else {
587                          xcf += mvs.x; ycf += mvs.y;                          xcf += mvs.x; ycf += mvs.y;
588                          xcb += b_mvs.x; ycb += b_mvs.y;                          xcb += b_mvs.x; ycb += b_mvs.y;
589                          mvs.x *= 2; mvs.y *= 2; //we move to qpel precision anyway                          mvs.x *= 2; mvs.y *= 2; /* we move to qpel precision anyway */
590                          b_mvs.x *= 2; b_mvs.y *= 2;                          b_mvs.x *= 2; b_mvs.y *= 2;
591                  }                  }
592    
# Line 578  Line 600 
600    
601          sad += (data->lambda16 * d_mv_bits(x, y, zeroMV, 1, 0, 0) * sad)>>10;          sad += (data->lambda16 * d_mv_bits(x, y, zeroMV, 1, 0, 0) * sad)>>10;
602    
603          if (data->chroma) sad += ChromaSAD2((xcf >> 3) + roundtab_76[xcf & 0xf],          if (data->chroma && sad < *data->iMinSAD)
604                    sad += ChromaSAD2((xcf >> 3) + roundtab_76[xcf & 0xf],
605                                                                                  (ycf >> 3) + roundtab_76[ycf & 0xf],                                                                                  (ycf >> 3) + roundtab_76[ycf & 0xf],
606                                                                                  (xcb >> 3) + roundtab_76[xcb & 0xf],                                                                                  (xcb >> 3) + roundtab_76[xcb & 0xf],
607                                                                                  (ycb >> 3) + roundtab_76[ycb & 0xf], data);                                                                                  (ycb >> 3) + roundtab_76[ycb & 0xf], data);
# Line 630  Line 653 
653          sad = sad16bi(data->Cur, ReferenceF, ReferenceB, data->iEdgedWidth);          sad = sad16bi(data->Cur, ReferenceF, ReferenceB, data->iEdgedWidth);
654          sad += (data->lambda16 * d_mv_bits(x, y, zeroMV, 1, 0, 0) * sad)>>10;          sad += (data->lambda16 * d_mv_bits(x, y, zeroMV, 1, 0, 0) * sad)>>10;
655    
656          if (data->chroma) sad += ChromaSAD2((xcf >> 3) + roundtab_76[xcf & 0xf],          if (data->chroma && sad < *data->iMinSAD)
657                    sad += ChromaSAD2((xcf >> 3) + roundtab_76[xcf & 0xf],
658                                                                                  (ycf >> 3) + roundtab_76[ycf & 0xf],                                                                                  (ycf >> 3) + roundtab_76[ycf & 0xf],
659                                                                                  (xcb >> 3) + roundtab_76[xcb & 0xf],                                                                                  (xcb >> 3) + roundtab_76[xcb & 0xf],
660                                                                                  (ycb >> 3) + roundtab_76[ycb & 0xf], data);                                                                                  (ycb >> 3) + roundtab_76[ycb & 0xf], data);
# Line 644  Line 668 
668    
669    
670  static void  static void
671  CheckCandidateBits16(const int x, const int y, const int Direction, int * const dir, const SearchData * const data)  CheckCandidateRD16(const int x, const int y, const int Direction, int * const dir, const SearchData * const data)
672  {  {
673    
674          int16_t *in = data->dctSpace, *coeff = data->dctSpace + 64;          int16_t *in = data->dctSpace, *coeff = data->dctSpace + 64;
675          int32_t bits = 0, sum;          int32_t rd = 0;
676          VECTOR * current;          VECTOR * current;
677          const uint8_t * ptr;          const uint8_t * ptr;
678          int i, cbp = 0, t, xc, yc;          int i, cbp = 0, t, xc, yc;
# Line 660  Line 684 
684                  ptr = GetReference(x, y, data);                  ptr = GetReference(x, y, data);
685                  current = data->currentMV;                  current = data->currentMV;
686                  xc = x; yc = y;                  xc = x; yc = y;
687          } else { // x and y are in 1/4 precision          } else { /* x and y are in 1/4 precision */
688                  ptr = Interpolate16x16qpel(x, y, 0, data);                  ptr = Interpolate16x16qpel(x, y, 0, data);
689                  current = data->currentQMV;                  current = data->currentQMV;
690                  xc = x/2; yc = y/2;                  xc = x/2; yc = y/2;
# Line 669  Line 693 
693          for(i = 0; i < 4; i++) {          for(i = 0; i < 4; i++) {
694                  int s = 8*((i&1) + (i>>1)*data->iEdgedWidth);                  int s = 8*((i&1) + (i>>1)*data->iEdgedWidth);
695                  transfer_8to16subro(in, data->Cur + s, ptr + s, data->iEdgedWidth);                  transfer_8to16subro(in, data->Cur + s, ptr + s, data->iEdgedWidth);
696                  fdct(in);                  rd += data->temp[i] = Block_CalcBits(coeff, in, data->dctSpace + 128, data->iQuant, data->quant_type, &cbp, i);
                 if (data->lambda8 == 0) sum = quant_inter(coeff, in, data->lambda16);  
                 else sum = quant4_inter(coeff, in, data->lambda16);  
                 if (sum > 0) {  
                         cbp |= 1 << (5 - i);  
                         bits += data->temp[i] = CodeCoeffInter_CalcBits(coeff, scan_tables[0]);  
                 } else data->temp[i] = 0;  
697          }          }
698    
699          bits += t = d_mv_bits(x, y, data->predMV, data->iFcode, data->qpel^data->qpel_precision, 0);          rd += t = BITS_MULT*d_mv_bits(x, y, data->predMV, data->iFcode, data->qpel^data->qpel_precision, 0);
700    
701            if (data->temp[0] + t < data->iMinSAD[1]) {
702                    data->iMinSAD[1] = data->temp[0] + t; current[1].x = x; current[1].y = y; data->cbp[1] = (data->cbp[1]&~32) | (cbp&32); }
703            if (data->temp[1] < data->iMinSAD[2]) {
704                    data->iMinSAD[2] = data->temp[1]; current[2].x = x; current[2].y = y; data->cbp[1] = (data->cbp[1]&~16) | (cbp&16); }
705            if (data->temp[2] < data->iMinSAD[3]) {
706                    data->iMinSAD[3] = data->temp[2]; current[3].x = x; current[3].y = y; data->cbp[1] = (data->cbp[1]&~8) | (cbp&8); }
707            if (data->temp[3] < data->iMinSAD[4]) {
708                    data->iMinSAD[4] = data->temp[3]; current[4].x = x; current[4].y = y; data->cbp[1] = (data->cbp[1]&~4) | (cbp&4); }
709    
710            rd += BITS_MULT*xvid_cbpy_tab[15-(cbp>>2)].len;
711    
712            if (rd >= data->iMinSAD[0]) return;
713    
714          if (bits < data->iMinSAD[0]) { // there is still a chance, adding chroma          /* chroma */
715                  xc = (xc >> 1) + roundtab_79[xc & 0x3];                  xc = (xc >> 1) + roundtab_79[xc & 0x3];
716                  yc = (yc >> 1) + roundtab_79[yc & 0x3];                  yc = (yc >> 1) + roundtab_79[yc & 0x3];
717    
718                  //chroma U          /* chroma U */
719                  ptr = interpolate8x8_switch2(data->RefQ + 64, data->RefP[4], 0, 0, xc, yc,  data->iEdgedWidth/2, data->rounding);          ptr = interpolate8x8_switch2(data->RefQ, data->RefP[4], 0, 0, xc, yc, data->iEdgedWidth/2, data->rounding);
720                  transfer_8to16subro(in, ptr, data->CurU, data->iEdgedWidth/2);          transfer_8to16subro(in, data->CurU, ptr, data->iEdgedWidth/2);
721                  fdct(in);          rd += Block_CalcBits(coeff, in, data->dctSpace + 128, data->iQuant, data->quant_type, &cbp, 4);
722                  if (data->lambda8 == 0) sum = quant_inter(coeff, in, data->lambda16);          if (rd >= data->iMinSAD[0]) return;
723                  else sum = quant4_inter(coeff, in, data->lambda16);  
724                  if (sum > 0) {          /* chroma V */
725                          cbp |= 1 << (5 - 4);          ptr = interpolate8x8_switch2(data->RefQ, data->RefP[5], 0, 0, xc, yc, data->iEdgedWidth/2, data->rounding);
726                          bits += CodeCoeffInter_CalcBits(coeff, scan_tables[0]);          transfer_8to16subro(in, data->CurV, ptr, data->iEdgedWidth/2);
727                  }          rd += Block_CalcBits(coeff, in, data->dctSpace + 128, data->iQuant, data->quant_type, &cbp, 5);
   
                 if (bits < data->iMinSAD[0]) {  
                         //chroma V  
                         ptr = interpolate8x8_switch2(data->RefQ + 64, data->RefP[5], 0, 0, xc, yc,  data->iEdgedWidth/2, data->rounding);  
                         transfer_8to16subro(in, ptr, data->CurV, data->iEdgedWidth/2);  
                         fdct(in);  
                         if (data->lambda8 == 0) sum = quant_inter(coeff, in, data->lambda16);  
                         else sum = quant4_inter(coeff, in, data->lambda16);  
                         if (sum > 0) {  
                                 cbp |= 1 << (5 - 5);  
                                 bits += CodeCoeffInter_CalcBits(coeff, scan_tables[0]);  
                         }  
                 }  
         }  
728    
729          bits += xvid_cbpy_tab[15-(cbp>>2)].len;          rd += BITS_MULT*mcbpc_inter_tab[(MODE_INTER & 7) | ((cbp & 3) << 3)].len;
         bits += mcbpc_inter_tab[(MODE_INTER & 7) | ((cbp & 3) << 3)].len;  
730    
731          if (bits < data->iMinSAD[0]) {          if (rd < data->iMinSAD[0]) {
732                  data->iMinSAD[0] = bits;                  data->iMinSAD[0] = rd;
733                  current[0].x = x; current[0].y = y;                  current[0].x = x; current[0].y = y;
734                  *dir = Direction;                  *dir = Direction;
735                    *data->cbp = cbp;
736          }          }
   
         if (data->temp[0] + t < data->iMinSAD[1]) {  
                 data->iMinSAD[1] = data->temp[0] + t; current[1].x = x; current[1].y = y; }  
         if (data->temp[1] < data->iMinSAD[2]) {  
                 data->iMinSAD[2] = data->temp[1]; current[2].x = x; current[2].y = y; }  
         if (data->temp[2] < data->iMinSAD[3]) {  
                 data->iMinSAD[3] = data->temp[2]; current[3].x = x; current[3].y = y; }  
         if (data->temp[3] < data->iMinSAD[4]) {  
                 data->iMinSAD[4] = data->temp[3]; current[4].x = x; current[4].y = y; }  
   
737  }  }
738    
739  static void  static void
740  CheckCandidateBits8(const int x, const int y, const int Direction, int * const dir, const SearchData * const data)  CheckCandidateRD8(const int x, const int y, const int Direction, int * const dir, const SearchData * const data)
741  {  {
742    
743          int16_t *in = data->dctSpace, *coeff = data->dctSpace + 64;          int16_t *in = data->dctSpace, *coeff = data->dctSpace + 64;
744          int32_t sum, bits;          int32_t rd;
745          VECTOR * current;          VECTOR * current;
746          const uint8_t * ptr;          const uint8_t * ptr;
747          int cbp;          int cbp = 0;
748    
749          if ( (x > data->max_dx) || (x < data->min_dx)          if ( (x > data->max_dx) || (x < data->min_dx)
750                  || (y > data->max_dy) || (y < data->min_dy) ) return;                  || (y > data->max_dy) || (y < data->min_dy) ) return;
# Line 744  Line 752 
752          if (!data->qpel_precision) {          if (!data->qpel_precision) {
753                  ptr = GetReference(x, y, data);                  ptr = GetReference(x, y, data);
754                  current = data->currentMV;                  current = data->currentMV;
755          } else { // x and y are in 1/4 precision          } else { /* x and y are in 1/4 precision */
756                  ptr = Interpolate8x8qpel(x, y, 0, 0, data);                  ptr = Interpolate8x8qpel(x, y, 0, 0, data);
757                  current = data->currentQMV;                  current = data->currentQMV;
758          }          }
759    
760          transfer_8to16subro(in, data->Cur, ptr, data->iEdgedWidth);          transfer_8to16subro(in, data->Cur, ptr, data->iEdgedWidth);
761          fdct(in);          rd = Block_CalcBits(coeff, in, data->dctSpace + 128, data->iQuant, data->quant_type, &cbp, 5);
762          if (data->lambda8 == 0) sum = quant_inter(coeff, in, data->lambda16);          rd += BITS_MULT*d_mv_bits(x, y, data->predMV, data->iFcode, data->qpel^data->qpel_precision, 0);
763          else sum = quant4_inter(coeff, in, data->lambda16);  
764          if (sum > 0) {          if (rd < data->iMinSAD[0]) {
765                  bits = CodeCoeffInter_CalcBits(coeff, scan_tables[0]);                  *data->cbp = cbp;
766                  cbp = 1;                  data->iMinSAD[0] = rd;
         } else cbp = bits = 0;  
   
         bits += sum = d_mv_bits(x, y, data->predMV, data->iFcode, data->qpel^data->qpel_precision, 0);  
   
         if (bits < data->iMinSAD[0]) {  
                 data->temp[0] = cbp;  
                 data->iMinSAD[0] = bits;  
767                  current[0].x = x; current[0].y = y;                  current[0].x = x; current[0].y = y;
768                  *dir = Direction;                  *dir = Direction;
769          }          }
# Line 780  Line 781 
781    
782          int iDirection;          int iDirection;
783    
784          for(;;) { //forever          for(;;) { /* forever */
785                  iDirection = 0;                  iDirection = 0;
786                  if (bDirection & 1) CHECK_CANDIDATE(x - iDiamondSize, y, 1);                  if (bDirection & 1) CHECK_CANDIDATE(x - iDiamondSize, y, 1);
787                  if (bDirection & 2) CHECK_CANDIDATE(x + iDiamondSize, y, 2);                  if (bDirection & 2) CHECK_CANDIDATE(x + iDiamondSize, y, 2);
# Line 789  Line 790 
790    
791                  /* now we're doing diagonal checks near our candidate */                  /* now we're doing diagonal checks near our candidate */
792    
793                  if (iDirection) {               //if anything found                  if (iDirection) {               /* if anything found */
794                          bDirection = iDirection;                          bDirection = iDirection;
795                          iDirection = 0;                          iDirection = 0;
796                          x = data->currentMV->x; y = data->currentMV->y;                          x = data->currentMV->x; y = data->currentMV->y;
797                          if (bDirection & 3) {   //our candidate is left or right                          if (bDirection & 3) {   /* our candidate is left or right */
798                                  CHECK_CANDIDATE(x, y + iDiamondSize, 8);                                  CHECK_CANDIDATE(x, y + iDiamondSize, 8);
799                                  CHECK_CANDIDATE(x, y - iDiamondSize, 4);                                  CHECK_CANDIDATE(x, y - iDiamondSize, 4);
800                          } else {                        // what remains here is up or down                          } else {                        /* what remains here is up or down */
801                                  CHECK_CANDIDATE(x + iDiamondSize, y, 2);                                  CHECK_CANDIDATE(x + iDiamondSize, y, 2);
802                                  CHECK_CANDIDATE(x - iDiamondSize, y, 1);                                  CHECK_CANDIDATE(x - iDiamondSize, y, 1);
803                          }                          }
# Line 805  Line 806 
806                                  bDirection += iDirection;                                  bDirection += iDirection;
807                                  x = data->currentMV->x; y = data->currentMV->y;                                  x = data->currentMV->x; y = data->currentMV->y;
808                          }                          }
809                  } else {                                //about to quit, eh? not so fast....                  } else {                                /* about to quit, eh? not so fast.... */
810                          switch (bDirection) {                          switch (bDirection) {
811                          case 2:                          case 2:
812                                  CHECK_CANDIDATE(x + iDiamondSize, y - iDiamondSize, 2 + 4);                                  CHECK_CANDIDATE(x + iDiamondSize, y - iDiamondSize, 2 + 4);
# Line 843  Line 844 
844                                  CHECK_CANDIDATE(x + iDiamondSize, y + iDiamondSize, 2 + 8);                                  CHECK_CANDIDATE(x + iDiamondSize, y + iDiamondSize, 2 + 8);
845                                  CHECK_CANDIDATE(x - iDiamondSize, y + iDiamondSize, 1 + 8);                                  CHECK_CANDIDATE(x - iDiamondSize, y + iDiamondSize, 1 + 8);
846                                  break;                                  break;
847                          default:                //1+2+4+8 == we didn't find anything at all                          default:                /* 1+2+4+8 == we didn't find anything at all */
848                                  CHECK_CANDIDATE(x - iDiamondSize, y - iDiamondSize, 1 + 4);                                  CHECK_CANDIDATE(x - iDiamondSize, y - iDiamondSize, 1 + 4);
849                                  CHECK_CANDIDATE(x - iDiamondSize, y + iDiamondSize, 1 + 8);                                  CHECK_CANDIDATE(x - iDiamondSize, y + iDiamondSize, 1 + 8);
850                                  CHECK_CANDIDATE(x + iDiamondSize, y - iDiamondSize, 2 + 4);                                  CHECK_CANDIDATE(x + iDiamondSize, y - iDiamondSize, 2 + 4);
851                                  CHECK_CANDIDATE(x + iDiamondSize, y + iDiamondSize, 2 + 8);                                  CHECK_CANDIDATE(x + iDiamondSize, y + iDiamondSize, 2 + 8);
852                                  break;                                  break;
853                          }                          }
854                          if (!iDirection) break;         //ok, the end. really                          if (!iDirection) break;         /* ok, the end. really */
855                          bDirection = iDirection;                          bDirection = iDirection;
856                          x = data->currentMV->x; y = data->currentMV->y;                          x = data->currentMV->x; y = data->currentMV->y;
857                  }                  }
# Line 895  Line 896 
896    
897                  /* now we're doing diagonal checks near our candidate */                  /* now we're doing diagonal checks near our candidate */
898    
899                  if (iDirection) {               //checking if anything found                  if (iDirection) {               /* checking if anything found */
900                          bDirection = iDirection;                          bDirection = iDirection;
901                          iDirection = 0;                          iDirection = 0;
902                          x = data->currentMV->x; y = data->currentMV->y;                          x = data->currentMV->x; y = data->currentMV->y;
903                          if (bDirection & 3) {   //our candidate is left or right                          if (bDirection & 3) {   /* our candidate is left or right */
904                                  CHECK_CANDIDATE(x, y + iDiamondSize, 8);                                  CHECK_CANDIDATE(x, y + iDiamondSize, 8);
905                                  CHECK_CANDIDATE(x, y - iDiamondSize, 4);                                  CHECK_CANDIDATE(x, y - iDiamondSize, 4);
906                          } else {                        // what remains here is up or down                          } else {                        /* what remains here is up or down */
907                                  CHECK_CANDIDATE(x + iDiamondSize, y, 2);                                  CHECK_CANDIDATE(x + iDiamondSize, y, 2);
908                                  CHECK_CANDIDATE(x - iDiamondSize, y, 1);                                  CHECK_CANDIDATE(x - iDiamondSize, y, 1);
909                          }                          }
# Line 920  Line 921 
921  {  {
922  /* Do a half-pel or q-pel refinement */  /* Do a half-pel or q-pel refinement */
923          const VECTOR centerMV = data->qpel_precision ? *data->currentQMV : *data->currentMV;          const VECTOR centerMV = data->qpel_precision ? *data->currentQMV : *data->currentMV;
924          int iDirection; //only needed because macro expects it          int iDirection; /* only needed because macro expects it */
925    
926          CHECK_CANDIDATE(centerMV.x, centerMV.y - 1, 0);          CHECK_CANDIDATE(centerMV.x, centerMV.y - 1, 0);
927          CHECK_CANDIDATE(centerMV.x + 1, centerMV.y - 1, 0);          CHECK_CANDIDATE(centerMV.x + 1, centerMV.y - 1, 0);
# Line 960  Line 961 
961  }  }
962    
963  static __inline void  static __inline void
964  SkipMacroblockP(MACROBLOCK *pMB, const int32_t sad)  ZeroMacroblockP(MACROBLOCK *pMB, const int32_t sad)
965  {  {
966          pMB->mode = MODE_NOT_CODED;          pMB->mode = MODE_INTER;
967          pMB->mvs[0] = pMB->mvs[1] = pMB->mvs[2] = pMB->mvs[3] = zeroMV;          pMB->mvs[0] = pMB->mvs[1] = pMB->mvs[2] = pMB->mvs[3] = zeroMV;
968          pMB->qmvs[0] = pMB->qmvs[1] = pMB->qmvs[2] = pMB->qmvs[3] = zeroMV;          pMB->qmvs[0] = pMB->qmvs[1] = pMB->qmvs[2] = pMB->qmvs[3] = zeroMV;
969          pMB->sad16 = pMB->sad8[0] = pMB->sad8[1] = pMB->sad8[2] = pMB->sad8[3] = sad;          pMB->sad16 = pMB->sad8[0] = pMB->sad8[1] = pMB->sad8[2] = pMB->sad8[3] = sad;
970  }  }
971    
972    static __inline void
973    ModeDecision(SearchData * const Data,
974                            MACROBLOCK * const pMB,
975                            const MACROBLOCK * const pMBs,
976                            const int x, const int y,
977                            const MBParam * const pParam,
978                            const uint32_t MotionFlags,
979                            const uint32_t VopFlags,
980                            const uint32_t VolFlags,
981                            const IMAGE * const pCurrent,
982                            const IMAGE * const pRef,
983                            const IMAGE * const vGMC,
984                            const int coding_type)
985    {
986            int mode = MODE_INTER;
987            int mcsel = 0;
988            int inter4v = (VopFlags & XVID_VOP_INTER4V) && (pMB->dquant == 0);
989            const uint32_t iQuant = pMB->quant;
990    
991            const int skip_possible = (coding_type == P_VOP) && (pMB->dquant == 0);
992    
993            pMB->mcsel = 0;
994    
995            if (!(VopFlags & XVID_VOP_MODEDECISION_RD)) { /* normal, fast, SAD-based mode decision */
996                    int sad;
997                    int InterBias = MV16_INTER_BIAS;
998                    if (inter4v == 0 || Data->iMinSAD[0] < Data->iMinSAD[1] + Data->iMinSAD[2] +
999                            Data->iMinSAD[3] + Data->iMinSAD[4] + IMV16X16 * (int32_t)iQuant) {
1000                            mode = MODE_INTER;
1001                            sad = Data->iMinSAD[0];
1002                    } else {
1003                            mode = MODE_INTER4V;
1004                            sad = Data->iMinSAD[1] + Data->iMinSAD[2] +
1005                                                    Data->iMinSAD[3] + Data->iMinSAD[4] + IMV16X16 * (int32_t)iQuant;
1006                            Data->iMinSAD[0] = sad;
1007                    }
1008    
1009                    /* final skip decision, a.k.a. "the vector you found, really that good?" */
1010                    if (skip_possible && (pMB->sad16 < (int)iQuant * MAX_SAD00_FOR_SKIP))
1011                            if ( (100*sad)/(pMB->sad16+1) > FINAL_SKIP_THRESH)
1012                                    if (Data->chroma || SkipDecisionP(pCurrent, pRef, x, y, Data->iEdgedWidth/2, iQuant, Data->rrv)) {
1013                                            mode = MODE_NOT_CODED;
1014                                            sad = 0;
1015                                    }
1016    
1017                    /* mcsel */
1018                    if (coding_type == S_VOP) {
1019    
1020                            int32_t iSAD = sad16(Data->Cur,
1021                                    vGMC->y + 16*y*Data->iEdgedWidth + 16*x, Data->iEdgedWidth, 65536);
1022    
1023                            if (Data->chroma) {
1024                                    iSAD += sad8(Data->CurU, vGMC->u + 8*y*(Data->iEdgedWidth/2) + 8*x, Data->iEdgedWidth/2);
1025                                    iSAD += sad8(Data->CurV, vGMC->v + 8*y*(Data->iEdgedWidth/2) + 8*x, Data->iEdgedWidth/2);
1026                            }
1027    
1028                            if (iSAD <= sad) {              /* mode decision GMC */
1029                                    mode = MODE_INTER;
1030                                    mcsel = 1;
1031                                    sad = iSAD;
1032                            }
1033    
1034                    }
1035    
1036                    /* intra decision */
1037    
1038                    if (iQuant > 8) InterBias += 100 * (iQuant - 8); /* to make high quants work */
1039                    if (y != 0)
1040                            if ((pMB - pParam->mb_width)->mode == MODE_INTRA ) InterBias -= 80;
1041                    if (x != 0)
1042                            if ((pMB - 1)->mode == MODE_INTRA ) InterBias -= 80;
1043    
1044                    if (Data->chroma) InterBias += 50; /* dev8(chroma) ??? <-- yes, we need dev8 (no big difference though) */
1045                    if (Data->rrv) InterBias *= 4;
1046    
1047                    if (InterBias < sad) {
1048                            int32_t deviation;
1049                            if (!Data->rrv)
1050                                    deviation = dev16(Data->Cur, Data->iEdgedWidth);
1051                            else
1052                                    deviation = dev16(Data->Cur, Data->iEdgedWidth) + /* dev32() */
1053                                                            dev16(Data->Cur+16, Data->iEdgedWidth) +
1054                                                            dev16(Data->Cur + 16*Data->iEdgedWidth, Data->iEdgedWidth) +
1055                                                            dev16(Data->Cur+16+16*Data->iEdgedWidth, Data->iEdgedWidth);
1056    
1057                            if (deviation < (sad - InterBias)) mode = MODE_INTRA;
1058                    }
1059    
1060                    pMB->cbp = 63;
1061                    pMB->sad16 = pMB->sad8[0] = pMB->sad8[1] = pMB->sad8[2] = pMB->sad8[3] = sad;
1062    
1063            } else { /* Rate-Distortion */
1064    
1065                    int min_rd, intra_rd, i, cbp, c[2] = {0, 0};
1066                    VECTOR backup[5], *v;
1067                    Data->iQuant = iQuant;
1068                    Data->cbp = c;
1069    
1070                    v = Data->qpel ? Data->currentQMV : Data->currentMV;
1071                    for (i = 0; i < 5; i++) {
1072                            Data->iMinSAD[i] = 256*4096;
1073                            backup[i] = v[i];
1074                    }
1075    
1076                    min_rd = findRDinter(Data, pMBs, x, y, pParam, MotionFlags);
1077                    cbp = *Data->cbp;
1078    
1079                    if (coding_type == S_VOP) {
1080                            int gmc_rd;
1081                            *Data->iMinSAD = min_rd += BITS_MULT*1; /* mcsel */
1082                            gmc_rd = findRDgmc(Data, vGMC, x, y);
1083                            if (gmc_rd < min_rd) {
1084                                    mcsel = 1;
1085                                    *Data->iMinSAD = min_rd = gmc_rd;
1086                                    mode = MODE_INTER;
1087                                    cbp = *Data->cbp;
1088                            }
1089                    }
1090    
1091                    if (inter4v) {
1092                            int v4_rd;
1093                            v4_rd = findRDinter4v(Data, pMB, pMBs, x, y, pParam, MotionFlags, backup);
1094                            if (v4_rd < min_rd) {
1095                                    Data->iMinSAD[0] = min_rd = v4_rd;
1096                                    mode = MODE_INTER4V;
1097                                    cbp = *Data->cbp;
1098                            }
1099                    }
1100    
1101                    intra_rd = findRDintra(Data);
1102                    if (intra_rd < min_rd) {
1103                            *Data->iMinSAD = min_rd = intra_rd;
1104                            mode = MODE_INTRA;
1105                    }
1106    
1107                    pMB->sad16 = pMB->sad8[0] = pMB->sad8[1] = pMB->sad8[2] = pMB->sad8[3] = 0;
1108                    pMB->cbp = cbp;
1109            }
1110    
1111            if (Data->rrv) {
1112                            Data->currentMV[0].x = RRV_MV_SCALEDOWN(Data->currentMV[0].x);
1113                            Data->currentMV[0].y = RRV_MV_SCALEDOWN(Data->currentMV[0].y);
1114            }
1115    
1116            if (mode == MODE_INTER && mcsel == 0) {
1117                    pMB->mvs[0] = pMB->mvs[1] = pMB->mvs[2] = pMB->mvs[3] = Data->currentMV[0];
1118    
1119                    if(Data->qpel) {
1120                            pMB->qmvs[0] = pMB->qmvs[1]
1121                                    = pMB->qmvs[2] = pMB->qmvs[3] = Data->currentQMV[0];
1122                            pMB->pmvs[0].x = Data->currentQMV[0].x - Data->predMV.x;
1123                            pMB->pmvs[0].y = Data->currentQMV[0].y - Data->predMV.y;
1124                    } else {
1125                            pMB->pmvs[0].x = Data->currentMV[0].x - Data->predMV.x;
1126                            pMB->pmvs[0].y = Data->currentMV[0].y - Data->predMV.y;
1127                    }
1128    
1129            } else if (mode == MODE_INTER ) { // but mcsel == 1
1130    
1131                    pMB->mcsel = 1;
1132                    if (Data->qpel) {
1133                            pMB->qmvs[0] = pMB->qmvs[1] = pMB->qmvs[2] = pMB->qmvs[3] = pMB->amv;
1134                            pMB->mvs[0].x = pMB->mvs[1].x = pMB->mvs[2].x = pMB->mvs[3].x = pMB->amv.x/2;
1135                            pMB->mvs[0].y = pMB->mvs[1].y = pMB->mvs[2].y = pMB->mvs[3].y = pMB->amv.y/2;
1136                    } else
1137                            pMB->mvs[0] = pMB->mvs[1] = pMB->mvs[2] = pMB->mvs[3] = pMB->amv;
1138    
1139            } else
1140                    if (mode == MODE_INTER4V) ; /* anything here? */
1141            else    /* INTRA, NOT_CODED */
1142                    ZeroMacroblockP(pMB, 0);
1143    
1144            pMB->mode = mode;
1145    }
1146    
1147  bool  bool
1148  MotionEstimation(MBParam * const pParam,  MotionEstimation(MBParam * const pParam,
1149                                   FRAMEINFO * const current,                                   FRAMEINFO * const current,
# Line 975  Line 1151 
1151                                   const IMAGE * const pRefH,                                   const IMAGE * const pRefH,
1152                                   const IMAGE * const pRefV,                                   const IMAGE * const pRefV,
1153                                   const IMAGE * const pRefHV,                                   const IMAGE * const pRefHV,
1154                                    const IMAGE * const pGMC,
1155                                   const uint32_t iLimit)                                   const uint32_t iLimit)
1156  {  {
1157          MACROBLOCK *const pMBs = current->mbs;          MACROBLOCK *const pMBs = current->mbs;
# Line 988  Line 1165 
1165    
1166          uint32_t x, y;          uint32_t x, y;
1167          uint32_t iIntra = 0;          uint32_t iIntra = 0;
1168          int32_t quant = current->quant, sad00;          int32_t sad00;
1169          int skip_thresh = \          int skip_thresh = INITIAL_SKIP_THRESH * \
                 INITIAL_SKIP_THRESH * \  
1170                  (current->vop_flags & XVID_VOP_REDUCED ? 4:1) * \                  (current->vop_flags & XVID_VOP_REDUCED ? 4:1) * \
1171                  (current->vop_flags & XVID_VOP_MODEDECISION_BITS ? 2:1);                  (current->vop_flags & XVID_VOP_MODEDECISION_RD ? 2:1);
1172    
1173          // some pre-initialized thingies for SearchP          /* some pre-initialized thingies for SearchP */
1174          int32_t temp[8];          int32_t temp[8];
1175          VECTOR currentMV[5];          VECTOR currentMV[5];
1176          VECTOR currentQMV[5];          VECTOR currentQMV[5];
1177          int32_t iMinSAD[5];          int32_t iMinSAD[5];
1178          DECLARE_ALIGNED_MATRIX(dct_space, 2, 64, int16_t, CACHE_LINE);          DECLARE_ALIGNED_MATRIX(dct_space, 3, 64, int16_t, CACHE_LINE);
1179          SearchData Data;          SearchData Data;
1180          memset(&Data, 0, sizeof(SearchData));          memset(&Data, 0, sizeof(SearchData));
1181          Data.iEdgedWidth = iEdgedWidth;          Data.iEdgedWidth = iEdgedWidth;
# Line 1010  Line 1186 
1186          Data.iFcode = current->fcode;          Data.iFcode = current->fcode;
1187          Data.rounding = pParam->m_rounding_type;          Data.rounding = pParam->m_rounding_type;
1188          Data.qpel = (current->vol_flags & XVID_VOL_QUARTERPEL ? 1:0);          Data.qpel = (current->vol_flags & XVID_VOL_QUARTERPEL ? 1:0);
1189          Data.chroma = MotionFlags & XVID_ME_CHROMA16;          Data.chroma = MotionFlags & XVID_ME_CHROMA_PVOP;
1190          Data.rrv = (current->vop_flags & XVID_VOP_REDUCED ? 1:0);          Data.rrv = (current->vop_flags & XVID_VOP_REDUCED) ? 1:0;
1191          Data.dctSpace = dct_space;          Data.dctSpace = dct_space;
1192            Data.quant_type = !(pParam->vol_flags & XVID_VOL_MPEGQUANT);
1193    
1194          if ((current->vop_flags & XVID_VOP_REDUCED)) {          if ((current->vop_flags & XVID_VOP_REDUCED)) {
1195                  mb_width = (pParam->width + 31) / 32;                  mb_width = (pParam->width + 31) / 32;
# Line 1020  Line 1197 
1197                  Data.qpel = 0;                  Data.qpel = 0;
1198          }          }
1199    
1200          Data.RefQ = pRefV->u; // a good place, also used in MC (for similar purpose)          Data.RefQ = pRefV->u; /* a good place, also used in MC (for similar purpose) */
1201          if (sadInit) (*sadInit) ();          if (sadInit) (*sadInit) ();
1202    
1203          for (y = 0; y < mb_height; y++) {          for (y = 0; y < mb_height; y++) {
# Line 1047  Line 1224 
1224    
1225                          sad00 = pMB->sad16;                          sad00 = pMB->sad16;
1226    
1227                          if (pMB->dquant != 0) {                          /* initial skip decision */
                                 quant += DQtab[pMB->dquant];  
                                 if (quant > 31) quant = 31;  
                                 else if (quant < 1) quant = 1;  
                         }  
   
                         pMB->quant = current->quant;  
   
 //initial skip decision  
1228  /* no early skip for GMC (global vector = skip vector is unknown!)  */  /* no early skip for GMC (global vector = skip vector is unknown!)  */
1229                          if (!(current->vol_flags & XVID_VOL_GMC))       { /* no fast SKIP for S(GMC)-VOPs */                          if (current->coding_type != S_VOP)      { /* no fast SKIP for S(GMC)-VOPs */
1230                                  if (pMB->dquant == 0 && sad00 < pMB->quant * skip_thresh)                                  if (pMB->dquant == 0 && sad00 < pMB->quant * skip_thresh)
1231                                          if (Data.chroma || SkipDecisionP(pCurrent, pRef, x, y, iEdgedWidth/2, pMB->quant, Data.rrv)) {                                          if (Data.chroma || SkipDecisionP(pCurrent, pRef, x, y, iEdgedWidth/2, pMB->quant, Data.rrv)) {
1232                                                  SkipMacroblockP(pMB, sad00);                                                  ZeroMacroblockP(pMB, sad00);
1233                                                    pMB->mode = MODE_NOT_CODED;
1234                                                  continue;                                                  continue;
1235                                          }                                          }
1236                          }                          }
1237    
1238                            if ((current->vop_flags & XVID_VOP_CARTOON) &&
1239                                    (sad00 < pMB->quant * 4 * skip_thresh)) { /* favorize (0,0) vector for cartoons */
1240                                    ZeroMacroblockP(pMB, sad00);
1241                                    continue;
1242                            }
1243    
1244                          SearchP(pRef, pRefH->y, pRefV->y, pRefHV->y, pCurrent, x,                          SearchP(pRef, pRefH->y, pRefV->y, pRefHV->y, pCurrent, x,
1245                                                  y, MotionFlags, current->vol_flags, pMB->quant,                                          y, MotionFlags, current->vop_flags, current->vol_flags,
1246                                                  &Data, pParam, pMBs, reference->mbs,                                          &Data, pParam, pMBs, reference->mbs, pMB);
1247                                                  current->vop_flags & XVID_VOP_INTER4V, pMB);  
1248                            ModeDecision(&Data, pMB, pMBs, x, y, pParam,
1249                                                     MotionFlags, current->vop_flags, current->vol_flags,
1250                                                     pCurrent, pRef, pGMC, current->coding_type);
1251    
 /* final skip decision, a.k.a. "the vector you found, really that good?" */  
                         if (!(current->vol_flags & XVID_VOL_GMC || current->vop_flags & XVID_VOP_MODEDECISION_BITS)) {  
                                 if ( pMB->dquant == 0 && sad00 < pMB->quant * MAX_SAD00_FOR_SKIP) {  
                                         if ( (100*pMB->sad16)/(sad00+1) > FINAL_SKIP_THRESH * (Data.rrv ? 4:1) )  
                                                 if (Data.chroma || SkipDecisionP(pCurrent, pRef, x, y, iEdgedWidth/2, pMB->quant, Data.rrv))  
                                                         SkipMacroblockP(pMB, sad00);  
                                 }  
                         }  
1252                          if (pMB->mode == MODE_INTRA)                          if (pMB->mode == MODE_INTRA)
1253                                  if (++iIntra > iLimit) return 1;                                  if (++iIntra > iLimit) return 1;
1254                  }                  }
1255          }          }
1256    
         if (current->vol_flags & XVID_VOL_GMC ) /* GMC only for S(GMC)-VOPs */  
                 current->warp = GlobalMotionEst( pMBs, pParam, current, reference, pRefH, pRefV, pRefHV);  
   
1257          return 0;          return 0;
1258  }  }
1259    
# Line 1095  Line 1263 
1263  {  {
1264          int mask = 255, j;          int mask = 255, j;
1265          for (j = 0; j < i; j++) {          for (j = 0; j < i; j++) {
1266                  if (MVequal(pmv[i], pmv[j])) return 0; // same vector has been checked already                  if (MVequal(pmv[i], pmv[j])) return 0; /* same vector has been checked already */
1267                  if (pmv[i].x == pmv[j].x) {                  if (pmv[i].x == pmv[j].x) {
1268                          if (pmv[i].y == pmv[j].y + iDiamondSize) mask &= ~4;                          if (pmv[i].y == pmv[j].y + iDiamondSize) mask &= ~4;
1269                          else if (pmv[i].y == pmv[j].y - iDiamondSize) mask &= ~8;                          else if (pmv[i].y == pmv[j].y - iDiamondSize) mask &= ~8;
# Line 1112  Line 1280 
1280  PreparePredictionsP(VECTOR * const pmv, int x, int y, int iWcount,  PreparePredictionsP(VECTOR * const pmv, int x, int y, int iWcount,
1281                          int iHcount, const MACROBLOCK * const prevMB, int rrv)                          int iHcount, const MACROBLOCK * const prevMB, int rrv)
1282  {  {
1283            /* this function depends on get_pmvdata which means that it sucks. It should get the predictions by itself */
 //this function depends on get_pmvdata which means that it sucks. It should get the predictions by itself  
1284          if (rrv) { iWcount /= 2; iHcount /= 2; }          if (rrv) { iWcount /= 2; iHcount /= 2; }
1285    
1286          if ( (y != 0) && (x < (iWcount-1)) ) {          // [5] top-right neighbour          if ( (y != 0) && (x < (iWcount-1)) ) {          /* [5] top-right neighbour */
1287                  pmv[5].x = EVEN(pmv[3].x);                  pmv[5].x = EVEN(pmv[3].x);
1288                  pmv[5].y = EVEN(pmv[3].y);                  pmv[5].y = EVEN(pmv[3].y);
1289          } else pmv[5].x = pmv[5].y = 0;          } else pmv[5].x = pmv[5].y = 0;
1290    
1291          if (x != 0) { pmv[3].x = EVEN(pmv[1].x); pmv[3].y = EVEN(pmv[1].y); }// pmv[3] is left neighbour          if (x != 0) { pmv[3].x = EVEN(pmv[1].x); pmv[3].y = EVEN(pmv[1].y); }/* pmv[3] is left neighbour */
1292          else pmv[3].x = pmv[3].y = 0;          else pmv[3].x = pmv[3].y = 0;
1293    
1294          if (y != 0) { pmv[4].x = EVEN(pmv[2].x); pmv[4].y = EVEN(pmv[2].y); }// [4] top neighbour          if (y != 0) { pmv[4].x = EVEN(pmv[2].x); pmv[4].y = EVEN(pmv[2].y); }/* [4] top neighbour */
1295          else pmv[4].x = pmv[4].y = 0;          else pmv[4].x = pmv[4].y = 0;
1296    
1297          // [1] median prediction          /* [1] median prediction */
1298          pmv[1].x = EVEN(pmv[0].x); pmv[1].y = EVEN(pmv[0].y);          pmv[1].x = EVEN(pmv[0].x); pmv[1].y = EVEN(pmv[0].y);
1299    
1300          pmv[0].x = pmv[0].y = 0; // [0] is zero; not used in the loop (checked before) but needed here for make_mask          pmv[0].x = pmv[0].y = 0; /* [0] is zero; not used in the loop (checked before) but needed here for make_mask */
1301    
1302          pmv[2].x = EVEN(prevMB->mvs[0].x); // [2] is last frame          pmv[2].x = EVEN(prevMB->mvs[0].x); /* [2] is last frame */
1303          pmv[2].y = EVEN(prevMB->mvs[0].y);          pmv[2].y = EVEN(prevMB->mvs[0].y);
1304    
1305          if ((x < iWcount-1) && (y < iHcount-1)) {          if ((x < iWcount-1) && (y < iHcount-1)) {
1306                  pmv[6].x = EVEN((prevMB+1+iWcount)->mvs[0].x); //[6] right-down neighbour in last frame                  pmv[6].x = EVEN((prevMB+1+iWcount)->mvs[0].x); /* [6] right-down neighbour in last frame */
1307                  pmv[6].y = EVEN((prevMB+1+iWcount)->mvs[0].y);                  pmv[6].y = EVEN((prevMB+1+iWcount)->mvs[0].y);
1308          } else pmv[6].x = pmv[6].y = 0;          } else pmv[6].x = pmv[6].y = 0;
1309    
# Line 1149  Line 1316 
1316          }          }
1317  }  }
1318    
 static int  
 ModeDecision(const uint32_t iQuant, SearchData * const Data,  
                 int inter4v,  
                 MACROBLOCK * const pMB,  
                 const MACROBLOCK * const pMBs,  
                 const int x, const int y,  
                 const MBParam * const pParam,  
                 const uint32_t MotionFlags,  
                 const uint32_t VopFlags)  
 {  
   
         int mode = MODE_INTER;  
   
         if (!(VopFlags & XVID_VOP_MODEDECISION_BITS)) { //normal, fast, SAD-based mode decision  
                 int sad;  
                 int InterBias = MV16_INTER_BIAS;  
                 if (inter4v == 0 || Data->iMinSAD[0] < Data->iMinSAD[1] + Data->iMinSAD[2] +  
                         Data->iMinSAD[3] + Data->iMinSAD[4] + IMV16X16 * (int32_t)iQuant) {  
                         mode = MODE_INTER;  
                         sad = Data->iMinSAD[0];  
                 } else {  
                         mode = MODE_INTER4V;  
                         sad = Data->iMinSAD[1] + Data->iMinSAD[2] +  
                                                 Data->iMinSAD[3] + Data->iMinSAD[4] + IMV16X16 * (int32_t)iQuant;  
                         Data->iMinSAD[0] = sad;  
                 }  
   
                 /* intra decision */  
   
                 if (iQuant > 8) InterBias += 100 * (iQuant - 8); // to make high quants work  
                 if (y != 0)  
                         if ((pMB - pParam->mb_width)->mode == MODE_INTRA ) InterBias -= 80;  
                 if (x != 0)  
                         if ((pMB - 1)->mode == MODE_INTRA ) InterBias -= 80;  
   
                 if (Data->chroma) InterBias += 50; // to compensate bigger SAD  
                 if (Data->rrv) InterBias *= 4;  
   
                 if (InterBias < pMB->sad16) {  
                         int32_t deviation;  
                         if (!Data->rrv) deviation = dev16(Data->Cur, Data->iEdgedWidth);  
                         else deviation = dev16(Data->Cur, Data->iEdgedWidth) +  
                                 dev16(Data->Cur+8, Data->iEdgedWidth) +  
                                 dev16(Data->Cur + 8*Data->iEdgedWidth, Data->iEdgedWidth) +  
                                 dev16(Data->Cur+8+8*Data->iEdgedWidth, Data->iEdgedWidth);  
   
                         if (deviation < (sad - InterBias)) return MODE_INTRA;  
                 }  
                 return mode;  
   
         } else {  
   
                 int bits, intra, i;  
                 VECTOR backup[5], *v;  
                 Data->lambda16 = iQuant;  
         Data->lambda8 = (pParam->vol_flags & XVID_VOL_MPEGQUANT)?1:0;  
   
                 v = Data->qpel ? Data->currentQMV : Data->currentMV;  
                 for (i = 0; i < 5; i++) {  
                         Data->iMinSAD[i] = 256*4096;  
                         backup[i] = v[i];  
                 }  
   
                 bits = CountMBBitsInter(Data, pMBs, x, y, pParam, MotionFlags);  
                 if (bits == 0) return MODE_INTER; // quick stop  
   
                 if (inter4v) {  
                         int bits_inter4v = CountMBBitsInter4v(Data, pMB, pMBs, x, y, pParam, MotionFlags, backup);  
                         if (bits_inter4v < bits) { Data->iMinSAD[0] = bits = bits_inter4v; mode = MODE_INTER4V; }  
                 }  
   
   
                 intra = CountMBBitsIntra(Data);  
   
                 if (intra < bits) { *Data->iMinSAD = bits = intra; return MODE_INTRA; }  
   
                 return mode;  
         }  
 }  
   
1319  static void  static void
1320  SearchP(const IMAGE * const pRef,  SearchP(const IMAGE * const pRef,
1321                  const uint8_t * const pRefH,                  const uint8_t * const pRefH,
# Line 1239  Line 1326 
1326                  const int y,                  const int y,
1327                  const uint32_t MotionFlags,                  const uint32_t MotionFlags,
1328                  const uint32_t VopFlags,                  const uint32_t VopFlags,
1329                  const uint32_t iQuant,                  const uint32_t VolFlags,
1330                  SearchData * const Data,                  SearchData * const Data,
1331                  const MBParam * const pParam,                  const MBParam * const pParam,
1332                  const MACROBLOCK * const pMBs,                  const MACROBLOCK * const pMBs,
1333                  const MACROBLOCK * const prevMBs,                  const MACROBLOCK * const prevMBs,
                 int inter4v,  
1334                  MACROBLOCK * const pMB)                  MACROBLOCK * const pMB)
1335  {  {
1336    
1337          int i, iDirection = 255, mask, threshA;          int i, iDirection = 255, mask, threshA;
1338          VECTOR pmv[7];          VECTOR pmv[7];
1339            int inter4v = (VopFlags & XVID_VOP_INTER4V) && (pMB->dquant == 0);
1340    
1341          get_range(&Data->min_dx, &Data->max_dx, &Data->min_dy, &Data->max_dy, x, y, 16,          get_range(&Data->min_dx, &Data->max_dx, &Data->min_dy, &Data->max_dy, x, y, 4,
1342                                                  pParam->width, pParam->height, Data->iFcode - Data->qpel, 0, Data->rrv);                                                  pParam->width, pParam->height, Data->iFcode - Data->qpel, 1, Data->rrv);
1343    
1344          get_pmvdata2(pMBs, pParam->mb_width, 0, x, y, 0, pmv, Data->temp);          get_pmvdata2(pMBs, pParam->mb_width, 0, x, y, 0, pmv, Data->temp);
1345    
1346          Data->temp[5] = Data->temp[6] = 0; // chroma-sad cache          Data->temp[5] = Data->temp[6] = 0; /* chroma-sad cache */
1347          i = Data->rrv ? 2 : 1;          i = Data->rrv ? 2 : 1;
1348          Data->Cur = pCur->y + (x + y * Data->iEdgedWidth) * 16*i;          Data->Cur = pCur->y + (x + y * Data->iEdgedWidth) * 16*i;
1349          Data->CurV = pCur->v + (x + y * (Data->iEdgedWidth/2)) * 8*i;          Data->CurV = pCur->v + (x + y * (Data->iEdgedWidth/2)) * 8*i;
# Line 1269  Line 1356 
1356          Data->RefP[4] = pRef->u + (x + y * (Data->iEdgedWidth/2)) * 8*i;          Data->RefP[4] = pRef->u + (x + y * (Data->iEdgedWidth/2)) * 8*i;
1357          Data->RefP[5] = pRef->v + (x + y * (Data->iEdgedWidth/2)) * 8*i;          Data->RefP[5] = pRef->v + (x + y * (Data->iEdgedWidth/2)) * 8*i;
1358    
1359          Data->lambda16 = lambda_vec16[iQuant];          Data->lambda16 = lambda_vec16[pMB->quant];
1360          Data->lambda8 = lambda_vec8[iQuant];          Data->lambda8 = lambda_vec8[pMB->quant];
1361          Data->qpel_precision = 0;          Data->qpel_precision = 0;
1362    
         if (pMB->dquant != 0) inter4v = 0;  
   
1363          memset(Data->currentMV, 0, 5*sizeof(VECTOR));          memset(Data->currentMV, 0, 5*sizeof(VECTOR));
1364    
1365          if (Data->qpel) Data->predMV = get_qpmv2(pMBs, pParam->mb_width, 0, x, y, 0);          if (Data->qpel) Data->predMV = get_qpmv2(pMBs, pParam->mb_width, 0, x, y, 0);
# Line 1287  Line 1372 
1372          Data->iMinSAD[3] = pMB->sad8[2];          Data->iMinSAD[3] = pMB->sad8[2];
1373          Data->iMinSAD[4] = pMB->sad8[3];          Data->iMinSAD[4] = pMB->sad8[3];
1374    
1375          if ((!(VopFlags & XVID_VOP_MODEDECISION_BITS)) || (x | y)) {          if ((!(VopFlags & XVID_VOP_MODEDECISION_RD)) && (x | y)) {
1376                  threshA = Data->temp[0]; // that's where we keep this SAD atm                  threshA = Data->temp[0]; /* that's where we keep this SAD atm */
1377                  if (threshA < 512) threshA = 512;                  if (threshA < 512) threshA = 512;
1378                  else if (threshA > 1024) threshA = 1024;                  else if (threshA > 1024) threshA = 1024;
1379          } else          } else
# Line 1299  Line 1384 
1384    
1385          if (!Data->rrv) {          if (!Data->rrv) {
1386                  if (inter4v | Data->chroma) CheckCandidate = CheckCandidate16;                  if (inter4v | Data->chroma) CheckCandidate = CheckCandidate16;
1387                          else CheckCandidate = CheckCandidate16no4v; //for extra speed                          else CheckCandidate = CheckCandidate16no4v; /* for extra speed */
1388          } else CheckCandidate = CheckCandidate32;          } else CheckCandidate = CheckCandidate32;
1389    
1390  /* main loop. checking all predictions (but first, which is 0,0 and has been checked in MotionEstimation())*/  /* main loop. checking all predictions (but first, which is 0,0 and has been checked in MotionEstimation())*/
# Line 1312  Line 1397 
1397    
1398          if ((Data->iMinSAD[0] <= threshA) ||          if ((Data->iMinSAD[0] <= threshA) ||
1399                          (MVequal(Data->currentMV[0], (prevMBs+x+y*pParam->mb_width)->mvs[0]) &&                          (MVequal(Data->currentMV[0], (prevMBs+x+y*pParam->mb_width)->mvs[0]) &&
1400                          (Data->iMinSAD[0] < (prevMBs+x+y*pParam->mb_width)->sad16))) {                          (Data->iMinSAD[0] < (prevMBs+x+y*pParam->mb_width)->sad16)))
1401                  if (!(VopFlags & XVID_VOP_MODEDECISION_BITS)) inter4v = 0;      }                  inter4v = 0;
1402          else {          else {
1403    
1404                  MainSearchFunc * MainSearchPtr;                  MainSearchFunc * MainSearchPtr;
# Line 1359  Line 1444 
1444          }          }
1445    
1446          if (MotionFlags & XVID_ME_HALFPELREFINE16)          if (MotionFlags & XVID_ME_HALFPELREFINE16)
                 if ((!(MotionFlags & XVID_ME_HALFPELREFINE16_BITS)) || Data->iMinSAD[0] < 200*(int)iQuant)  
1447                          SubpelRefine(Data);                          SubpelRefine(Data);
1448    
1449          for(i = 0; i < 5; i++) {          for(i = 0; i < 5; i++) {
1450                  Data->currentQMV[i].x = 2 * Data->currentMV[i].x; // initialize qpel vectors                  Data->currentQMV[i].x = 2 * Data->currentMV[i].x; /* initialize qpel vectors */
1451                  Data->currentQMV[i].y = 2 * Data->currentMV[i].y;                  Data->currentQMV[i].y = 2 * Data->currentMV[i].y;
1452          }          }
1453    
1454          if (MotionFlags & XVID_ME_QUARTERPELREFINE16) {          if (Data->qpel) {
1455                    get_range(&Data->min_dx, &Data->max_dx, &Data->min_dy, &Data->max_dy, x, y, 4,
1456                  get_range(&Data->min_dx, &Data->max_dx, &Data->min_dy, &Data->max_dy, x, y, 16,                                  pParam->width, pParam->height, Data->iFcode, 2, 0);
                                 pParam->width, pParam->height, Data->iFcode, 1, 0);  
   
                 if ((!(MotionFlags & XVID_ME_QUARTERPELREFINE16_BITS)) || (Data->iMinSAD[0] < 200*(int)iQuant)) {  
1457                          Data->qpel_precision = 1;                          Data->qpel_precision = 1;
1458                    if (MotionFlags & XVID_ME_QUARTERPELREFINE16)
1459                          SubpelRefine(Data);                          SubpelRefine(Data);
1460                  }                  }
         }  
   
         if ((!(VopFlags & XVID_VOP_MODEDECISION_BITS)) && (Data->iMinSAD[0] < (int32_t)iQuant * 30)) inter4v = 0;  
1461    
1462          if (inter4v && (!(VopFlags & XVID_VOP_MODEDECISION_BITS) ||          if (Data->iMinSAD[0] < (int32_t)pMB->quant * 30)
1463                          (!(MotionFlags & XVID_ME_QUARTERPELREFINE8_BITS)) || (!(MotionFlags & XVID_ME_HALFPELREFINE8_BITS)) ||                  inter4v = 0;
                         ((!(MotionFlags & XVID_ME_EXTSEARCH_BITS)) && (!(MotionFlags&XVID_ME_EXTSEARCH8)) ))) {  
                 // if decision is BITS-based and all refinement steps will be done in BITS domain, there is no reason to call this loop  
1464    
1465            if (inter4v) {
1466                  SearchData Data8;                  SearchData Data8;
1467                  memcpy(&Data8, Data, sizeof(SearchData)); //quick copy of common data                  memcpy(&Data8, Data, sizeof(SearchData)); /* quick copy of common data */
1468    
1469                  Search8(Data, 2*x, 2*y, MotionFlags, pParam, pMB, pMBs, 0, &Data8);                  Search8(Data, 2*x, 2*y, MotionFlags, pParam, pMB, pMBs, 0, &Data8);
1470                  Search8(Data, 2*x + 1, 2*y, MotionFlags, pParam, pMB, pMBs, 1, &Data8);                  Search8(Data, 2*x + 1, 2*y, MotionFlags, pParam, pMB, pMBs, 1, &Data8);
1471                  Search8(Data, 2*x, 2*y + 1, MotionFlags, pParam, pMB, pMBs, 2, &Data8);                  Search8(Data, 2*x, 2*y + 1, MotionFlags, pParam, pMB, pMBs, 2, &Data8);
1472                  Search8(Data, 2*x + 1, 2*y + 1, MotionFlags, pParam, pMB, pMBs, 3, &Data8);                  Search8(Data, 2*x + 1, 2*y + 1, MotionFlags, pParam, pMB, pMBs, 3, &Data8);
1473    
1474                  if ((Data->chroma) && (!(VopFlags & XVID_VOP_MODEDECISION_BITS))) {                  if ((Data->chroma) && (!(VopFlags & XVID_VOP_MODEDECISION_RD))) {
1475                          // chroma is only used for comparsion to INTER. if the comparsion will be done in BITS domain, there is no reason to compute it                          /* chroma is only used for comparsion to INTER. if the comparsion will be done in BITS domain, it will not be used */
1476                          int sumx = 0, sumy = 0;                          int sumx = 0, sumy = 0;
                         const int div = 1 + Data->qpel;  
                         const VECTOR * const mv = Data->qpel ? pMB->qmvs : pMB->mvs;  
1477    
1478                          for (i = 0; i < 4; i++) {                          if (Data->qpel)
1479                                  sumx += mv[i].x / div;                                  for (i = 1; i < 5; i++) {
1480                                  sumy += mv[i].y / div;                                          sumx += Data->currentQMV[i].x/2;
1481                                            sumy += Data->currentQMV[i].y/2;
1482                                    }
1483                            else
1484                                    for (i = 1; i < 5; i++) {
1485                                            sumx += Data->currentMV[i].x;
1486                                            sumy += Data->currentMV[i].y;
1487                          }                          }
1488    
1489                          Data->iMinSAD[1] += ChromaSAD(  (sumx >> 3) + roundtab_76[sumx & 0xf],                          Data->iMinSAD[1] += ChromaSAD(  (sumx >> 3) + roundtab_76[sumx & 0xf],
1490                                                                                          (sumy >> 3) + roundtab_76[sumy & 0xf], Data);                                                                                          (sumy >> 3) + roundtab_76[sumy & 0xf], Data);
1491                  }                  }
1492          }          } else Data->iMinSAD[1] = 4096*256;
   
         inter4v = ModeDecision(iQuant, Data, inter4v, pMB, pMBs, x, y, pParam, MotionFlags, VopFlags);  
   
         if (Data->rrv) {  
                         Data->currentMV[0].x = RRV_MV_SCALEDOWN(Data->currentMV[0].x);  
                         Data->currentMV[0].y = RRV_MV_SCALEDOWN(Data->currentMV[0].y);  
         }  
   
         if (inter4v == MODE_INTER) {  
                 pMB->mode = MODE_INTER;  
                 pMB->mvs[0] = pMB->mvs[1] = pMB->mvs[2] = pMB->mvs[3] = Data->currentMV[0];  
                 pMB->sad16 = pMB->sad8[0] = pMB->sad8[1] = pMB->sad8[2] = pMB->sad8[3] = Data->iMinSAD[0];  
   
                 if(Data->qpel) {  
                         pMB->qmvs[0] = pMB->qmvs[1]  
                                 = pMB->qmvs[2] = pMB->qmvs[3] = Data->currentQMV[0];  
                         pMB->pmvs[0].x = Data->currentQMV[0].x - Data->predMV.x;  
                         pMB->pmvs[0].y = Data->currentQMV[0].y - Data->predMV.y;  
                 } else {  
                         pMB->pmvs[0].x = Data->currentMV[0].x - Data->predMV.x;  
                         pMB->pmvs[0].y = Data->currentMV[0].y - Data->predMV.y;  
                 }  
   
         } else if (inter4v == MODE_INTER4V) {  
                 pMB->mode = MODE_INTER4V;  
                 pMB->sad16 = Data->iMinSAD[0];  
         } else { // INTRA mode  
                 SkipMacroblockP(pMB, 0); // not skip, but similar enough  
                 pMB->mode = MODE_INTRA;  
         }  
   
1493  }  }
1494    
1495  static void  static void
# Line 1480  Line 1531 
1531                  Data->Cur = OldData->Cur + i * ((block&1) + Data->iEdgedWidth*(block>>1));                  Data->Cur = OldData->Cur + i * ((block&1) + Data->iEdgedWidth*(block>>1));
1532                  Data->qpel_precision = 0;                  Data->qpel_precision = 0;
1533    
1534                  get_range(&Data->min_dx, &Data->max_dx, &Data->min_dy, &Data->max_dy, x, y, 8,                  get_range(&Data->min_dx, &Data->max_dx, &Data->min_dy, &Data->max_dy, x, y, 3,
1535                                          pParam->width, pParam->height, Data->iFcode - Data->qpel, 0, Data->rrv);                                          pParam->width, pParam->height, Data->iFcode - Data->qpel, 1, Data->rrv);
1536    
1537                  if (!Data->rrv) CheckCandidate = CheckCandidate8;                  if (!Data->rrv) CheckCandidate = CheckCandidate8;
1538                  else CheckCandidate = CheckCandidate16no4v;                  else CheckCandidate = CheckCandidate16no4v;
1539    
1540                  if (MotionFlags & XVID_ME_EXTSEARCH8 && (!(MotionFlags & XVID_ME_EXTSEARCH_BITS))) {                  if (MotionFlags & XVID_ME_EXTSEARCH8 && (!(MotionFlags & XVID_ME_EXTSEARCH_RD))) {
1541                          int32_t temp_sad = *(Data->iMinSAD); // store current MinSAD                          int32_t temp_sad = *(Data->iMinSAD); /* store current MinSAD */
1542    
1543                          MainSearchFunc *MainSearchPtr;                          MainSearchFunc *MainSearchPtr;
1544                          if (MotionFlags & XVID_ME_USESQUARES8) MainSearchPtr = SquareSearch;                          if (MotionFlags & XVID_ME_USESQUARES8) MainSearchPtr = SquareSearch;
# Line 1497  Line 1548 
1548                          MainSearchPtr(Data->currentMV->x, Data->currentMV->y, Data, 255);                          MainSearchPtr(Data->currentMV->x, Data->currentMV->y, Data, 255);
1549    
1550                          if(*(Data->iMinSAD) < temp_sad) {                          if(*(Data->iMinSAD) < temp_sad) {
1551                                          Data->currentQMV->x = 2 * Data->currentMV->x; // update our qpel vector                                          Data->currentQMV->x = 2 * Data->currentMV->x; /* update our qpel vector */
1552                                          Data->currentQMV->y = 2 * Data->currentMV->y;                                          Data->currentQMV->y = 2 * Data->currentMV->y;
1553                          }                          }
1554                  }                  }
1555    
1556                  if (MotionFlags & XVID_ME_HALFPELREFINE8) {                  if (MotionFlags & XVID_ME_HALFPELREFINE8) {
1557                          int32_t temp_sad = *(Data->iMinSAD); // store current MinSAD                          int32_t temp_sad = *(Data->iMinSAD); /* store current MinSAD */
1558    
1559                          SubpelRefine(Data); // perform halfpel refine of current best vector                          SubpelRefine(Data); /* perform halfpel refine of current best vector */
1560    
1561                          if(*(Data->iMinSAD) < temp_sad) { // we have found a better match                          if(*(Data->iMinSAD) < temp_sad) { /* we have found a better match */
1562                                  Data->currentQMV->x = 2 * Data->currentMV->x; // update our qpel vector                                  Data->currentQMV->x = 2 * Data->currentMV->x; /* update our qpel vector */
1563                                  Data->currentQMV->y = 2 * Data->currentMV->y;                                  Data->currentQMV->y = 2 * Data->currentMV->y;
1564                          }                          }
1565                  }                  }
1566    
1567                  if (Data->qpel && MotionFlags & XVID_ME_QUARTERPELREFINE8) {                  if (Data->qpel && MotionFlags & XVID_ME_QUARTERPELREFINE8) {
1568                                  Data->qpel_precision = 1;                                  Data->qpel_precision = 1;
1569                                  get_range(&Data->min_dx, &Data->max_dx, &Data->min_dy, &Data->max_dy, x, y, 8,                                  get_range(&Data->min_dx, &Data->max_dx, &Data->min_dy, &Data->max_dy, x, y, 3,
1570                                          pParam->width, pParam->height, Data->iFcode, 1, 0);                                          pParam->width, pParam->height, Data->iFcode, 2, 0);
1571                                  SubpelRefine(Data);                                  SubpelRefine(Data);
1572                  }                  }
1573          }          }
# Line 1555  Line 1606 
1606                                                          const uint32_t mode_curr)                                                          const uint32_t mode_curr)
1607  {  {
1608    
1609          // [0] is prediction          /* [0] is prediction */
1610          pmv[0].x = EVEN(pmv[0].x); pmv[0].y = EVEN(pmv[0].y);          pmv[0].x = EVEN(pmv[0].x); pmv[0].y = EVEN(pmv[0].y);
1611    
1612          pmv[1].x = pmv[1].y = 0; // [1] is zero          pmv[1].x = pmv[1].y = 0; /* [1] is zero */
1613    
1614          pmv[2] = ChoosePred(pMB, mode_curr);          pmv[2] = ChoosePred(pMB, mode_curr);
1615          pmv[2].x = EVEN(pmv[2].x); pmv[2].y = EVEN(pmv[2].y);          pmv[2].x = EVEN(pmv[2].x); pmv[2].y = EVEN(pmv[2].y);
1616    
1617          if ((y != 0)&&(x != (int)(iWcount+1))) {                        // [3] top-right neighbour          if ((y != 0)&&(x != (int)(iWcount+1))) {                        /* [3] top-right neighbour */
1618                  pmv[3] = ChoosePred(pMB+1-iWcount, mode_curr);                  pmv[3] = ChoosePred(pMB+1-iWcount, mode_curr);
1619                  pmv[3].x = EVEN(pmv[3].x); pmv[3].y = EVEN(pmv[3].y);                  pmv[3].x = EVEN(pmv[3].x); pmv[3].y = EVEN(pmv[3].y);
1620          } else pmv[3].x = pmv[3].y = 0;          } else pmv[3].x = pmv[3].y = 0;
# Line 1609  Line 1660 
1660          *Data->iMinSAD = MV_MAX_ERROR;          *Data->iMinSAD = MV_MAX_ERROR;
1661          Data->iFcode = iFcode;          Data->iFcode = iFcode;
1662          Data->qpel_precision = 0;          Data->qpel_precision = 0;
1663          Data->temp[5] = Data->temp[6] = Data->temp[7] = 256*4096; // reset chroma-sad cache          Data->temp[5] = Data->temp[6] = Data->temp[7] = 256*4096; /* reset chroma-sad cache */
1664    
1665          Data->RefP[0] = pRef->y + (x + Data->iEdgedWidth*y) * 16;          Data->RefP[0] = pRef->y + (x + Data->iEdgedWidth*y) * 16;
1666          Data->RefP[2] = pRefH + (x + Data->iEdgedWidth*y) * 16;          Data->RefP[2] = pRefH + (x + Data->iEdgedWidth*y) * 16;
# Line 1620  Line 1671 
1671    
1672          Data->predMV = *predMV;          Data->predMV = *predMV;
1673    
1674          get_range(&Data->min_dx, &Data->max_dx, &Data->min_dy, &Data->max_dy, x, y, 16,          get_range(&Data->min_dx, &Data->max_dx, &Data->min_dy, &Data->max_dy, x, y, 4,
1675                                  pParam->width, pParam->height, iFcode - Data->qpel, 0, 0);                                  pParam->width, pParam->height, iFcode - Data->qpel, 1, 0);
1676    
1677          pmv[0] = Data->predMV;          pmv[0] = Data->predMV;
1678          if (Data->qpel) { pmv[0].x /= 2; pmv[0].y /= 2; }          if (Data->qpel) { pmv[0].x /= 2; pmv[0].y /= 2; }
# Line 1631  Line 1682 
1682          Data->currentMV->x = Data->currentMV->y = 0;          Data->currentMV->x = Data->currentMV->y = 0;
1683          CheckCandidate = CheckCandidate16no4v;          CheckCandidate = CheckCandidate16no4v;
1684    
1685  // main loop. checking all predictions          /* main loop. checking all predictions */
1686          for (i = 0; i < 7; i++) {          for (i = 0; i < 7; i++) {
1687                  if (!(mask = make_mask(pmv, i)) ) continue;                  if (!(mask = make_mask(pmv, i)) ) continue;
1688                  CheckCandidate16no4v(pmv[i].x, pmv[i].y, mask, &iDirection, Data);                  CheckCandidate16no4v(pmv[i].x, pmv[i].y, mask, &iDirection, Data);
# Line 1649  Line 1700 
1700                  Data->currentQMV->x = 2*Data->currentMV->x;                  Data->currentQMV->x = 2*Data->currentMV->x;
1701                  Data->currentQMV->y = 2*Data->currentMV->y;                  Data->currentQMV->y = 2*Data->currentMV->y;
1702                  Data->qpel_precision = 1;                  Data->qpel_precision = 1;
1703                  get_range(&Data->min_dx, &Data->max_dx, &Data->min_dy, &Data->max_dy, x, y, 16,                  get_range(&Data->min_dx, &Data->max_dx, &Data->min_dy, &Data->max_dy, x, y, 4,
1704                                          pParam->width, pParam->height, iFcode, 1, 0);                                          pParam->width, pParam->height, iFcode, 2, 0);
1705                  SubpelRefine(Data);                  SubpelRefine(Data);
1706          }          }
1707    
1708  // three bits are needed to code backward mode. four for forward          /* three bits are needed to code backward mode. four for forward */
1709    
1710          if (mode_current == MODE_FORWARD) *Data->iMinSAD += 4 * Data->lambda16;          if (mode_current == MODE_FORWARD) *Data->iMinSAD += 4 * Data->lambda16;
1711          else *Data->iMinSAD += 3 * Data->lambda16;          else *Data->iMinSAD += 3 * Data->lambda16;
# Line 1678  Line 1729 
1729          }          }
1730    
1731          if (mode_current == MODE_FORWARD) *(Data->currentMV+2) = *Data->currentMV;          if (mode_current == MODE_FORWARD) *(Data->currentMV+2) = *Data->currentMV;
1732          else *(Data->currentMV+1) = *Data->currentMV; //we store currmv for interpolate search          else *(Data->currentMV+1) = *Data->currentMV; /* we store currmv for interpolate search */
1733  }  }
1734    
1735  static void  static void
# Line 1694  Line 1745 
1745          const int div = 1 + Data->qpel;          const int div = 1 + Data->qpel;
1746          int k;          int k;
1747          const uint32_t stride = Data->iEdgedWidth/2;          const uint32_t stride = Data->iEdgedWidth/2;
1748  //this is not full chroma compensation, only it's fullpel approximation. should work though          /* this is not full chroma compensation, only it's fullpel approximation. should work though */
1749    
1750          for (k = 0; k < 4; k++) {          for (k = 0; k < 4; k++) {
1751                  dy += Data->directmvF[k].y / div;                  dy += Data->directmvF[k].y / div;
# Line 1713  Line 1764 
1764                                          b_Ref->u + (y*8 + b_dy/2) * stride + x*8 + b_dx/2,                                          b_Ref->u + (y*8 + b_dy/2) * stride + x*8 + b_dx/2,
1765                                          stride);                                          stride);
1766    
1767          if (sum >= 2 * MAX_CHROMA_SAD_FOR_SKIP * pMB->quant) return; //no skip          if (sum >= MAX_CHROMA_SAD_FOR_SKIP * pMB->quant) return; /* no skip */
1768    
1769          sum += sad8bi(pCur->v + 8*x + 8 * y * stride,          sum += sad8bi(pCur->v + 8*x + 8 * y * stride,
1770                                          f_Ref->v + (y*8 + dy/2) * stride + x*8 + dx/2,                                          f_Ref->v + (y*8 + dy/2) * stride + x*8 + dx/2,
1771                                          b_Ref->v + (y*8 + b_dy/2) * stride + x*8 + b_dx/2,                                          b_Ref->v + (y*8 + b_dy/2) * stride + x*8 + b_dx/2,
1772                                          stride);                                          stride);
1773    
1774          if (sum < 2 * MAX_CHROMA_SAD_FOR_SKIP * pMB->quant) {          if (sum < MAX_CHROMA_SAD_FOR_SKIP * pMB->quant) {
1775                  pMB->mode = MODE_DIRECT_NONE_MV; //skipped                  pMB->mode = MODE_DIRECT_NONE_MV; /* skipped */
1776                  for (k = 0; k < 4; k++) {                  for (k = 0; k < 4; k++) {
1777                          pMB->qmvs[k] = pMB->mvs[k];                          pMB->qmvs[k] = pMB->mvs[k];
1778                          pMB->b_qmvs[k] = pMB->b_mvs[k];                          pMB->b_qmvs[k] = pMB->b_mvs[k];
# Line 1785  Line 1836 
1836                  if ( (pMB->b_mvs[k].x > Data->max_dx) | (pMB->b_mvs[k].x < Data->min_dx)                  if ( (pMB->b_mvs[k].x > Data->max_dx) | (pMB->b_mvs[k].x < Data->min_dx)
1837                          | (pMB->b_mvs[k].y > Data->max_dy) | (pMB->b_mvs[k].y < Data->min_dy) ) {                          | (pMB->b_mvs[k].y > Data->max_dy) | (pMB->b_mvs[k].y < Data->min_dy) ) {
1838    
1839                          *best_sad = 256*4096; // in that case, we won't use direct mode                          *best_sad = 256*4096; /* in that case, we won't use direct mode */
1840                          pMB->mode = MODE_DIRECT; // just to make sure it doesn't say "MODE_DIRECT_NONE_MV"                          pMB->mode = MODE_DIRECT; /* just to make sure it doesn't say "MODE_DIRECT_NONE_MV" */
1841                          pMB->b_mvs[0].x = pMB->b_mvs[0].y = 0;                          pMB->b_mvs[0].x = pMB->b_mvs[0].y = 0;
1842                          return 256*4096;                          return 256*4096;
1843                  }                  }
# Line 1803  Line 1854 
1854    
1855          CheckCandidate(0, 0, 255, &k, Data);          CheckCandidate(0, 0, 255, &k, Data);
1856    
1857  // initial (fast) skip decision          /* initial (fast) skip decision */
1858          if (*Data->iMinSAD < pMB->quant * INITIAL_SKIP_THRESH * (2 + Data->chroma?1:0)) {          if (*Data->iMinSAD < pMB->quant * INITIAL_SKIP_THRESH * (Data->chroma?3:2)) {
1859                  //possible skip                  /* possible skip */
1860                  if (Data->chroma) {                  if (Data->chroma) {
1861                          pMB->mode = MODE_DIRECT_NONE_MV;                          pMB->mode = MODE_DIRECT_NONE_MV;
1862                          return *Data->iMinSAD; // skip.                          return *Data->iMinSAD; /* skip. */
1863                  } else {                  } else {
1864                          SkipDecisionB(pCur, f_Ref, b_Ref, pMB, x, y, Data);                          SkipDecisionB(pCur, f_Ref, b_Ref, pMB, x, y, Data);
1865                          if (pMB->mode == MODE_DIRECT_NONE_MV) return *Data->iMinSAD; // skip.                          if (pMB->mode == MODE_DIRECT_NONE_MV) return *Data->iMinSAD; /* skip. */
1866                  }                  }
1867          }          }
1868    
1869          *Data->iMinSAD += Data->lambda16;          *Data->iMinSAD += Data->lambda16;
1870          skip_sad = *Data->iMinSAD;          skip_sad = *Data->iMinSAD;
1871    
1872  //      DIRECT MODE DELTA VECTOR SEARCH.          /*
1873  //      This has to be made more effective, but at the moment I'm happy it's running at all           * DIRECT MODE DELTA VECTOR SEARCH.
1874             * This has to be made more effective, but at the moment I'm happy it's running at all
1875             */
1876    
1877          if (MotionFlags & XVID_ME_USESQUARES16) MainSearchPtr = SquareSearch;          if (MotionFlags & XVID_ME_USESQUARES16) MainSearchPtr = SquareSearch;
1878                  else if (MotionFlags & XVID_ME_ADVANCEDDIAMOND16) MainSearchPtr = AdvDiamondSearch;                  else if (MotionFlags & XVID_ME_ADVANCEDDIAMOND16) MainSearchPtr = AdvDiamondSearch;
# Line 1832  Line 1885 
1885          *best_sad = *Data->iMinSAD;          *best_sad = *Data->iMinSAD;
1886    
1887          if (Data->qpel || b_mb->mode == MODE_INTER4V) pMB->mode = MODE_DIRECT;          if (Data->qpel || b_mb->mode == MODE_INTER4V) pMB->mode = MODE_DIRECT;
1888          else pMB->mode = MODE_DIRECT_NO4V; //for faster compensation          else pMB->mode = MODE_DIRECT_NO4V; /* for faster compensation */
1889    
1890          pMB->pmvs[3] = *Data->currentMV;          pMB->pmvs[3] = *Data->currentMV;
1891    
# Line 1890  Line 1943 
1943          SearchData bData;          SearchData bData;
1944    
1945          fData->qpel_precision = 0;          fData->qpel_precision = 0;
1946          memcpy(&bData, fData, sizeof(SearchData)); //quick copy of common data          memcpy(&bData, fData, sizeof(SearchData)); /* quick copy of common data */
1947          *fData->iMinSAD = 4096*256;          *fData->iMinSAD = 4096*256;
1948          bData.currentMV++; bData.currentQMV++;          bData.currentMV++; bData.currentQMV++;
1949          fData->iFcode = bData.bFcode = fcode; fData->bFcode = bData.iFcode = bcode;          fData->iFcode = bData.bFcode = fcode; fData->bFcode = bData.iFcode = bcode;
# Line 1914  Line 1967 
1967          fData->bpredMV = bData.predMV = *b_predMV;          fData->bpredMV = bData.predMV = *b_predMV;
1968          fData->currentMV[0] = fData->currentMV[2];          fData->currentMV[0] = fData->currentMV[2];
1969    
1970          get_range(&fData->min_dx, &fData->max_dx, &fData->min_dy, &fData->max_dy, x, y, 16, pParam->width, pParam->height, fcode - fData->qpel, 0, 0);          get_range(&fData->min_dx, &fData->max_dx, &fData->min_dy, &fData->max_dy, x, y, 4, pParam->width, pParam->height, fcode - fData->qpel, 1, 0);
1971          get_range(&bData.min_dx, &bData.max_dx, &bData.min_dy, &bData.max_dy, x, y, 16, pParam->width, pParam->height, bcode - fData->qpel, 0, 0);          get_range(&bData.min_dx, &bData.max_dx, &bData.min_dy, &bData.max_dy, x, y, 4, pParam->width, pParam->height, bcode - fData->qpel, 1, 0);
1972    
1973          if (fData->currentMV[0].x > fData->max_dx) fData->currentMV[0].x = fData->max_dx;          if (fData->currentMV[0].x > fData->max_dx) fData->currentMV[0].x = fData->max_dx;
1974          if (fData->currentMV[0].x < fData->min_dx) fData->currentMV[0].x = fData->min_dx;          if (fData->currentMV[0].x < fData->min_dx) fData->currentMV[0].x = fData->min_dx;
# Line 1929  Line 1982 
1982    
1983          CheckCandidateInt(fData->currentMV[0].x, fData->currentMV[0].y, 255, &iDirection, fData);          CheckCandidateInt(fData->currentMV[0].x, fData->currentMV[0].y, 255, &iDirection, fData);
1984    
1985  //diamond          /* diamond */
1986          do {          do {
1987                  iDirection = 255;                  iDirection = 255;
1988                  // forward MV moves                  /* forward MV moves */
1989                  i = fData->currentMV[0].x; j = fData->currentMV[0].y;                  i = fData->currentMV[0].x; j = fData->currentMV[0].y;
1990    
1991                  CheckCandidateInt(i + 1, j, 0, &iDirection, fData);                  CheckCandidateInt(i + 1, j, 0, &iDirection, fData);
# Line 1940  Line 1993 
1993                  CheckCandidateInt(i - 1, j, 0, &iDirection, fData);                  CheckCandidateInt(i - 1, j, 0, &iDirection, fData);
1994                  CheckCandidateInt(i, j - 1, 0, &iDirection, fData);                  CheckCandidateInt(i, j - 1, 0, &iDirection, fData);
1995    
1996                  // backward MV moves                  /* backward MV moves */
1997                  i = fData->currentMV[1].x; j = fData->currentMV[1].y;                  i = fData->currentMV[1].x; j = fData->currentMV[1].y;
1998                  fData->currentMV[2] = fData->currentMV[0];                  fData->currentMV[2] = fData->currentMV[0];
1999                  CheckCandidateInt(i + 1, j, 0, &iDirection, &bData);                  CheckCandidateInt(i + 1, j, 0, &iDirection, &bData);
# Line 1950  Line 2003 
2003    
2004          } while (!(iDirection));          } while (!(iDirection));
2005    
2006  //qpel refinement          /* qpel refinement */
2007          if (fData->qpel) {          if (fData->qpel) {
2008                  if (*fData->iMinSAD > *best_sad + 500) return;                  if (*fData->iMinSAD > *best_sad + 500) return;
2009                  CheckCandidate = CheckCandidateInt;                  CheckCandidate = CheckCandidateInt;
2010                  fData->qpel_precision = bData.qpel_precision = 1;                  fData->qpel_precision = bData.qpel_precision = 1;
2011                  get_range(&fData->min_dx, &fData->max_dx, &fData->min_dy, &fData->max_dy, x, y, 16, pParam->width, pParam->height, fcode, 1, 0);                  get_range(&fData->min_dx, &fData->max_dx, &fData->min_dy, &fData->max_dy, x, y, 4, pParam->width, pParam->height, fcode, 2, 0);
2012                  get_range(&bData.min_dx, &bData.max_dx, &bData.min_dy, &bData.max_dy, x, y, 16, pParam->width, pParam->height, bcode, 1, 0);                  get_range(&bData.min_dx, &bData.max_dx, &bData.min_dy, &bData.max_dy, x, y, 4, pParam->width, pParam->height, bcode, 2, 0);
2013                  fData->currentQMV[2].x = fData->currentQMV[0].x = 2 * fData->currentMV[0].x;                  fData->currentQMV[2].x = fData->currentQMV[0].x = 2 * fData->currentMV[0].x;
2014                  fData->currentQMV[2].y = fData->currentQMV[0].y = 2 * fData->currentMV[0].y;                  fData->currentQMV[2].y = fData->currentQMV[0].y = 2 * fData->currentMV[0].y;
2015                  fData->currentQMV[1].x = 2 * fData->currentMV[1].x;                  fData->currentQMV[1].x = 2 * fData->currentMV[1].x;
# Line 1967  Line 2020 
2020                  SubpelRefine(&bData);                  SubpelRefine(&bData);
2021          }          }
2022    
2023          *fData->iMinSAD += (2+3) * fData->lambda16; // two bits are needed to code interpolate mode.          *fData->iMinSAD += (2+3) * fData->lambda16; /* two bits are needed to code interpolate mode. */
2024    
2025          if (*fData->iMinSAD < *best_sad) {          if (*fData->iMinSAD < *best_sad) {
2026                  *best_sad = *fData->iMinSAD;                  *best_sad = *fData->iMinSAD;
# Line 1995  Line 2048 
2048                                           FRAMEINFO * const frame,                                           FRAMEINFO * const frame,
2049                                           const int32_t time_bp,                                           const int32_t time_bp,
2050                                           const int32_t time_pp,                                           const int32_t time_pp,
2051                                           // forward (past) reference                                           /* forward (past) reference */
2052                                           const MACROBLOCK * const f_mbs,                                           const MACROBLOCK * const f_mbs,
2053                                           const IMAGE * const f_ref,                                           const IMAGE * const f_ref,
2054                                           const IMAGE * const f_refH,                                           const IMAGE * const f_refH,
2055                                           const IMAGE * const f_refV,                                           const IMAGE * const f_refV,
2056                                           const IMAGE * const f_refHV,                                           const IMAGE * const f_refHV,
2057                                           // backward (future) reference                                           /* backward (future) reference */
2058                                           const FRAMEINFO * const b_reference,                                           const FRAMEINFO * const b_reference,
2059                                           const IMAGE * const b_ref,                                           const IMAGE * const b_ref,
2060                                           const IMAGE * const b_refH,                                           const IMAGE * const b_refH,
# Line 2019  Line 2072 
2072          const int32_t TRB = time_pp - time_bp;          const int32_t TRB = time_pp - time_bp;
2073          const int32_t TRD = time_pp;          const int32_t TRD = time_pp;
2074    
2075  // some pre-inintialized data for the rest of the search          /* some pre-inintialized data for the rest of the search */
2076    
2077          SearchData Data;          SearchData Data;
2078          int32_t iMinSAD;          int32_t iMinSAD;
# Line 2031  Line 2084 
2084          Data.currentMV = currentMV; Data.currentQMV = currentQMV;          Data.currentMV = currentMV; Data.currentQMV = currentQMV;
2085          Data.iMinSAD = &iMinSAD;          Data.iMinSAD = &iMinSAD;
2086          Data.lambda16 = lambda_vec16[frame->quant];          Data.lambda16 = lambda_vec16[frame->quant];
2087          Data.qpel = pParam->vol_flags & XVID_VOL_QUARTERPEL;          Data.qpel = pParam->vol_flags & XVID_VOL_QUARTERPEL ? 1 : 0;
2088          Data.rounding = 0;          Data.rounding = 0;
2089          Data.chroma = frame->motion_flags & XVID_ME_CHROMA8;          Data.chroma = frame->motion_flags & XVID_ME_CHROMA_BVOP;
2090          Data.temp = temp;          Data.temp = temp;
2091    
2092          Data.RefQ = f_refV->u; // a good place, also used in MC (for similar purpose)          Data.RefQ = f_refV->u; /* a good place, also used in MC (for similar purpose) */
2093          // note: i==horizontal, j==vertical  
2094            /* note: i==horizontal, j==vertical */
2095          for (j = 0; j < pParam->mb_height; j++) {          for (j = 0; j < pParam->mb_height; j++) {
2096    
2097                  f_predMV = b_predMV = zeroMV;   /* prediction is reset at left boundary */                  f_predMV = b_predMV = zeroMV;   /* prediction is reset at left boundary */
# Line 2073  Line 2127 
2127    
2128                          if (pMB->mode == MODE_DIRECT_NONE_MV) { n_count++; continue; }                          if (pMB->mode == MODE_DIRECT_NONE_MV) { n_count++; continue; }
2129    
2130                          // forward search                          /* forward search */
2131                          SearchBF(f_ref, f_refH->y, f_refV->y, f_refHV->y,                          SearchBF(f_ref, f_refH->y, f_refV->y, f_refHV->y,
2132                                                  &frame->image, i, j,                                                  &frame->image, i, j,
2133                                                  frame->motion_flags,                                                  frame->motion_flags,
# Line 2081  Line 2135 
2135                                                  pMB, &f_predMV, &best_sad,                                                  pMB, &f_predMV, &best_sad,
2136                                                  MODE_FORWARD, &Data);                                                  MODE_FORWARD, &Data);
2137    
2138                          // backward search                          /* backward search */
2139                          SearchBF(b_ref, b_refH->y, b_refV->y, b_refHV->y,                          SearchBF(b_ref, b_refH->y, b_refV->y, b_refHV->y,
2140                                                  &frame->image, i, j,                                                  &frame->image, i, j,
2141                                                  frame->motion_flags,                                                  frame->motion_flags,
# Line 2089  Line 2143 
2143                                                  pMB, &b_predMV, &best_sad,                                                  pMB, &b_predMV, &best_sad,
2144                                                  MODE_BACKWARD, &Data);                                                  MODE_BACKWARD, &Data);
2145    
2146                          // interpolate search comes last, because it uses data from forward and backward as prediction                          /* interpolate search comes last, because it uses data from forward and backward as prediction */
2147                          SearchInterpolate(f_ref, f_refH->y, f_refV->y, f_refHV->y,                          SearchInterpolate(f_ref, f_refH->y, f_refV->y, f_refHV->y,
2148                                                  b_ref, b_refH->y, b_refV->y, b_refHV->y,                                                  b_ref, b_refH->y, b_refV->y, b_refHV->y,
2149                                                  &frame->image,                                                  &frame->image,
# Line 2101  Line 2155 
2155                                                  pMB, &best_sad,                                                  pMB, &best_sad,
2156                                                  &Data);                                                  &Data);
2157    
2158  // final skip decision                          /* final skip decision */
2159                          if ( (skip_sad < frame->quant * MAX_SAD00_FOR_SKIP * 2)                          if ( (skip_sad < frame->quant * MAX_SAD00_FOR_SKIP * 2)
2160                                          && ((100*best_sad)/(skip_sad+1) > FINAL_SKIP_THRESH) )                                          && ((100*best_sad)/(skip_sad+1) > FINAL_SKIP_THRESH) )
2161                                  SkipDecisionB(&frame->image, f_ref, b_ref, pMB, i, j, &Data);                                  SkipDecisionB(&frame->image, f_ref, b_ref, pMB, i, j, &Data);
# Line 2147  Line 2201 
2201    
2202          for (i = 0; i < 5; i++) Data->iMinSAD[i] = MV_MAX_ERROR;          for (i = 0; i < 5; i++) Data->iMinSAD[i] = MV_MAX_ERROR;
2203    
2204          //median is only used as prediction. it doesn't have to be real          /* median is only used as prediction. it doesn't have to be real */
2205          if (x == 1 && y == 1) Data->predMV.x = Data->predMV.y = 0;          if (x == 1 && y == 1) Data->predMV.x = Data->predMV.y = 0;
2206          else          else
2207                  if (x == 1) //left macroblock does not have any vector now                  if (x == 1) /* left macroblock does not have any vector now */
2208                          Data->predMV = (pMB - pParam->mb_width)->mvs[0]; // top instead of median                          Data->predMV = (pMB - pParam->mb_width)->mvs[0]; /* top instead of median */
2209                  else if (y == 1) // top macroblock doesn't have it's vector                  else if (y == 1) /* top macroblock doesn't have it's vector */
2210                          Data->predMV = (pMB - 1)->mvs[0]; // left instead of median                          Data->predMV = (pMB - 1)->mvs[0]; /* left instead of median */
2211                          else Data->predMV = get_pmv2(pMBs, pParam->mb_width, 0, x, y, 0); //else median                          else Data->predMV = get_pmv2(pMBs, pParam->mb_width, 0, x, y, 0); /* else median */
2212    
2213          get_range(&Data->min_dx, &Data->max_dx, &Data->min_dy, &Data->max_dy, x, y, 16,          get_range(&Data->min_dx, &Data->max_dx, &Data->min_dy, &Data->max_dy, x, y, 4,
2214          pParam->width, pParam->height, Data->iFcode - quarterpel, 0, 0);                          pParam->width, pParam->height, Data->iFcode - quarterpel, 1, 0);
2215    
2216          Data->Cur = pCur + (x + y * pParam->edged_width) * 16;          Data->Cur = pCur + (x + y * pParam->edged_width) * 16;
2217          Data->RefP[0] = pRef + (x + y * pParam->edged_width) * 16;          Data->RefP[0] = pRef + (x + y * pParam->edged_width) * 16;
# Line 2177  Line 2231 
2231                  if (!(mask = make_mask(pmv, 2)))                  if (!(mask = make_mask(pmv, 2)))
2232                          CheckCandidate32I(pmv[2].x, pmv[2].y, mask, &i, Data);                          CheckCandidate32I(pmv[2].x, pmv[2].y, mask, &i, Data);
2233    
2234                  if (*Data->iMinSAD > 4 * MAX_SAD00_FOR_SKIP) // diamond only if needed                  if (*Data->iMinSAD > 4 * MAX_SAD00_FOR_SKIP) /* diamond only if needed */
2235                          DiamondSearch(Data->currentMV->x, Data->currentMV->y, Data, i);                          DiamondSearch(Data->currentMV->x, Data->currentMV->y, Data, i);
2236          }          }
2237    
# Line 2189  Line 2243 
2243          }          }
2244  }  }
2245    
2246  #define INTRA_THRESH    2400  #define INTRA_THRESH    2200
2247  #define INTER_THRESH    1300  #define INTER_THRESH    50
2248    #define INTRA_THRESH2   95
2249    
2250  int  int
2251  MEanalysis(     const IMAGE * const pRef,  MEanalysis(     const IMAGE * const pRef,
# Line 2205  Line 2260 
2260          int sSAD = 0;          int sSAD = 0;
2261          MACROBLOCK * const pMBs = Current->mbs;          MACROBLOCK * const pMBs = Current->mbs;
2262          const IMAGE * const pCurrent = &Current->image;          const IMAGE * const pCurrent = &Current->image;
2263          int IntraThresh = INTRA_THRESH, InterThresh = INTER_THRESH + 10*b_thresh;          int IntraThresh = INTRA_THRESH, InterThresh = INTER_THRESH + b_thresh;
2264          int s = 0, blocks = 0;          int blocks = 0;
2265            int complexity = 0;
2266    
2267          int32_t iMinSAD[5], temp[5];          int32_t iMinSAD[5], temp[5];
2268          VECTOR currentMV[5];          VECTOR currentMV[5];
# Line 2218  Line 2274 
2274          Data.temp = temp;          Data.temp = temp;
2275          CheckCandidate = CheckCandidate32I;          CheckCandidate = CheckCandidate32I;
2276    
2277          if (intraCount != 0 && intraCount < 10) // we're right after an I frame          if (intraCount != 0) {
2278                  IntraThresh += 8 * (intraCount - 10) * (intraCount - 10);                  if (intraCount < 10) // we're right after an I frame
2279                            IntraThresh += 15* (intraCount - 10) * (intraCount - 10);
2280          else          else
2281                  if ( 5*(maxIntra - intraCount) < maxIntra) // we're close to maximum. 2 sec when max is 10 sec                  if ( 5*(maxIntra - intraCount) < maxIntra) // we're close to maximum. 2 sec when max is 10 sec
2282                          IntraThresh -= (IntraThresh * (maxIntra - 5*(maxIntra - intraCount)))/maxIntra;                                  IntraThresh -= (IntraThresh * (maxIntra - 8*(maxIntra - intraCount)))/maxIntra;
2283            }
2284    
2285          InterThresh -= (350 - 8*b_thresh) * bCount;          InterThresh -= 12 * bCount;
2286          if (InterThresh < 300 + 5*b_thresh) InterThresh = 300 + 5*b_thresh;          if (InterThresh < 15 + b_thresh) InterThresh = 15 + b_thresh;
2287    
2288          if (sadInit) (*sadInit) ();          if (sadInit) (*sadInit) ();
2289    
2290          for (y = 1; y < pParam->mb_height-1; y += 2) {          for (y = 1; y < pParam->mb_height-1; y += 2) {
2291                  for (x = 1; x < pParam->mb_width-1; x += 2) {                  for (x = 1; x < pParam->mb_width-1; x += 2) {
2292                          int i;                          int i;
2293                          blocks += 4;                          blocks += 10;
2294    
2295                          if (bCount == 0) pMBs[x + y * pParam->mb_width].mvs[0] = zeroMV;                          if (bCount == 0) pMBs[x + y * pParam->mb_width].mvs[0] = zeroMV;
2296                          else { //extrapolation of the vector found for last frame                          else { //extrapolation of the vector found for last frame
# Line 2247  Line 2305 
2305                          for (i = 0; i < 4; i++) {                          for (i = 0; i < 4; i++) {
2306                                  int dev;                                  int dev;
2307                                  MACROBLOCK *pMB = &pMBs[x+(i&1) + (y+(i>>1)) * pParam->mb_width];                                  MACROBLOCK *pMB = &pMBs[x+(i&1) + (y+(i>>1)) * pParam->mb_width];
                                 if (pMB->sad16 > IntraThresh) {  
2308                                          dev = dev16(pCurrent->y + (x + (i&1) + (y + (i>>1)) * pParam->edged_width) * 16,                                          dev = dev16(pCurrent->y + (x + (i&1) + (y + (i>>1)) * pParam->edged_width) * 16,
2309                                                                          pParam->edged_width);                                                                          pParam->edged_width);
2310    
2311                                    complexity += MAX(dev, 300);
2312                                          if (dev + IntraThresh < pMB->sad16) {                                          if (dev + IntraThresh < pMB->sad16) {
2313                                                  pMB->mode = MODE_INTRA;                                                  pMB->mode = MODE_INTRA;
2314                                                  if (++intra > ((pParam->mb_height-2)*(pParam->mb_width-2))/2) return I_VOP;                                                  if (++intra > ((pParam->mb_height-2)*(pParam->mb_width-2))/2) return I_VOP;
2315                                          }                                          }
                                 }  
                                 if (pMB->mvs[0].x == 0 && pMB->mvs[0].y == 0) s++;  
2316    
2317                                  sSAD += pMB->sad16;                                  if (pMB->mvs[0].x == 0 && pMB->mvs[0].y == 0)
2318                                            if (dev > 500 && pMB->sad16 < 1000)
2319                                                    sSAD += 1000;
2320    
2321                                    sSAD += (dev < 3000) ? pMB->sad16 : pMB->sad16/2; /* blocks with big contrast differences usually have large SAD - while they look very good in b-frames */
2322                          }                          }
2323                  }                  }
2324          }          }
2325            complexity >>= 7;
2326    
2327          sSAD /= blocks;          sSAD /= complexity + 4*blocks;
         s = (10*s) / blocks;  
   
         if (s > 4) sSAD += (s - 3) * (300 - 2*b_thresh); //static block - looks bad when in bframe...  
2328    
2329            if (intraCount > 80 && sSAD > INTRA_THRESH2 ) return I_VOP;
2330          if (sSAD > InterThresh ) return P_VOP;          if (sSAD > InterThresh ) return P_VOP;
2331          emms();          emms();
2332          return B_VOP;          return B_VOP;
2333  }  }
2334    
2335    
2336  static WARPPOINTS  /* functions which perform BITS-based search/bitcount */
 GlobalMotionEst(const MACROBLOCK * const pMBs,  
                                 const MBParam * const pParam,  
                                 const FRAMEINFO * const current,  
                                 const FRAMEINFO * const reference,  
                                 const IMAGE * const pRefH,  
                                 const IMAGE * const pRefV,  
                                 const IMAGE * const pRefHV      )  
 {  
   
         const int deltax=8;             // upper bound for difference between a MV and it's neighbour MVs  
         const int deltay=8;  
         const int grad=512;             // lower bound for deviation in MB  
   
         WARPPOINTS gmc;  
   
         uint32_t mx, my;  
   
         int MBh = pParam->mb_height;  
         int MBw = pParam->mb_width;  
   
         int *MBmask= calloc(MBh*MBw,sizeof(int));  
         double DtimesF[4] = { 0.,0., 0., 0. };  
         double sol[4] = { 0., 0., 0., 0. };  
         double a,b,c,n,denom;  
         double meanx,meany;  
         int num,oldnum;  
   
         if (!MBmask) {  fprintf(stderr,"Mem error\n");  
                                         gmc.duv[0].x= gmc.duv[0].y =  
                                                 gmc.duv[1].x= gmc.duv[1].y =  
                                                 gmc.duv[2].x= gmc.duv[2].y = 0;  
                                         return gmc; }  
   
 // filter mask of all blocks  
   
         for (my = 1; my < (uint32_t)MBh-1; my++)  
         for (mx = 1; mx < (uint32_t)MBw-1; mx++)  
         {  
                 const int mbnum = mx + my * MBw;  
                 const MACROBLOCK *pMB = &pMBs[mbnum];  
                 const VECTOR mv = pMB->mvs[0];  
   
                 if (pMB->mode == MODE_INTRA || pMB->mode == MODE_NOT_CODED)  
                         continue;  
   
                 if ( ( (abs(mv.x -   (pMB-1)->mvs[0].x) < deltax) && (abs(mv.y -   (pMB-1)->mvs[0].y) < deltay) )  
                 &&   ( (abs(mv.x -   (pMB+1)->mvs[0].x) < deltax) && (abs(mv.y -   (pMB+1)->mvs[0].y) < deltay) )  
                 &&   ( (abs(mv.x - (pMB-MBw)->mvs[0].x) < deltax) && (abs(mv.y - (pMB-MBw)->mvs[0].y) < deltay) )  
                 &&   ( (abs(mv.x - (pMB+MBw)->mvs[0].x) < deltax) && (abs(mv.y - (pMB+MBw)->mvs[0].y) < deltay) ) )  
                         MBmask[mbnum]=1;  
         }  
   
         for (my = 1; my < (uint32_t)MBh-1; my++)  
         for (mx = 1; mx < (uint32_t)MBw-1; mx++)  
         {  
                 const uint8_t *const pCur = current->image.y + 16*my*pParam->edged_width + 16*mx;  
   
                 const int mbnum = mx + my * MBw;  
                 if (!MBmask[mbnum])  
                         continue;  
   
                 if (sad16 ( pCur, pCur+1 , pParam->edged_width, 65536) <= (uint32_t)grad )  
                         MBmask[mbnum] = 0;  
                 if (sad16 ( pCur, pCur+pParam->edged_width, pParam->edged_width, 65536) <= (uint32_t)grad )  
                         MBmask[mbnum] = 0;  
   
         }  
   
         emms();  
   
         do {            /* until convergence */  
   
         a = b = c = n = 0;  
         DtimesF[0] = DtimesF[1] = DtimesF[2] = DtimesF[3] = 0.;  
         for (my = 0; my < (uint32_t)MBh; my++)  
                 for (mx = 0; mx < (uint32_t)MBw; mx++)  
                 {  
                         const int mbnum = mx + my * MBw;  
                         const MACROBLOCK *pMB = &pMBs[mbnum];  
                         const VECTOR mv = pMB->mvs[0];  
   
                         if (!MBmask[mbnum])  
                                 continue;  
   
                         n++;  
                         a += 16*mx+8;  
                         b += 16*my+8;  
                         c += (16*mx+8)*(16*mx+8)+(16*my+8)*(16*my+8);  
   
                         DtimesF[0] += (double)mv.x;  
                         DtimesF[1] += (double)mv.x*(16*mx+8) + (double)mv.y*(16*my+8);  
                         DtimesF[2] += (double)mv.x*(16*my+8) - (double)mv.y*(16*mx+8);  
                         DtimesF[3] += (double)mv.y;  
                 }  
   
         denom = a*a+b*b-c*n;  
   
 /* Solve the system:    sol = (D'*E*D)^{-1} D'*E*F   */  
 /* D'*E*F has been calculated in the same loop as matrix */  
   
         sol[0] = -c*DtimesF[0] + a*DtimesF[1] + b*DtimesF[2];  
         sol[1] =  a*DtimesF[0] - n*DtimesF[1]                + b*DtimesF[3];  
         sol[2] =  b*DtimesF[0]                - n*DtimesF[2] - a*DtimesF[3];  
         sol[3] =                 b*DtimesF[1] - a*DtimesF[2] - c*DtimesF[3];  
   
         sol[0] /= denom;  
         sol[1] /= denom;  
         sol[2] /= denom;  
         sol[3] /= denom;  
   
         meanx = meany = 0.;  
         oldnum = 0;  
         for (my = 0; my < (uint32_t)MBh; my++)  
                 for (mx = 0; mx < (uint32_t)MBw; mx++)  
                 {  
                         const int mbnum = mx + my * MBw;  
                         const MACROBLOCK *pMB = &pMBs[mbnum];  
                         const VECTOR mv = pMB->mvs[0];  
   
                         if (!MBmask[mbnum])  
                                 continue;  
   
                         oldnum++;  
                         meanx += fabs(( sol[0] + (16*mx+8)*sol[1] + (16*my+8)*sol[2] ) - mv.x );  
                         meany += fabs(( sol[3] - (16*mx+8)*sol[2] + (16*my+8)*sol[1] ) - mv.y );  
                 }  
   
         if (4*meanx > oldnum)   /* better fit than 0.25 is useless */  
                 meanx /= oldnum;  
         else  
                 meanx = 0.25;  
   
         if (4*meany > oldnum)  
                 meany /= oldnum;  
         else  
                 meany = 0.25;  
   
 /*      fprintf(stderr,"sol = (%8.5f, %8.5f, %8.5f, %8.5f)\n",sol[0],sol[1],sol[2],sol[3]);  
         fprintf(stderr,"meanx = %8.5f  meany = %8.5f   %d\n",meanx,meany, oldnum);  
 */  
         num = 0;  
         for (my = 0; my < (uint32_t)MBh; my++)  
                 for (mx = 0; mx < (uint32_t)MBw; mx++)  
                 {  
                         const int mbnum = mx + my * MBw;  
                         const MACROBLOCK *pMB = &pMBs[mbnum];  
                         const VECTOR mv = pMB->mvs[0];  
   
                         if (!MBmask[mbnum])  
                                 continue;  
   
                         if  ( ( fabs(( sol[0] + (16*mx+8)*sol[1] + (16*my+8)*sol[2] ) - mv.x ) > meanx )  
                            || ( fabs(( sol[3] - (16*mx+8)*sol[2] + (16*my+8)*sol[1] ) - mv.y ) > meany ) )  
                                 MBmask[mbnum]=0;  
                         else  
                                 num++;  
                 }  
   
         } while ( (oldnum != num) && (num>=4) );  
   
         if (num < 4)  
         {  
                 gmc.duv[0].x= gmc.duv[0].y= gmc.duv[1].x= gmc.duv[1].y= gmc.duv[2].x= gmc.duv[2].y=0;  
         } else {  
   
                 gmc.duv[0].x=(int)(sol[0]+0.5);  
                 gmc.duv[0].y=(int)(sol[3]+0.5);  
   
                 gmc.duv[1].x=(int)(sol[1]*pParam->width+0.5);  
                 gmc.duv[1].y=(int)(-sol[2]*pParam->width+0.5);  
   
                 gmc.duv[2].x=0;  
                 gmc.duv[2].y=0;  
         }  
 //      fprintf(stderr,"wp1 = ( %4d, %4d)  wp2 = ( %4d, %4d) \n", gmc.duv[0].x, gmc.duv[0].y, gmc.duv[1].x, gmc.duv[1].y);  
   
         free(MBmask);  
   
         return gmc;  
 }  
   
 // functions which perform BITS-based search/bitcount  
2337    
2338  static int  static int
2339  CountMBBitsInter(SearchData * const Data,  findRDinter(SearchData * const Data,
2340                                  const MACROBLOCK * const pMBs, const int x, const int y,                                  const MACROBLOCK * const pMBs, const int x, const int y,
2341                                  const MBParam * const pParam,                                  const MBParam * const pParam,
2342                                  const uint32_t MotionFlags)                                  const uint32_t MotionFlags)
# Line 2466  Line 2344 
2344          int i, iDirection;          int i, iDirection;
2345          int32_t bsad[5];          int32_t bsad[5];
2346    
2347          CheckCandidate = CheckCandidateBits16;          CheckCandidate = CheckCandidateRD16;
2348    
2349          if (Data->qpel) {          if (Data->qpel) {
2350                  for(i = 0; i < 5; i++) {                  for(i = 0; i < 5; i++) {
# Line 2474  Line 2352 
2352                          Data->currentMV[i].y = Data->currentQMV[i].y/2;                          Data->currentMV[i].y = Data->currentQMV[i].y/2;
2353                  }                  }
2354                  Data->qpel_precision = 1;                  Data->qpel_precision = 1;
2355                  CheckCandidateBits16(Data->currentQMV[0].x, Data->currentQMV[0].y, 255, &iDirection, Data);                  CheckCandidateRD16(Data->currentQMV[0].x, Data->currentQMV[0].y, 255, &iDirection, Data);
   
                 //checking if this vector is perfect. if it is, we stop.  
                 if (Data->temp[0] == 0 && Data->temp[1] == 0 && Data->temp[2] == 0 && Data->temp[3] == 0)  
                         return 0; //quick stop  
2356    
2357                  if (MotionFlags & (XVID_ME_HALFPELREFINE16_BITS | XVID_ME_EXTSEARCH_BITS)) { //we have to prepare for halfpixel-precision search                  if (MotionFlags & (XVID_ME_HALFPELREFINE16_RD | XVID_ME_EXTSEARCH_RD)) { /* we have to prepare for halfpixel-precision search */
2358                          for(i = 0; i < 5; i++) bsad[i] = Data->iMinSAD[i];                          for(i = 0; i < 5; i++) bsad[i] = Data->iMinSAD[i];
2359                          get_range(&Data->min_dx, &Data->max_dx, &Data->min_dy, &Data->max_dy, x, y, 16,                          get_range(&Data->min_dx, &Data->max_dx, &Data->min_dy, &Data->max_dy, x, y, 4,
2360                                                  pParam->width, pParam->height, Data->iFcode - Data->qpel, 0, Data->rrv);                                                  pParam->width, pParam->height, Data->iFcode - Data->qpel, 1, Data->rrv);
2361                          Data->qpel_precision = 0;                          Data->qpel_precision = 0;
2362                          if (Data->currentQMV->x & 1 || Data->currentQMV->y & 1)                          if (Data->currentQMV->x & 1 || Data->currentQMV->y & 1)
2363                                  CheckCandidateBits16(Data->currentMV[0].x, Data->currentMV[0].y, 255, &iDirection, Data);                                  CheckCandidateRD16(Data->currentMV[0].x, Data->currentMV[0].y, 255, &iDirection, Data);
2364                  }                  }
2365    
2366          } else { // not qpel          } else { /* not qpel */
2367    
2368                  CheckCandidateBits16(Data->currentMV[0].x, Data->currentMV[0].y, 255, &iDirection, Data);                  CheckCandidateRD16(Data->currentMV[0].x, Data->currentMV[0].y, 255, &iDirection, Data);
                 //checking if this vector is perfect. if it is, we stop.  
                 if (Data->temp[0] == 0 && Data->temp[1] == 0 && Data->temp[2] == 0 && Data->temp[3] == 0) {  
                         return 0; //inter  
                 }  
2369          }          }
2370    
2371          if (MotionFlags&XVID_ME_EXTSEARCH_BITS) SquareSearch(Data->currentMV->x, Data->currentMV->y, Data, iDirection);          if (MotionFlags&XVID_ME_EXTSEARCH_RD) SquareSearch(Data->currentMV->x, Data->currentMV->y, Data, iDirection);
2372    
2373          if (MotionFlags&XVID_ME_HALFPELREFINE16_BITS) SubpelRefine(Data);          if (MotionFlags&XVID_ME_HALFPELREFINE16_RD) SubpelRefine(Data);
2374    
2375          if (Data->qpel) {          if (Data->qpel) {
2376                  if (MotionFlags&(XVID_ME_EXTSEARCH_BITS | XVID_ME_HALFPELREFINE16_BITS)) { // there was halfpel-precision search                  if (MotionFlags&(XVID_ME_EXTSEARCH_RD | XVID_ME_HALFPELREFINE16_RD)) { /* there was halfpel-precision search */
2377                          for(i = 0; i < 5; i++) if (bsad[i] > Data->iMinSAD[i]) {                          for(i = 0; i < 5; i++) if (bsad[i] > Data->iMinSAD[i]) {
2378                                  Data->currentQMV[i].x = 2 * Data->currentMV[i].x; // we have found a better match                                  Data->currentQMV[i].x = 2 * Data->currentMV[i].x; /* we have found a better match */
2379                                  Data->currentQMV[i].y = 2 * Data->currentMV[i].y;                                  Data->currentQMV[i].y = 2 * Data->currentMV[i].y;
2380                          }                          }
2381    
2382                          // preparing for qpel-precision search                          /* preparing for qpel-precision search */
2383                          Data->qpel_precision = 1;                          Data->qpel_precision = 1;
2384                          get_range(&Data->min_dx, &Data->max_dx, &Data->min_dy, &Data->max_dy, x, y, 16,                          get_range(&Data->min_dx, &Data->max_dx, &Data->min_dy, &Data->max_dy, x, y, 4,
2385                                          pParam->width, pParam->height, Data->iFcode, 1, 0);                                          pParam->width, pParam->height, Data->iFcode, 2, 0);
2386                  }                  }
2387                  if (MotionFlags&XVID_ME_QUARTERPELREFINE16_BITS) SubpelRefine(Data);                  if (MotionFlags&XVID_ME_QUARTERPELREFINE16_RD) SubpelRefine(Data);
2388          }          }
2389    
2390          if (MotionFlags&XVID_ME_CHECKPREDICTION_BITS) { //let's check vector equal to prediction          if (MotionFlags&XVID_ME_CHECKPREDICTION_RD) { /* let's check vector equal to prediction */
2391                  VECTOR * v = Data->qpel ? Data->currentQMV : Data->currentMV;                  VECTOR * v = Data->qpel ? Data->currentQMV : Data->currentMV;
2392                  if (!(Data->predMV.x == v->x && Data->predMV.y == v->y))                  if (!(Data->predMV.x == v->x && Data->predMV.y == v->y))
2393                          CheckCandidateBits16(Data->predMV.x, Data->predMV.y, 255, &iDirection, Data);                          CheckCandidateRD16(Data->predMV.x, Data->predMV.y, 255, &iDirection, Data);
2394          }          }
2395          return Data->iMinSAD[0];          return Data->iMinSAD[0];
2396  }  }
2397    
   
2398  static int  static int
2399  CountMBBitsInter4v(const SearchData * const Data,  findRDinter4v(const SearchData * const Data,
2400                                          MACROBLOCK * const pMB, const MACROBLOCK * const pMBs,                                          MACROBLOCK * const pMB, const MACROBLOCK * const pMBs,
2401                                          const int x, const int y,                                          const int x, const int y,
2402                                          const MBParam * const pParam, const uint32_t MotionFlags,                                          const MBParam * const pParam, const uint32_t MotionFlags,
# Line 2538  Line 2407 
2407          SearchData Data2, *Data8 = &Data2;          SearchData Data2, *Data8 = &Data2;
2408          int sumx = 0, sumy = 0;          int sumx = 0, sumy = 0;
2409          int16_t *in = Data->dctSpace, *coeff = Data->dctSpace + 64;          int16_t *in = Data->dctSpace, *coeff = Data->dctSpace + 64;
2410            uint8_t * ptr;
2411    
2412          memcpy(Data8, Data, sizeof(SearchData));          memcpy(Data8, Data, sizeof(SearchData));
2413          CheckCandidate = CheckCandidateBits8;          CheckCandidate = CheckCandidateRD8;
2414    
2415            for (i = 0; i < 4; i++) { /* for all luma blocks */
2416    
         for (i = 0; i < 4; i++) {  
2417                  Data8->iMinSAD = Data->iMinSAD + i + 1;                  Data8->iMinSAD = Data->iMinSAD + i + 1;
2418                  Data8->currentMV = Data->currentMV + i + 1;                  Data8->currentMV = Data->currentMV + i + 1;
2419                  Data8->currentQMV = Data->currentQMV + i + 1;                  Data8->currentQMV = Data->currentQMV + i + 1;
# Line 2551  Line 2422 
2422                  Data8->RefP[2] = Data->RefP[2] + 8*((i&1) + (i>>1)*Data->iEdgedWidth);                  Data8->RefP[2] = Data->RefP[2] + 8*((i&1) + (i>>1)*Data->iEdgedWidth);
2423                  Data8->RefP[1] = Data->RefP[1] + 8*((i&1) + (i>>1)*Data->iEdgedWidth);                  Data8->RefP[1] = Data->RefP[1] + 8*((i&1) + (i>>1)*Data->iEdgedWidth);
2424                  Data8->RefP[3] = Data->RefP[3] + 8*((i&1) + (i>>1)*Data->iEdgedWidth);                  Data8->RefP[3] = Data->RefP[3] + 8*((i&1) + (i>>1)*Data->iEdgedWidth);
2425                    *Data8->cbp = (Data->cbp[1] & (1<<(5-i))) ? 1:0; // copy corresponding cbp bit
2426    
2427                  if(Data->qpel) {                  if(Data->qpel) {
2428                          Data8->predMV = get_qpmv2(pMBs, pParam->mb_width, 0, x, y, i);                          Data8->predMV = get_qpmv2(pMBs, pParam->mb_width, 0, x, y, i);
# Line 2562  Line 2434 
2434                                                                                  Data8->predMV, Data8->iFcode, 0, 0);                                                                                  Data8->predMV, Data8->iFcode, 0, 0);
2435                  }                  }
2436    
2437                  get_range(&Data8->min_dx, &Data8->max_dx, &Data8->min_dy, &Data8->max_dy, 2*x + (i&1), 2*y + (i>>1), 8,                  get_range(&Data8->min_dx, &Data8->max_dx, &Data8->min_dy, &Data8->max_dy, 2*x + (i&1), 2*y + (i>>1), 3,
2438                                          pParam->width, pParam->height, Data8->iFcode, Data8->qpel, 0);                                          pParam->width, pParam->height, Data8->iFcode, Data8->qpel+1, 0);
2439    
2440                  *Data8->iMinSAD += t;                  *Data8->iMinSAD += BITS_MULT*t;
2441    
2442                  Data8->qpel_precision = Data8->qpel;                  Data8->qpel_precision = Data8->qpel;
2443                  // checking the vector which has been found by SAD-based 8x8 search (if it's different than the one found so far)                  /* checking the vector which has been found by SAD-based 8x8 search (if it's different than the one found so far) */
2444                  if (Data8->qpel) {                  {
2445                          if (!(Data8->currentQMV->x == backup[i+1].x && Data8->currentQMV->y == backup[i+1].y))                          VECTOR *v = Data8->qpel ? Data8->currentQMV : Data8->currentMV;
2446                                  CheckCandidateBits8(backup[i+1].x, backup[i+1].y, 255, &iDirection, Data8);                          if (!MVequal (*v, backup[i+1]) )
2447                  } else {                                  CheckCandidateRD8(backup[i+1].x, backup[i+1].y, 255, &iDirection, Data8);
                         if (!(Data8->currentMV->x == backup[i+1].x && Data8->currentMV->y == backup[i+1].y))  
                                 CheckCandidateBits8(backup[i+1].x, backup[i+1].y, 255, &iDirection, Data8);  
2448                  }                  }
2449    
2450                  if (Data8->qpel) {                  if (Data8->qpel) {
2451                          if (MotionFlags&XVID_ME_HALFPELREFINE8_BITS || (MotionFlags&XVID_ME_EXTSEARCH8 && MotionFlags&XVID_ME_EXTSEARCH_BITS)) { // halfpixel motion search follows                          if (MotionFlags&XVID_ME_HALFPELREFINE8_RD || (MotionFlags&XVID_ME_EXTSEARCH8 && MotionFlags&XVID_ME_EXTSEARCH_RD)) { /* halfpixel motion search follows */
2452                                  int32_t s = *Data8->iMinSAD;                                  int32_t s = *Data8->iMinSAD;
2453                                  Data8->currentMV->x = Data8->currentQMV->x/2;                                  Data8->currentMV->x = Data8->currentQMV->x/2;
2454                                  Data8->currentMV->y = Data8->currentQMV->y/2;                                  Data8->currentMV->y = Data8->currentQMV->y/2;
2455                                  Data8->qpel_precision = 0;                                  Data8->qpel_precision = 0;
2456                                  get_range(&Data8->min_dx, &Data8->max_dx, &Data8->min_dy, &Data8->max_dy, 2*x + (i&1), 2*y + (i>>1), 8,                                  get_range(&Data8->min_dx, &Data8->max_dx, &Data8->min_dy, &Data8->max_dy, 2*x + (i&1), 2*y + (i>>1), 3,
2457                                                          pParam->width, pParam->height, Data8->iFcode - 1, 0, 0);                                                          pParam->width, pParam->height, Data8->iFcode - 1, 1, 0);
2458    
2459                                  if (Data8->currentQMV->x & 1 || Data8->currentQMV->y & 1)                                  if (Data8->currentQMV->x & 1 || Data8->currentQMV->y & 1)
2460                                          CheckCandidateBits8(Data8->currentMV->x, Data8->currentMV->y, 255, &iDirection, Data8);                                          CheckCandidateRD8(Data8->currentMV->x, Data8->currentMV->y, 255, &iDirection, Data8);
2461    
2462                                  if (MotionFlags & XVID_ME_EXTSEARCH8 && MotionFlags & XVID_ME_EXTSEARCH_BITS)                                  if (MotionFlags & XVID_ME_EXTSEARCH8 && MotionFlags & XVID_ME_EXTSEARCH_RD)
2463                                          SquareSearch(Data8->currentMV->x, Data8->currentMV->x, Data8, 255);                                          SquareSearch(Data8->currentMV->x, Data8->currentMV->x, Data8, 255);
2464    
2465                                  if (MotionFlags & XVID_ME_HALFPELREFINE8_BITS) SubpelRefine(Data8);                                  if (MotionFlags & XVID_ME_HALFPELREFINE8_RD)
2466                                            SubpelRefine(Data8);
2467    
2468                                  if(s > *Data8->iMinSAD) { //we have found a better match                                  if(s > *Data8->iMinSAD) { /* we have found a better match */
2469                                          Data8->currentQMV->x = 2*Data8->currentMV->x;                                          Data8->currentQMV->x = 2*Data8->currentMV->x;
2470                                          Data8->currentQMV->y = 2*Data8->currentMV->y;                                          Data8->currentQMV->y = 2*Data8->currentMV->y;
2471                                  }                                  }
2472    
2473                                  Data8->qpel_precision = 1;                                  Data8->qpel_precision = 1;
2474                                  get_range(&Data8->min_dx, &Data8->max_dx, &Data8->min_dy, &Data8->max_dy, 2*x + (i&1), 2*y + (i>>1), 8,                                  get_range(&Data8->min_dx, &Data8->max_dx, &Data8->min_dy, &Data8->max_dy, 2*x + (i&1), 2*y + (i>>1), 3,
2475                                                          pParam->width, pParam->height, Data8->iFcode, 1, 0);                                                          pParam->width, pParam->height, Data8->iFcode, 2, 0);
2476    
2477                          }                          }
2478                          if (MotionFlags & XVID_ME_QUARTERPELREFINE8_BITS) SubpelRefine(Data8);                          if (MotionFlags & XVID_ME_QUARTERPELREFINE8_RD) SubpelRefine(Data8);
2479    
2480                  } else // not qpel                  } else { /* not qpel */
                         if (MotionFlags & XVID_ME_HALFPELREFINE8_BITS) SubpelRefine(Data8); //halfpel mode, halfpel refinement  
2481    
2482                  //checking vector equal to predicion                          if (MotionFlags & XVID_ME_EXTSEARCH8 && MotionFlags & XVID_ME_EXTSEARCH_RD) /* extsearch */
2483                  if (i != 0 && MotionFlags & XVID_ME_CHECKPREDICTION_BITS) {                                  SquareSearch(Data8->currentMV->x, Data8->currentMV->x, Data8, 255);
2484    
2485                            if (MotionFlags & XVID_ME_HALFPELREFINE8_RD)
2486                                    SubpelRefine(Data8); /* halfpel refinement */
2487                    }
2488    
2489                    /* checking vector equal to predicion */
2490                    if (i != 0 && MotionFlags & XVID_ME_CHECKPREDICTION_RD) {
2491                          const VECTOR * v = Data->qpel ? Data8->currentQMV : Data8->currentMV;                          const VECTOR * v = Data->qpel ? Data8->currentQMV : Data8->currentMV;
2492                          if (!(Data8->predMV.x == v->x && Data8->predMV.y == v->y))                          if (!MVequal(*v, Data8->predMV))
2493                                  CheckCandidateBits8(Data8->predMV.x, Data8->predMV.y, 255, &iDirection, Data8);                                  CheckCandidateRD8(Data8->predMV.x, Data8->predMV.y, 255, &iDirection, Data8);
2494                  }                  }
2495    
2496                  bits += *Data8->iMinSAD;                  bits += *Data8->iMinSAD;
2497                  if (bits >= Data->iMinSAD[0]) break; // no chances for INTER4V                  if (bits >= Data->iMinSAD[0]) return bits; /* no chances for INTER4V */
2498    
2499                  // MB structures for INTER4V mode; we have to set them here, we don't have predictor anywhere else                  /* MB structures for INTER4V mode; we have to set them here, we don't have predictor anywhere else */
2500                  if(Data->qpel) {                  if(Data->qpel) {
2501                          pMB->pmvs[i].x = Data8->currentQMV->x - Data8->predMV.x;                          pMB->pmvs[i].x = Data8->currentQMV->x - Data8->predMV.x;
2502                          pMB->pmvs[i].y = Data8->currentQMV->y - Data8->predMV.y;                          pMB->pmvs[i].y = Data8->currentQMV->y - Data8->predMV.y;
# Line 2634  Line 2511 
2511                  }                  }
2512                  pMB->mvs[i] = *Data8->currentMV;                  pMB->mvs[i] = *Data8->currentMV;
2513                  pMB->sad8[i] = 4 * *Data8->iMinSAD;                  pMB->sad8[i] = 4 * *Data8->iMinSAD;
2514                  if (Data8->temp[0]) cbp |= 1 << (5 - i);                  if (Data8->cbp[0]) cbp |= 1 << (5 - i);
         }  
2515    
2516          if (bits < *Data->iMinSAD) { // there is still a chance for inter4v mode. let's check chroma          } /* end - for all luma blocks */
2517                  const uint8_t * ptr;  
2518            bits += BITS_MULT*xvid_cbpy_tab[15-(cbp>>2)].len;
2519    
2520            /* let's check chroma */
2521                  sumx = (sumx >> 3) + roundtab_76[sumx & 0xf];                  sumx = (sumx >> 3) + roundtab_76[sumx & 0xf];
2522                  sumy = (sumy >> 3) + roundtab_76[sumy & 0xf];                  sumy = (sumy >> 3) + roundtab_76[sumy & 0xf];
2523    
2524                  //chroma U          /* chroma U */
2525                  ptr = interpolate8x8_switch2(Data->RefQ + 64, Data->RefP[4], 0, 0, sumx, sumy, Data->iEdgedWidth/2, Data->rounding);                  ptr = interpolate8x8_switch2(Data->RefQ + 64, Data->RefP[4], 0, 0, sumx, sumy, Data->iEdgedWidth/2, Data->rounding);
2526                  transfer_8to16subro(in, Data->CurU, ptr, Data->iEdgedWidth/2);                  transfer_8to16subro(in, Data->CurU, ptr, Data->iEdgedWidth/2);
2527                  fdct(in);          bits += Block_CalcBits(coeff, in, Data->dctSpace + 128, Data->iQuant, Data->quant_type, &cbp, 4);
2528                  if (Data->lambda8 == 0) i = quant_inter(coeff, in, Data->lambda16);  
2529                  else i = quant4_inter(coeff, in, Data->lambda16);          if (bits >= *Data->iMinSAD) return bits;
                 if (i > 0) {  
                         bits += CodeCoeffInter_CalcBits(coeff, scan_tables[0]);  
                         cbp |= 1 << (5 - 4);  
                 }  
2530    
2531                  if (bits < *Data->iMinSAD) { // still possible          /* chroma V */
                         //chroma V  
2532                          ptr = interpolate8x8_switch2(Data->RefQ + 64, Data->RefP[5], 0, 0, sumx, sumy, Data->iEdgedWidth/2, Data->rounding);                          ptr = interpolate8x8_switch2(Data->RefQ + 64, Data->RefP[5], 0, 0, sumx, sumy, Data->iEdgedWidth/2, Data->rounding);
2533                          transfer_8to16subro(in, Data->CurV, ptr, Data->iEdgedWidth/2);                          transfer_8to16subro(in, Data->CurV, ptr, Data->iEdgedWidth/2);
2534                          fdct(in);          bits += Block_CalcBits(coeff, in, Data->dctSpace + 128, Data->iQuant, Data->quant_type, &cbp, 5);
2535                          if (Data->lambda8 == 0) i = quant_inter(coeff, in, Data->lambda16);  
2536                          else i = quant4_inter(coeff, in, Data->lambda16);          bits += BITS_MULT*mcbpc_inter_tab[(MODE_INTER4V & 7) | ((cbp & 3) << 3)].len;
                         if (i > 0) {  
                                 bits += CodeCoeffInter_CalcBits(coeff, scan_tables[0]);  
                                 cbp |= 1 << (5 - 5);  
                         }  
                         bits += xvid_cbpy_tab[15-(cbp>>2)].len;  
                         bits += mcbpc_inter_tab[(MODE_INTER4V & 7) | ((cbp & 3) << 3)].len;  
                 }  
         }  
2537    
2538            *Data->cbp = cbp;
2539          return bits;          return bits;
2540  }  }
2541    
   
2542  static int  static int
2543  CountMBBitsIntra(const SearchData * const Data)  findRDintra(const SearchData * const Data)
2544  {  {
2545          int bits = 1; //this one is ac/dc prediction flag. always 1.          int bits = BITS_MULT*1; /* this one is ac/dc prediction flag bit */
2546          int cbp = 0, i, t, dc = 1024, b_dc;          int cbp = 0, i, dc = 0;
         const uint32_t iQuant = Data->lambda16;  
2547          int16_t *in = Data->dctSpace, * coeff = Data->dctSpace + 64;          int16_t *in = Data->dctSpace, * coeff = Data->dctSpace + 64;
         uint32_t iDcScaler = get_dc_scaler(iQuant, 1);;  
2548    
2549          for(i = 0; i < 4; i++) {          for(i = 0; i < 4; i++) {
2550                  int s = 8*((i&1) + (i>>1)*Data->iEdgedWidth);                  int s = 8*((i&1) + (i>>1)*Data->iEdgedWidth);
2551                  transfer_8to16copy(in, Data->Cur + s, Data->iEdgedWidth);                  transfer_8to16copy(in, Data->Cur + s, Data->iEdgedWidth);
2552                  fdct(in);                  bits += Block_CalcBitsIntra(coeff, in, Data->dctSpace + 128, Data->iQuant, Data->quant_type, &cbp, i, &dc);
2553                  b_dc = in[0];  
2554                  in[0] -= dc;                  if (bits >= Data->iMinSAD[0]) return bits;
2555                  dc = b_dc;          }
2556                  if (Data->lambda8 == 0) quant_intra(coeff, in, iQuant, iDcScaler);  
2557                  else quant4_intra(coeff, in, iQuant, iDcScaler);          bits += BITS_MULT*xvid_cbpy_tab[cbp>>2].len;
2558    
2559                  bits += t = CodeCoeffIntra_CalcBits(coeff, scan_tables[0]) + dcy_tab[coeff[0] + 255].len;;          /*chroma U */
                 Data->temp[i] = t;  
                 if (t != 0)  cbp |= 1 << (5 - i);  
                 if (bits >= Data->iMinSAD[0]) break;  
         }  
   
         if (bits < Data->iMinSAD[0]) { // INTRA still looks good, let's add chroma  
                 iDcScaler = get_dc_scaler(iQuant, 0);  
                 //chroma U  
2560                  transfer_8to16copy(in, Data->CurU, Data->iEdgedWidth/2);                  transfer_8to16copy(in, Data->CurU, Data->iEdgedWidth/2);
2561                  fdct(in);          bits += Block_CalcBitsIntra(coeff, in, Data->dctSpace + 128, Data->iQuant, Data->quant_type, &cbp, 4, &dc);
                 in[0] -= 1024;  
                 if (Data->lambda8 == 0) quant_intra(coeff, in, iQuant, iDcScaler);  
                 else quant4_intra(coeff, in, iQuant, iDcScaler);  
2562    
2563                  bits += t = CodeCoeffIntra_CalcBits(coeff, scan_tables[0]) + dcc_tab[coeff[0] + 255].len;          if (bits >= Data->iMinSAD[0]) return bits;
                 if (t != 0) cbp |= 1 << (5 - 4);  
2564    
2565                  if (bits < Data->iMinSAD[0]) {          /* chroma V */
                         //chroma V  
2566                          transfer_8to16copy(in, Data->CurV, Data->iEdgedWidth/2);                          transfer_8to16copy(in, Data->CurV, Data->iEdgedWidth/2);
2567                          fdct(in);          bits += Block_CalcBitsIntra(coeff, in, Data->dctSpace + 128, Data->iQuant, Data->quant_type, &cbp, 5, &dc);
                         in[0] -= 1024;  
                         if (Data->lambda8 == 0) quant_intra(coeff, in, iQuant, iDcScaler);  
                         else quant4_intra(coeff, in, iQuant, iDcScaler);  
2568    
2569                          bits += t = CodeCoeffIntra_CalcBits(coeff, scan_tables[0]) + dcc_tab[coeff[0] + 255].len;          bits += BITS_MULT*mcbpc_inter_tab[(MODE_INTRA & 7) | ((cbp & 3) << 3)].len;
                         if (t != 0) cbp |= 1 << (5 - 5);  
2570    
2571                          bits += xvid_cbpy_tab[cbp>>2].len;          return bits;
                         bits += mcbpc_inter_tab[(MODE_INTRA & 7) | ((cbp & 3) << 3)].len;  
2572                  }                  }
2573    
2574    static int
2575    findRDgmc(const SearchData * const Data, const IMAGE * const vGMC, const int x, const int y)
2576    {
2577            int bits = BITS_MULT*1; /* this one is mcsel */
2578            int cbp = 0, i;
2579            int16_t *in = Data->dctSpace, * coeff = Data->dctSpace + 64;
2580    
2581            for(i = 0; i < 4; i++) {
2582                    int s = 8*((i&1) + (i>>1)*Data->iEdgedWidth);
2583                    transfer_8to16subro(in, Data->Cur + s, vGMC->y + s + 16*(x+y*Data->iEdgedWidth), Data->iEdgedWidth);
2584                    bits += Block_CalcBits(coeff, in, Data->dctSpace + 128, Data->iQuant, Data->quant_type, &cbp, i);
2585                    if (bits >= Data->iMinSAD[0]) return bits;
2586          }          }
2587    
2588            bits += BITS_MULT*xvid_cbpy_tab[15-(cbp>>2)].len;
2589    
2590            /*chroma U */
2591            transfer_8to16subro(in, Data->CurU, vGMC->u + 8*(x+y*(Data->iEdgedWidth/2)), Data->iEdgedWidth/2);
2592            bits += Block_CalcBits(coeff, in, Data->dctSpace + 128, Data->iQuant, Data->quant_type, &cbp, 4);
2593    
2594            if (bits >= Data->iMinSAD[0]) return bits;
2595    
2596            /* chroma V */
2597            transfer_8to16subro(in, Data->CurV , vGMC->v + 8*(x+y*(Data->iEdgedWidth/2)), Data->iEdgedWidth/2);
2598            bits += Block_CalcBits(coeff, in, Data->dctSpace + 128, Data->iQuant, Data->quant_type, &cbp, 5);
2599    
2600            bits += BITS_MULT*mcbpc_inter_tab[(MODE_INTER & 7) | ((cbp & 3) << 3)].len;
2601    
2602            *Data->cbp = cbp;
2603    
2604          return bits;          return bits;
2605  }  }
2606    
2607    
2608    
2609    
2610    static __inline void
2611    GMEanalyzeMB (  const uint8_t * const pCur,
2612                                    const uint8_t * const pRef,
2613                                    const uint8_t * const pRefH,
2614                                    const uint8_t * const pRefV,
2615                                    const uint8_t * const pRefHV,
2616                                    const int x,
2617                                    const int y,
2618                                    const MBParam * const pParam,
2619                                    MACROBLOCK * const pMBs,
2620                                    SearchData * const Data)
2621    {
2622    
2623            int i=0;
2624            MACROBLOCK * const pMB = &pMBs[x + y * pParam->mb_width];
2625    
2626            Data->iMinSAD[0] = MV_MAX_ERROR;
2627    
2628            Data->predMV = get_pmv2(pMBs, pParam->mb_width, 0, x, y, 0);
2629    
2630            get_range(&Data->min_dx, &Data->max_dx, &Data->min_dy, &Data->max_dy, x, y, 4,
2631                                    pParam->width, pParam->height, 16, 1, 0);
2632    
2633            Data->Cur = pCur + 16*(x + y * pParam->edged_width);
2634            Data->RefP[0] = pRef + 16*(x + y * pParam->edged_width);
2635            Data->RefP[1] = pRefV + 16*(x + y * pParam->edged_width);
2636            Data->RefP[2] = pRefH + 16*(x + y * pParam->edged_width);
2637            Data->RefP[3] = pRefHV + 16*(x + y * pParam->edged_width);
2638    
2639            Data->currentMV[0].x = Data->currentMV[0].y = 0;
2640            CheckCandidate16I(0, 0, 255, &i, Data);
2641    
2642            if ( (Data->predMV.x !=0) || (Data->predMV.y != 0) )
2643                    CheckCandidate16I(Data->predMV.x, Data->predMV.y, 255, &i, Data);
2644    
2645            AdvDiamondSearch(Data->currentMV[0].x, Data->currentMV[0].y, Data, 255);
2646    
2647            SubpelRefine(Data);
2648    
2649    
2650            /* for QPel halfpel positions are worse than in halfpel mode :( */
2651    /*      if (Data->qpel) {
2652                    Data->currentQMV->x = 2*Data->currentMV->x;
2653                    Data->currentQMV->y = 2*Data->currentMV->y;
2654                    Data->qpel_precision = 1;
2655                    get_range(&Data->min_dx, &Data->max_dx, &Data->min_dy, &Data->max_dy, x, y, 4,
2656                                            pParam->width, pParam->height, iFcode, 2, 0);
2657                    SubpelRefine(Data);
2658            }
2659    */
2660    
2661            pMB->mvs[0] = pMB->mvs[1] = pMB->mvs[2] = pMB->mvs[3] = Data->currentMV[0];
2662            pMB->sad16 = Data->iMinSAD[0];
2663            pMB->mode = MODE_INTER;
2664            pMB->sad16 += 10*d_mv_bits(pMB->mvs[0].x, pMB->mvs[0].y, Data->predMV, Data->iFcode, 0, 0);
2665            return;
2666    }
2667    
2668    void
2669    GMEanalysis(const MBParam * const pParam,
2670                            const FRAMEINFO * const current,
2671                            const FRAMEINFO * const reference,
2672                            const IMAGE * const pRefH,
2673                            const IMAGE * const pRefV,
2674                            const IMAGE * const pRefHV)
2675    {
2676            uint32_t x, y;
2677            MACROBLOCK * const pMBs = current->mbs;
2678            const IMAGE * const pCurrent = &current->image;
2679            const IMAGE * const pReference = &reference->image;
2680    
2681            int32_t iMinSAD[5], temp[5];
2682            VECTOR currentMV[5];
2683            SearchData Data;
2684            memset(&Data, 0, sizeof(SearchData));
2685    
2686            Data.iEdgedWidth = pParam->edged_width;
2687            Data.rounding = pParam->m_rounding_type;
2688    
2689            Data.currentMV = &currentMV[0];
2690            Data.iMinSAD = &iMinSAD[0];
2691            Data.iFcode = current->fcode;
2692            Data.temp = temp;
2693    
2694            CheckCandidate = CheckCandidate16I;
2695    
2696            if (sadInit) (*sadInit) ();
2697    
2698            for (y = 0; y < pParam->mb_height; y ++) {
2699                    for (x = 0; x < pParam->mb_width; x ++) {
2700    
2701                            GMEanalyzeMB(pCurrent->y, pReference->y, pRefH->y, pRefV->y, pRefHV->y, x, y, pParam, pMBs, &Data);
2702                    }
2703            }
2704            return;
2705    }
2706    
2707    
2708    WARPPOINTS
2709    GlobalMotionEst(MACROBLOCK * const pMBs,
2710                                    const MBParam * const pParam,
2711                                    const FRAMEINFO * const current,
2712                                    const FRAMEINFO * const reference,
2713                                    const IMAGE * const pRefH,
2714                                    const IMAGE * const pRefV,
2715                                    const IMAGE * const pRefHV)
2716    {
2717    
2718            const int deltax=8;             // upper bound for difference between a MV and it's neighbour MVs
2719            const int deltay=8;
2720            const unsigned int gradx=512;           // lower bound for gradient in MB (ignore "flat" blocks)
2721            const unsigned int grady=512;
2722    
2723            double sol[4] = { 0., 0., 0., 0. };
2724    
2725            WARPPOINTS gmc;
2726    
2727            uint32_t mx, my;
2728    
2729            int MBh = pParam->mb_height;
2730            int MBw = pParam->mb_width;
2731            const int minblocks = 9; //MBh*MBw/32+3;                /* just some reasonable number 3% + 3 */
2732            const int maxblocks = MBh*MBw/4;                /* just some reasonable number 3% + 3 */
2733    
2734            int num=0;
2735            int oldnum;
2736    
2737            gmc.duv[0].x = gmc.duv[0].y = gmc.duv[1].x = gmc.duv[1].y = gmc.duv[2].x = gmc.duv[2].y = 0;
2738    
2739            GMEanalysis(pParam,current, reference, pRefH, pRefV, pRefHV);
2740    
2741            /* block based ME isn't done, yet, so do a quick presearch */
2742    
2743    // filter mask of all blocks
2744    
2745            for (my = 0; my < (uint32_t)MBh; my++)
2746            for (mx = 0; mx < (uint32_t)MBw; mx++)
2747            {
2748                    const int mbnum = mx + my * MBw;
2749                            pMBs[mbnum].mcsel = 0;
2750            }
2751    
2752    
2753            for (my = 1; my < (uint32_t)MBh-1; my++) /* ignore boundary blocks */
2754            for (mx = 1; mx < (uint32_t)MBw-1; mx++) /* theirs MVs are often wrong */
2755            {
2756                    const int mbnum = mx + my * MBw;
2757                    MACROBLOCK *const pMB = &pMBs[mbnum];
2758                    const VECTOR mv = pMB->mvs[0];
2759    
2760                    /* don't use object boundaries */
2761                    if   ( (abs(mv.x -   (pMB-1)->mvs[0].x) < deltax)
2762                            && (abs(mv.y -   (pMB-1)->mvs[0].y) < deltay)
2763                            && (abs(mv.x -   (pMB+1)->mvs[0].x) < deltax)
2764                            && (abs(mv.y -   (pMB+1)->mvs[0].y) < deltay)
2765                            && (abs(mv.x - (pMB-MBw)->mvs[0].x) < deltax)
2766                            && (abs(mv.y - (pMB-MBw)->mvs[0].y) < deltay)
2767                            && (abs(mv.x - (pMB+MBw)->mvs[0].x) < deltax)
2768                            && (abs(mv.y - (pMB+MBw)->mvs[0].y) < deltay) )
2769                    {       const int iEdgedWidth = pParam->edged_width;
2770                            const uint8_t *const pCur = current->image.y + 16*(my*iEdgedWidth + mx);
2771                            if ( (sad16 ( pCur, pCur+1 , iEdgedWidth, 65536) >= gradx )
2772                             &&  (sad16 ( pCur, pCur+iEdgedWidth, iEdgedWidth, 65536) >= grady ) )
2773                             {      pMB->mcsel = 1;
2774                                    num++;
2775                             }
2776    
2777                    /* only use "structured" blocks */
2778                    }
2779            }
2780            emms();
2781    
2782            /*      further filtering would be possible, but during iteration, remaining
2783                    outliers usually are removed, too */
2784    
2785            if (num>= minblocks)
2786            do {            /* until convergence */
2787                    double DtimesF[4];
2788                    double a,b,c,n,invdenom;
2789                    double meanx,meany;
2790    
2791                    a = b = c = n = 0;
2792                    DtimesF[0] = DtimesF[1] = DtimesF[2] = DtimesF[3] = 0.;
2793                    for (my = 1; my < (uint32_t)MBh-1; my++)
2794                    for (mx = 1; mx < (uint32_t)MBw-1; mx++)
2795                    {
2796                            const int mbnum = mx + my * MBw;
2797                            const VECTOR mv = pMBs[mbnum].mvs[0];
2798    
2799                            if (!pMBs[mbnum].mcsel)
2800                                    continue;
2801    
2802                            n++;
2803                            a += 16*mx+8;
2804                            b += 16*my+8;
2805                            c += (16*mx+8)*(16*mx+8)+(16*my+8)*(16*my+8);
2806    
2807                            DtimesF[0] += (double)mv.x;
2808                            DtimesF[1] += (double)mv.x*(16*mx+8) + (double)mv.y*(16*my+8);
2809                            DtimesF[2] += (double)mv.x*(16*my+8) - (double)mv.y*(16*mx+8);
2810                            DtimesF[3] += (double)mv.y;
2811                    }
2812    
2813            invdenom = a*a+b*b-c*n;
2814    
2815    /* Solve the system:    sol = (D'*E*D)^{-1} D'*E*F   */
2816    /* D'*E*F has been calculated in the same loop as matrix */
2817    
2818            sol[0] = -c*DtimesF[0] + a*DtimesF[1] + b*DtimesF[2];
2819            sol[1] =  a*DtimesF[0] - n*DtimesF[1]                           + b*DtimesF[3];
2820            sol[2] =  b*DtimesF[0]                          - n*DtimesF[2] - a*DtimesF[3];
2821            sol[3] =                                 b*DtimesF[1] - a*DtimesF[2] - c*DtimesF[3];
2822    
2823            sol[0] /= invdenom;
2824            sol[1] /= invdenom;
2825            sol[2] /= invdenom;
2826            sol[3] /= invdenom;
2827    
2828            meanx = meany = 0.;
2829            oldnum = 0;
2830            for (my = 1; my < (uint32_t)MBh-1; my++)
2831                    for (mx = 1; mx < (uint32_t)MBw-1; mx++)
2832                    {
2833                            const int mbnum = mx + my * MBw;
2834                            const VECTOR mv = pMBs[mbnum].mvs[0];
2835    
2836                            if (!pMBs[mbnum].mcsel)
2837                                    continue;
2838    
2839                            oldnum++;
2840                            meanx += fabs(( sol[0] + (16*mx+8)*sol[1] + (16*my+8)*sol[2] ) - (double)mv.x );
2841                            meany += fabs(( sol[3] - (16*mx+8)*sol[2] + (16*my+8)*sol[1] ) - (double)mv.y );
2842                    }
2843    
2844            if (4*meanx > oldnum)   /* better fit than 0.25 (=1/4pel) is useless */
2845                    meanx /= oldnum;
2846            else
2847                    meanx = 0.25;
2848    
2849            if (4*meany > oldnum)
2850                    meany /= oldnum;
2851            else
2852                    meany = 0.25;
2853    
2854            num = 0;
2855            for (my = 0; my < (uint32_t)MBh; my++)
2856                    for (mx = 0; mx < (uint32_t)MBw; mx++)
2857                    {
2858                            const int mbnum = mx + my * MBw;
2859                            const VECTOR mv = pMBs[mbnum].mvs[0];
2860    
2861                            if (!pMBs[mbnum].mcsel)
2862                                    continue;
2863    
2864                            if  ( ( fabs(( sol[0] + (16*mx+8)*sol[1] + (16*my+8)*sol[2] ) - (double)mv.x ) > meanx )
2865                                    || ( fabs(( sol[3] - (16*mx+8)*sol[2] + (16*my+8)*sol[1] ) - (double)mv.y ) > meany ) )
2866                                    pMBs[mbnum].mcsel=0;
2867                            else
2868                                    num++;
2869                    }
2870    
2871            } while ( (oldnum != num) && (num>= minblocks) );
2872    
2873            if (num < minblocks)
2874            {
2875                    const int iEdgedWidth = pParam->edged_width;
2876                    num = 0;
2877    
2878    /*              fprintf(stderr,"Warning! Unreliable GME (%d/%d blocks), falling back to translation.\n",num,MBh*MBw);
2879    */
2880                    gmc.duv[0].x= gmc.duv[0].y= gmc.duv[1].x= gmc.duv[1].y= gmc.duv[2].x= gmc.duv[2].y=0;
2881    
2882                    if (!(current->motion_flags & XVID_ME_GME_REFINE))
2883                            return gmc;
2884    
2885                    for (my = 1; my < (uint32_t)MBh-1; my++) /* ignore boundary blocks */
2886                    for (mx = 1; mx < (uint32_t)MBw-1; mx++) /* theirs MVs are often wrong */
2887                    {
2888                            const int mbnum = mx + my * MBw;
2889                            MACROBLOCK *const pMB = &pMBs[mbnum];
2890                            const uint8_t *const pCur = current->image.y + 16*(my*iEdgedWidth + mx);
2891                            if ( (sad16 ( pCur, pCur+1 , iEdgedWidth, 65536) >= gradx )
2892                             &&  (sad16 ( pCur, pCur+iEdgedWidth, iEdgedWidth, 65536) >= grady ) )
2893                             {      pMB->mcsel = 1;
2894                                    gmc.duv[0].x += pMB->mvs[0].x;
2895                                    gmc.duv[0].y += pMB->mvs[0].y;
2896                                    num++;
2897                             }
2898                    }
2899    
2900                    if (gmc.duv[0].x)
2901                            gmc.duv[0].x /= num;
2902                    if (gmc.duv[0].y)
2903                            gmc.duv[0].y /= num;
2904            } else {
2905    
2906                    gmc.duv[0].x=(int)(sol[0]+0.5);
2907                    gmc.duv[0].y=(int)(sol[3]+0.5);
2908    
2909                    gmc.duv[1].x=(int)(sol[1]*pParam->width+0.5);
2910                    gmc.duv[1].y=(int)(-sol[2]*pParam->width+0.5);
2911    
2912                    gmc.duv[2].x=-gmc.duv[1].y;             /* two warp points only */
2913                    gmc.duv[2].y=gmc.duv[1].x;
2914            }
2915            if (num>maxblocks)
2916            {       for (my = 1; my < (uint32_t)MBh-1; my++)
2917                    for (mx = 1; mx < (uint32_t)MBw-1; mx++)
2918                    {
2919                            const int mbnum = mx + my * MBw;
2920                            if (pMBs[mbnum-1].mcsel)
2921                                    pMBs[mbnum].mcsel=0;
2922                            else
2923                                    if (pMBs[mbnum-MBw].mcsel)
2924                                            pMBs[mbnum].mcsel=0;
2925                    }
2926            }
2927            return gmc;
2928    }
2929    
2930    int
2931    GlobalMotionEstRefine(
2932                                    WARPPOINTS *const startwp,
2933                                    MACROBLOCK * const pMBs,
2934                                    const MBParam * const pParam,
2935                                    const FRAMEINFO * const current,
2936                                    const FRAMEINFO * const reference,
2937                                    const IMAGE * const pCurr,
2938                                    const IMAGE * const pRef,
2939                                    const IMAGE * const pRefH,
2940                                    const IMAGE * const pRefV,
2941                                    const IMAGE * const pRefHV)
2942    {
2943            uint8_t* GMCblock = (uint8_t*)malloc(16*pParam->edged_width);
2944            WARPPOINTS bestwp=*startwp;
2945            WARPPOINTS centerwp,currwp;
2946            int gmcminSAD=0;
2947            int gmcSAD=0;
2948            int direction;
2949    //      int mx,my;
2950    
2951    /* use many blocks... */
2952    /*              for (my = 0; my < (uint32_t)pParam->mb_height; my++)
2953                    for (mx = 0; mx < (uint32_t)pParam->mb_width; mx++)
2954                    {
2955                            const int mbnum = mx + my * pParam->mb_width;
2956                            pMBs[mbnum].mcsel=1;
2957                    }
2958    */
2959    
2960    /* or rather don't use too many blocks... */
2961    /*
2962                    for (my = 1; my < (uint32_t)MBh-1; my++)
2963                    for (mx = 1; mx < (uint32_t)MBw-1; mx++)
2964                    {
2965                            const int mbnum = mx + my * MBw;
2966                            if (MBmask[mbnum-1])
2967                                    MBmask[mbnum-1]=0;
2968                            else
2969                                    if (MBmask[mbnum-MBw])
2970                                            MBmask[mbnum-1]=0;
2971    
2972                    }
2973    */
2974                    gmcminSAD = globalSAD(&bestwp, pParam, pMBs, current, pRef, pCurr, GMCblock);
2975    
2976                    if ( (reference->coding_type == S_VOP)
2977                            && ( (reference->warp.duv[1].x != bestwp.duv[1].x)
2978                              || (reference->warp.duv[1].y != bestwp.duv[1].y)
2979                              || (reference->warp.duv[0].x != bestwp.duv[0].x)
2980                              || (reference->warp.duv[0].y != bestwp.duv[0].y)
2981                              || (reference->warp.duv[2].x != bestwp.duv[2].x)
2982                              || (reference->warp.duv[2].y != bestwp.duv[2].y) ) )
2983                    {
2984                            gmcSAD = globalSAD(&reference->warp, pParam, pMBs,
2985                                                                    current, pRef, pCurr, GMCblock);
2986    
2987                            if (gmcSAD < gmcminSAD)
2988                            {       bestwp = reference->warp;
2989                                    gmcminSAD = gmcSAD;
2990                            }
2991                    }
2992    
2993            do {
2994                    direction = 0;
2995                    centerwp = bestwp;
2996    
2997                    currwp = centerwp;
2998    
2999                    currwp.duv[0].x--;
3000                    gmcSAD = globalSAD(&currwp, pParam, pMBs, current, pRef, pCurr, GMCblock);
3001                    if (gmcSAD < gmcminSAD)
3002                    {       bestwp = currwp;
3003                            gmcminSAD = gmcSAD;
3004                            direction = 1;
3005                    }
3006                    else
3007                    {
3008                    currwp = centerwp; currwp.duv[0].x++;
3009                    gmcSAD = globalSAD(&currwp, pParam, pMBs, current, pRef, pCurr, GMCblock);
3010                    if (gmcSAD < gmcminSAD)
3011                    {       bestwp = currwp;
3012                            gmcminSAD = gmcSAD;
3013                            direction = 2;
3014                    }
3015                    }
3016                    if (direction) continue;
3017    
3018                    currwp = centerwp; currwp.duv[0].y--;
3019                    gmcSAD = globalSAD(&currwp, pParam, pMBs, current, pRef, pCurr, GMCblock);
3020                    if (gmcSAD < gmcminSAD)
3021                    {       bestwp = currwp;
3022                            gmcminSAD = gmcSAD;
3023                            direction = 4;
3024                    }
3025                    else
3026                    {
3027                    currwp = centerwp; currwp.duv[0].y++;
3028                    gmcSAD = globalSAD(&currwp, pParam, pMBs, current, pRef, pCurr, GMCblock);
3029                    if (gmcSAD < gmcminSAD)
3030                    {       bestwp = currwp;
3031                            gmcminSAD = gmcSAD;
3032                            direction = 8;
3033                    }
3034                    }
3035                    if (direction) continue;
3036    
3037                    currwp = centerwp; currwp.duv[1].x++;
3038                    gmcSAD = globalSAD(&currwp, pParam, pMBs, current, pRef, pCurr, GMCblock);
3039                    if (gmcSAD < gmcminSAD)
3040                    {       bestwp = currwp;
3041                            gmcminSAD = gmcSAD;
3042                            direction = 32;
3043                    }
3044                    currwp.duv[2].y++;
3045                    gmcSAD = globalSAD(&currwp, pParam, pMBs, current, pRef, pCurr, GMCblock);
3046                    if (gmcSAD < gmcminSAD)
3047                    {       bestwp = currwp;
3048                            gmcminSAD = gmcSAD;
3049                            direction = 1024;
3050                    }
3051    
3052                    currwp = centerwp; currwp.duv[1].x--;
3053                    gmcSAD = globalSAD(&currwp, pParam, pMBs, current, pRef, pCurr, GMCblock);
3054                    if (gmcSAD < gmcminSAD)
3055                    {       bestwp = currwp;
3056                            gmcminSAD = gmcSAD;
3057                            direction = 16;
3058                    }
3059                    else
3060                    {
3061                    currwp = centerwp; currwp.duv[1].x++;
3062                    gmcSAD = globalSAD(&currwp, pParam, pMBs, current, pRef, pCurr, GMCblock);
3063                    if (gmcSAD < gmcminSAD)
3064                    {       bestwp = currwp;
3065                            gmcminSAD = gmcSAD;
3066                            direction = 32;
3067                    }
3068                    }
3069                    if (direction) continue;
3070    
3071    
3072                    currwp = centerwp; currwp.duv[1].y--;
3073                    gmcSAD = globalSAD(&currwp, pParam, pMBs, current, pRef, pCurr, GMCblock);
3074                    if (gmcSAD < gmcminSAD)
3075                    {       bestwp = currwp;
3076                            gmcminSAD = gmcSAD;
3077                            direction = 64;
3078                    }
3079                    else
3080                    {
3081                    currwp = centerwp; currwp.duv[1].y++;
3082                    gmcSAD = globalSAD(&currwp, pParam, pMBs, current, pRef, pCurr, GMCblock);
3083                    if (gmcSAD < gmcminSAD)
3084                    {       bestwp = currwp;
3085                            gmcminSAD = gmcSAD;
3086                            direction = 128;
3087                    }
3088                    }
3089                    if (direction) continue;
3090    
3091                    currwp = centerwp; currwp.duv[2].x--;
3092                    gmcSAD = globalSAD(&currwp, pParam, pMBs, current, pRef, pCurr, GMCblock);
3093                    if (gmcSAD < gmcminSAD)
3094                    {       bestwp = currwp;
3095                            gmcminSAD = gmcSAD;
3096                            direction = 256;
3097                    }
3098                    else
3099                    {
3100                    currwp = centerwp; currwp.duv[2].x++;
3101                    gmcSAD = globalSAD(&currwp, pParam, pMBs, current, pRef, pCurr, GMCblock);
3102                    if (gmcSAD < gmcminSAD)
3103                    {       bestwp = currwp;
3104                            gmcminSAD = gmcSAD;
3105                            direction = 512;
3106                    }
3107                    }
3108                    if (direction) continue;
3109    
3110                    currwp = centerwp; currwp.duv[2].y--;
3111                    gmcSAD = globalSAD(&currwp, pParam, pMBs, current, pRef, pCurr, GMCblock);
3112                    if (gmcSAD < gmcminSAD)
3113                    {       bestwp = currwp;
3114                            gmcminSAD = gmcSAD;
3115                            direction = 1024;
3116                    }
3117                    else
3118                    {
3119                    currwp = centerwp; currwp.duv[2].y++;
3120                    gmcSAD = globalSAD(&currwp, pParam, pMBs, current, pRef, pCurr, GMCblock);
3121                    if (gmcSAD < gmcminSAD)
3122                    {       bestwp = currwp;
3123                            gmcminSAD = gmcSAD;
3124                            direction = 2048;
3125                    }
3126                    }
3127            } while (direction);
3128            free(GMCblock);
3129    
3130            *startwp = bestwp;
3131    
3132            return gmcminSAD;
3133    }
3134    
3135    int
3136    globalSAD(const WARPPOINTS *const wp,
3137                      const MBParam * const pParam,
3138                      const MACROBLOCK * const pMBs,
3139                      const FRAMEINFO * const current,
3140                      const IMAGE * const pRef,
3141                      const IMAGE * const pCurr,
3142                      uint8_t *const GMCblock)
3143    {
3144            NEW_GMC_DATA gmc_data;
3145            int iSAD, gmcSAD=0;
3146            int num=0;
3147            unsigned int mx, my;
3148    
3149            generate_GMCparameters( 3, 3, wp, pParam->width, pParam->height, &gmc_data);
3150    
3151            for (my = 0; my < (uint32_t)pParam->mb_height; my++)
3152                    for (mx = 0; mx < (uint32_t)pParam->mb_width; mx++) {
3153    
3154                    const int mbnum = mx + my * pParam->mb_width;
3155                    const int iEdgedWidth = pParam->edged_width;
3156    
3157                    if (!pMBs[mbnum].mcsel)
3158                            continue;
3159    
3160                    gmc_data.predict_16x16(&gmc_data, GMCblock,
3161                                                    pRef->y,
3162                                                    iEdgedWidth,
3163                                                    iEdgedWidth,
3164                                                    mx, my,
3165                                                    pParam->m_rounding_type);
3166    
3167                    iSAD = sad16 ( pCurr->y + 16*(my*iEdgedWidth + mx),
3168                                                    GMCblock , iEdgedWidth, 65536);
3169                    iSAD -= pMBs[mbnum].sad16;
3170    
3171                    if (iSAD<0)
3172                            gmcSAD += iSAD;
3173                    num++;
3174            }
3175            return gmcSAD;
3176    }
3177    

Legend:
Removed from v.982  
changed lines
  Added in v.1129

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