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

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

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

trunk/xvidcore/src/motion/motion_est.c revision 115, Thu Apr 11 10:18:40 2002 UTC branches/dev-api-3/xvidcore/src/motion/motion_est.c revision 631, Thu Nov 7 10:31:03 2002 UTC
# Line 1  Line 1 
1  /**************************************************************************  /**************************************************************************
2   *   *
3   *  Modifications:   *      XVID MPEG-4 VIDEO CODEC
4     *      motion estimation
5   *   *
6   *  02.04.2002 add EPZS(^2) as ME algorithm, use PMV_USESQUARES to choose between   *      This program is an implementation of a part of one or more MPEG-4
7   *             EPZS and EPZS^2   *      Video tools as specified in ISO/IEC 14496-2 standard.  Those intending
8   *  08.02.2002 split up PMVfast into three routines: PMVFast, PMVFast_MainLoop   *      to use this software module in hardware or software products are
9   *             PMVFast_Refine to support multiple searches with different start points   *      advised that its use may infringe existing patents or copyrights, and
10   *  07.01.2002 uv-block-based interpolation   *      any such use would be at such party's own risk.  The original
11   *  06.01.2002 INTER/INTRA-decision is now done before any SEARCH8 (speedup)   *      developer of this software module and his/her company, and subsequent
12   *             changed INTER_BIAS to 150 (as suggested by suxen_drol)   *      editors and their companies, will have no liability for use of this
13   *             removed halfpel refinement step in PMVfastSearch8 + quality=5   *      software or modifications or derivatives thereof.
  *             added new quality mode = 6 which performs halfpel refinement  
  *             filesize difference between quality 5 and 6 is smaller than 1%  
  *             (Isibaar)  
  *  31.12.2001 PMVfastSearch16 and PMVfastSearch8 (gruel)  
  *  30.12.2001 get_range/MotionSearchX simplified; blue/green bug fix  
  *  22.12.2001 commented best_point==99 check  
  *  19.12.2001 modified get_range (purple bug fix)  
  *  15.12.2001 moved pmv displacement from mbprediction  
  *  02.12.2001 motion estimation/compensation split (Isibaar)  
  *  16.11.2001 rewrote/tweaked search algorithms; pross@cs.rmit.edu.au  
  *  10.11.2001 support for sad16/sad8 functions  
  *  28.08.2001 reactivated MODE_INTER4V for EXT_MODE  
  *  24.08.2001 removed MODE_INTER4V_Q, disabled MODE_INTER4V for EXT_MODE  
  *  22.08.2001 added MODE_INTER4V_Q  
  *  20.08.2001 added pragma to get rid of internal compiler error with VC6  
  *             idea by Cyril. Thanks.  
14   *   *
15   *  Michael Militzer <isibaar@videocoding.de>   *      This program is free software; you can redistribute it and/or modify
16     *      it under the terms of the GNU General Public License as published by
17     *      the Free Software Foundation; either version 2 of the License, or
18     *      (at your option) any later version.
19   *   *
20   **************************************************************************/   *      This program is distributed in the hope that it will be useful,
21     *      but WITHOUT ANY WARRANTY; without even the implied warranty of
22     *      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
23     *      GNU General Public License for more details.
24     *
25     *      You should have received a copy of the GNU General Public License
26     *      along with this program; if not, write to the Free Software
27     *      Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
28     *
29     *************************************************************************/
30    
31  #include <assert.h>  #include <assert.h>
32  #include <stdio.h>  #include <stdio.h>
# Line 40  Line 37 
37  #include "../prediction/mbprediction.h"  #include "../prediction/mbprediction.h"
38  #include "../global.h"  #include "../global.h"
39  #include "../utils/timer.h"  #include "../utils/timer.h"
40    #include "../image/interpolate8x8.h"
41    #include "motion_est.h"
42    #include "motion.h"
43  #include "sad.h"  #include "sad.h"
44    #include "../utils/emms.h"
45    
46  // very large value  #define INITIAL_SKIP_THRESH     (10)
47  #define MV_MAX_ERROR    (4096 * 256)  #define FINAL_SKIP_THRESH       (50)
48    #define MAX_SAD00_FOR_SKIP      (20)
49    #define MAX_CHROMA_SAD_FOR_SKIP (22)
50    #define SKIP_THRESH_B (25)
51    
52  // stop search if sdelta < THRESHOLD  #define CHECK_CANDIDATE(X,Y,D) { \
53  #define MV16_THRESHOLD  192  (*CheckCandidate)((const int)(X),(const int)(Y), (D), &iDirection, data ); }
 #define MV8_THRESHOLD   56  
54    
55  /* sad16(0,0) bias; mpeg4 spec suggests nb/2+1 */  #define GET_REFERENCE(X, Y, REF) { \
56  /* nb  = vop pixels * 2^(bpp-8) */          switch ( (((X)&1)<<1) + ((Y)&1) ) \
57  #define MV16_00_BIAS    (128+1)          { \
58                    case 0 : REF = (uint8_t *)data->Ref + (X)/2 + ((Y)/2)*(data->iEdgedWidth); break; \
59                    case 1 : REF = (uint8_t *)data->RefV + (X)/2 + (((Y)-1)/2)*(data->iEdgedWidth); break; \
60                    case 2 : REF = (uint8_t *)data->RefH + ((X)-1)/2 + ((Y)/2)*(data->iEdgedWidth); break; \
61                    default : REF = (uint8_t *)data->RefHV + ((X)-1)/2 + (((Y)-1)/2)*(data->iEdgedWidth); break; \
62            } \
63    }
64    
65  /* INTER bias for INTER/INTRA decision; mpeg4 spec suggests 2*nb */  #define iDiamondSize 2
 #define INTER_BIAS      512  
66    
67  /* Parameters which control inter/inter4v decision */  static __inline int
68  #define IMV16X16                        5  d_mv_bits(int x, int y, const uint32_t iFcode)
69    {
70            int xb, yb;
71    
72  /* vector map (vlc delta size) smoother parameters */          if (x == 0) xb = 1;
73  #define NEIGH_TEND_16X16        2          else {
74  #define NEIGH_TEND_8X8          2                  if (x < 0) x = -x;
75                    x += (1 << (iFcode - 1)) - 1;
76                    x >>= (iFcode - 1);
77                    if (x > 32) x = 32;
78                    xb = mvtab[x] + iFcode;
79            }
80    
81            if (y == 0) yb = 1;
82            else {
83                    if (y < 0) y = -y;
84                    y += (1 << (iFcode - 1)) - 1;
85                    y >>= (iFcode - 1);
86                    if (y > 32) y = 32;
87                    yb = mvtab[y] + iFcode;
88            }
89            return xb + yb;
90    }
91    
92  // fast ((A)/2)*2  static int32_t
93  #define EVEN(A)         (((A)<0?(A)+1:(A)) & ~1)  ChromaSAD(int dx, int dy, const SearchData * const data)
94    {
95            int sad;
96            dx = (dx >> 1) + roundtab_79[dx & 0x3];
97            dy = (dy >> 1) + roundtab_79[dy & 0x3];
98    
99            switch (((dx & 1) << 1) + (dy & 1))     { // ((dx%2)?2:0)+((dy%2)?1:0)
100                    case 0:
101                            sad = sad8(data->CurU, data->RefCU + (dy/2) * (data->iEdgedWidth/2) + dx/2, data->iEdgedWidth/2);
102                            sad += sad8(data->CurV, data->RefCV + (dy/2) * (data->iEdgedWidth/2) + dx/2, data->iEdgedWidth/2);
103                            break;
104                    case 1:
105                            dx = dx / 2; dy = (dy - 1) / 2;
106                            sad = sad8bi(data->CurU, data->RefCU + dy * (data->iEdgedWidth/2) + dx, data->RefCU + (dy+1) * (data->iEdgedWidth/2) + dx, data->iEdgedWidth/2);
107                            sad += sad8bi(data->CurV, data->RefCV + dy * (data->iEdgedWidth/2) + dx, data->RefCV + (dy+1) * (data->iEdgedWidth/2) + dx, data->iEdgedWidth/2);
108                            break;
109                    case 2:
110                            dx = (dx - 1) / 2; dy = dy / 2;
111                            sad = sad8bi(data->CurU, data->RefCU + dy * (data->iEdgedWidth/2) + dx, data->RefCU + dy * (data->iEdgedWidth/2) + dx+1, data->iEdgedWidth/2);
112                            sad += sad8bi(data->CurV, data->RefCV + dy * (data->iEdgedWidth/2) + dx, data->RefCV + dy * (data->iEdgedWidth/2) + dx+1, data->iEdgedWidth/2);
113                            break;
114                    default:
115                            dx = (dx - 1) / 2; dy = (dy - 1) / 2;
116                            interpolate8x8_halfpel_hv(data->RefQ,
117                                                                             data->RefCU + dy * (data->iEdgedWidth/2) + dx, data->iEdgedWidth/2,
118                                                                             data->rounding);
119                            sad = sad8(data->CurU, data->RefQ, data->iEdgedWidth/2);
120                            interpolate8x8_halfpel_hv(data->RefQ,
121                                                                             data->RefCV + dy * (data->iEdgedWidth/2) + dx, data->iEdgedWidth/2,
122                                                                             data->rounding);
123                            sad += sad8(data->CurV, data->RefQ, data->iEdgedWidth/2);
124                            break;
125            }
126            return sad;
127    }
128    
 #define MIN(X, Y) ((X)<(Y)?(X):(Y))  
 #define MAX(X, Y) ((X)>(Y)?(X):(Y))  
 #define ABS(X)    (((X)>0)?(X):-(X))  
 #define SIGN(X)   (((X)>0)?1:-1)  
129    
130  int32_t PMVfastSearch16(  /* CHECK_CANDIATE FUNCTIONS START */
                                         const uint8_t * const pRef,  
                                         const uint8_t * const pRefH,  
                                         const uint8_t * const pRefV,  
                                         const uint8_t * const pRefHV,  
                                         const IMAGE * const pCur,  
                                         const int x, const int y,  
                                         const uint32_t MotionFlags,  
                                         const MBParam * const pParam,  
                                         MACROBLOCK * const pMBs,  
                                         VECTOR * const currMV,  
                                         VECTOR * const currPMV);  
131    
 int32_t EPZSSearch16(  
                                         const uint8_t * const pRef,  
                                         const uint8_t * const pRefH,  
                                         const uint8_t * const pRefV,  
                                         const uint8_t * const pRefHV,  
                                         const IMAGE * const pCur,  
                                         const int x, const int y,  
                                         const uint32_t MotionFlags,  
                                         const MBParam * const pParam,  
                                         MACROBLOCK * const pMBs,  
                                         VECTOR * const currMV,  
                                         VECTOR * const currPMV);  
132    
133    static void
134    CheckCandidate16(const int x, const int y, const int Direction, int * const dir, const SearchData * const data)
135    {
136            int t;
137            const uint8_t * Reference;
138    
139  int32_t PMVfastSearch8(          if (( x > data->max_dx) || ( x < data->min_dx)
140                                          const uint8_t * const pRef,                  || ( y > data->max_dy) || (y < data->min_dy)) return;
                                         const uint8_t * const pRefH,  
                                         const uint8_t * const pRefV,  
                                         const uint8_t * const pRefHV,  
                                         const IMAGE * const pCur,  
                                         const int x, const int y,  
                                         const int start_x, int start_y,  
                                         const uint32_t MotionFlags,  
                                         const MBParam * const pParam,  
                                         MACROBLOCK * const pMBs,  
                                         VECTOR * const currMV,  
                                         VECTOR * const currPMV);  
141    
142  int32_t EPZSSearch8(          switch ( ((x&1)<<1) + (y&1) ) {
143                                          const uint8_t * const pRef,                  case 0 : Reference = data->Ref + x/2 + (y/2)*(data->iEdgedWidth); break;
144                                          const uint8_t * const pRefH,                  case 1 : Reference = data->RefV + x/2 + ((y-1)/2)*(data->iEdgedWidth); break;
145                                          const uint8_t * const pRefV,                  case 2 : Reference = data->RefH + (x-1)/2 + (y/2)*(data->iEdgedWidth); break;
146                                          const uint8_t * const pRefHV,                  default : Reference = data->RefHV + (x-1)/2 + ((y-1)/2)*(data->iEdgedWidth); break;
147                                          const IMAGE * const pCur,          }
                                         const int x, const int y,  
                                         const int start_x, int start_y,  
                                         const uint32_t MotionFlags,  
                                         const MBParam * const pParam,  
                                         MACROBLOCK * const pMBs,  
                                         VECTOR * const currMV,  
                                         VECTOR * const currPMV);  
148    
149            data->temp[0] = sad16v(data->Cur, Reference, data->iEdgedWidth, data->temp + 1);
150    
151  typedef int32_t (MainSearch16Func)(          if (data->qpel) t = d_mv_bits(2*x - data->predQMV.x, 2*y - data->predQMV.y, data->iFcode);
152          const uint8_t * const pRef,          else t = d_mv_bits(x - data->predMV.x, y - data->predMV.y, data->iFcode);
         const uint8_t * const pRefH,  
         const uint8_t * const pRefV,  
         const uint8_t * const pRefHV,  
         const uint8_t * const cur,  
         const int x, const int y,  
         int32_t startx, int32_t starty,  
         int32_t iMinSAD,  
         VECTOR * const currMV,  
         const VECTOR * const pmv,  
         const int32_t min_dx, const int32_t max_dx,  
         const int32_t min_dy, const int32_t max_dy,  
         const int32_t iEdgedWidth,  
         const int32_t iDiamondSize,  
         const int32_t iFcode,  
         const int32_t iQuant,  
         int iFound);  
153    
154  typedef MainSearch16Func* MainSearch16FuncPtr;          data->temp[0] += (data->lambda16 * t * data->temp[0])/1000;
155            data->temp[1] += (data->lambda8 * t * (data->temp[1] + NEIGH_8X8_BIAS))/100;
156    
157            if (data->chroma) data->temp[0] += ChromaSAD(x, y, data);
158    
159  typedef int32_t (MainSearch8Func)(          if (data->temp[0] < data->iMinSAD[0]) {
160          const uint8_t * const pRef,                  data->iMinSAD[0] = data->temp[0];
161          const uint8_t * const pRefH,                  data->currentMV[0].x = x; data->currentMV[0].y = y;
162          const uint8_t * const pRefV,                  *dir = Direction; }
         const uint8_t * const pRefHV,  
         const uint8_t * const cur,  
         const int x, const int y,  
         int32_t startx, int32_t starty,  
         int32_t iMinSAD,  
         VECTOR * const currMV,  
         const VECTOR * const pmv,  
         const int32_t min_dx, const int32_t max_dx,  
         const int32_t min_dy, const int32_t max_dy,  
         const int32_t iEdgedWidth,  
         const int32_t iDiamondSize,  
         const int32_t iFcode,  
         const int32_t iQuant,  
         int iFound);  
   
 typedef MainSearch8Func* MainSearch8FuncPtr;  
   
 // mv.length table  
 static const uint32_t mvtab[33] = {  
     1,  2,  3,  4,  6,  7,  7,  7,  
     9,  9,  9,  10, 10, 10, 10, 10,  
     10, 10, 10, 10, 10, 10, 10, 10,  
     10, 11, 11, 11, 11, 11, 11, 12, 12  
 };  
163    
164            if (data->temp[1] < data->iMinSAD[1]) {
165                    data->iMinSAD[1] = data->temp[1]; data->currentMV[1].x = x; data->currentMV[1].y = y; }
166            if (data->temp[2] < data->iMinSAD[2]) {
167                    data->iMinSAD[2] = data->temp[2]; data->currentMV[2].x = x; data->currentMV[2].y = y; }
168            if (data->temp[3] < data->iMinSAD[3]) {
169                    data->iMinSAD[3] = data->temp[3]; data->currentMV[3].x = x; data->currentMV[3].y = y; }
170            if (data->temp[4] < data->iMinSAD[4]) {
171                    data->iMinSAD[4] = data->temp[4]; data->currentMV[4].x = x; data->currentMV[4].y = y; }
172    
173  static __inline uint32_t mv_bits(int32_t component, const uint32_t iFcode)  }
174    
175    static void
176    CheckCandidate16no4v(const int x, const int y, const int Direction, int * const dir, const SearchData * const data)
177  {  {
178      if (component == 0)          int32_t sad;
179                  return 1;          const uint8_t * Reference;
180    
181      if (component < 0)          if (( x > data->max_dx) || ( x < data->min_dx)
182                  component = -component;                  || ( y > data->max_dy) || (y < data->min_dy)) return;
183    
184      if (iFcode == 1)          switch ( ((x&1)<<1) + (y&1) )
185      {      {
186                  if (component > 32)                  case 0 : Reference = data->Ref + x/2 + (y/2)*(data->iEdgedWidth); break;
187                      component = 32;                  case 1 : Reference = data->RefV + x/2 + ((y-1)/2)*(data->iEdgedWidth); break;
188                    case 2 : Reference = data->RefH + (x-1)/2 + (y/2)*(data->iEdgedWidth); break;
189                  return mvtab[component] + 1;                  default : Reference = data->RefHV + (x-1)/2 + ((y-1)/2)*(data->iEdgedWidth); break;
190      }      }
191    
192      component += (1 << (iFcode - 1)) - 1;          sad = sad16(data->Cur, Reference, data->iEdgedWidth, MV_MAX_ERROR);
193      component >>= (iFcode - 1);          sad += (data->lambda16 * d_mv_bits(x - data->predMV.x, y - data->predMV.y, data->iFcode) * sad)/1000;
   
     if (component > 32)  
                 component = 32;  
194    
195      return mvtab[component] + 1 + iFcode - 1;          if (sad < *(data->iMinSAD)) {
196                    *(data->iMinSAD) = sad;
197                    data->currentMV[0].x = x; data->currentMV[0].y = y;
198                    *dir = Direction; }
199  }  }
200    
201    static void
202    CheckCandidate16_qpel(const int x, const int y, const int Direction, int * const dir, const SearchData * const data)
203    
204  static __inline uint32_t calc_delta_16(const int32_t dx, const int32_t dy, const uint32_t iFcode)  // CheckCandidate16 variant which expects x and y in quarter pixel resolution
205    // Important: This is no general usable routine! x and y must be +/-1 (qpel resolution!)
206    // around currentMV!
207  {  {
208          return NEIGH_TEND_16X16 * (mv_bits(dx, iFcode) + mv_bits(dy, iFcode));          int t;
209  }          uint8_t * Reference = (uint8_t *)data->RefQ;
210            const uint8_t *ref1, *ref2, *ref3, *ref4;
211            VECTOR halfpelMV = *(data->currentMV);
212    
213  static __inline uint32_t calc_delta_8(const int32_t dx, const int32_t dy, const uint32_t iFcode)          int32_t iEdgedWidth = data->iEdgedWidth;
214            uint32_t rounding = data->rounding;
215    
216  {          if (( x > data->max_dx) || ( x < data->min_dx)
217      return NEIGH_TEND_8X8 * (mv_bits(dx, iFcode) + mv_bits(dy, iFcode));                  || ( y > data->max_dy) || (y < data->min_dy)) return;
 }  
218    
219            GET_REFERENCE(halfpelMV.x, halfpelMV.y, ref1); // this refenrence is used in all cases
220            switch( ((x&1)<<1) + (y&1) )
221            {
222            case 0: // pure halfpel position - shouldn't happen during a refinement step
223                    GET_REFERENCE(halfpelMV.x, halfpelMV.y, Reference);
224                    break;
225    
226            case 1: // x halfpel, y qpel - top or bottom during qpel refinement
227                    GET_REFERENCE(halfpelMV.x, y - halfpelMV.y, ref2);
228                    interpolate8x8_avg2(Reference, ref1, ref2, iEdgedWidth, rounding);
229                    interpolate8x8_avg2(Reference+8, ref1+8, ref2+8, iEdgedWidth, rounding);
230                    interpolate8x8_avg2(Reference+8*iEdgedWidth, ref1+8*iEdgedWidth, ref2+8*iEdgedWidth, iEdgedWidth, rounding);
231                    interpolate8x8_avg2(Reference+8*iEdgedWidth+8, ref1+8*iEdgedWidth+8, ref2+8*iEdgedWidth+8, iEdgedWidth, rounding);
232                    break;
233    
234            case 2: // x qpel, y halfpel - left or right during qpel refinement
235                    GET_REFERENCE(x - halfpelMV.x, halfpelMV.y, ref2);
236                    interpolate8x8_avg2(Reference, ref1, ref2, iEdgedWidth, rounding);
237                    interpolate8x8_avg2(Reference+8, ref1+8, ref2+8, iEdgedWidth, rounding);
238                    interpolate8x8_avg2(Reference+8*iEdgedWidth, ref1+8*iEdgedWidth, ref2+8*iEdgedWidth, iEdgedWidth, rounding);
239                    interpolate8x8_avg2(Reference+8*iEdgedWidth+8, ref1+8*iEdgedWidth+8, ref2+8*iEdgedWidth+8, iEdgedWidth, rounding);
240                    break;
241    
242  /* calculate the min/max range (in halfpixels)          default: // x and y in qpel resolution - the "corners" (top left/right and
243          relative to the _MACROBLOCK_ position                           // bottom left/right) during qpel refinement
244  */                  GET_REFERENCE(halfpelMV.x, y - halfpelMV.y, ref2);
245                    GET_REFERENCE(x - halfpelMV.x, halfpelMV.y, ref3);
246                    GET_REFERENCE(x - halfpelMV.x, y - halfpelMV.y, ref4);
247    
248                    interpolate8x8_avg4(Reference, ref1, ref2, ref3, ref4, iEdgedWidth, rounding);
249                    interpolate8x8_avg4(Reference+8, ref1+8, ref2+8, ref3+8, ref4+8, iEdgedWidth, rounding);
250                    interpolate8x8_avg4(Reference+8*iEdgedWidth, ref1+8*iEdgedWidth, ref2+8*iEdgedWidth, ref3+8*iEdgedWidth, ref4+8*iEdgedWidth, iEdgedWidth, rounding);
251                    interpolate8x8_avg4(Reference+8*iEdgedWidth+8, ref1+8*iEdgedWidth+8, ref2+8*iEdgedWidth+8, ref3+8*iEdgedWidth+8, ref4+8*iEdgedWidth+8, iEdgedWidth, rounding);
252                    break;
253            }
254    
255  static void __inline get_range(          data->temp[0] = sad16v(data->Cur, Reference, data->iEdgedWidth, data->temp+1);
         int32_t * const min_dx, int32_t * const max_dx,  
         int32_t * const min_dy, int32_t * const max_dy,  
         const uint32_t x, const uint32_t y,  
         const uint32_t block_sz,                                        // block dimension, 8 or 16  
         const uint32_t width, const uint32_t height,  
         const uint32_t fcode)  
 {  
256    
257          const int search_range = 32 << (fcode - 1);          t = d_mv_bits(x - data->predQMV.x, y - data->predQMV.y, data->iFcode);
258          const int high = search_range - 1;          data->temp[0] += (data->lambda16 * t * data->temp[0])/1000;
259          const int low = -search_range;          data->temp[1] += (data->lambda8 * t * (data->temp[1] + NEIGH_8X8_BIAS))/100;
260    
261          // convert full-pixel measurements to half pixel          if (data->chroma)
262          const int hp_width = 2 * width;                  data->temp[0] += ChromaSAD(x/2, y/2, data);
         const int hp_height = 2 * height;  
         const int hp_edge = 2 * block_sz;  
         const int hp_x = 2 * (x) * block_sz;            // we need _right end_ of block, not x-coordinate  
         const int hp_y = 2 * (y) * block_sz;            // same for _bottom end_  
263    
264          *max_dx = MIN(high,     hp_width - hp_x);          if (data->temp[0] < data->iMinSAD[0]) {
265          *max_dy = MIN(high,     hp_height - hp_y);                  data->iMinSAD[0] = data->temp[0];
266          *min_dx = MAX(low,      -(hp_edge + hp_x));                  data->currentQMV[0].x = x; data->currentQMV[0].y = y;
267          *min_dy = MAX(low,      -(hp_edge + hp_y));          /*      *dir = Direction;*/ }
268    
269            if (data->temp[1] < data->iMinSAD[1]) {
270                    data->iMinSAD[1] = data->temp[1]; data->currentQMV[1].x = x; data->currentQMV[1].y = y; }
271            if (data->temp[2] < data->iMinSAD[2]) {
272                    data->iMinSAD[2] = data->temp[2]; data->currentQMV[2].x = x; data->currentQMV[2].y = y; }
273            if (data->temp[3] < data->iMinSAD[3]) {
274                    data->iMinSAD[3] = data->temp[3]; data->currentQMV[3].x = x; data->currentQMV[3].y = y; }
275            if (data->temp[4] < data->iMinSAD[4]) {
276                    data->iMinSAD[4] = data->temp[4]; data->currentQMV[4].x = x; data->currentQMV[4].y = y; }
277  }  }
278    
279    static void
280  /*  CheckCandidate16no4vI(const int x, const int y, const int Direction, int * const dir, const SearchData * const data)
  * getref: calculate reference image pointer  
  * the decision to use interpolation h/v/hv or the normal image is  
  * based on dx & dy.  
  */  
   
 static __inline const uint8_t * get_ref(  
         const uint8_t * const refn,  
         const uint8_t * const refh,  
         const uint8_t * const refv,  
         const uint8_t * const refhv,  
         const uint32_t x, const uint32_t y,  
         const uint32_t block,                                   // block dimension, 8 or 16  
         const int32_t dx, const int32_t dy,  
         const uint32_t stride)  
281  {  {
282            int32_t sad;
283    
284          switch ( ((dx&1)<<1) + (dy&1) )         // ((dx%2)?2:0)+((dy%2)?1:0)          if (( x > data->max_dx) || ( x < data->min_dx)
285          {                  || ( y > data->max_dy) || (y < data->min_dy)) return;
         case 0  : return refn + (x*block+dx/2) + (y*block+dy/2)*stride;  
         case 1  : return refv + (x*block+dx/2) + (y*block+(dy-1)/2)*stride;  
         case 2  : return refh + (x*block+(dx-1)/2) + (y*block+dy/2)*stride;  
         default :  
         case 3  : return refhv + (x*block+(dx-1)/2) + (y*block+(dy-1)/2)*stride;  
         }  
286    
287  }          sad = sad16(data->Cur, data->Ref + x/2 + (y/2)*(data->iEdgedWidth),
288                                            data->iEdgedWidth, 256*4096);
289    
290            if (sad < *(data->iMinSAD)) {
291                    *(data->iMinSAD) = sad;
292                    data->currentMV[0].x = x; data->currentMV[0].y = y;
293                    *dir = Direction; }
294    }
295    
 /* This is somehow a copy of get_ref, but with MV instead of X,Y */  
296    
297  static __inline const uint8_t * get_ref_mv(  static void
298          const uint8_t * const refn,  CheckCandidateInt(const int xf, const int yf, const int Direction, int * const dir, const SearchData * const data)
         const uint8_t * const refh,  
         const uint8_t * const refv,  
         const uint8_t * const refhv,  
         const uint32_t x, const uint32_t y,  
         const uint32_t block,                   // block dimension, 8 or 16  
         const VECTOR* mv,       // measured in half-pel!  
         const uint32_t stride)  
299  {  {
300            int32_t sad;
301            const int xb = data->currentMV[1].x;
302            const int yb = data->currentMV[1].y;
303            const uint8_t *ReferenceF, *ReferenceB;
304    
305          switch ( (((mv->x)&1)<<1) + ((mv->y)&1) )          if (( xf > data->max_dx) || ( xf < data->min_dx)
306          {                  || ( yf > data->max_dy) || (yf < data->min_dy)) return;
307          case 0  : return refn + (x*block+(mv->x)/2) + (y*block+(mv->y)/2)*stride;  
308          case 1  : return refv + (x*block+(mv->x)/2) + (y*block+((mv->y)-1)/2)*stride;          switch ( ((xf&1)<<1) + (yf&1) ) {
309          case 2  : return refh + (x*block+((mv->x)-1)/2) + (y*block+(mv->y)/2)*stride;                  case 0 : ReferenceF = data->Ref + xf/2 + (yf/2)*(data->iEdgedWidth); break;
310          default :                  case 1 : ReferenceF = data->RefV + xf/2 + ((yf-1)/2)*(data->iEdgedWidth); break;
311          case 3  : return refhv + (x*block+((mv->x)-1)/2) + (y*block+((mv->y)-1)/2)*stride;                  case 2 : ReferenceF = data->RefH + (xf-1)/2 + (yf/2)*(data->iEdgedWidth); break;
312                    default : ReferenceF = data->RefHV + (xf-1)/2 + ((yf-1)/2)*(data->iEdgedWidth); break;
313          }          }
314    
315            switch ( ((xb&1)<<1) + (yb&1) ) {
316                    case 0 : ReferenceB = data->bRef + xb/2 + (yb/2)*(data->iEdgedWidth); break;
317                    case 1 : ReferenceB = data->bRefV + xb/2 + ((yb-1)/2)*(data->iEdgedWidth); break;
318                    case 2 : ReferenceB = data->bRefH + (xb-1)/2 + (yb/2)*(data->iEdgedWidth); break;
319                    default : ReferenceB = data->bRefHV + (xb-1)/2 + ((yb-1)/2)*(data->iEdgedWidth); break;
320  }  }
321    
322  #ifndef SEARCH16          sad = sad16bi(data->Cur, ReferenceF, ReferenceB, data->iEdgedWidth);
 #define SEARCH16        PMVfastSearch16  
 //#define SEARCH16      FullSearch16  
 //#define SEARCH16      EPZSSearch16  
 #endif  
323    
324  #ifndef SEARCH8          sad += (data->lambda16 *
325  #define SEARCH8         PMVfastSearch8                          ( d_mv_bits(xf - data->predMV.x, yf - data->predMV.y, data->iFcode) +
326  //#define SEARCH8       EPZSSearch8                            d_mv_bits(xb - data->bpredMV.x, yb - data->bpredMV.y, data->iFcode)) * sad)/1000;
 #endif  
327    
328  bool MotionEstimation(          if (sad < *(data->iMinSAD)) {
329          MACROBLOCK * const pMBs,                  *(data->iMinSAD) = sad;
330          MBParam * const pParam,                  data->currentMV->x = xf; data->currentMV->y = yf;
331          const IMAGE * const pRef,                  *dir = Direction; }
332          const IMAGE * const pRefH,  }
         const IMAGE * const pRefV,  
         const IMAGE * const pRefHV,  
         IMAGE * const pCurrent,  
         const uint32_t iLimit)  
333    
334    static void
335    CheckCandidateDirect(const int x, const int y, const int Direction, int * const dir, const SearchData * const data)
336  {  {
337          const uint32_t iWcount = pParam->mb_width;          int32_t sad = 0;
338          const uint32_t iHcount = pParam->mb_height;          int k;
339            const uint8_t *ReferenceF;
340          uint32_t i, j, iIntra = 0;          const uint8_t *ReferenceB;
341            VECTOR mvs, b_mvs;
         VECTOR mv16;  
         VECTOR pmv16;  
   
         int32_t sad8 = 0;  
         int32_t sad16;  
         int32_t deviation;  
342    
343          if (sadInit);          if (( x > 31) || ( x < -32) || ( y > 31) || (y < -32)) return;
                 (*sadInit)();  
344    
345          // note: i==horizontal, j==vertical          for (k = 0; k < 4; k++) {
346          for (i = 0; i < iHcount; i++)                  mvs.x = data->directmvF[k].x + x;
347                  for (j = 0; j < iWcount; j++)                  b_mvs.x = ((x == 0) ?
348                  {                          data->directmvB[k].x
349                          MACROBLOCK *pMB = &pMBs[j + i * iWcount];                          : mvs.x - data->referencemv[k].x);
350    
351                          sad16 = SEARCH16(pRef->y, pRefH->y, pRefV->y, pRefHV->y, pCurrent,                  mvs.y = data->directmvF[k].y + y;
352                                           j, i, pParam->motion_flags,                  b_mvs.y = ((y == 0) ?
353                                           pParam, pMBs, &mv16, &pmv16);                          data->directmvB[k].y
354                          pMB->sad16=sad16;                          : mvs.y - data->referencemv[k].y);
355    
356                    if (( mvs.x > data->max_dx ) || ( mvs.x < data->min_dx )
357                            || ( mvs.y > data->max_dy ) || ( mvs.y < data->min_dy )
358                            || ( b_mvs.x > data->max_dx ) || ( b_mvs.x < data->min_dx )
359                            || ( b_mvs.y > data->max_dy ) || ( b_mvs.y < data->min_dy )) return;
360    
361                          /* decide: MODE_INTER or MODE_INTRA                  switch ( ((mvs.x&1)<<1) + (mvs.y&1) ) {
362                             if (dev_intra < sad_inter - 2 * nb) use_intra                          case 0 : ReferenceF = data->Ref + mvs.x/2 + (mvs.y/2)*(data->iEdgedWidth); break;
363                          */                          case 1 : ReferenceF = data->RefV + mvs.x/2 + ((mvs.y-1)/2)*(data->iEdgedWidth); break;
364                            case 2 : ReferenceF = data->RefH + (mvs.x-1)/2 + (mvs.y/2)*(data->iEdgedWidth); break;
365                            default : ReferenceF = data->RefHV + (mvs.x-1)/2 + ((mvs.y-1)/2)*(data->iEdgedWidth); break;
366                    }
367    
368                          deviation = dev16(pCurrent->y + j*16 + i*16*pParam->edged_width, pParam->edged_width);                  switch ( ((b_mvs.x&1)<<1) + (b_mvs.y&1) ) {
369                            case 0 : ReferenceB = data->bRef + b_mvs.x/2 + (b_mvs.y/2)*(data->iEdgedWidth); break;
370                            case 1 : ReferenceB = data->bRefV + b_mvs.x/2 + ((b_mvs.y-1)/2)*(data->iEdgedWidth); break;
371                            case 2 : ReferenceB = data->bRefH + (b_mvs.x-1)/2 + (b_mvs.y/2)*(data->iEdgedWidth); break;
372                            default : ReferenceB = data->bRefHV + (b_mvs.x-1)/2 + ((b_mvs.y-1)/2)*(data->iEdgedWidth); break;
373                    }
374    
375                          if (deviation < (sad16 - INTER_BIAS))                  sad += sad8bi(data->Cur + 8*(k&1) + 8*(k>>1)*(data->iEdgedWidth),
376                          {                                                  ReferenceF + 8*(k&1) + 8*(k>>1)*(data->iEdgedWidth),
377                                  pMB->mode = MODE_INTRA;                                                  ReferenceB + 8*(k&1) + 8*(k>>1)*(data->iEdgedWidth),
378                                  pMB->mvs[0].x = pMB->mvs[1].x = pMB->mvs[2].x = pMB->mvs[3].x = 0;                                                  data->iEdgedWidth);
379                                  pMB->mvs[0].y = pMB->mvs[1].y = pMB->mvs[2].y = pMB->mvs[3].y = 0;                  if (sad > *(data->iMinSAD)) return;
380            }
381    
382                                  iIntra++;          sad += (data->lambda16 * d_mv_bits(x, y, 1) * sad)/1000;
                                 if(iIntra >= iLimit)  
                                         return 1;  
383    
384                                  continue;          if (sad < *(data->iMinSAD)) {
385                    *(data->iMinSAD) = sad;
386                    data->currentMV->x = x; data->currentMV->y = y;
387                    *dir = Direction; }
388                          }                          }
389    
390                          if (pParam->global_flags & XVID_INTER4V)  static void
391    CheckCandidateDirectno4v(const int x, const int y, const int Direction, int * const dir, const SearchData * const data)
392                          {                          {
393                                  pMB->sad8[0] = SEARCH8(pRef->y, pRefH->y, pRefV->y, pRefHV->y, pCurrent,          int32_t sad;
394                                                         2 * j, 2 * i, mv16.x, mv16.y, pParam->motion_flags,          const uint8_t *ReferenceF;
395                                                         pParam, pMBs, &pMB->mvs[0], &pMB->pmvs[0]);          const uint8_t *ReferenceB;
396            VECTOR mvs, b_mvs;
397    
398                                  pMB->sad8[1] = SEARCH8(pRef->y, pRefH->y, pRefV->y, pRefHV->y, pCurrent,          if (( x > 31) || ( x < -32) || ( y > 31) || (y < -32)) return;
                                                        2 * j + 1, 2 * i, mv16.x, mv16.y, pParam->motion_flags,  
                                                        pParam, pMBs, &pMB->mvs[1], &pMB->pmvs[1]);  
399    
400                                  pMB->sad8[2] = SEARCH8(pRef->y, pRefH->y, pRefV->y, pRefHV->y, pCurrent,          mvs.x = data->directmvF[0].x + x;
401                                                         2 * j, 2 * i + 1, mv16.x, mv16.y, pParam->motion_flags,          b_mvs.x = ((x == 0) ?
402                                                         pParam, pMBs, &pMB->mvs[2], &pMB->pmvs[2]);                  data->directmvB[0].x
403                    : mvs.x - data->referencemv[0].x);
404    
405                                  pMB->sad8[3] = SEARCH8(pRef->y, pRefH->y, pRefV->y, pRefHV->y, pCurrent,          mvs.y = data->directmvF[0].y + y;
406                                                         2 * j + 1, 2 * i + 1, mv16.x, mv16.y, pParam->motion_flags,          b_mvs.y = ((y == 0) ?
407                                                         pParam, pMBs, &pMB->mvs[3], &pMB->pmvs[3]);                  data->directmvB[0].y
408                    : mvs.y - data->referencemv[0].y);
409    
410                                  sad8 = pMB->sad8[0] + pMB->sad8[1] + pMB->sad8[2] + pMB->sad8[3];          if (( mvs.x > data->max_dx ) || ( mvs.x < data->min_dx )
411                          }                  || ( mvs.y > data->max_dy ) || ( mvs.y < data->min_dy )
412                    || ( b_mvs.x > data->max_dx ) || ( b_mvs.x < data->min_dx )
413                    || ( b_mvs.y > data->max_dy ) || ( b_mvs.y < data->min_dy )) return;
                         /* decide: MODE_INTER or MODE_INTER4V  
                            mpeg4:   if (sad8 < sad16 - nb/2+1) use_inter4v  
                         */  
   
                         if (pMB->dquant == NO_CHANGE) {  
                                 if (((pParam->global_flags & XVID_INTER4V)==0) ||  
                                     (sad16 < (sad8 + (int32_t)(IMV16X16 * pParam->quant)))) {  
414    
415                                          sad8 = sad16;          switch ( ((mvs.x&1)<<1) + (mvs.y&1) ) {
416                                          pMB->mode = MODE_INTER;                  case 0 : ReferenceF = data->Ref + mvs.x/2 + (mvs.y/2)*(data->iEdgedWidth); break;
417                                          pMB->mvs[0].x = pMB->mvs[1].x = pMB->mvs[2].x = pMB->mvs[3].x = mv16.x;                  case 1 : ReferenceF = data->RefV + mvs.x/2 + ((mvs.y-1)/2)*(data->iEdgedWidth); break;
418                                          pMB->mvs[0].y = pMB->mvs[1].y = pMB->mvs[2].y = pMB->mvs[3].y = mv16.y;                  case 2 : ReferenceF = data->RefH + (mvs.x-1)/2 + (mvs.y/2)*(data->iEdgedWidth); break;
419                                          pMB->pmvs[0].x = pmv16.x;                  default : ReferenceF = data->RefHV + (mvs.x-1)/2 + ((mvs.y-1)/2)*(data->iEdgedWidth); break;
                                         pMB->pmvs[0].y = pmv16.y;  
                                 }  
                                 else  
                                         pMB->mode = MODE_INTER4V;  
                         }  
                         else  
                         {  
                                 sad8 = sad16;  
                                 pMB->mode = MODE_INTER;  
                                 pMB->mvs[0].x = pMB->mvs[1].x = pMB->mvs[2].x = pMB->mvs[3].x = mv16.x;  
                                 pMB->mvs[0].y = pMB->mvs[1].y = pMB->mvs[2].y = pMB->mvs[3].y = mv16.y;  
                                 pMB->pmvs[0].x = pmv16.x;  
                                 pMB->pmvs[0].y = pmv16.y;  
                         }  
420                  }                  }
421    
422          return 0;          switch ( ((b_mvs.x&1)<<1) + (b_mvs.y&1) ) {
423                    case 0 : ReferenceB = data->bRef + b_mvs.x/2 + (b_mvs.y/2)*(data->iEdgedWidth); break;
424                    case 1 : ReferenceB = data->bRefV + b_mvs.x/2 + ((b_mvs.y-1)/2)*(data->iEdgedWidth); break;
425                    case 2 : ReferenceB = data->bRefH + (b_mvs.x-1)/2 + (b_mvs.y/2)*(data->iEdgedWidth); break;
426                    default : ReferenceB = data->bRefHV + (b_mvs.x-1)/2 + ((b_mvs.y-1)/2)*(data->iEdgedWidth); break;
427  }  }
428    
429  #define MVzero(A) ( ((A).x)==(0) && ((A).y)==(0) )          sad = sad16bi(data->Cur, ReferenceF, ReferenceB, data->iEdgedWidth);
430            sad += (data->lambda16 * d_mv_bits(x, y, 1) * sad)/1000;
431    
432  #define MVequal(A,B) ( ((A).x)==((B).x) && ((A).y)==((B).y) )          if (sad < *(data->iMinSAD)) {
433                    *(data->iMinSAD) = sad;
434                    data->currentMV->x = x; data->currentMV->y = y;
435                    *dir = Direction; }
436    }
437    
438    static void
439    CheckCandidate8(const int x, const int y, const int Direction, int * const dir, const SearchData * const data)
440    {
441            int32_t sad; int t;
442            const uint8_t * Reference;
443    
444  #define CHECK_MV16_ZERO {\          if (( x > data->max_dx) || ( x < data->min_dx)
445    if ( (0 <= max_dx) && (0 >= min_dx) \                  || ( y > data->max_dy) || (y < data->min_dy)) return;
     && (0 <= max_dy) && (0 >= min_dy) ) \  
   { \  
     iSAD = sad16( cur, get_ref(pRef, pRefH, pRefV, pRefHV, x, y, 16, 0, 0 , iEdgedWidth), iEdgedWidth, MV_MAX_ERROR); \  
     iSAD += calc_delta_16(-pmv[0].x, -pmv[0].y, (uint8_t)iFcode) * iQuant;\  
     if (iSAD <= iQuant * 96)    \  
         iSAD -= MV16_00_BIAS; \  
     if (iSAD < iMinSAD) \  
     {  iMinSAD=iSAD; currMV->x=0; currMV->y=0; }  }     \  
 }  
   
 #define NOCHECK_MV16_CANDIDATE(X,Y) { \  
     iSAD = sad16( cur, get_ref(pRef, pRefH, pRefV, pRefHV, x, y, 16, X, Y, iEdgedWidth),iEdgedWidth, iMinSAD); \  
     iSAD += calc_delta_16((X) - pmv[0].x, (Y) - pmv[0].y, (uint8_t)iFcode) * iQuant;\  
     if (iSAD < iMinSAD) \  
     {  iMinSAD=iSAD; currMV->x=(X); currMV->y=(Y); } \  
 }  
   
 #define CHECK_MV16_CANDIDATE(X,Y) { \  
   if ( ((X) <= max_dx) && ((X) >= min_dx) \  
     && ((Y) <= max_dy) && ((Y) >= min_dy) ) \  
   { \  
     iSAD = sad16( cur, get_ref(pRef, pRefH, pRefV, pRefHV, x, y, 16, X, Y, iEdgedWidth),iEdgedWidth, iMinSAD); \  
     iSAD += calc_delta_16((X) - pmv[0].x, (Y) - pmv[0].y, (uint8_t)iFcode) * iQuant;\  
     if (iSAD < iMinSAD) \  
     {  iMinSAD=iSAD; currMV->x=(X); currMV->y=(Y); } } \  
 }  
446    
447  #define CHECK_MV16_CANDIDATE_DIR(X,Y,D) { \          switch ( ((x&1)<<1) + (y&1) )
448    if ( ((X) <= max_dx) && ((X) >= min_dx) \          {
449      && ((Y) <= max_dy) && ((Y) >= min_dy) ) \                  case 0 : Reference = data->Ref + x/2 + (y/2)*(data->iEdgedWidth); break;
450    { \                  case 1 : Reference = data->RefV + x/2 + ((y-1)/2)*(data->iEdgedWidth); break;
451      iSAD = sad16( cur, get_ref(pRef, pRefH, pRefV, pRefHV, x, y, 16, X, Y, iEdgedWidth),iEdgedWidth, iMinSAD); \                  case 2 : Reference = data->RefH + (x-1)/2 + (y/2)*(data->iEdgedWidth); break;
452      iSAD += calc_delta_16((X) - pmv[0].x, (Y) - pmv[0].y, (uint8_t)iFcode) * iQuant;\                  default : Reference = data->RefHV + (x-1)/2 + ((y-1)/2)*(data->iEdgedWidth); break;
     if (iSAD < iMinSAD) \  
     {  iMinSAD=iSAD; currMV->x=(X); currMV->y=(Y); iDirection=(D); } } \  
453  }  }
454    
455  #define CHECK_MV16_CANDIDATE_FOUND(X,Y,D) { \          sad = sad8(data->Cur, Reference, data->iEdgedWidth);
456    if ( ((X) <= max_dx) && ((X) >= min_dx) \          if (data->qpel) t = d_mv_bits(2 * x - data->predQMV.x, 2 * y - data->predQMV.y, data->iFcode);
457      && ((Y) <= max_dy) && ((Y) >= min_dy) ) \          else t = d_mv_bits(x - data->predMV.x, y - data->predMV.y, data->iFcode);
   { \  
     iSAD = sad16( cur, get_ref(pRef, pRefH, pRefV, pRefHV, x, y, 16, X, Y, iEdgedWidth),iEdgedWidth, iMinSAD); \  
     iSAD += calc_delta_16((X) - pmv[0].x, (Y) - pmv[0].y, (uint8_t)iFcode) * iQuant;\  
     if (iSAD < iMinSAD) \  
     {  iMinSAD=iSAD; currMV->x=(X); currMV->y=(Y); iDirection=(D); iFound=0; } } \  
 }  
458    
459            sad += (data->lambda8 * t * (sad+NEIGH_8X8_BIAS))/100;
460    
461  #define CHECK_MV8_ZERO {\          if (sad < *(data->iMinSAD)) {
462    iSAD = sad8( cur, get_ref(pRef, pRefH, pRefV, pRefHV, x, y, 8, 0, 0 , iEdgedWidth), iEdgedWidth); \                  *(data->iMinSAD) = sad;
463    iSAD += calc_delta_8(-pmv[0].x, -pmv[0].y, (uint8_t)iFcode) * iQuant;\                  data->currentMV->x = x; data->currentMV->y = y;
464    if (iSAD < iMinSAD) \                  *dir = Direction; }
   { iMinSAD=iSAD; currMV->x=0; currMV->y=0; } \  
465  }  }
466    
467  #define NOCHECK_MV8_CANDIDATE(X,Y) \  static void
468    { \  CheckCandidate8_qpel(const int x, const int y, const int Direction, int * const dir, const SearchData * const data)
469      iSAD = sad8( cur, get_ref(pRef, pRefH, pRefV, pRefHV, x, y, 8, (X), (Y), iEdgedWidth),iEdgedWidth); \  // CheckCandidate16no4v variant which expects x and y in quarter pixel resolution
470      iSAD += calc_delta_8((X)-pmv[0].x, (Y)-pmv[0].y, (uint8_t)iFcode) * iQuant;\  // Important: This is no general usable routine! x and y must be +/-1 (qpel resolution!)
471      if (iSAD < iMinSAD) \  // around currentMV!
     {  iMinSAD=iSAD; currMV->x=(X); currMV->y=(Y); } \  
 }  
472    
473  #define CHECK_MV8_CANDIDATE(X,Y) { \  {
474    if ( ((X) <= max_dx) && ((X) >= min_dx) \          int32_t sad;
475      && ((Y) <= max_dy) && ((Y) >= min_dy) ) \          uint8_t *Reference = (uint8_t *) data->RefQ;
476    { \          const uint8_t *ref1, *ref2, *ref3, *ref4;
477      iSAD = sad8( cur, get_ref(pRef, pRefH, pRefV, pRefHV, x, y, 8, (X), (Y), iEdgedWidth),iEdgedWidth); \          VECTOR halfpelMV = *(data->currentMV);
     iSAD += calc_delta_8((X)-pmv[0].x, (Y)-pmv[0].y, (uint8_t)iFcode) * iQuant;\  
     if (iSAD < iMinSAD) \  
     {  iMinSAD=iSAD; currMV->x=(X); currMV->y=(Y); } } \  
 }  
478    
479  #define CHECK_MV8_CANDIDATE_DIR(X,Y,D) { \          int32_t iEdgedWidth = data->iEdgedWidth;
480    if ( ((X) <= max_dx) && ((X) >= min_dx) \          uint32_t rounding = data->rounding;
     && ((Y) <= max_dy) && ((Y) >= min_dy) ) \  
   { \  
     iSAD = sad8( cur, get_ref(pRef, pRefH, pRefV, pRefHV, x, y, 8, (X), (Y), iEdgedWidth),iEdgedWidth); \  
     iSAD += calc_delta_8((X)-pmv[0].x, (Y)-pmv[0].y, (uint8_t)iFcode) * iQuant;\  
     if (iSAD < iMinSAD) \  
     {  iMinSAD=iSAD; currMV->x=(X); currMV->y=(Y); iDirection=(D); } } \  
 }  
481    
482  #define CHECK_MV8_CANDIDATE_FOUND(X,Y,D) { \          if (( x > data->max_dx) || ( x < data->min_dx)
483    if ( ((X) <= max_dx) && ((X) >= min_dx) \                  || ( y > data->max_dy) || (y < data->min_dy)) return;
     && ((Y) <= max_dy) && ((Y) >= min_dy) ) \  
   { \  
     iSAD = sad8( cur, get_ref(pRef, pRefH, pRefV, pRefHV, x, y, 8, (X), (Y), iEdgedWidth),iEdgedWidth); \  
     iSAD += calc_delta_8((X)-pmv[0].x, (Y)-pmv[0].y, (uint8_t)iFcode) * iQuant;\  
     if (iSAD < iMinSAD) \  
     {  iMinSAD=iSAD; currMV->x=(X); currMV->y=(Y); iDirection=(D); iFound=0; } } \  
 }  
484    
485  /* too slow and not fully functional at the moment */          GET_REFERENCE(halfpelMV.x, halfpelMV.y, ref1);
486  /*          switch( ((x&1)<<1) + (y&1) )
 int32_t ZeroSearch16(  
                                         const uint8_t * const pRef,  
                                         const uint8_t * const pRefH,  
                                         const uint8_t * const pRefV,  
                                         const uint8_t * const pRefHV,  
                                         const IMAGE * const pCur,  
                                         const int x, const int y,  
                                         const uint32_t MotionFlags,  
                                         MBParam * const pParam,  
                                         MACROBLOCK * const pMBs,  
                                         VECTOR * const currMV,  
                                         VECTOR * const currPMV)  
487  {  {
488          const int32_t iEdgedWidth = pParam->edged_width;          case 0: // pure halfpel position - shouldn't happen during a refinement step
489          const int32_t iQuant = pParam->quant;                  GET_REFERENCE(halfpelMV.x, halfpelMV.y, Reference);
490          const uint8_t * cur = pCur->y + x*16 + y*16*iEdgedWidth;                  break;
         int32_t iSAD;  
         int32_t pred_x,pred_y;  
491    
492          get_pmv(pMBs, x, y, pParam->mb_width, 0, &pred_x, &pred_y);          case 1: // x halfpel, y qpel - top or bottom during qpel refinement
493                    GET_REFERENCE(halfpelMV.x, y - halfpelMV.y, ref2);
494    
495          iSAD = sad16( cur,                  interpolate8x8_avg2(Reference, ref1, ref2, iEdgedWidth, rounding);
496                  get_ref(pRef, pRefH, pRefV, pRefHV, x, y, 16, 0,0, iEdgedWidth),                  break;
                 iEdgedWidth, MV_MAX_ERROR);  
         if (iSAD <= iQuant * 96)  
                 iSAD -= MV16_00_BIAS;  
497    
498          currMV->x = 0;          case 2: // x qpel, y halfpel - left or right during qpel refinement
499          currMV->y = 0;                  GET_REFERENCE(x - halfpelMV.x, halfpelMV.y, ref2);
         currPMV->x = -pred_x;  
         currPMV->y = -pred_y;  
500    
501          return iSAD;                  interpolate8x8_avg2(Reference, ref1, ref2, iEdgedWidth, rounding);
502                    break;
503    
504  }          default: // x and y in qpel resolution - the "corners" (top left/right and
505  */                           // bottom left/right) during qpel refinement
506                    GET_REFERENCE(halfpelMV.x, y - halfpelMV.y, ref2);
507                    GET_REFERENCE(x - halfpelMV.x, halfpelMV.y, ref3);
508                    GET_REFERENCE(x - halfpelMV.x, y - halfpelMV.y, ref4);
509    
510  int32_t Diamond16_MainSearch(                  interpolate8x8_avg4(Reference, ref1, ref2, ref3, ref4, iEdgedWidth, rounding);
511          const uint8_t * const pRef,                  break;
         const uint8_t * const pRefH,  
         const uint8_t * const pRefV,  
         const uint8_t * const pRefHV,  
         const uint8_t * const cur,  
         const int x, const int y,  
         int32_t startx, int32_t starty,  
         int32_t iMinSAD,  
         VECTOR * const currMV,  
         const VECTOR * const pmv,  
         const int32_t min_dx, const int32_t max_dx,  
         const int32_t min_dy, const int32_t max_dy,  
         const int32_t iEdgedWidth,  
         const int32_t iDiamondSize,  
         const int32_t iFcode,  
         const int32_t iQuant,  
         int iFound)  
 {  
 /* Do a diamond search around given starting point, return SAD of best */  
   
         int32_t iDirection=0;  
         int32_t iSAD;  
         VECTOR backupMV;  
         backupMV.x = startx;  
         backupMV.y = starty;  
   
 /* It's one search with full Diamond pattern, and only 3 of 4 for all following diamonds */  
   
         CHECK_MV16_CANDIDATE_DIR(backupMV.x-iDiamondSize,backupMV.y,1);  
         CHECK_MV16_CANDIDATE_DIR(backupMV.x+iDiamondSize,backupMV.y,2);  
         CHECK_MV16_CANDIDATE_DIR(backupMV.x,backupMV.y-iDiamondSize,3);  
         CHECK_MV16_CANDIDATE_DIR(backupMV.x,backupMV.y+iDiamondSize,4);  
   
         if (iDirection)  
                 while (!iFound)  
                 {  
                         iFound = 1;  
                         backupMV=*currMV;  
   
                         if ( iDirection != 2)  
                                 CHECK_MV16_CANDIDATE_FOUND(backupMV.x-iDiamondSize,backupMV.y,1);  
                         if ( iDirection != 1)  
                                 CHECK_MV16_CANDIDATE_FOUND(backupMV.x+iDiamondSize,backupMV.y,2);  
                         if ( iDirection != 4)  
                                 CHECK_MV16_CANDIDATE_FOUND(backupMV.x,backupMV.y-iDiamondSize,3);  
                         if ( iDirection != 3)  
                                 CHECK_MV16_CANDIDATE_FOUND(backupMV.x,backupMV.y+iDiamondSize,4);  
                 }  
         else  
         {  
                 currMV->x = startx;  
                 currMV->y = starty;  
         }  
         return iMinSAD;  
512  }  }
513    
514  int32_t Square16_MainSearch(          sad = sad8(data->Cur, Reference, data->iEdgedWidth);
515                                          const uint8_t * const pRef,          sad += (data->lambda8 * d_mv_bits(x - data->predQMV.x, y - data->predQMV.y, data->iFcode) * (sad+NEIGH_8X8_BIAS))/100;
                                         const uint8_t * const pRefH,  
                                         const uint8_t * const pRefV,  
                                         const uint8_t * const pRefHV,  
                                         const uint8_t * const cur,  
                                         const int x, const int y,  
                                         int32_t startx, int32_t starty,  
                                         int32_t iMinSAD,  
                                         VECTOR * const currMV,  
                                         const VECTOR * const pmv,  
                                         const int32_t min_dx, const int32_t max_dx,  
                                         const int32_t min_dy, const int32_t max_dy,  
                                         const int32_t iEdgedWidth,  
                                         const int32_t iDiamondSize,  
                                         const int32_t iFcode,  
                                         const int32_t iQuant,  
                                         int iFound)  
 {  
 /* Do a square search around given starting point, return SAD of best */  
   
         int32_t iDirection=0;  
         int32_t iSAD;  
         VECTOR backupMV;  
         backupMV.x = startx;  
         backupMV.y = starty;  
   
 /* It's one search with full square pattern, and new parts for all following diamonds */  
   
 /*   new direction are extra, so 1-4 is normal diamond  
       537  
       1*2  
       648  
 */  
   
         CHECK_MV16_CANDIDATE_DIR(backupMV.x-iDiamondSize,backupMV.y,1);  
         CHECK_MV16_CANDIDATE_DIR(backupMV.x+iDiamondSize,backupMV.y,2);  
         CHECK_MV16_CANDIDATE_DIR(backupMV.x,backupMV.y-iDiamondSize,3);  
         CHECK_MV16_CANDIDATE_DIR(backupMV.x,backupMV.y+iDiamondSize,4);  
   
         CHECK_MV16_CANDIDATE_DIR(backupMV.x-iDiamondSize,backupMV.y-iDiamondSize,5);  
         CHECK_MV16_CANDIDATE_DIR(backupMV.x-iDiamondSize,backupMV.y+iDiamondSize,6);  
         CHECK_MV16_CANDIDATE_DIR(backupMV.x+iDiamondSize,backupMV.y-iDiamondSize,7);  
         CHECK_MV16_CANDIDATE_DIR(backupMV.x+iDiamondSize,backupMV.y+iDiamondSize,8);  
516    
517            if (sad < *(data->iMinSAD)) {
518                    *(data->iMinSAD) = sad;
519                    data->currentQMV->x = x; data->currentQMV->y = y;
520                    *dir = Direction; }
521    }
522    
523          if (iDirection)  /* CHECK_CANDIATE FUNCTIONS END */
524                  while (!iFound)  
525                  {  /* MAINSEARCH FUNCTIONS START */
                         iFound = 1;  
                         backupMV=*currMV;  
526    
527                          switch (iDirection)  static void
528    AdvDiamondSearch(int x, int y, const SearchData * const data, int bDirection)
529                          {                          {
                                 case 1:  
                                         CHECK_MV16_CANDIDATE_FOUND(backupMV.x-iDiamondSize,backupMV.y,1);  
                                         CHECK_MV16_CANDIDATE_DIR(backupMV.x-iDiamondSize,backupMV.y-iDiamondSize,5);  
                                         CHECK_MV16_CANDIDATE_DIR(backupMV.x+iDiamondSize,backupMV.y-iDiamondSize,7);  
                                         break;  
                                 case 2:  
                                         CHECK_MV16_CANDIDATE_DIR(backupMV.x+iDiamondSize,backupMV.y,2);  
                                         CHECK_MV16_CANDIDATE_DIR(backupMV.x-iDiamondSize,backupMV.y+iDiamondSize,6);  
                                         CHECK_MV16_CANDIDATE_DIR(backupMV.x+iDiamondSize,backupMV.y+iDiamondSize,8);  
                                         break;  
530    
531                                  case 3:  /* directions: 1 - left (x-1); 2 - right (x+1), 4 - up (y-1); 8 - down (y+1) */
                                         CHECK_MV16_CANDIDATE_DIR(backupMV.x,backupMV.y+iDiamondSize,4);  
                                         CHECK_MV16_CANDIDATE_DIR(backupMV.x+iDiamondSize,backupMV.y-iDiamondSize,7);  
                                         CHECK_MV16_CANDIDATE_DIR(backupMV.x+iDiamondSize,backupMV.y+iDiamondSize,8);  
                                         break;  
532    
533                                  case 4:                  int iDirection;
                                         CHECK_MV16_CANDIDATE_DIR(backupMV.x,backupMV.y-iDiamondSize,3);  
                                         CHECK_MV16_CANDIDATE_DIR(backupMV.x-iDiamondSize,backupMV.y-iDiamondSize,5);  
                                         CHECK_MV16_CANDIDATE_DIR(backupMV.x-iDiamondSize,backupMV.y+iDiamondSize,6);  
                                         break;  
534    
535                                  case 5:                  do {
536                                          CHECK_MV16_CANDIDATE_DIR(backupMV.x-iDiamondSize,backupMV.y,1);                          iDirection = 0;
537                                          CHECK_MV16_CANDIDATE_DIR(backupMV.x,backupMV.y-iDiamondSize,3);                          if (bDirection & 1) CHECK_CANDIDATE(x - iDiamondSize, y, 1);
538                                          CHECK_MV16_CANDIDATE_DIR(backupMV.x-iDiamondSize,backupMV.y-iDiamondSize,5);                          if (bDirection & 2) CHECK_CANDIDATE(x + iDiamondSize, y, 2);
539                                          CHECK_MV16_CANDIDATE_DIR(backupMV.x-iDiamondSize,backupMV.y+iDiamondSize,6);                          if (bDirection & 4) CHECK_CANDIDATE(x, y - iDiamondSize, 4);
540                                          CHECK_MV16_CANDIDATE_DIR(backupMV.x+iDiamondSize,backupMV.y-iDiamondSize,7);                          if (bDirection & 8) CHECK_CANDIDATE(x, y + iDiamondSize, 8);
                                         break;  
541    
542                                  case 6:                          /* now we're doing diagonal checks near our candidate */
                                         CHECK_MV16_CANDIDATE_DIR(backupMV.x+iDiamondSize,backupMV.y,2);  
                                         CHECK_MV16_CANDIDATE_DIR(backupMV.x,backupMV.y-iDiamondSize,3);  
543    
544                                          CHECK_MV16_CANDIDATE_DIR(backupMV.x-iDiamondSize,backupMV.y-iDiamondSize,5);                          if (iDirection) {               //checking if anything found
545                                          CHECK_MV16_CANDIDATE_DIR(backupMV.x-iDiamondSize,backupMV.y+iDiamondSize,6);                                  bDirection = iDirection;
546                                          CHECK_MV16_CANDIDATE_DIR(backupMV.x+iDiamondSize,backupMV.y+iDiamondSize,8);                                  iDirection = 0;
547                                    x = data->currentMV->x; y = data->currentMV->y;
548                                    if (bDirection & 3) {   //our candidate is left or right
549                                            CHECK_CANDIDATE(x, y + iDiamondSize, 8);
550                                            CHECK_CANDIDATE(x, y - iDiamondSize, 4);
551                                    } else {                        // what remains here is up or down
552                                            CHECK_CANDIDATE(x + iDiamondSize, y, 2);
553                                            CHECK_CANDIDATE(x - iDiamondSize, y, 1); }
554    
555                                    if (iDirection) {
556                                            bDirection += iDirection;
557                                            x = data->currentMV->x; y = data->currentMV->y; }
558                            } else {                                //about to quit, eh? not so fast....
559                                    switch (bDirection) {
560                                    case 2:
561                                            CHECK_CANDIDATE(x + iDiamondSize, y - iDiamondSize, 2 + 4);
562                                            CHECK_CANDIDATE(x + iDiamondSize, y + iDiamondSize, 2 + 8);
563                                          break;                                          break;
564                                    case 1:
565                                  case 7:                                          CHECK_CANDIDATE(x - iDiamondSize, y - iDiamondSize, 1 + 4);
566                                          CHECK_MV16_CANDIDATE_FOUND(backupMV.x-iDiamondSize,backupMV.y,1);                                          CHECK_CANDIDATE(x - iDiamondSize, y + iDiamondSize, 1 + 8);
567                                          CHECK_MV16_CANDIDATE_DIR(backupMV.x,backupMV.y+iDiamondSize,4);                                          break;
568                                          CHECK_MV16_CANDIDATE_DIR(backupMV.x-iDiamondSize,backupMV.y-iDiamondSize,5);                                  case 2 + 4:
569                                          CHECK_MV16_CANDIDATE_DIR(backupMV.x+iDiamondSize,backupMV.y-iDiamondSize,7);                                          CHECK_CANDIDATE(x - iDiamondSize, y - iDiamondSize, 1 + 4);
570                                          CHECK_MV16_CANDIDATE_DIR(backupMV.x+iDiamondSize,backupMV.y+iDiamondSize,8);                                          CHECK_CANDIDATE(x + iDiamondSize, y - iDiamondSize, 2 + 4);
571                                            CHECK_CANDIDATE(x + iDiamondSize, y + iDiamondSize, 2 + 8);
572                                            break;
573                                    case 4:
574                                            CHECK_CANDIDATE(x + iDiamondSize, y - iDiamondSize, 2 + 4);
575                                            CHECK_CANDIDATE(x - iDiamondSize, y - iDiamondSize, 1 + 4);
576                                          break;                                          break;
   
577                                  case 8:                                  case 8:
578                                          CHECK_MV16_CANDIDATE_DIR(backupMV.x+iDiamondSize,backupMV.y,2);                                          CHECK_CANDIDATE(x + iDiamondSize, y + iDiamondSize, 2 + 8);
579                                          CHECK_MV16_CANDIDATE_DIR(backupMV.x,backupMV.y+iDiamondSize,4);                                          CHECK_CANDIDATE(x - iDiamondSize, y + iDiamondSize, 1 + 8);
                                         CHECK_MV16_CANDIDATE_DIR(backupMV.x-iDiamondSize,backupMV.y+iDiamondSize,6);  
                                         CHECK_MV16_CANDIDATE_DIR(backupMV.x+iDiamondSize,backupMV.y-iDiamondSize,7);  
                                         CHECK_MV16_CANDIDATE_DIR(backupMV.x+iDiamondSize,backupMV.y+iDiamondSize,8);  
580                                          break;                                          break;
581                          default:                                  case 1 + 4:
582                                          CHECK_MV16_CANDIDATE_DIR(backupMV.x-iDiamondSize,backupMV.y,1);                                          CHECK_CANDIDATE(x - iDiamondSize, y + iDiamondSize, 1 + 8);
583                                          CHECK_MV16_CANDIDATE_DIR(backupMV.x+iDiamondSize,backupMV.y,2);                                          CHECK_CANDIDATE(x - iDiamondSize, y - iDiamondSize, 1 + 4);
584                                          CHECK_MV16_CANDIDATE_DIR(backupMV.x,backupMV.y-iDiamondSize,3);                                          CHECK_CANDIDATE(x + iDiamondSize, y - iDiamondSize, 2 + 4);
585                                          CHECK_MV16_CANDIDATE_DIR(backupMV.x,backupMV.y+iDiamondSize,4);                                          break;
586                                    case 2 + 8:
587                                          CHECK_MV16_CANDIDATE_DIR(backupMV.x-iDiamondSize,backupMV.y-iDiamondSize,5);                                          CHECK_CANDIDATE(x - iDiamondSize, y - iDiamondSize, 1 + 4);
588                                          CHECK_MV16_CANDIDATE_DIR(backupMV.x-iDiamondSize,backupMV.y+iDiamondSize,6);                                          CHECK_CANDIDATE(x - iDiamondSize, y + iDiamondSize, 1 + 8);
589                                          CHECK_MV16_CANDIDATE_DIR(backupMV.x+iDiamondSize,backupMV.y-iDiamondSize,7);                                          CHECK_CANDIDATE(x + iDiamondSize, y + iDiamondSize, 2 + 8);
590                                          CHECK_MV16_CANDIDATE_DIR(backupMV.x+iDiamondSize,backupMV.y+iDiamondSize,8);                                          break;
591                                    case 1 + 8:
592                                            CHECK_CANDIDATE(x + iDiamondSize, y - iDiamondSize, 2 + 4);
593                                            CHECK_CANDIDATE(x + iDiamondSize, y + iDiamondSize, 2 + 8);
594                                            CHECK_CANDIDATE(x - iDiamondSize, y + iDiamondSize, 1 + 8);
595                                            break;
596                                    default:                //1+2+4+8 == we didn't find anything at all
597                                            CHECK_CANDIDATE(x - iDiamondSize, y - iDiamondSize, 1 + 4);
598                                            CHECK_CANDIDATE(x - iDiamondSize, y + iDiamondSize, 1 + 8);
599                                            CHECK_CANDIDATE(x + iDiamondSize, y - iDiamondSize, 2 + 4);
600                                            CHECK_CANDIDATE(x + iDiamondSize, y + iDiamondSize, 2 + 8);
601                                          break;                                          break;
602                          }                          }
603                                    if (!iDirection) break;         //ok, the end. really
604                                    bDirection = iDirection;
605                                    x = data->currentMV->x; y = data->currentMV->y;
606                  }                  }
         else  
                 {  
                         currMV->x = startx;  
                         currMV->y = starty;  
607                  }                  }
608          return iMinSAD;                  while (1);                              //forever
609  }  }
610    
611    static void
612    SquareSearch(int x, int y, const SearchData * const data, int bDirection)
613    {
614            int iDirection;
615    
616  int32_t Full16_MainSearch(          do {
617                                          const uint8_t * const pRef,                  iDirection = 0;
618                                          const uint8_t * const pRefH,                  if (bDirection & 1) CHECK_CANDIDATE(x - iDiamondSize, y, 1+16+64);
619                                          const uint8_t * const pRefV,                  if (bDirection & 2) CHECK_CANDIDATE(x + iDiamondSize, y, 2+32+128);
620                                          const uint8_t * const pRefHV,                  if (bDirection & 4) CHECK_CANDIDATE(x, y - iDiamondSize, 4+16+32);
621                                          const uint8_t * const cur,                  if (bDirection & 8) CHECK_CANDIDATE(x, y + iDiamondSize, 8+64+128);
622                                          const int x, const int y,                  if (bDirection & 16) CHECK_CANDIDATE(x - iDiamondSize, y - iDiamondSize, 1+4+16+32+64);
623                                          int32_t startx, int32_t starty,                  if (bDirection & 32) CHECK_CANDIDATE(x + iDiamondSize, y - iDiamondSize, 2+4+16+32+128);
624                                          int32_t iMinSAD,                  if (bDirection & 64) CHECK_CANDIDATE(x - iDiamondSize, y + iDiamondSize, 1+8+16+64+128);
625                                          VECTOR * const currMV,                  if (bDirection & 128) CHECK_CANDIDATE(x + iDiamondSize, y + iDiamondSize, 2+8+32+64+128);
                                         const VECTOR * const pmv,  
                                         const int32_t min_dx, const int32_t max_dx,  
                                         const int32_t min_dy, const int32_t max_dy,  
                                         const int32_t iEdgedWidth,  
                                         const int32_t iDiamondSize,  
                                         const int32_t iFcode,  
                                         const int32_t iQuant,  
                                         int iFound)  
 {  
         int32_t iSAD;  
         int32_t dx,dy;  
         VECTOR backupMV;  
         backupMV.x = startx;  
         backupMV.y = starty;  
   
         for (dx = min_dx; dx<=max_dx; dx+=iDiamondSize)  
                 for (dy = min_dy; dy<= max_dy; dy+=iDiamondSize)  
                         NOCHECK_MV16_CANDIDATE(dx,dy);  
626    
627          return iMinSAD;                  bDirection = iDirection;
628                    x = data->currentMV->x; y = data->currentMV->y;
629            } while (iDirection);
630  }  }
631    
632  int32_t Full8_MainSearch(  static void
633                                          const uint8_t * const pRef,  DiamondSearch(int x, int y, const SearchData * const data, int bDirection)
634                                          const uint8_t * const pRefH,  {
                                         const uint8_t * const pRefV,  
                                         const uint8_t * const pRefHV,  
                                         const uint8_t * const cur,  
                                         const int x, const int y,  
                                         int32_t startx, int32_t starty,  
                                         int32_t iMinSAD,  
                                         VECTOR * const currMV,  
                                         const VECTOR * const pmv,  
                                         const int32_t min_dx, const int32_t max_dx,  
                                         const int32_t min_dy, const int32_t max_dy,  
                                         const int32_t iEdgedWidth,  
                                         const int32_t iDiamondSize,  
                                         const int32_t iFcode,  
                                         const int32_t iQuant,  
                                         int iFound)  
 {  
         int32_t iSAD;  
         int32_t dx,dy;  
         VECTOR backupMV;  
         backupMV.x = startx;  
         backupMV.y = starty;  
   
         for (dx = min_dx; dx<=max_dx; dx+=iDiamondSize)  
                 for (dy = min_dy; dy<= max_dy; dy+=iDiamondSize)  
                         NOCHECK_MV8_CANDIDATE(dx,dy);  
   
         return iMinSAD;  
 }  
635    
636    /* directions: 1 - left (x-1); 2 - right (x+1), 4 - up (y-1); 8 - down (y+1) */
637    
638                    int iDirection;
639    
640  int32_t Halfpel16_Refine(                  do {
641          const uint8_t * const pRef,                          iDirection = 0;
642          const uint8_t * const pRefH,                          if (bDirection & 1) CHECK_CANDIDATE(x - iDiamondSize, y, 1);
643          const uint8_t * const pRefV,                          if (bDirection & 2) CHECK_CANDIDATE(x + iDiamondSize, y, 2);
644          const uint8_t * const pRefHV,                          if (bDirection & 4) CHECK_CANDIDATE(x, y - iDiamondSize, 4);
645          const uint8_t * const cur,                          if (bDirection & 8) CHECK_CANDIDATE(x, y + iDiamondSize, 8);
         const int x, const int y,  
         VECTOR * const currMV,  
         int32_t iMinSAD,  
         const VECTOR * const pmv,  
         const int32_t min_dx, const int32_t max_dx,  
         const int32_t min_dy, const int32_t max_dy,  
         const int32_t iFcode,  
         const int32_t iQuant,  
         const int32_t iEdgedWidth)  
 {  
 /* Do a half-pel refinement (or rather a "smallest possible amount" refinement) */  
646    
647          int32_t iSAD;                          /* now we're doing diagonal checks near our candidate */
         VECTOR backupMV = *currMV;  
648    
649          CHECK_MV16_CANDIDATE(backupMV.x-1,backupMV.y-1);                          if (iDirection) {               //checking if anything found
650          CHECK_MV16_CANDIDATE(backupMV.x  ,backupMV.y-1);                                  bDirection = iDirection;
651          CHECK_MV16_CANDIDATE(backupMV.x+1,backupMV.y-1);                                  iDirection = 0;
652          CHECK_MV16_CANDIDATE(backupMV.x-1,backupMV.y);                                  x = data->currentMV->x; y = data->currentMV->y;
653          CHECK_MV16_CANDIDATE(backupMV.x+1,backupMV.y);                                  if (bDirection & 3) {   //our candidate is left or right
654          CHECK_MV16_CANDIDATE(backupMV.x-1,backupMV.y+1);                                          CHECK_CANDIDATE(x, y + iDiamondSize, 8);
655          CHECK_MV16_CANDIDATE(backupMV.x  ,backupMV.y+1);                                          CHECK_CANDIDATE(x, y - iDiamondSize, 4);
656          CHECK_MV16_CANDIDATE(backupMV.x+1,backupMV.y+1);                                  } else {                        // what remains here is up or down
657                                            CHECK_CANDIDATE(x + iDiamondSize, y, 2);
658                                            CHECK_CANDIDATE(x - iDiamondSize, y, 1); }
659    
660          return iMinSAD;                                  bDirection += iDirection;
661                                    x = data->currentMV->x; y = data->currentMV->y;
662                            }
663                    }
664                    while (iDirection);
665  }  }
666    
667  #define PMV_HALFPEL16 (PMV_HALFPELDIAMOND16|PMV_HALFPELREFINE16)  /* MAINSEARCH FUNCTIONS END */
668    
669    /* HALFPELREFINE COULD BE A MAINSEARCH FUNCTION, BUT THERE IS NO NEED FOR IT */
670    
671  int32_t PMVfastSearch16(  static void
672                                          const uint8_t * const pRef,  HalfpelRefine(const SearchData * const data)
                                         const uint8_t * const pRefH,  
                                         const uint8_t * const pRefV,  
                                         const uint8_t * const pRefHV,  
                                         const IMAGE * const pCur,  
                                         const int x, const int y,  
                                         const uint32_t MotionFlags,  
                                         const MBParam * const pParam,  
                                         MACROBLOCK * const pMBs,  
                                         VECTOR * const currMV,  
                                         VECTOR * const currPMV)  
673  {  {
674          const uint32_t iWcount = pParam->mb_width;  /* Do a half-pel refinement (or rather a "smallest possible amount" refinement) */
         const int32_t iFcode = pParam->fixed_code;  
         const int32_t iQuant = pParam->quant;  
         const int32_t iWidth = pParam->width;  
         const int32_t iHeight = pParam->height;  
         const int32_t iEdgedWidth = pParam->edged_width;  
   
         const uint8_t * cur = pCur->y + x*16 + y*16*iEdgedWidth;  
675    
676          int32_t iDiamondSize;          VECTOR backupMV = *(data->currentMV);
677            int iDirection; //not needed
678    
679          int32_t min_dx;          CHECK_CANDIDATE(backupMV.x - 1, backupMV.y - 1, 0);
680          int32_t max_dx;          CHECK_CANDIDATE(backupMV.x + 1, backupMV.y - 1, 0);
681          int32_t min_dy;          CHECK_CANDIDATE(backupMV.x - 1, backupMV.y + 1, 0);
682          int32_t max_dy;          CHECK_CANDIDATE(backupMV.x + 1, backupMV.y + 1, 0);
683    
684          int32_t iFound;          CHECK_CANDIDATE(backupMV.x - 1, backupMV.y, 0);
685            CHECK_CANDIDATE(backupMV.x + 1, backupMV.y, 0);
686    
687          VECTOR newMV;          CHECK_CANDIDATE(backupMV.x, backupMV.y + 1, 0);
688          VECTOR backupMV;        /* just for PMVFAST */          CHECK_CANDIDATE(backupMV.x, backupMV.y - 1, 0);
689    }
690    
         VECTOR pmv[4];  
         int32_t psad[4];  
691    
692          MACROBLOCK * const pMB = pMBs + x + y * iWcount;  static void
693    QuarterpelRefine(const SearchData * const data)
694    {
695    /* Perform quarter pixel refinement*/
696    
697          static int32_t threshA,threshB;          VECTOR backupMV = *(data->currentQMV);
698          int32_t bPredEq;          int iDirection; //not needed
         int32_t iMinSAD,iSAD;  
699    
700  /* Get maximum range */          CHECK_CANDIDATE(backupMV.x - 1, backupMV.y - 1, 0);
701          get_range(&min_dx, &max_dx, &min_dy, &max_dy,          CHECK_CANDIDATE(backupMV.x + 1, backupMV.y - 1, 0);
702                    x, y, 16, iWidth, iHeight, iFcode);          CHECK_CANDIDATE(backupMV.x - 1, backupMV.y + 1, 0);
703            CHECK_CANDIDATE(backupMV.x + 1, backupMV.y + 1, 0);
704    
705  /* we work with abs. MVs, not relative to prediction, so get_range is called relative to 0,0 */          CHECK_CANDIDATE(backupMV.x - 1, backupMV.y, 0);
706            CHECK_CANDIDATE(backupMV.x + 1, backupMV.y, 0);
707    
708          if (!(MotionFlags & PMV_HALFPEL16 ))          CHECK_CANDIDATE(backupMV.x, backupMV.y + 1, 0);
709          { min_dx = EVEN(min_dx);          CHECK_CANDIDATE(backupMV.x, backupMV.y - 1, 0);
         max_dx = EVEN(max_dx);  
         min_dy = EVEN(min_dy);  
         max_dy = EVEN(max_dy);  
         }               /* because we might use something like IF (dx>max_dx) THEN dx=max_dx; */  
710    
711    }
712    
713          bPredEq  = get_pmvdata(pMBs, x, y, iWcount, 0, pmv, psad);  static __inline int
714    SkipDecisionP(const IMAGE * current, const IMAGE * reference,
715                                                            const int x, const int y,
716                                                            const uint32_t iEdgedWidth, const uint32_t iQuant)
717    
         if ((x==0) && (y==0) )  
718          {          {
719                  threshA =  512;  /*      keep repeating checks for all b-frames before this P frame,
720                  threshB = 1024;          to make sure that SKIP is possible (todo)
721            how: if skip is not possible set sad00 to a very high value */
722    
723            uint32_t sadC = sad8(current->u + x*8 + y*(iEdgedWidth/2)*8,
724                                            reference->u + x*8 + y*(iEdgedWidth/2)*8, iEdgedWidth/2);
725            if (sadC > iQuant * MAX_CHROMA_SAD_FOR_SKIP) return 0;
726            sadC += sad8(current->v + (x + y*(iEdgedWidth/2))*8,
727                                            reference->v + (x + y*(iEdgedWidth/2))*8, iEdgedWidth/2);
728            if (sadC > iQuant * MAX_CHROMA_SAD_FOR_SKIP) return 0;
729    
730            return 1;
731          }          }
         else  
         {  
                 threshA = psad[0];  
                 threshB = threshA+256;  
                 if (threshA< 512) threshA =  512;  
                 if (threshA>1024) threshA = 1024;  
                 if (threshB>1792) threshB = 1792;  
         }  
   
         iFound=0;  
   
 /* Step 2: Calculate Distance= |MedianMVX| + |MedianMVY| where MedianMV is the motion  
    vector of the median.  
    If PredEq=1 and MVpredicted = Previous Frame MV, set Found=2  
 */  
   
         if ((bPredEq) && (MVequal(pmv[0],pMB->mvs[0]) ) )  
                 iFound=2;  
   
 /* Step 3: If Distance>0 or thresb<1536 or PredEq=1 Select small Diamond Search.  
    Otherwise select large Diamond Search.  
 */  
   
         if ( (pmv[0].x != 0) || (pmv[0].y != 0) || (threshB<1536) || (bPredEq) )  
                 iDiamondSize=1; // halfpel!  
         else  
                 iDiamondSize=2; // halfpel!  
   
         if (!(MotionFlags & PMV_HALFPELDIAMOND16) )  
                 iDiamondSize*=2;  
   
 /* Step 4: Calculate SAD around the Median prediction.  
    MinSAD=SAD  
    If Motion Vector equal to Previous frame motion vector  
    and MinSAD<PrevFrmSAD goto Step 10.  
    If SAD<=256 goto Step 10.  
 */  
732    
733    static __inline void
734    SkipMacroblockP(MACROBLOCK *pMB, const int32_t sad)
735    {
736            pMB->mode = MODE_NOT_CODED;
737            pMB->mvs[0].x = pMB->mvs[1].x = pMB->mvs[2].x = pMB->mvs[3].x = 0;
738            pMB->mvs[0].y = pMB->mvs[1].y = pMB->mvs[2].y = pMB->mvs[3].y = 0;
739    
740  // Prepare for main loop          pMB->qmvs[0].x = pMB->qmvs[1].x = pMB->qmvs[2].x = pMB->qmvs[3].x = 0;
741            pMB->qmvs[0].y = pMB->qmvs[1].y = pMB->qmvs[2].y = pMB->qmvs[3].y = 0;
742    
743          *currMV=pmv[0];         /* current best := prediction */          pMB->sad16 = pMB->sad8[0] = pMB->sad8[1] = pMB->sad8[2] = pMB->sad8[3] = sad;
         if (!(MotionFlags & PMV_HALFPEL16 ))  
         {       /* This should NOT be necessary! */  
                 currMV->x = EVEN(currMV->x);  
                 currMV->y = EVEN(currMV->y);  
744          }          }
745    
746          if (currMV->x > max_dx)  bool
747          {  MotionEstimation(MBParam * const pParam,
748                  currMV->x=max_dx;                                   FRAMEINFO * const current,
749          }                                   FRAMEINFO * const reference,
750          if (currMV->x < min_dx)                                   const IMAGE * const pRefH,
751          {                                   const IMAGE * const pRefV,
752                  currMV->x=min_dx;                                   const IMAGE * const pRefHV,
753          }                                   const uint32_t iLimit)
         if (currMV->y > max_dy)  
754          {          {
755                  currMV->y=max_dy;          MACROBLOCK *const pMBs = current->mbs;
756            const IMAGE *const pCurrent = &current->image;
757            const IMAGE *const pRef = &reference->image;
758    
759            const VECTOR zeroMV = { 0, 0 };
760    
761            uint32_t x, y;
762            uint32_t iIntra = 0;
763            int32_t InterBias, quant = current->quant, sad00;
764            uint8_t *qimage;
765    
766            // some pre-initialized thingies for SearchP
767            int32_t temp[5];
768            VECTOR currentMV[5];
769            VECTOR currentQMV[5];
770            int32_t iMinSAD[5];
771            SearchData Data;
772            Data.iEdgedWidth = pParam->edged_width;
773            Data.currentMV = currentMV;
774            Data.currentQMV = currentQMV;
775            Data.iMinSAD = iMinSAD;
776            Data.temp = temp;
777            Data.iFcode = current->fcode;
778            Data.rounding = pParam->m_rounding_type;
779            Data.qpel = pParam->m_quarterpel;
780            Data.chroma = current->global_flags & XVID_ME_COLOUR;
781    
782            if((qimage = (uint8_t *) malloc(32 * pParam->edged_width)) == NULL)
783                    return 1; // allocate some mem for qpel interpolated blocks
784                                      // somehow this is dirty since I think we shouldn't use malloc outside
785                                      // encoder_create() - so please fix me!
786            Data.RefQ = qimage;
787            if (sadInit) (*sadInit) ();
788    
789            for (y = 0; y < pParam->mb_height; y++) {
790                    for (x = 0; x < pParam->mb_width; x++)  {
791                            MACROBLOCK *pMB = &pMBs[x + y * pParam->mb_width];
792    
793                            pMB->sad16
794                                    = sad16v(pCurrent->y + (x + y * pParam->edged_width) * 16,
795                                                            pRef->y + (x + y * pParam->edged_width) * 16,
796                                                            pParam->edged_width, pMB->sad8 );
797    
798                            if (Data.chroma) {
799                                    pMB->sad16 += sad8(pCurrent->u + x*8 + y*(pParam->edged_width/2)*8,
800                                                                    pRef->u + x*8 + y*(pParam->edged_width/2)*8, pParam->edged_width/2);
801    
802                                    pMB->sad16 += sad8(pCurrent->v + (x + y*(pParam->edged_width/2))*8,
803                                                                    pRef->v + (x + y*(pParam->edged_width/2))*8, pParam->edged_width/2);
804                            }
805    
806                            sad00 = pMB->sad16; //if no gmc; else sad00 = (..)
807    
808                            if (!(current->global_flags & XVID_LUMIMASKING)) {
809                                    pMB->dquant = NO_CHANGE;
810                                    pMB->quant = current->quant;
811                            } else {
812                                    if (pMB->dquant != NO_CHANGE) {
813                                            quant += DQtab[pMB->dquant];
814                                            if (quant > 31) quant = 31;
815                                            else if (quant < 1) quant = 1;
816                                    }
817                                    pMB->quant = quant;
818                            }
819    
820    //initial skip decision
821    /* no early skip for GMC (global vector = skip vector is unknown!)  */
822                            if (current->coding_type == P_VOP)      { /* no fast SKIP for S(GMC)-VOPs */
823                                    if (pMB->dquant == NO_CHANGE && sad00 < pMB->quant * INITIAL_SKIP_THRESH)
824                                            if (Data.chroma || SkipDecisionP(pCurrent, pRef, x, y, pParam->edged_width, pMB->quant)) {
825                                                    SkipMacroblockP(pMB, sad00);
826                                                    continue;
827          }          }
         if (currMV->y < min_dy)  
         {  
                 currMV->y=min_dy;  
828          }          }
829    
830          iMinSAD = sad16( cur,                          SearchP(pRef, pRefH->y, pRefV->y, pRefHV->y, pCurrent, x,
831                           get_ref_mv(pRef, pRefH, pRefV, pRefHV, x, y, 16, currMV, iEdgedWidth),                                                  y, current->motion_flags, pMB->quant,
832                           iEdgedWidth, MV_MAX_ERROR);                                                  &Data, pParam, pMBs, reference->mbs,
833          iMinSAD += calc_delta_16(currMV->x-pmv[0].x, currMV->y-pmv[0].y, (uint8_t)iFcode) * iQuant;                                                  current->global_flags & XVID_INTER4V, pMB);
834    
835          if ( (iMinSAD < 256 ) || ( (MVequal(*currMV,pMB->mvs[0])) && (iMinSAD < pMB->sad16) ) )  /* final skip decision, a.k.a. "the vector you found, really that good?" */
836          {                          if (current->coding_type == P_VOP)      {
837                                    if ( (pMB->dquant == NO_CHANGE) && (sad00 < pMB->quant * MAX_SAD00_FOR_SKIP)
838                  if (MotionFlags & PMV_QUICKSTOP16)                                  && ((100*pMB->sad16)/(sad00+1) > FINAL_SKIP_THRESH) )
839                          goto PMVfast16_Terminate_without_Refine;                                          if (Data.chroma || SkipDecisionP(pCurrent, pRef, x, y, pParam->edged_width, pMB->quant)) {
840                  if (MotionFlags & PMV_EARLYSTOP16)                                                  SkipMacroblockP(pMB, sad00);
841                          goto PMVfast16_Terminate_with_Refine;                                                  continue;
842                                            }
843          }          }
844    
845  /*  /* finally, intra decision */
    Step 5: Calculate SAD for motion vectors taken from left block, top, top-right, and Previous frame block.  
    Also calculate (0,0) but do not subtract offset.  
    Let MinSAD be the smallest SAD up to this point.  
    If MV is (0,0) subtract offset. ******** WHAT'S THIS 'OFFSET' ??? ***********  
 */  
846    
847  // (0,0) is always possible                          InterBias = MV16_INTER_BIAS;
848                            if (pMB->quant > 8)  InterBias += 80 * (pMB->quant - 8); // to make high quants work
849                            if (y != 0)
850                                    if ((pMB - pParam->mb_width)->mode == MODE_INTER ) InterBias -= 80;
851                            if (x != 0)
852                                    if ((pMB - 1)->mode == MODE_INTER ) InterBias -= 80;
853    
854          CHECK_MV16_ZERO;                          if (Data.chroma) InterBias += 50; // to compensate bigger SAD
855    
856  // previous frame MV is always possible                          if (InterBias < pMB->sad16)  {
857          CHECK_MV16_CANDIDATE(pMB->mvs[0].x,pMB->mvs[0].y);                                  const int32_t deviation =
858                                            dev16(pCurrent->y + (x + y * pParam->edged_width) * 16,
859                                                      pParam->edged_width);
860    
861  // left neighbour, if allowed                                  if (deviation < (pMB->sad16 - InterBias)) {
862          if (x != 0)                                          if (++iIntra >= iLimit) { free(qimage); return 1; }
863          {                                          pMB->mode = MODE_INTRA;
864                  if (!(MotionFlags & PMV_HALFPEL16 ))                                          pMB->mvs[0] = pMB->mvs[1] = pMB->mvs[2] =
865                  {       pmv[1].x = EVEN(pmv[1].x);                                                          pMB->mvs[3] = zeroMV;
866                  pmv[1].y = EVEN(pmv[1].y);                                          pMB->qmvs[0] = pMB->qmvs[1] = pMB->qmvs[2] =
867                  }                                                          pMB->qmvs[3] = zeroMV;
868                  CHECK_MV16_CANDIDATE(pmv[1].x,pmv[1].y);                                          pMB->sad16 = pMB->sad8[0] = pMB->sad8[1] = pMB->sad8[2] =
869                                                    pMB->sad8[3] = 0;
870          }          }
   
 // top neighbour, if allowed  
         if (y != 0)  
         {  
                 if (!(MotionFlags & PMV_HALFPEL16 ))  
                 {       pmv[2].x = EVEN(pmv[2].x);  
                 pmv[2].y = EVEN(pmv[2].y);  
871                  }                  }
                 CHECK_MV16_CANDIDATE(pmv[2].x,pmv[2].y);  
   
 // top right neighbour, if allowed  
                 if (x != (iWcount-1))  
                 {  
                         if (!(MotionFlags & PMV_HALFPEL16 ))  
                         {       pmv[3].x = EVEN(pmv[3].x);  
                         pmv[3].y = EVEN(pmv[3].y);  
                         }  
                         CHECK_MV16_CANDIDATE(pmv[3].x,pmv[3].y);  
872                  }                  }
873          }          }
874            free(qimage);
875    
876  /* Step 6: If MinSAD <= thresa goto Step 10.          if (current->coding_type == S_VOP)      /* first GMC step only for S(GMC)-VOPs */
877     If Motion Vector equal to Previous frame motion vector and MinSAD<PrevFrmSAD goto Step 10.                  current->GMC_MV = GlobalMotionEst( pMBs, pParam, current->fcode );
878  */          else
879                    current->GMC_MV = zeroMV;
880    
881          if ( (iMinSAD <= threshA) || ( MVequal(*currMV,pMB->mvs[0]) && (iMinSAD < pMB->sad16) ) )          return 0;
         {  
                 if (MotionFlags & PMV_QUICKSTOP16)  
                         goto PMVfast16_Terminate_without_Refine;  
                 if (MotionFlags & PMV_EARLYSTOP16)  
                         goto PMVfast16_Terminate_with_Refine;  
882          }          }
883    
884    
885  /************ (Diamond Search)  **************/  #define PMV_HALFPEL16 (PMV_HALFPELDIAMOND16|PMV_HALFPELREFINE16)
 /*  
    Step 7: Perform Diamond search, with either the small or large diamond.  
    If Found=2 only examine one Diamond pattern, and afterwards goto step 10  
    Step 8: If small diamond, iterate small diamond search pattern until motion vector lies in the center of the diamond.  
    If center then goto step 10.  
    Step 9: If large diamond, iterate large diamond search pattern until motion vector lies in the center.  
    Refine by using small diamond and goto step 10.  
 */  
   
         backupMV = *currMV; /* save best prediction, actually only for EXTSEARCH */  
   
 /* default: use best prediction as starting point for one call of PMVfast_MainSearch */  
         iSAD = Diamond16_MainSearch(pRef, pRefH, pRefV, pRefHV, cur,  
                                           x, y,  
                                           currMV->x, currMV->y, iMinSAD, &newMV,  
                                           pmv, min_dx, max_dx, min_dy, max_dy, iEdgedWidth, iDiamondSize, iFcode, iQuant, iFound);  
886    
887          if (iSAD < iMinSAD)  static __inline int
888    make_mask(const VECTOR * const pmv, const int i)
889          {          {
890                  *currMV = newMV;          int mask = 255, j;
891                  iMinSAD = iSAD;          for (j = 0; j < i; j++) {
892                    if (MVequal(pmv[i], pmv[j])) return 0; // same vector has been checked already
893                    if (pmv[i].x == pmv[j].x) {
894                            if (pmv[i].y == pmv[j].y + iDiamondSize) { mask &= ~4; continue; }
895                            if (pmv[i].y == pmv[j].y - iDiamondSize) { mask &= ~8; continue; }
896                    } else
897                            if (pmv[i].y == pmv[j].y) {
898                                    if (pmv[i].x == pmv[j].x + iDiamondSize) { mask &= ~1; continue; }
899                                    if (pmv[i].x == pmv[j].x - iDiamondSize) { mask &= ~2; continue; }
900          }          }
   
         if (MotionFlags & PMV_EXTSEARCH16)  
         {  
 /* extended: search (up to) two more times: orignal prediction and (0,0) */  
   
                 if (!(MVequal(pmv[0],backupMV)) )  
                 {       iSAD = Diamond16_MainSearch(pRef, pRefH, pRefV, pRefHV, cur,  
                                                           x, y,  
                                                           pmv[0].x, pmv[0].y, iMinSAD, &newMV,  
                                                           pmv, min_dx, max_dx, min_dy, max_dy, iEdgedWidth, iDiamondSize, iFcode, iQuant, iFound);  
   
                 if (iSAD < iMinSAD)  
                 {  
                         *currMV = newMV;  
                         iMinSAD = iSAD;  
901                  }                  }
902            return mask;
903                  }                  }
904    
905                  if ( (!(MVzero(pmv[0]))) && (!(MVzero(backupMV))) )  static __inline void
906                  {       iSAD = Diamond16_MainSearch(pRef, pRefH, pRefV, pRefHV, cur,  PreparePredictionsP(VECTOR * const pmv, int x, int y, const int iWcount,
907                                                            x, y,                          const int iHcount, const MACROBLOCK * const prevMB)
                                                           0, 0, iMinSAD, &newMV,  
                                                           pmv, min_dx, max_dx, min_dy, max_dy, iEdgedWidth, iDiamondSize, iFcode, iQuant, iFound);  
   
                 if (iSAD < iMinSAD)  
908                  {                  {
                         *currMV = newMV;  
                         iMinSAD = iSAD;  
                 }  
                 }  
         }  
   
 /*  
    Step 10:  The motion vector is chosen according to the block corresponding to MinSAD.  
 */  
909    
910  PMVfast16_Terminate_with_Refine:  //this function depends on get_pmvdata which means that it sucks. It should get the predictions by itself
         if (MotionFlags & PMV_HALFPELREFINE16)          // perform final half-pel step  
                 iMinSAD = Halfpel16_Refine( pRef, pRefH, pRefV, pRefHV, cur,  
                                   x, y,  
                                   currMV, iMinSAD,  
                                   pmv, min_dx, max_dx, min_dy, max_dy, iFcode, iQuant, iEdgedWidth);  
911    
912  PMVfast16_Terminate_without_Refine:          if ( (y != 0) && (x != (iWcount-1)) ) {         // [5] top-right neighbour
913          currPMV->x = currMV->x - pmv[0].x;                  pmv[5].x = EVEN(pmv[3].x);
914          currPMV->y = currMV->y - pmv[0].y;                  pmv[5].y = EVEN(pmv[3].y);
915          return iMinSAD;          } else pmv[5].x = pmv[5].y = 0;
 }  
916    
917            if (x != 0) { pmv[3].x = EVEN(pmv[1].x); pmv[3].y = EVEN(pmv[1].y); }// pmv[3] is left neighbour
918            else pmv[3].x = pmv[3].y = 0;
919    
920            if (y != 0) { pmv[4].x = EVEN(pmv[2].x); pmv[4].y = EVEN(pmv[2].y); }// [4] top neighbour
921        else pmv[4].x = pmv[4].y = 0;
922    
923            // [1] median prediction
924            pmv[1].x = EVEN(pmv[0].x); pmv[1].y = EVEN(pmv[0].y);
925    
926            pmv[0].x = pmv[0].y = 0; // [0] is zero; not used in the loop (checked before) but needed here for make_mask
927    
928            pmv[2].x = EVEN(prevMB->mvs[0].x); // [2] is last frame
929            pmv[2].y = EVEN(prevMB->mvs[0].y);
930    
931  int32_t Diamond8_MainSearch(          if ((x != iWcount-1) && (y != iHcount-1)) {
932          const uint8_t * const pRef,                  pmv[6].x = EVEN((prevMB+1+iWcount)->mvs[0].x); //[6] right-down neighbour in last frame
933          const uint8_t * const pRefH,                  pmv[6].y = EVEN((prevMB+1+iWcount)->mvs[0].y);
934          const uint8_t * const pRefV,          } else pmv[6].x = pmv[6].y = 0;
         const uint8_t * const pRefHV,  
         const uint8_t * const cur,  
         const int x, const int y,  
         int32_t startx, int32_t starty,  
         int32_t iMinSAD,  
         VECTOR * const currMV,  
         const VECTOR * const pmv,  
         const int32_t min_dx, const int32_t max_dx,  
         const int32_t min_dy, const int32_t max_dy,  
         const int32_t iEdgedWidth,  
         const int32_t iDiamondSize,  
         const int32_t iFcode,  
         const int32_t iQuant,  
         int iFound)  
 {  
 /* Do a diamond search around given starting point, return SAD of best */  
   
         int32_t iDirection=0;  
         int32_t iSAD;  
         VECTOR backupMV;  
         backupMV.x = startx;  
         backupMV.y = starty;  
   
 /* It's one search with full Diamond pattern, and only 3 of 4 for all following diamonds */  
   
         CHECK_MV8_CANDIDATE_DIR(backupMV.x-iDiamondSize,backupMV.y,1);  
         CHECK_MV8_CANDIDATE_DIR(backupMV.x+iDiamondSize,backupMV.y,2);  
         CHECK_MV8_CANDIDATE_DIR(backupMV.x,backupMV.y-iDiamondSize,3);  
         CHECK_MV8_CANDIDATE_DIR(backupMV.x,backupMV.y+iDiamondSize,4);  
   
         if (iDirection)  
                 while (!iFound)  
                 {  
                         iFound = 1;  
                         backupMV=*currMV;       // since iDirection!=0, this is well defined!  
   
                         if ( iDirection != 2)  
                                 CHECK_MV8_CANDIDATE_FOUND(backupMV.x-iDiamondSize,backupMV.y,1);  
                         if ( iDirection != 1)  
                                 CHECK_MV8_CANDIDATE_FOUND(backupMV.x+iDiamondSize,backupMV.y,2);  
                         if ( iDirection != 4)  
                                 CHECK_MV8_CANDIDATE_FOUND(backupMV.x,backupMV.y-iDiamondSize,3);  
                         if ( iDirection != 3)  
                                 CHECK_MV8_CANDIDATE_FOUND(backupMV.x,backupMV.y+iDiamondSize,4);  
                 }  
         else  
         {  
                 currMV->x = startx;  
                 currMV->y = starty;  
         }  
         return iMinSAD;  
935  }  }
936    
937  int32_t Halfpel8_Refine(  static void
938          const uint8_t * const pRef,  SearchP(const IMAGE * const pRef,
939          const uint8_t * const pRefH,          const uint8_t * const pRefH,
940          const uint8_t * const pRefV,          const uint8_t * const pRefV,
941          const uint8_t * const pRefHV,          const uint8_t * const pRefHV,
942          const uint8_t * const cur,                  const IMAGE * const pCur,
943          const int x, const int y,                  const int x,
944          VECTOR * const currMV,                  const int y,
945          int32_t iMinSAD,                  const uint32_t MotionFlags,
946          const VECTOR * const pmv,                  const uint32_t iQuant,
947          const int32_t min_dx, const int32_t max_dx,                  SearchData * const Data,
948          const int32_t min_dy, const int32_t max_dy,                  const MBParam * const pParam,
949          const int32_t iFcode,                  const MACROBLOCK * const pMBs,
950          const int32_t iQuant,                  const MACROBLOCK * const prevMBs,
951          const int32_t iEdgedWidth)                  int inter4v,
952  {                  MACROBLOCK * const pMB)
953  /* Do a half-pel refinement (or rather a "smallest possible amount" refinement) */  {
954    
955            int i, iDirection = 255, mask, threshA;
956            VECTOR pmv[7];
957    
958            get_pmvdata2(pMBs, pParam->mb_width, 0, x, y, 0, pmv, Data->temp);  //has to be changed to get_pmv(2)()
959            get_range(&Data->min_dx, &Data->max_dx, &Data->min_dy, &Data->max_dy, x, y, 16,
960                                    pParam->width, pParam->height, Data->iFcode, pParam->m_quarterpel);
961    
962            Data->predMV = pmv[0];
963    
964            Data->Cur = pCur->y + (x + y * Data->iEdgedWidth) * 16;
965            Data->CurV = pCur->v + (x + y * (Data->iEdgedWidth/2)) * 8;
966            Data->CurU = pCur->u + (x + y * (Data->iEdgedWidth/2)) * 8;
967    
968            Data->Ref = pRef->y + (x + Data->iEdgedWidth*y) * 16;
969            Data->RefH = pRefH + (x + Data->iEdgedWidth*y) * 16;
970            Data->RefV = pRefV + (x + Data->iEdgedWidth*y) * 16;
971            Data->RefHV = pRefHV + (x + Data->iEdgedWidth*y) * 16;
972            Data->RefCV = pRef->v + (x + y * (Data->iEdgedWidth/2)) * 8;
973            Data->RefCU = pRef->u + (x + y * (Data->iEdgedWidth/2)) * 8;
974    
975            Data->lambda16 = lambda_vec16[iQuant];
976            Data->lambda8 = lambda_vec8[iQuant];
977    
978            if (!(MotionFlags & PMV_HALFPEL16)) {
979                    Data->min_dx = EVEN(Data->min_dx);
980                    Data->max_dx = EVEN(Data->max_dx);
981                    Data->min_dy = EVEN(Data->min_dy);
982                    Data->max_dy = EVEN(Data->max_dy); }
983    
984            if (pMB->dquant != NO_CHANGE) inter4v = 0;
985    
986            for(i = 0;  i < 5; i++)
987                    Data->currentMV[i].x = Data->currentMV[i].y = 0;
988    
989            if (pParam->m_quarterpel) {
990                    Data->predQMV = get_qpmv2(pMBs, pParam->mb_width, 0, x, y, 0);
991                    i = d_mv_bits(Data->predQMV.x, Data->predQMV.y, Data->iFcode);
992            } else i = d_mv_bits(Data->predMV.x, Data->predMV.y, Data->iFcode);
993    
994            Data->iMinSAD[0] = pMB->sad16 + (Data->lambda16 * i * pMB->sad16)/1000;
995            Data->iMinSAD[1] = pMB->sad8[0] + (Data->lambda8 * i * (pMB->sad8[0]+NEIGH_8X8_BIAS))/100;
996            Data->iMinSAD[2] = pMB->sad8[1];
997            Data->iMinSAD[3] = pMB->sad8[2];
998            Data->iMinSAD[4] = pMB->sad8[3];
999    
1000            if ((x == 0) && (y == 0)) threshA = 512;
1001            else {
1002                    threshA = Data->temp[0]; // that's when we keep this SAD atm
1003                    if (threshA < 512) threshA = 512;
1004                    if (threshA > 1024) threshA = 1024; }
1005    
1006            PreparePredictionsP(pmv, x, y, pParam->mb_width, pParam->mb_height,
1007                                            prevMBs + x + y * pParam->mb_width);
1008    
1009          int32_t iSAD;          if (inter4v || pParam->m_quarterpel || Data->chroma) CheckCandidate = CheckCandidate16;
1010          VECTOR backupMV = *currMV;          else CheckCandidate = CheckCandidate16no4v;
1011    
1012          CHECK_MV8_CANDIDATE(backupMV.x-1,backupMV.y-1);  /* main loop. checking all predictions */
         CHECK_MV8_CANDIDATE(backupMV.x  ,backupMV.y-1);  
         CHECK_MV8_CANDIDATE(backupMV.x+1,backupMV.y-1);  
         CHECK_MV8_CANDIDATE(backupMV.x-1,backupMV.y);  
         CHECK_MV8_CANDIDATE(backupMV.x+1,backupMV.y);  
         CHECK_MV8_CANDIDATE(backupMV.x-1,backupMV.y+1);  
         CHECK_MV8_CANDIDATE(backupMV.x  ,backupMV.y+1);  
         CHECK_MV8_CANDIDATE(backupMV.x+1,backupMV.y+1);  
1013    
1014          return iMinSAD;          for (i = 1; i < 7; i++) {
1015                    if (!(mask = make_mask(pmv, i)) ) continue;
1016                    (*CheckCandidate)(pmv[i].x, pmv[i].y, mask, &iDirection, Data);
1017                    if (Data->iMinSAD[0] <= threshA) break;
1018  }  }
1019    
1020            if ((Data->iMinSAD[0] <= threshA) ||
1021                            (MVequal(Data->currentMV[0], (prevMBs+x+y*pParam->mb_width)->mvs[0]) &&
1022                            (Data->iMinSAD[0] < (prevMBs+x+y*pParam->mb_width)->sad16))) {
1023                    inter4v = 0;
1024            } else {
1025    
1026  #define PMV_HALFPEL8 (PMV_HALFPELDIAMOND8|PMV_HALFPELREFINE8)                  MainSearchFunc * MainSearchPtr;
1027                    if (MotionFlags & PMV_USESQUARES16) MainSearchPtr = SquareSearch;
1028                    else if (MotionFlags & PMV_ADVANCEDDIAMOND16) MainSearchPtr = AdvDiamondSearch;
1029                            else MainSearchPtr = DiamondSearch;
1030    
1031  int32_t PMVfastSearch8(                  (*MainSearchPtr)(Data->currentMV->x, Data->currentMV->y, Data, iDirection);
                                         const uint8_t * const pRef,  
                                         const uint8_t * const pRefH,  
                                         const uint8_t * const pRefV,  
                                         const uint8_t * const pRefHV,  
                                         const IMAGE * const pCur,  
                                         const int x, const int y,  
                                         const int start_x, int start_y,  
                                         const uint32_t MotionFlags,  
                                         const MBParam * const pParam,  
                                         MACROBLOCK * const pMBs,  
                                         VECTOR * const currMV,  
                                         VECTOR * const currPMV)  
 {  
         const uint32_t iWcount = pParam->mb_width;  
1032    
1033          const int32_t iFcode = pParam->fixed_code;  /* extended search, diamond starting in 0,0 and in prediction.
1034          const int32_t iQuant = pParam->quant;          note that this search is/might be done in halfpel positions,
1035          const int32_t iWidth = pParam->width;          which makes it more different than the diamond above */
         const int32_t iHeight = pParam->height;  
         const int32_t iEdgedWidth = pParam->edged_width;  
1036    
1037          const uint8_t * cur = pCur->y + x*8 + y*8*iEdgedWidth;                  if (MotionFlags & PMV_EXTSEARCH16) {
1038                            int32_t bSAD;
1039                            VECTOR startMV = Data->predMV, backupMV = Data->currentMV[0];
1040                            if (!(MotionFlags & PMV_HALFPELREFINE16)) // who's gonna use extsearch and no halfpel?
1041                                    startMV.x = EVEN(startMV.x); startMV.y = EVEN(startMV.y);
1042                            if (!(MVequal(startMV, backupMV))) {
1043                                    bSAD = Data->iMinSAD[0]; Data->iMinSAD[0] = MV_MAX_ERROR;
1044    
1045          int32_t iDiamondSize;                                  (*CheckCandidate)(startMV.x, startMV.y, 255, &iDirection, Data);
1046                                    (*MainSearchPtr)(startMV.x, startMV.y, Data, 255);
1047                                    if (bSAD < Data->iMinSAD[0]) {
1048                                            Data->currentMV[0] = backupMV;
1049                                            Data->iMinSAD[0] = bSAD; }
1050                            }
1051    
1052          int32_t min_dx;                          backupMV = Data->currentMV[0];
1053          int32_t max_dx;                          if (MotionFlags & PMV_HALFPELREFINE16) startMV.x = startMV.y = 1;
1054          int32_t min_dy;                          else startMV.x = startMV.y = 0;
1055          int32_t max_dy;                          if (!(MVequal(startMV, backupMV))) {
1056                                    bSAD = Data->iMinSAD[0]; Data->iMinSAD[0] = MV_MAX_ERROR;
1057    
1058          VECTOR pmv[4];                                  (*CheckCandidate)(startMV.x, startMV.y, 255, &iDirection, Data);
1059          int32_t psad[4];                                  (*MainSearchPtr)(startMV.x, startMV.y, Data, 255);
1060          VECTOR newMV;                                  if (bSAD < Data->iMinSAD[0]) {
1061          VECTOR backupMV;                                          Data->currentMV[0] = backupMV;
1062                                            Data->iMinSAD[0] = bSAD; }
1063                            }
1064                    }
1065            }
1066    
1067          MACROBLOCK * const pMB = pMBs + (x>>1) + (y>>1) * iWcount;          if (MotionFlags & PMV_HALFPELREFINE16) HalfpelRefine(Data);
1068    
1069          static int32_t threshA,threshB;          for(i = 0; i < 5; i++) {
1070          int32_t iFound,bPredEq;                  Data->currentQMV[i].x = 2 * Data->currentMV[i].x; // initialize qpel vectors
1071          int32_t iMinSAD,iSAD;                  Data->currentQMV[i].y = 2 * Data->currentMV[i].y;
1072            }
1073    
1074          int32_t iSubBlock = ((y&1)<<1) + (x&1);          if((pParam->m_quarterpel) && (MotionFlags & PMV_QUARTERPELREFINE16)) {
1075    
1076  /* Get maximum range */                  CheckCandidate = CheckCandidate16_qpel;
1077          get_range(&min_dx, &max_dx, &min_dy, &max_dy,                  get_range(&Data->min_dx, &Data->max_dx, &Data->min_dy, &Data->max_dy, x, y, 16,
1078                    x, y, 8, iWidth, iHeight, iFcode);                                  pParam->width, pParam->height, Data->iFcode, 0);
1079    
1080  /* we work with abs. MVs, not relative to prediction, so range is relative to 0,0 */                  QuarterpelRefine(Data);
1081            }
1082    
1083          if (!(MotionFlags & PMV_HALFPELDIAMOND8 ))          if (Data->iMinSAD[0] < (int32_t)iQuant * 30 ) inter4v = 0;
1084          { min_dx = EVEN(min_dx);          if (inter4v) {
1085          max_dx = EVEN(max_dx);                  SearchData Data8;
1086          min_dy = EVEN(min_dy);                  Data8.iFcode = Data->iFcode;
1087          max_dy = EVEN(max_dy);                  Data8.lambda8 = Data->lambda8;
1088          }               /* because we might use IF (dx>max_dx) THEN dx=max_dx; */                  Data8.iEdgedWidth = Data->iEdgedWidth;
1089                    Data8.RefQ = Data->RefQ;
1090                    Data8.qpel = Data->qpel;
1091                    Search8(Data, 2*x, 2*y, MotionFlags, pParam, pMB, pMBs, 0, &Data8);
1092                    Search8(Data, 2*x + 1, 2*y, MotionFlags, pParam, pMB, pMBs, 1, &Data8);
1093                    Search8(Data, 2*x, 2*y + 1, MotionFlags, pParam, pMB, pMBs, 2, &Data8);
1094                    Search8(Data, 2*x + 1, 2*y + 1, MotionFlags, pParam, pMB, pMBs, 3, &Data8);
1095    
1096                    if (Data->chroma) {
1097                            int sum, dx, dy;
1098    
1099          bPredEq  = get_pmvdata(pMBs, (x>>1), (y>>1), iWcount, iSubBlock, pmv, psad);                          if(pParam->m_quarterpel) {
1100                                    sum = pMB->qmvs[0].y/2 + pMB->qmvs[1].y/2 + pMB->qmvs[2].y/2 + pMB->qmvs[3].y/2;
1101                            } else sum = pMB->mvs[0].y + pMB->mvs[1].y + pMB->mvs[2].y + pMB->mvs[3].y;
1102                            dy = (sum >> 3) + roundtab_76[sum & 0xf];
1103    
1104          if ((x==0) && (y==0) )                          if(pParam->m_quarterpel) {
1105          {                                  sum = pMB->qmvs[0].x/2 + pMB->qmvs[1].x/2 + pMB->qmvs[2].x/2 + pMB->qmvs[3].x/2;
1106                  threshA =  512/4;                          } else sum = pMB->mvs[0].x + pMB->mvs[1].x + pMB->mvs[2].x + pMB->mvs[3].x;
1107                  threshB = 1024/4;                          dx = (sum >> 3) + roundtab_76[sum & 0xf];
1108    
1109                            Data->iMinSAD[1] += ChromaSAD(dx, dy, Data);
1110          }          }
         else  
         {  
                 threshA = psad[0]/4;                    /* good estimate */  
                 threshB = threshA+256/4;  
                 if (threshA< 512/4) threshA =  512/4;  
                 if (threshA>1024/4) threshA = 1024/4;  
                 if (threshB>1792/4) threshB = 1792/4;  
1111          }          }
1112    
1113          iFound=0;          if (!(inter4v) ||
1114                    (Data->iMinSAD[0] < Data->iMinSAD[1] + Data->iMinSAD[2] +
1115  /* Step 2: Calculate Distance= |MedianMVX| + |MedianMVY| where MedianMV is the motion                          Data->iMinSAD[3] + Data->iMinSAD[4] + IMV16X16 * (int32_t)iQuant )) {
1116     vector of the median.  // INTER MODE
1117     If PredEq=1 and MVpredicted = Previous Frame MV, set Found=2                  pMB->mode = MODE_INTER;
1118  */                  pMB->mvs[0] = pMB->mvs[1]
1119                            = pMB->mvs[2] = pMB->mvs[3] = Data->currentMV[0];
1120    
1121          if ((bPredEq) && (MVequal(pmv[0],pMB->mvs[iSubBlock]) ) )                  pMB->qmvs[0] = pMB->qmvs[1]
1122                  iFound=2;                          = pMB->qmvs[2] = pMB->qmvs[3] = Data->currentQMV[0];
1123    
1124  /* Step 3: If Distance>0 or thresb<1536 or PredEq=1 Select small Diamond Search.                  pMB->sad16 = pMB->sad8[0] = pMB->sad8[1] =
1125     Otherwise select large Diamond Search.                          pMB->sad8[2] = pMB->sad8[3] =  Data->iMinSAD[0];
 */  
1126    
1127          if ( (pmv[0].x != 0) || (pmv[0].y != 0) || (threshB<1536/4) || (bPredEq) )                  if(pParam->m_quarterpel) {
1128                  iDiamondSize=1; // 1 halfpel!                          pMB->pmvs[0].x = Data->currentQMV[0].x - Data->predQMV.x;
1129          else                          pMB->pmvs[0].y = Data->currentQMV[0].y - Data->predQMV.y;
1130                  iDiamondSize=2; // 2 halfpel = 1 full pixel!                  } else {
1131                            pMB->pmvs[0].x = Data->currentMV[0].x - Data->predMV.x;
1132                            pMB->pmvs[0].y = Data->currentMV[0].y - Data->predMV.y;
1133                    }
1134            } else {
1135    // INTER4V MODE; all other things are already set in Search8
1136                    pMB->mode = MODE_INTER4V;
1137                    pMB->sad16 = Data->iMinSAD[1] + Data->iMinSAD[2] +
1138                            Data->iMinSAD[3] + Data->iMinSAD[4] + IMV16X16 * iQuant;
1139            }
1140    }
1141    
1142          if (!(MotionFlags & PMV_HALFPELDIAMOND8) )  static void
1143                  iDiamondSize*=2;  Search8(const SearchData * const OldData,
1144                    const int x, const int y,
1145                    const uint32_t MotionFlags,
1146                    const MBParam * const pParam,
1147                    MACROBLOCK * const pMB,
1148                    const MACROBLOCK * const pMBs,
1149                    const int block,
1150                    SearchData * const Data)
1151    {
1152            Data->iMinSAD = OldData->iMinSAD + 1 + block;
1153            Data->currentMV = OldData->currentMV + 1 + block;
1154            Data->currentQMV = OldData->currentQMV + 1 + block;
1155    
1156  /* Step 4: Calculate SAD around the Median prediction.          if(pParam->m_quarterpel) {
1157     MinSAD=SAD                  Data->predQMV = get_qpmv2(pMBs, pParam->mb_width, 0, x/2 , y/2, block);
1158     If Motion Vector equal to Previous frame motion vector                  if (block != 0) *(Data->iMinSAD) += (Data->lambda8 *
1159     and MinSAD<PrevFrmSAD goto Step 10.                                                                          d_mv_bits(      Data->currentQMV->x - Data->predQMV.x,
1160     If SAD<=256 goto Step 10.                                                                                                  Data->currentQMV->y - Data->predQMV.y,
1161  */                                                                                                  Data->iFcode) * (*Data->iMinSAD + NEIGH_8X8_BIAS))/100;
1162            } else {
1163                    Data->predMV = get_pmv2(pMBs, pParam->mb_width, 0, x/2 , y/2, block);
1164                    if (block != 0) *(Data->iMinSAD) += (Data->lambda8 *
1165                                                                            d_mv_bits(      Data->currentMV->x - Data->predMV.x,
1166                                                                                                    Data->currentMV->y - Data->predMV.y,
1167                                                                                                    Data->iFcode) * (*Data->iMinSAD + NEIGH_8X8_BIAS))/100;
1168            }
1169    
1170            if (MotionFlags & (PMV_EXTSEARCH8|PMV_HALFPELREFINE8)) {
1171    
1172  // Prepare for main loop                  Data->Ref = OldData->Ref + 8 * ((block&1) + pParam->edged_width*(block>>1));
1173                    Data->RefH = OldData->RefH + 8 * ((block&1) + pParam->edged_width*(block>>1));
1174                    Data->RefV = OldData->RefV + 8 * ((block&1) + pParam->edged_width*(block>>1));
1175                    Data->RefHV = OldData->RefHV + 8 * ((block&1) + pParam->edged_width*(block>>1));
1176    
1177          currMV->x=start_x;              /* start with mv16 */                  Data->Cur = OldData->Cur + 8 * ((block&1) + pParam->edged_width*(block>>1));
         currMV->y=start_y;  
1178    
1179          iMinSAD = sad8( cur,                  get_range(&Data->min_dx, &Data->max_dx, &Data->min_dy, &Data->max_dy, x, y, 8,
1180                          get_ref_mv(pRef, pRefH, pRefV, pRefHV, x, y, 8, currMV, iEdgedWidth),                                  pParam->width, pParam->height, OldData->iFcode, pParam->m_quarterpel);
1181                          iEdgedWidth);                  CheckCandidate = CheckCandidate8;
         iMinSAD += calc_delta_8(currMV->x - pmv[0].x, currMV->y - pmv[0].y, (uint8_t)iFcode) * iQuant;  
1182    
1183          if ( (iMinSAD < 256/4 ) || ( (MVequal(*currMV,pMB->mvs[iSubBlock])) && (iMinSAD < pMB->sad8[iSubBlock]) ) )                  if (MotionFlags & PMV_EXTSEARCH8) {
1184          {                          int32_t temp_sad = *(Data->iMinSAD); // store current MinSAD
                 if (MotionFlags & PMV_QUICKSTOP16)  
                         goto PMVfast8_Terminate_without_Refine;  
                 if (MotionFlags & PMV_EARLYSTOP16)  
                         goto PMVfast8_Terminate_with_Refine;  
         }  
1185    
1186                            MainSearchFunc *MainSearchPtr;
1187                            if (MotionFlags & PMV_USESQUARES8) MainSearchPtr = SquareSearch;
1188                                    else if (MotionFlags & PMV_ADVANCEDDIAMOND8) MainSearchPtr = AdvDiamondSearch;
1189                                            else MainSearchPtr = DiamondSearch;
1190    
1191  /*                          (*MainSearchPtr)(Data->currentMV->x, Data->currentMV->y, Data, 255);
    Step 5: Calculate SAD for motion vectors taken from left block, top, top-right, and Previous frame block.  
    Also calculate (0,0) but do not subtract offset.  
    Let MinSAD be the smallest SAD up to this point.  
    If MV is (0,0) subtract offset. ******** WHAT'S THIS 'OFFSET' ??? ***********  
 */  
1192    
1193  // the prediction might be even better than mv16                          if(*(Data->iMinSAD) < temp_sad) {
1194          CHECK_MV8_CANDIDATE(pmv[0].x,pmv[0].y);                                          Data->currentQMV->x = 2 * Data->currentMV->x; // update our qpel vector
1195                                            Data->currentQMV->y = 2 * Data->currentMV->y;
1196                            }
1197                    }
1198    
1199  // (0,0) is always possible                  if (MotionFlags & PMV_HALFPELREFINE8) {
1200          CHECK_MV8_ZERO;                          int32_t temp_sad = *(Data->iMinSAD); // store current MinSAD
1201    
1202  // previous frame MV is always possible                          HalfpelRefine(Data); // perform halfpel refine of current best vector
         CHECK_MV8_CANDIDATE(pMB->mvs[iSubBlock].x,pMB->mvs[iSubBlock].y);  
1203    
1204  // left neighbour, if allowed                          if(*(Data->iMinSAD) < temp_sad) { // we have found a better match
1205          if (psad[1] != MV_MAX_ERROR)                                  Data->currentQMV->x = 2 * Data->currentMV->x; // update our qpel vector
1206          {                                  Data->currentQMV->y = 2 * Data->currentMV->y;
                 if (!(MotionFlags & PMV_HALFPEL8 ))  
                 {       pmv[1].x = EVEN(pmv[1].x);  
                 pmv[1].y = EVEN(pmv[1].y);  
                 }  
                 CHECK_MV8_CANDIDATE(pmv[1].x,pmv[1].y);  
1207          }          }
   
 // top neighbour, if allowed  
         if (psad[2] != MV_MAX_ERROR)  
         {  
                 if (!(MotionFlags & PMV_HALFPEL8 ))  
                 {       pmv[2].x = EVEN(pmv[2].x);  
                 pmv[2].y = EVEN(pmv[2].y);  
1208                  }                  }
                 CHECK_MV8_CANDIDATE(pmv[2].x,pmv[2].y);  
1209    
1210  // top right neighbour, if allowed                  if(pParam->m_quarterpel) {
1211                  if (psad[3] != MV_MAX_ERROR)                          if((!(Data->currentQMV->x & 1)) && (!(Data->currentQMV->y & 1)) &&
1212                  {                                  (MotionFlags & PMV_QUARTERPELREFINE8)) {
1213                          if (!(MotionFlags & PMV_HALFPEL8 ))                          CheckCandidate = CheckCandidate8_qpel;
1214                          {       pmv[3].x = EVEN(pmv[3].x);                          get_range(&Data->min_dx, &Data->max_dx, &Data->min_dy, &Data->max_dy, x, y, 8,
1215                          pmv[3].y = EVEN(pmv[3].y);                                  pParam->width, pParam->height, OldData->iFcode, pParam->m_quarterpel);
1216                            QuarterpelRefine(Data);
1217                          }                          }
                         CHECK_MV8_CANDIDATE(pmv[3].x,pmv[3].y);  
1218                  }                  }
1219          }          }
1220    
1221  /* Step 6: If MinSAD <= thresa goto Step 10.          if(pParam->m_quarterpel) {
1222     If Motion Vector equal to Previous frame motion vector and MinSAD<PrevFrmSAD goto Step 10.                  pMB->pmvs[block].x = Data->currentQMV->x - Data->predQMV.x;
1223  */                  pMB->pmvs[block].y = Data->currentQMV->y - Data->predQMV.y;
1224            }
1225          if ( (iMinSAD <= threshA) || ( MVequal(*currMV,pMB->mvs[iSubBlock]) && (iMinSAD < pMB->sad8[iSubBlock]) ) )          else {
1226          {                  pMB->pmvs[block].x = Data->currentMV->x - Data->predMV.x;
1227                  if (MotionFlags & PMV_QUICKSTOP16)                  pMB->pmvs[block].y = Data->currentMV->y - Data->predMV.y;
                         goto PMVfast8_Terminate_without_Refine;  
                 if (MotionFlags & PMV_EARLYSTOP16)  
                         goto PMVfast8_Terminate_with_Refine;  
1228          }          }
1229    
1230  /************ (Diamond Search)  **************/          pMB->mvs[block] = *(Data->currentMV);
1231  /*          pMB->qmvs[block] = *(Data->currentQMV);
    Step 7: Perform Diamond search, with either the small or large diamond.  
    If Found=2 only examine one Diamond pattern, and afterwards goto step 10  
    Step 8: If small diamond, iterate small diamond search pattern until motion vector lies in the center of the diamond.  
    If center then goto step 10.  
    Step 9: If large diamond, iterate large diamond search pattern until motion vector lies in the center.  
    Refine by using small diamond and goto step 10.  
 */  
1232    
1233          backupMV = *currMV; /* save best prediction, actually only for EXTSEARCH */          pMB->sad8[block] =  4 * (*Data->iMinSAD);
1234    }
1235    
1236  /* default: use best prediction as starting point for one call of PMVfast_MainSearch */  /* B-frames code starts here */
         iSAD = Diamond8_MainSearch(pRef, pRefH, pRefV, pRefHV, cur,  
                                          x, y,  
                                          currMV->x, currMV->y, iMinSAD, &newMV,  
                                          pmv, min_dx, max_dx, min_dy, max_dy, iEdgedWidth, iDiamondSize, iFcode, iQuant, iFound);  
1237    
1238          if (iSAD < iMinSAD)  static __inline VECTOR
1239    ChoosePred(const MACROBLOCK * const pMB, const uint32_t mode)
1240          {          {
1241                  *currMV = newMV;  /* the stupidiest function ever */
1242                  iMinSAD = iSAD;          if (mode == MODE_FORWARD) return pMB->mvs[0];
1243            else return pMB->b_mvs[0];
1244          }          }
1245    
1246          if (MotionFlags & PMV_EXTSEARCH8)  static void __inline
1247    PreparePredictionsBF(VECTOR * const pmv, const int x, const int y,
1248                                                            const uint32_t iWcount,
1249                                                            const MACROBLOCK * const pMB,
1250                                                            const uint32_t mode_curr)
1251          {          {
 /* extended: search (up to) two more times: orignal prediction and (0,0) */  
   
                 if (!(MVequal(pmv[0],backupMV)) )  
                 {       iSAD = Diamond16_MainSearch(pRef, pRefH, pRefV, pRefHV, cur,  
                                                           x, y,  
                                                           pmv[0].x, pmv[0].y, iMinSAD, &newMV,  
                                                           pmv, min_dx, max_dx, min_dy, max_dy, iEdgedWidth, iDiamondSize, iFcode, iQuant, iFound);  
1252    
1253                  if (iSAD < iMinSAD)          // [0] is prediction
1254                  {          pmv[0].x = EVEN(pmv[0].x); pmv[0].y = EVEN(pmv[0].y);
                         *currMV = newMV;  
                         iMinSAD = iSAD;  
                 }  
                 }  
1255    
1256                  if ( (!(MVzero(pmv[0]))) && (!(MVzero(backupMV))) )          pmv[1].x = pmv[1].y = 0; // [1] is zero
                 {       iSAD = Diamond16_MainSearch(pRef, pRefH, pRefV, pRefHV, cur,  
                                                           x, y,  
                                                           0, 0, iMinSAD, &newMV,  
                                                           pmv, min_dx, max_dx, min_dy, max_dy, iEdgedWidth, iDiamondSize, iFcode, iQuant, iFound);  
1257    
1258                  if (iSAD < iMinSAD)          pmv[2] = ChoosePred(pMB, mode_curr);
1259                  {          pmv[2].x = EVEN(pmv[2].x); pmv[2].y = EVEN(pmv[2].y);
                         *currMV = newMV;  
                         iMinSAD = iSAD;  
                 }  
                 }  
         }  
1260    
1261  /* Step 10: The motion vector is chosen according to the block corresponding to MinSAD.          if ((y != 0)&&(x != (int)(iWcount+1))) {                        // [3] top-right neighbour
1262     By performing an optional local half-pixel search, we can refine this result even further.                  pmv[3] = ChoosePred(pMB+1-iWcount, mode_curr);
1263  */                  pmv[3].x = EVEN(pmv[3].x); pmv[3].y = EVEN(pmv[3].y);
1264            } else pmv[3].x = pmv[3].y = 0;
1265    
1266  PMVfast8_Terminate_with_Refine:          if (y != 0) {
1267          if (MotionFlags & PMV_HALFPELREFINE8)           // perform final half-pel step                  pmv[4] = ChoosePred(pMB-iWcount, mode_curr);
1268                  iMinSAD = Halfpel8_Refine( pRef, pRefH, pRefV, pRefHV, cur,                  pmv[4].x = EVEN(pmv[4].x); pmv[4].y = EVEN(pmv[4].y);
1269                                                   x, y,          } else pmv[4].x = pmv[4].y = 0;
                                                  currMV, iMinSAD,  
                                                  pmv, min_dx, max_dx, min_dy, max_dy, iFcode, iQuant, iEdgedWidth);  
1270    
1271            if (x != 0) {
1272                    pmv[5] = ChoosePred(pMB-1, mode_curr);
1273                    pmv[5].x = EVEN(pmv[5].x); pmv[5].y = EVEN(pmv[5].y);
1274            } else pmv[5].x = pmv[5].y = 0;
1275    
1276  PMVfast8_Terminate_without_Refine:          if ((x != 0)&&(y != 0)) {
1277          currPMV->x = currMV->x - pmv[0].x;                  pmv[6] = ChoosePred(pMB-1-iWcount, mode_curr);
1278          currPMV->y = currMV->y - pmv[0].y;                  pmv[6].x = EVEN(pmv[5].x); pmv[5].y = EVEN(pmv[5].y);
1279            } else pmv[6].x = pmv[6].y = 0;
1280    
1281          return iMinSAD;  // more?
1282  }  }
1283    
1284  int32_t EPZSSearch16(  
1285                                          const uint8_t * const pRef,  /* search backward or forward, for b-frames */
1286    static void
1287    SearchBF(       const uint8_t * const pRef,
1288                                          const uint8_t * const pRefH,                                          const uint8_t * const pRefH,
1289                                          const uint8_t * const pRefV,                                          const uint8_t * const pRefV,
1290                                          const uint8_t * const pRefHV,                                          const uint8_t * const pRefHV,
1291                                          const IMAGE * const pCur,                                          const IMAGE * const pCur,
1292                                          const int x, const int y,                                          const int x, const int y,
1293                                          const uint32_t MotionFlags,                                          const uint32_t MotionFlags,
1294                            const uint32_t iFcode,
1295                                          const MBParam * const pParam,                                          const MBParam * const pParam,
1296                                          MACROBLOCK * const pMBs,                          MACROBLOCK * const pMB,
1297                                          VECTOR * const currMV,                          const VECTOR * const predMV,
1298                                          VECTOR * const currPMV)                          int32_t * const best_sad,
1299                            const int32_t mode_current,
1300                            SearchData * const Data)
1301  {  {
         const uint32_t iWcount = pParam->mb_width;  
         const uint32_t iHcount = pParam->mb_height;  
         const int32_t iFcode = pParam->fixed_code;  
         const int32_t iQuant = pParam->quant;  
1302    
         const int32_t iWidth = pParam->width;  
         const int32_t iHeight = pParam->height;  
1303          const int32_t iEdgedWidth = pParam->edged_width;          const int32_t iEdgedWidth = pParam->edged_width;
1304    
1305          const uint8_t * cur = pCur->y + x*16 + y*16*iEdgedWidth;          int i, iDirection, mask;
1306            VECTOR pmv[7];
1307            MainSearchFunc *MainSearchPtr;
1308            *Data->iMinSAD = MV_MAX_ERROR;
1309            Data->iFcode = iFcode;
1310    
1311          int32_t min_dx;          Data->Ref = pRef + (x + y * iEdgedWidth) * 16;
1312          int32_t max_dx;          Data->RefH = pRefH + (x + y * iEdgedWidth) * 16;
1313          int32_t min_dy;          Data->RefV = pRefV + (x + y * iEdgedWidth) * 16;
1314          int32_t max_dy;          Data->RefHV = pRefHV + (x + y * iEdgedWidth) * 16;
1315    
1316          VECTOR newMV;          Data->predMV = *predMV;
         VECTOR backupMV;  
1317    
1318          VECTOR pmv[4];          get_range(&Data->min_dx, &Data->max_dx, &Data->min_dy, &Data->max_dy, x, y, 16,
1319          int32_t psad[8];                                  pParam->width, pParam->height, iFcode, pParam->m_quarterpel);
1320    
1321          static MACROBLOCK * oldMBs = NULL;          pmv[0] = Data->predMV;
1322          MACROBLOCK * const pMB = pMBs + x + y * iWcount;          PreparePredictionsBF(pmv, x, y, pParam->mb_width, pMB, mode_current);
         MACROBLOCK * oldMB = NULL;  
1323    
1324          static int32_t thresh2;          Data->currentMV->x = Data->currentMV->y = 0;
         int32_t bPredEq;  
         int32_t iMinSAD,iSAD=9999;  
1325    
1326          MainSearch16FuncPtr EPZSMainSearchPtr;          CheckCandidate = CheckCandidate16no4v;
1327    
1328          if (oldMBs == NULL)  // main loop. checking all predictions
1329          {       oldMBs = (MACROBLOCK*) calloc(1,iWcount*iHcount*sizeof(MACROBLOCK));          for (i = 0; i < 8; i++) {
1330                  fprintf(stderr,"allocated %d bytes for oldMBs\n",iWcount*iHcount*sizeof(MACROBLOCK));                  if (!(mask = make_mask(pmv, i)) ) continue;
1331                    CheckCandidate16no4v(pmv[i].x, pmv[i].y, mask, &iDirection, Data);
1332          }          }
         oldMB = oldMBs + x + y * iWcount;  
   
 /* Get maximum range */  
         get_range(&min_dx, &max_dx, &min_dy, &max_dy,  
                         x, y, 16, iWidth, iHeight, iFcode);  
   
 /* we work with abs. MVs, not relative to prediction, so get_range is called relative to 0,0 */  
1333    
1334          if (!(MotionFlags & PMV_HALFPEL16 ))          if (MotionFlags & PMV_USESQUARES16)
1335          { min_dx = EVEN(min_dx);                  MainSearchPtr = SquareSearch;
1336            max_dx = EVEN(max_dx);          else if (MotionFlags & PMV_ADVANCEDDIAMOND16)
1337            min_dy = EVEN(min_dy);                  MainSearchPtr = AdvDiamondSearch;
1338            max_dy = EVEN(max_dy);                  else MainSearchPtr = DiamondSearch;
1339          }               /* because we might use something like IF (dx>max_dx) THEN dx=max_dx; */  
1340            (*MainSearchPtr)(Data->currentMV->x, Data->currentMV->y, Data, 255);
1341          bPredEq  = get_pmvdata(pMBs, x, y, iWcount, 0, pmv, psad);  
1342            HalfpelRefine(Data);
1343  /* Step 4: Calculate SAD around the Median prediction.  
1344          MinSAD=SAD  // three bits are needed to code backward mode. four for forward
1345          If Motion Vector equal to Previous frame motion vector  // we treat the bits just like they were vector's
1346                  and MinSAD<PrevFrmSAD goto Step 10.          if (mode_current == MODE_FORWARD) *Data->iMinSAD +=  4 * Data->lambda16;
1347          If SAD<=256 goto Step 10.          else *Data->iMinSAD +=  3 * Data->lambda16;
1348  */  
1349            if (*Data->iMinSAD < *best_sad) {
1350  // Prepare for main loop                  *best_sad = *Data->iMinSAD;
1351                    pMB->mode = mode_current;
1352          *currMV=pmv[0];         /* current best := median prediction */                  pMB->pmvs[0].x = Data->currentMV->x - predMV->x;
1353          if (!(MotionFlags & PMV_HALFPEL16))                  pMB->pmvs[0].y = Data->currentMV->y - predMV->y;
1354          {                  if (mode_current == MODE_FORWARD) pMB->mvs[0] = *(Data->currentMV+2) = *Data->currentMV;
1355                  currMV->x = EVEN(currMV->x);                  else pMB->b_mvs[0] = *(Data->currentMV+1) = *Data->currentMV; //we store currmv for interpolate search
                 currMV->y = EVEN(currMV->y);  
1356          }          }
1357    
1358          if (currMV->x > max_dx)  }
                 currMV->x=max_dx;  
         if (currMV->x < min_dx)  
                 currMV->x=min_dx;  
         if (currMV->y > max_dy)  
                 currMV->y=max_dy;  
         if (currMV->y < min_dy)  
                 currMV->y=min_dy;  
   
 /***************** This is predictor SET A: only median prediction ******************/  
   
         iMinSAD = sad16( cur,  
                 get_ref_mv(pRef, pRefH, pRefV, pRefHV, x, y, 16, currMV, iEdgedWidth),  
                 iEdgedWidth, MV_MAX_ERROR);  
         iMinSAD += calc_delta_16(currMV->x-pmv[0].x, currMV->y-pmv[0].y, (uint8_t)iFcode) * iQuant;  
1359    
1360  // thresh1 is fixed to 256  static int32_t
1361          if ( (iMinSAD < 256 ) || ( (MVequal(*currMV,pMB->mvs[0])) && (iMinSAD < pMB->sad16) ) )  SearchDirect(const IMAGE * const f_Ref,
1362                  {                                  const uint8_t * const f_RefH,
1363                          if (MotionFlags & PMV_QUICKSTOP16)                                  const uint8_t * const f_RefV,
1364                                  goto EPZS16_Terminate_without_Refine;                                  const uint8_t * const f_RefHV,
1365                          if (MotionFlags & PMV_EARLYSTOP16)                                  const IMAGE * const b_Ref,
1366                                  goto EPZS16_Terminate_with_Refine;                                  const uint8_t * const b_RefH,
1367                                    const uint8_t * const b_RefV,
1368                                    const uint8_t * const b_RefHV,
1369                                    const IMAGE * const pCur,
1370                                    const int x, const int y,
1371                                    const uint32_t MotionFlags,
1372                                    const int32_t TRB, const int32_t TRD,
1373                                    const MBParam * const pParam,
1374                                    MACROBLOCK * const pMB,
1375                                    const MACROBLOCK * const b_mb,
1376                                    int32_t * const best_sad,
1377                                    SearchData * const Data)
1378    
1379    {
1380            int32_t skip_sad;
1381            int k;
1382    
1383            MainSearchFunc *MainSearchPtr;
1384    
1385            *Data->iMinSAD = 256*4096;
1386            Data->referencemv = b_mb->mvs;
1387    
1388            Data->Ref = f_Ref->y + (x + Data->iEdgedWidth*y) * 16;
1389            Data->RefH = f_RefH + (x + Data->iEdgedWidth*y) * 16;
1390            Data->RefV = f_RefV + (x + Data->iEdgedWidth*y) * 16;
1391            Data->RefHV = f_RefHV + (x + Data->iEdgedWidth*y) * 16;
1392            Data->bRef = b_Ref->y + (x + Data->iEdgedWidth*y) * 16;
1393            Data->bRefH = b_RefH + (x + Data->iEdgedWidth*y) * 16;
1394            Data->bRefV = b_RefV + (x + Data->iEdgedWidth*y) * 16;
1395            Data->bRefHV = b_RefHV + (x + Data->iEdgedWidth*y) * 16;
1396    
1397            Data->max_dx = 2 * pParam->width - 2 * (x) * 16;
1398            Data->max_dy = 2 * pParam->height - 2 * (y) * 16;
1399            Data->min_dx = -(2 * 16 + 2 * (x) * 16);
1400            Data->min_dy = -(2 * 16 + 2 * (y) * 16);
1401    
1402            for (k = 0; k < 4; k++) {
1403                    pMB->mvs[k].x = Data->directmvF[k].x = ((TRB * Data->referencemv[k].x) / TRD);
1404                    pMB->b_mvs[k].x = Data->directmvB[k].x = ((TRB - TRD) * Data->referencemv[k].x) / TRD;
1405                    pMB->mvs[k].y = Data->directmvF[k].y = ((TRB * Data->referencemv[k].y) / TRD);
1406                    pMB->b_mvs[k].y = Data->directmvB[k].y = ((TRB - TRD) * Data->referencemv[k].y) / TRD;
1407    
1408                    if ( ( pMB->b_mvs[k].x > Data->max_dx ) || ( pMB->b_mvs[k].x < Data->min_dx )
1409                            || ( pMB->b_mvs[k].y > Data->max_dy ) || ( pMB->b_mvs[k].y < Data->min_dy )) {
1410    
1411                            *best_sad = 256*4096; // in that case, we won't use direct mode
1412                            pMB->mode = MODE_DIRECT; // just to make sure it doesn't say "MODE_DIRECT_NONE_MV"
1413                            pMB->b_mvs[0].x = pMB->b_mvs[0].y = 0;
1414                            return 0;
1415                    }
1416                    if (b_mb->mode != MODE_INTER4V) {
1417                            pMB->mvs[1] = pMB->mvs[2] = pMB->mvs[3] = pMB->mvs[0];
1418                            pMB->b_mvs[1] = pMB->b_mvs[2] = pMB->b_mvs[3] = pMB->b_mvs[0];
1419                            Data->directmvF[1] = Data->directmvF[2] = Data->directmvF[3] = Data->directmvF[0];
1420                            Data->directmvB[1] = Data->directmvB[2] = Data->directmvB[3] = Data->directmvB[0];
1421                            break;
1422                    }
1423                  }                  }
1424    
1425  /************** This is predictor SET B: (0,0), prev.frame MV, neighbours **************/          if (b_mb->mode == MODE_INTER4V)
1426                    CheckCandidate = CheckCandidateDirect;
1427            else CheckCandidate = CheckCandidateDirectno4v;
1428    
1429  // previous frame MV          (*CheckCandidate)(0, 0, 255, &k, Data);
         CHECK_MV16_CANDIDATE(pMB->mvs[0].x,pMB->mvs[0].y);  
1430    
1431  // set threshhold based on Min of Prediction and SAD of collocated block  // skip decision
1432  // CHECK_MV16 always uses iSAD for the SAD of last vector to check, so now iSAD is what we want          if (*Data->iMinSAD < pMB->quant * SKIP_THRESH_B) {
1433                    //possible skip - checking chroma. everything copied from MC
1434                    //this is not full chroma compensation, only it's fullpel approximation. should work though
1435                    int sum, dx, dy, b_dx, b_dy;
1436    
1437          if ((x==0) && (y==0) )                  sum = pMB->mvs[0].x + pMB->mvs[1].x + pMB->mvs[2].x + pMB->mvs[3].x;
1438          {                  dx = (sum == 0 ? 0 : SIGN(sum) * (roundtab[ABS(sum) % 16] + (ABS(sum) / 16) * 2));
                 thresh2 =  512;  
         }  
         else  
         {  
 /* T_k = 1.2 * MIN(SAD_top,SAD_left,SAD_topleft,SAD_coll) +128;   [Tourapis, 2002] */  
1439    
1440                  thresh2 = MIN(psad[0],iSAD)*6/5 + 128;                  sum = pMB->mvs[0].y + pMB->mvs[1].y + pMB->mvs[2].y + pMB->mvs[3].y;
1441          }                  dy = (sum == 0 ? 0 : SIGN(sum) * (roundtab[ABS(sum) % 16] + (ABS(sum) / 16) * 2));
1442    
1443  // MV=(0,0) is often a good choice                  sum = pMB->b_mvs[0].x + pMB->b_mvs[1].x + pMB->b_mvs[2].x + pMB->b_mvs[3].x;
1444                    b_dx = (sum == 0 ? 0 : SIGN(sum) * (roundtab[ABS(sum) % 16] + (ABS(sum) / 16) * 2));
1445    
1446          CHECK_MV16_ZERO;                  sum = pMB->b_mvs[0].y + pMB->b_mvs[1].y + pMB->b_mvs[2].y + pMB->b_mvs[3].y;
1447                    b_dy = (sum == 0 ? 0 : SIGN(sum) * (roundtab[ABS(sum) % 16] + (ABS(sum) / 16) * 2));
1448    
1449                    sum = sad8bi(pCur->u + 8*x + 8*y*(Data->iEdgedWidth/2),
1450                                            f_Ref->u + (y*8 + dy/2) * (Data->iEdgedWidth/2) + x*8 + dx/2,
1451                                            b_Ref->u + (y*8 + b_dy/2) * (Data->iEdgedWidth/2) + x*8 + b_dx/2,
1452                                            Data->iEdgedWidth/2);
1453                    sum += sad8bi(pCur->v + 8*x + 8*y*(Data->iEdgedWidth/2),
1454                                            f_Ref->v + (y*8 + dy/2) * (Data->iEdgedWidth/2) + x*8 + dx/2,
1455                                            b_Ref->v + (y*8 + b_dy/2) * (Data->iEdgedWidth/2) + x*8 + b_dx/2,
1456                                            Data->iEdgedWidth/2);
1457    
1458  // left neighbour, if allowed                  if (sum < MAX_CHROMA_SAD_FOR_SKIP * pMB->quant) {
1459          if (x != 0)                          pMB->mode = MODE_DIRECT_NONE_MV;
1460          {                          return *Data->iMinSAD;
                 if (!(MotionFlags & PMV_HALFPEL16 ))  
                 {       pmv[1].x = EVEN(pmv[1].x);  
                         pmv[1].y = EVEN(pmv[1].y);  
1461                  }                  }
                 CHECK_MV16_CANDIDATE(pmv[1].x,pmv[1].y);  
1462          }          }
1463    
1464  // top neighbour, if allowed          skip_sad = *Data->iMinSAD;
         if (y != 0)  
         {  
                 if (!(MotionFlags & PMV_HALFPEL16 ))  
                 {       pmv[2].x = EVEN(pmv[2].x);  
                         pmv[2].y = EVEN(pmv[2].y);  
                 }  
                 CHECK_MV16_CANDIDATE(pmv[2].x,pmv[2].y);  
1465    
1466  // top right neighbour, if allowed  //  DIRECT MODE DELTA VECTOR SEARCH.
1467                  if (x != (iWcount-1))  //      This has to be made more effective, but at the moment I'm happy it's running at all
                 {  
                         if (!(MotionFlags & PMV_HALFPEL16 ))  
                         {       pmv[3].x = EVEN(pmv[3].x);  
                                 pmv[3].y = EVEN(pmv[3].y);  
                         }  
                         CHECK_MV16_CANDIDATE(pmv[3].x,pmv[3].y);  
                 }  
         }  
1468    
1469  /* Terminate if MinSAD <= T_2          if (MotionFlags & PMV_USESQUARES16) MainSearchPtr = SquareSearch;
1470     Terminate if MV[t] == MV[t-1] and MinSAD[t] <= MinSAD[t-1]                  else if (MotionFlags & PMV_ADVANCEDDIAMOND16) MainSearchPtr = AdvDiamondSearch;
1471  */                          else MainSearchPtr = DiamondSearch;
1472    
1473          if ( (iMinSAD <= thresh2)          (*MainSearchPtr)(0, 0, Data, 255);
                 || ( MVequal(*currMV,pMB->mvs[0]) && (iMinSAD <= pMB->sad16) ) )  
                 {  
                         if (MotionFlags & PMV_QUICKSTOP16)  
                                 goto EPZS16_Terminate_without_Refine;  
                         if (MotionFlags & PMV_EARLYSTOP16)  
                                 goto EPZS16_Terminate_with_Refine;  
                 }  
1474    
1475  /***** predictor SET C: acceleration MV (new!), neighbours in prev. frame(new!) ****/          HalfpelRefine(Data);
1476    
1477          backupMV = pMB->mvs[0];                 // last MV          *Data->iMinSAD +=  1 * Data->lambda16; // one bit is needed to code direct mode
1478          backupMV.x += (pMB->mvs[0].x - oldMB->mvs[0].x );       // acceleration X          *best_sad = *Data->iMinSAD;
         backupMV.y += (pMB->mvs[0].y - oldMB->mvs[0].y );       // acceleration Y  
1479    
1480          CHECK_MV16_CANDIDATE(backupMV.x,backupMV.y);          if (b_mb->mode == MODE_INTER4V)
1481                    pMB->mode = MODE_DIRECT;
1482            else pMB->mode = MODE_DIRECT_NO4V; //for faster compensation
1483    
1484  // left neighbour          pMB->pmvs[3] = *Data->currentMV;
         if (x != 0)  
                 CHECK_MV16_CANDIDATE((oldMB-1)->mvs[0].x,oldMB->mvs[0].y);  
   
 // top neighbour  
         if (y != 0)  
                 CHECK_MV16_CANDIDATE((oldMB-iWcount)->mvs[0].x,oldMB->mvs[0].y);  
1485    
1486  // right neighbour, if allowed (this value is not written yet, so take it from   pMB->mvs          for (k = 0; k < 4; k++) {
1487                    pMB->mvs[k].x = Data->directmvF[k].x + Data->currentMV->x;
1488                    pMB->b_mvs[k].x = ((Data->currentMV->x == 0)
1489                                                            ? Data->directmvB[k].x
1490                                                            : pMB->mvs[k].x - Data->referencemv[k].x);
1491                    pMB->mvs[k].y = (Data->directmvF[k].y + Data->currentMV->y);
1492                    pMB->b_mvs[k].y = ((Data->currentMV->y == 0)
1493                                                            ? Data->directmvB[k].y
1494                                                            : pMB->mvs[k].y - Data->referencemv[k].y);
1495                    if (b_mb->mode != MODE_INTER4V) {
1496                            pMB->mvs[3] = pMB->mvs[2] = pMB->mvs[1] = pMB->mvs[0];
1497                            pMB->b_mvs[3] = pMB->b_mvs[2] = pMB->b_mvs[1] = pMB->b_mvs[0];
1498                            break;
1499                    }
1500            }
1501            return skip_sad;
1502    }
1503    
         if (x != iWcount-1)  
                 CHECK_MV16_CANDIDATE((pMB+1)->mvs[0].x,oldMB->mvs[0].y);  
1504    
1505  // bottom neighbour, dito  static __inline void
1506          if (y != iHcount-1)  SearchInterpolate(const uint8_t * const f_Ref,
1507                  CHECK_MV16_CANDIDATE((pMB+iWcount)->mvs[0].x,oldMB->mvs[0].y);                                  const uint8_t * const f_RefH,
1508                                    const uint8_t * const f_RefV,
1509                                    const uint8_t * const f_RefHV,
1510                                    const uint8_t * const b_Ref,
1511                                    const uint8_t * const b_RefH,
1512                                    const uint8_t * const b_RefV,
1513                                    const uint8_t * const b_RefHV,
1514                                    const IMAGE * const pCur,
1515                                    const int x, const int y,
1516                                    const uint32_t fcode,
1517                                    const uint32_t bcode,
1518                                    const uint32_t MotionFlags,
1519                                    const MBParam * const pParam,
1520                                    const VECTOR * const f_predMV,
1521                                    const VECTOR * const b_predMV,
1522                                    MACROBLOCK * const pMB,
1523                                    int32_t * const best_sad,
1524                                    SearchData * const fData)
1525    
 /* Terminate if MinSAD <= T_3 (here T_3 = T_2)  */  
         if (iMinSAD <= thresh2)  
1526                  {                  {
                         if (MotionFlags & PMV_QUICKSTOP16)  
                                 goto EPZS16_Terminate_without_Refine;  
                         if (MotionFlags & PMV_EARLYSTOP16)  
                                 goto EPZS16_Terminate_with_Refine;  
                 }  
1527    
1528  /************ (if Diamond Search)  **************/          const int32_t iEdgedWidth = pParam->edged_width;
1529    
1530          backupMV = *currMV; /* save best prediction, actually only for EXTSEARCH */          int iDirection, i, j;
1531            SearchData bData;
1532    
1533  /* default: use best prediction as starting point for one call of PMVfast_MainSearch */          *(bData.iMinSAD = fData->iMinSAD) = 4096*256;
1534            bData.Cur = fData->Cur;
1535            fData->iEdgedWidth = bData.iEdgedWidth = iEdgedWidth;
1536            bData.currentMV = fData->currentMV + 1;
1537            bData.lambda16 = fData->lambda16;
1538            fData->iFcode = bData.bFcode = fcode; fData->bFcode = bData.iFcode = bcode;
1539    
1540            bData.bRef = fData->Ref = f_Ref + (x + y * iEdgedWidth) * 16;
1541            bData.bRefH = fData->RefH = f_RefH + (x + y * iEdgedWidth) * 16;
1542            bData.bRefV = fData->RefV = f_RefV + (x + y * iEdgedWidth) * 16;
1543            bData.bRefHV = fData->RefHV = f_RefHV + (x + y * iEdgedWidth) * 16;
1544            bData.Ref = fData->bRef = b_Ref + (x + y * iEdgedWidth) * 16;
1545            bData.RefH = fData->bRefH = b_RefH + (x + y * iEdgedWidth) * 16;
1546            bData.RefV = fData->bRefV = b_RefV + (x + y * iEdgedWidth) * 16;
1547            bData.RefHV = fData->bRefHV = b_RefHV + (x + y * iEdgedWidth) * 16;
1548    
1549            bData.bpredMV = fData->predMV = *f_predMV;
1550            fData->bpredMV = bData.predMV = *b_predMV;
1551    
1552            fData->currentMV[0] = fData->currentMV[3]; //forward search stored it's vector here. backward stored it in the place it's needed
1553            get_range(&fData->min_dx, &fData->max_dx, &fData->min_dy, &fData->max_dy, x, y, 16, pParam->width, pParam->height, fcode, pParam->m_quarterpel);
1554            get_range(&bData.min_dx, &bData.max_dx, &bData.min_dy, &bData.max_dy, x, y, 16, pParam->width, pParam->height, bcode, pParam->m_quarterpel);
1555    
1556            if (fData->currentMV[0].x > fData->max_dx) fData->currentMV[0].x = fData->max_dx;
1557            if (fData->currentMV[0].x < fData->min_dx) fData->currentMV[0].x = fData->min_dy;
1558            if (fData->currentMV[0].y > fData->max_dy) fData->currentMV[0].y = fData->max_dx;
1559            if (fData->currentMV[0].y > fData->min_dy) fData->currentMV[0].y = fData->min_dy;
1560    
1561            if (fData->currentMV[1].x > bData.max_dx) fData->currentMV[1].x = bData.max_dx;
1562            if (fData->currentMV[1].x < bData.min_dx) fData->currentMV[1].x = bData.min_dy;
1563            if (fData->currentMV[1].y > bData.max_dy) fData->currentMV[1].y = bData.max_dx;
1564            if (fData->currentMV[1].y > bData.min_dy) fData->currentMV[1].y = bData.min_dy;
1565    
1566            CheckCandidateInt(fData->currentMV[0].x, fData->currentMV[0].y, 255, &iDirection, fData);
1567    
1568    //diamond. I wish we could use normal mainsearch functions (square, advdiamond)
1569    
1570            do {
1571                    iDirection = 255;
1572                    // forward MV moves
1573                    i = fData->currentMV[0].x; j = fData->currentMV[0].y;
1574    
1575                    CheckCandidateInt(i + 1, j, 0, &iDirection, fData);
1576                    CheckCandidateInt(i, j + 1, 0, &iDirection, fData);
1577                    CheckCandidateInt(i - 1, j, 0, &iDirection, fData);
1578                    CheckCandidateInt(i, j - 1, 0, &iDirection, fData);
1579    
1580                    // backward MV moves
1581                    i = fData->currentMV[1].x; j = fData->currentMV[1].y;
1582                    fData->currentMV[2] = fData->currentMV[0];
1583    
1584                    CheckCandidateInt(i + 1, j, 0, &iDirection, &bData);
1585                    CheckCandidateInt(i, j + 1, 0, &iDirection, &bData);
1586                    CheckCandidateInt(i - 1, j, 0, &iDirection, &bData);
1587                    CheckCandidateInt(i, j - 1, 0, &iDirection, &bData);
1588    
1589            } while (!(iDirection));
1590    
1591            *fData->iMinSAD +=  2 * fData->lambda16; // two bits are needed to code interpolate mode.
1592    
1593            if (*fData->iMinSAD < *best_sad) {
1594                    *best_sad = *fData->iMinSAD;
1595                    pMB->mvs[0] = fData->currentMV[0];
1596                    pMB->b_mvs[0] = fData->currentMV[1];
1597                    pMB->mode = MODE_INTERPOLATE;
1598    
1599                    pMB->pmvs[1].x = pMB->mvs[0].x - f_predMV->x;
1600                    pMB->pmvs[1].y = pMB->mvs[0].y - f_predMV->y;
1601                    pMB->pmvs[0].x = pMB->b_mvs[0].x - b_predMV->x;
1602                    pMB->pmvs[0].y = pMB->b_mvs[0].y - b_predMV->y;
1603            }
1604    }
1605    
1606    void
1607    MotionEstimationBVOP(MBParam * const pParam,
1608                                             FRAMEINFO * const frame,
1609                                             const int32_t time_bp,
1610                                             const int32_t time_pp,
1611                                             // forward (past) reference
1612                                             const MACROBLOCK * const f_mbs,
1613                                             const IMAGE * const f_ref,
1614                                             const IMAGE * const f_refH,
1615                                             const IMAGE * const f_refV,
1616                                             const IMAGE * const f_refHV,
1617                                             // backward (future) reference
1618                                             const MACROBLOCK * const b_mbs,
1619                                             const IMAGE * const b_ref,
1620                                             const IMAGE * const b_refH,
1621                                             const IMAGE * const b_refV,
1622                                             const IMAGE * const b_refHV)
1623    {
1624            uint32_t i, j;
1625            int32_t best_sad, skip_sad;
1626            int f_count = 0, b_count = 0, i_count = 0, d_count = 0, n_count = 0;
1627            static const VECTOR zeroMV={0,0};
1628    
1629            VECTOR f_predMV, b_predMV;      /* there is no prediction for direct mode*/
1630    
1631            const int32_t TRB = time_pp - time_bp;
1632            const int32_t TRD = time_pp;
1633    
1634    // some pre-inintialized data for the rest of the search
1635    
1636            SearchData Data;
1637            int32_t iMinSAD;
1638            VECTOR currentMV[3];
1639            Data.iEdgedWidth = pParam->edged_width;
1640            Data.currentMV = currentMV;
1641            Data.iMinSAD = &iMinSAD;
1642            Data.lambda16 = lambda_vec16[frame->quant];
1643    
1644          if (MotionFlags & PMV_USESQUARES16)          // note: i==horizontal, j==vertical
                 EPZSMainSearchPtr = Square16_MainSearch;  
         else  
                 EPZSMainSearchPtr = Diamond16_MainSearch;  
   
         iSAD = (*EPZSMainSearchPtr)(pRef, pRefH, pRefV, pRefHV, cur,  
                         x, y,  
                         currMV->x, currMV->y, iMinSAD, &newMV, pmv, min_dx, max_dx, min_dy, max_dy, iEdgedWidth,  
                         2, iFcode, iQuant, 0);  
   
         if (iSAD < iMinSAD)  
         {  
                 *currMV = newMV;  
                 iMinSAD = iSAD;  
         }  
1645    
1646            for (j = 0; j < pParam->mb_height; j++) {
1647    
1648          if (MotionFlags & PMV_EXTSEARCH16)                  f_predMV = b_predMV = zeroMV;   /* prediction is reset at left boundary */
         {  
 /* extended mode: search (up to) two more times: orignal prediction and (0,0) */  
1649    
1650                  if (!(MVequal(pmv[0],backupMV)) )                  for (i = 0; i < pParam->mb_width; i++) {
1651                  {                          MACROBLOCK * const pMB = frame->mbs + i + j * pParam->mb_width;
1652                          iSAD = (*EPZSMainSearchPtr)(pRef, pRefH, pRefV, pRefHV, cur,                          const MACROBLOCK * const b_mb = b_mbs + i + j * pParam->mb_width;
                                 x, y,  
                                 pmv[0].x, pmv[0].y, iMinSAD, &newMV,  
                                 pmv, min_dx, max_dx, min_dy, max_dy, iEdgedWidth, 2, iFcode, iQuant, 0);  
                 }  
1653    
1654                  if (iSAD < iMinSAD)  /* special case, if collocated block is SKIPed in P-VOP: encoding is forward (0,0), cpb=0 without further ado */
1655                  {                          if (b_mb->mode == MODE_NOT_CODED) {
1656                          *currMV = newMV;                                  pMB->mode = MODE_NOT_CODED;
1657                          iMinSAD = iSAD;                                  continue;
1658                  }                  }
1659    
1660                  if ( (!(MVzero(pmv[0]))) && (!(MVzero(backupMV))) )                          Data.Cur = frame->image.y + (j * Data.iEdgedWidth + i) * 16;
1661                  {                          pMB->quant = frame->quant;
                         iSAD = (*EPZSMainSearchPtr)(pRef, pRefH, pRefV, pRefHV, cur,  
                                 x, y,  
                         0, 0, iMinSAD, &newMV,  
                         pmv, min_dx, max_dx, min_dy, max_dy, iEdgedWidth, /*iDiamondSize*/ 2, iFcode, iQuant, 0);  
1662    
1663                          if (iSAD < iMinSAD)  /* direct search comes first, because it (1) checks for SKIP-mode
1664                          {          and (2) sets very good predictions for forward and backward search */
1665                                  *currMV = newMV;                          skip_sad = SearchDirect(f_ref, f_refH->y, f_refV->y, f_refHV->y,
1666                                  iMinSAD = iSAD;                                                                          b_ref, b_refH->y, b_refV->y, b_refHV->y,
1667                                                                            &frame->image,
1668                                                                            i, j,
1669                                                                            frame->motion_flags,
1670                                                                            TRB, TRD,
1671                                                                            pParam,
1672                                                                            pMB, b_mb,
1673                                                                            &best_sad,
1674                                                                            &Data);
1675    
1676                            if (pMB->mode == MODE_DIRECT_NONE_MV) { n_count++; continue; }
1677    
1678                            // forward search
1679                            SearchBF(f_ref->y, f_refH->y, f_refV->y, f_refHV->y,
1680                                                    &frame->image, i, j,
1681                                                    frame->motion_flags,
1682                                                    frame->fcode, pParam,
1683                                                    pMB, &f_predMV, &best_sad,
1684                                                    MODE_FORWARD, &Data);
1685    
1686                            // backward search
1687                            SearchBF(b_ref->y, b_refH->y, b_refV->y, b_refHV->y,
1688                                                    &frame->image, i, j,
1689                                                    frame->motion_flags,
1690                                                    frame->bcode, pParam,
1691                                                    pMB, &b_predMV, &best_sad,
1692                                                    MODE_BACKWARD, &Data);
1693    
1694                            // interpolate search comes last, because it uses data from forward and backward as prediction
1695    
1696                            SearchInterpolate(f_ref->y, f_refH->y, f_refV->y, f_refHV->y,
1697                                                    b_ref->y, b_refH->y, b_refV->y, b_refHV->y,
1698                                                    &frame->image,
1699                                                    i, j,
1700                                                    frame->fcode, frame->bcode,
1701                                                    frame->motion_flags,
1702                                                    pParam,
1703                                                    &f_predMV, &b_predMV,
1704                                                    pMB, &best_sad,
1705                                                    &Data);
1706    
1707                            switch (pMB->mode) {
1708                                    case MODE_FORWARD:
1709                                            f_count++;
1710                                            f_predMV = pMB->mvs[0];
1711                                            break;
1712                                    case MODE_BACKWARD:
1713                                            b_count++;
1714                                            b_predMV = pMB->b_mvs[0];
1715                                            break;
1716                                    case MODE_INTERPOLATE:
1717                                            i_count++;
1718                                            f_predMV = pMB->mvs[0];
1719                                            b_predMV = pMB->b_mvs[0];
1720                                            break;
1721                                    case MODE_DIRECT:
1722                                    case MODE_DIRECT_NO4V:
1723                                            d_count++;
1724                                            break;
1725                                    default:
1726                                            break;
1727                          }                          }
1728                  }                  }
1729          }          }
   
 /***************        Choose best MV found     **************/  
   
 EPZS16_Terminate_with_Refine:  
         if (MotionFlags & PMV_HALFPELREFINE16)          // perform final half-pel step  
                 iMinSAD = Halfpel16_Refine( pRef, pRefH, pRefV, pRefHV, cur,  
                                 x, y,  
                                 currMV, iMinSAD,  
                                 pmv, min_dx, max_dx, min_dy, max_dy, iFcode, iQuant, iEdgedWidth);  
   
 EPZS16_Terminate_without_Refine:  
   
         *oldMB = *pMB;  
   
         currPMV->x = currMV->x - pmv[0].x;  
         currPMV->y = currMV->y - pmv[0].y;  
         return iMinSAD;  
1730  }  }
1731    
1732    /* Hinted ME starts here */
1733    
1734  int32_t EPZSSearch8(  static void
1735                                          const uint8_t * const pRef,  SearchPhinted ( const IMAGE * const pRef,
1736                                          const uint8_t * const pRefH,                                          const uint8_t * const pRefH,
1737                                          const uint8_t * const pRefV,                                          const uint8_t * const pRefV,
1738                                          const uint8_t * const pRefHV,                                          const uint8_t * const pRefHV,
1739                                          const IMAGE * const pCur,                                          const IMAGE * const pCur,
1740                                          const int x, const int y,                                  const int x,
1741                                          const int start_x, const int start_y,                                  const int y,
1742                                          const uint32_t MotionFlags,                                          const uint32_t MotionFlags,
1743                                    const uint32_t iQuant,
1744                                          const MBParam * const pParam,                                          const MBParam * const pParam,
1745                                          MACROBLOCK * const pMBs,                                  const MACROBLOCK * const pMBs,
1746                                          VECTOR * const currMV,                                  int inter4v,
1747                                          VECTOR * const currPMV)                                  MACROBLOCK * const pMB,
1748  {                                  SearchData * const Data)
1749          const uint32_t iWcount = pParam->mb_width;  {
1750          const int32_t iFcode = pParam->fixed_code;  
1751          const int32_t iQuant = pParam->quant;          int i, t;
1752            MainSearchFunc * MainSearchPtr;
1753          const int32_t iWidth = pParam->width;  
1754          const int32_t iHeight = pParam->height;          Data->predMV = get_pmv2(pMBs, pParam->mb_width, 0, x, y, 0);
1755          const int32_t iEdgedWidth = pParam->edged_width;          Data->predQMV = get_qpmv2(pMBs, pParam->mb_width, 0, x, y, 0);
1756            get_range(&Data->min_dx, &Data->max_dx, &Data->min_dy, &Data->max_dy, x, y, 16,
1757                                    pParam->width, pParam->height, Data->iFcode, pParam->m_quarterpel);
1758    
1759            Data->Cur = pCur->y + (x + y * Data->iEdgedWidth) * 16;
1760            Data->CurV = pCur->v + (x + y * (Data->iEdgedWidth/2)) * 8;
1761            Data->CurU = pCur->u + (x + y * (Data->iEdgedWidth/2)) * 8;
1762    
1763            Data->Ref = pRef->y + (x + Data->iEdgedWidth*y) * 16;
1764            Data->RefH = pRefH + (x + Data->iEdgedWidth*y) * 16;
1765            Data->RefV = pRefV + (x + Data->iEdgedWidth*y) * 16;
1766            Data->RefHV = pRefHV + (x + Data->iEdgedWidth*y) * 16;
1767            Data->RefCV = pRef->v + (x + y * (Data->iEdgedWidth/2)) * 8;
1768            Data->RefCU = pRef->u + (x + y * (Data->iEdgedWidth/2)) * 8;
1769    
1770            if (!(MotionFlags & PMV_HALFPEL16)) {
1771                    Data->min_dx = EVEN(Data->min_dx);
1772                    Data->max_dx = EVEN(Data->max_dx);
1773                    Data->min_dy = EVEN(Data->min_dy);
1774                    Data->max_dy = EVEN(Data->max_dy);
1775            }
1776    
1777            for(i = 0; i < 5; i++) Data->iMinSAD[i] = MV_MAX_ERROR;
1778    
1779            if (pMB->dquant != NO_CHANGE) inter4v = 0;
1780    
1781            if (inter4v || pParam->m_quarterpel || Data->chroma) CheckCandidate = CheckCandidate16;
1782            else CheckCandidate = CheckCandidate16no4v;
1783    
1784            pMB->mvs[0].x = EVEN(pMB->mvs[0].x);
1785            pMB->mvs[0].y = EVEN(pMB->mvs[0].y);
1786            if (pMB->mvs[0].x > Data->max_dx) pMB->mvs[0].x = Data->max_dx; // this is in case iFcode changed
1787            if (pMB->mvs[0].x < Data->min_dx) pMB->mvs[0].x = Data->min_dx;
1788            if (pMB->mvs[0].y > Data->max_dy) pMB->mvs[0].y = Data->max_dy;
1789            if (pMB->mvs[0].y < Data->min_dy) pMB->mvs[0].y = Data->min_dy;
1790    
1791            (*CheckCandidate)(pMB->mvs[0].x, pMB->mvs[0].y, 0, &t, Data);
1792    
1793            if (pMB->mode == MODE_INTER4V)
1794                    for (i = 1; i < 4; i++) { // all four vectors will be used as four predictions for 16x16 search
1795                            pMB->mvs[i].x = EVEN(pMB->mvs[i].x);
1796                            pMB->mvs[i].y = EVEN(pMB->mvs[i].y);
1797                            if (!(make_mask(pMB->mvs, i)))
1798                                    (*CheckCandidate)(pMB->mvs[i].x, pMB->mvs[i].y, 0, &t, Data);
1799                    }
1800    
1801          const uint8_t * cur = pCur->y + x*8 + y*8*iEdgedWidth;          if (MotionFlags & PMV_USESQUARES16)
1802                    MainSearchPtr = SquareSearch;
1803            else if (MotionFlags & PMV_ADVANCEDDIAMOND16)
1804                    MainSearchPtr = AdvDiamondSearch;
1805                    else MainSearchPtr = DiamondSearch;
1806    
1807            (*MainSearchPtr)(Data->currentMV->x, Data->currentMV->y, Data, 255);
1808    
1809            if (MotionFlags & PMV_HALFPELREFINE16) HalfpelRefine(Data);
1810    
1811            for(i = 0; i < 5; i++) {
1812                    Data->currentQMV[i].x = 2 * Data->currentMV[i].x; // initialize qpel vectors
1813                    Data->currentQMV[i].y = 2 * Data->currentMV[i].y;
1814            }
1815    
1816            if((pParam->m_quarterpel) && (MotionFlags & PMV_QUARTERPELREFINE16)) {
1817                    get_range(&Data->min_dx, &Data->max_dx, &Data->min_dy, &Data->max_dy, x, y, 16,
1818                                    pParam->width, pParam->height, Data->iFcode, 0);
1819                    CheckCandidate = CheckCandidate16_qpel;
1820                    QuarterpelRefine(Data);
1821            }
1822    
1823            if (inter4v) {
1824                    SearchData Data8;
1825                    Data8.iFcode = Data->iFcode;
1826                    Data8.lambda8 = Data->lambda8;
1827                    Data8.iEdgedWidth = Data->iEdgedWidth;
1828                    Data8.RefQ = Data->RefQ;
1829                    Data8.qpel = Data->qpel;
1830                    Search8(Data, 2*x, 2*y, MotionFlags, pParam, pMB, pMBs, 0, &Data8);
1831                    Search8(Data, 2*x + 1, 2*y, MotionFlags, pParam, pMB, pMBs, 1, &Data8);
1832                    Search8(Data, 2*x, 2*y + 1, MotionFlags, pParam, pMB, pMBs, 2, &Data8);
1833                    Search8(Data, 2*x + 1, 2*y + 1, MotionFlags, pParam, pMB, pMBs, 3, &Data8);
1834    
1835                    if (Data->chroma) {
1836                            int sum, dx, dy;
1837    
1838                            if(pParam->m_quarterpel)
1839                                    sum = (pMB->qmvs[0].y + pMB->qmvs[1].y + pMB->qmvs[2].y + pMB->qmvs[3].y)/2;
1840                            else sum = pMB->mvs[0].y + pMB->mvs[1].y + pMB->mvs[2].y + pMB->mvs[3].y;
1841                            dy = (sum ? SIGN(sum) *
1842                                      (roundtab[ABS(sum) % 16] + (ABS(sum) / 16) * 2) : 0);
1843    
1844                            if(pParam->m_quarterpel)
1845                                    sum = (pMB->qmvs[0].x + pMB->qmvs[1].x + pMB->qmvs[2].x + pMB->qmvs[3].x)/2;
1846                            else sum = pMB->mvs[0].x + pMB->mvs[1].x + pMB->mvs[2].x + pMB->mvs[3].x;
1847                            dx = (sum ? SIGN(sum) *
1848                                      (roundtab[ABS(sum) % 16] + (ABS(sum) / 16) * 2) : 0);
1849                            Data->iMinSAD[1] += ChromaSAD(dx, dy, Data);
1850                    }
1851            }
1852    
1853          int32_t iDiamondSize=1;          if (!(inter4v) ||
1854                    (Data->iMinSAD[0] < Data->iMinSAD[1] + Data->iMinSAD[2] + Data->iMinSAD[3] +
1855                                                            Data->iMinSAD[4] + IMV16X16 * (int32_t)iQuant )) {
1856    // INTER MODE
1857                    pMB->mode = MODE_INTER;
1858                    pMB->mvs[0] = pMB->mvs[1]
1859                            = pMB->mvs[2] = pMB->mvs[3] = Data->currentMV[0];
1860    
1861          int32_t min_dx;                  pMB->qmvs[0] = pMB->qmvs[1]
1862          int32_t max_dx;                          = pMB->qmvs[2] = pMB->qmvs[3] = Data->currentQMV[0];
         int32_t min_dy;  
         int32_t max_dy;  
1863    
1864          VECTOR newMV;                  pMB->sad16 = pMB->sad8[0] = pMB->sad8[1] =
1865          VECTOR backupMV;                          pMB->sad8[2] = pMB->sad8[3] =  Data->iMinSAD[0];
1866    
1867          VECTOR pmv[4];                  if(pParam->m_quarterpel) {
1868          int32_t psad[8];                          pMB->pmvs[0].x = Data->currentQMV[0].x - Data->predQMV.x;
1869                            pMB->pmvs[0].y = Data->currentQMV[0].y - Data->predQMV.y;
1870                    } else {
1871                            pMB->pmvs[0].x = Data->currentMV[0].x - Data->predMV.x;
1872                            pMB->pmvs[0].y = Data->currentMV[0].y - Data->predMV.y;
1873                    }
1874            } else {
1875    // INTER4V MODE; all other things are already set in Search8
1876                    pMB->mode = MODE_INTER4V;
1877                    pMB->sad16 = Data->iMinSAD[1] + Data->iMinSAD[2] + Data->iMinSAD[3]
1878                                                    + Data->iMinSAD[4] + IMV16X16 * iQuant;
1879            }
1880    
1881          const   int32_t iSubBlock = ((y&1)<<1) + (x&1);  }
1882    
1883          MACROBLOCK * const pMB = pMBs + (x>>1) + (y>>1) * iWcount;  void
1884    MotionEstimationHinted( MBParam * const pParam,
1885                                                    FRAMEINFO * const current,
1886                                                    FRAMEINFO * const reference,
1887                                                    const IMAGE * const pRefH,
1888                                                    const IMAGE * const pRefV,
1889                                                    const IMAGE * const pRefHV)
1890    {
1891            MACROBLOCK *const pMBs = current->mbs;
1892            const IMAGE *const pCurrent = &current->image;
1893            const IMAGE *const pRef = &reference->image;
1894    
1895          int32_t bPredEq;          uint32_t x, y;
1896          int32_t iMinSAD,iSAD=9999;          uint8_t * qimage;
1897            int32_t temp[5], quant = current->quant;
1898            int32_t iMinSAD[5];
1899            VECTOR currentMV[5], currentQMV[5];
1900            SearchData Data;
1901            Data.iEdgedWidth = pParam->edged_width;
1902            Data.currentMV = currentMV;
1903            Data.currentQMV = currentQMV;
1904            Data.iMinSAD = iMinSAD;
1905            Data.temp = temp;
1906            Data.iFcode = current->fcode;
1907            Data.rounding = pParam->m_rounding_type;
1908            Data.qpel = pParam->m_quarterpel;
1909            Data.chroma = current->global_flags & XVID_ME_COLOUR;
1910    
1911          MainSearch8FuncPtr EPZSMainSearchPtr;          if((qimage = (uint8_t *) malloc(32 * pParam->edged_width)) == NULL)
1912                    return; // allocate some mem for qpel interpolated blocks
1913                                      // somehow this is dirty since I think we shouldn't use malloc outside
1914                                      // encoder_create() - so please fix me!
1915    
1916  /* Get maximum range */          Data.RefQ = qimage;
         get_range(&min_dx, &max_dx, &min_dy, &max_dy,  
                         x, y, 8, iWidth, iHeight, iFcode);  
1917    
1918  /* we work with abs. MVs, not relative to prediction, so get_range is called relative to 0,0 */          if (sadInit) (*sadInit) ();
1919    
1920          if (!(MotionFlags & PMV_HALFPEL8 ))          for (y = 0; y < pParam->mb_height; y++) {
1921          { min_dx = EVEN(min_dx);                  for (x = 0; x < pParam->mb_width; x++)  {
           max_dx = EVEN(max_dx);  
           min_dy = EVEN(min_dy);  
           max_dy = EVEN(max_dy);  
         }               /* because we might use something like IF (dx>max_dx) THEN dx=max_dx; */  
1922    
1923          bPredEq  = get_pmvdata(pMBs, x>>1, y>>1, iWcount, iSubBlock, pmv, psad);                          MACROBLOCK *pMB = &pMBs[x + y * pParam->mb_width];
1924    
1925    //intra mode is copied from the first pass. At least for the time being
1926                            if  ((pMB->mode == MODE_INTRA) || (pMB->mode == MODE_NOT_CODED) ) continue;
1927    
1928  /* Step 4: Calculate SAD around the Median prediction.                          if (!(current->global_flags & XVID_LUMIMASKING)) {
1929          MinSAD=SAD                                  pMB->dquant = NO_CHANGE;
1930          If Motion Vector equal to Previous frame motion vector                                  pMB->quant = current->quant; }
1931                  and MinSAD<PrevFrmSAD goto Step 10.                          else {
1932          If SAD<=256 goto Step 10.                                  if (pMB->dquant != NO_CHANGE) {
1933  */                                          quant += DQtab[pMB->dquant];
1934                                            if (quant > 31) quant = 31;
1935                                            else if (quant < 1) quant = 1;
1936                                    }
1937                                    pMB->quant = quant;
1938                            }
1939    
1940  // Prepare for main loop                          SearchPhinted(pRef, pRefH->y, pRefV->y, pRefHV->y, pCurrent, x,
1941                                                            y, current->motion_flags, pMB->quant,
1942                                                            pParam, pMBs, current->global_flags & XVID_INTER4V, pMB,
1943                                                            &Data);
1944    
1945                    }
1946            }
1947            free(qimage);
1948    }
1949    
1950          if (!(MotionFlags & PMV_HALFPEL8))  static __inline int
1951    MEanalyzeMB (   const uint8_t * const pRef,
1952                                    const uint8_t * const pCur,
1953                                    const int x,
1954                                    const int y,
1955                                    const MBParam * const pParam,
1956                                    const MACROBLOCK * const pMBs,
1957                                    MACROBLOCK * const pMB,
1958                                    SearchData * const Data)
1959          {          {
                 currMV->x = EVEN(currMV->x);  
                 currMV->y = EVEN(currMV->y);  
         }  
1960    
1961          if (currMV->x > max_dx)          int i = 255, mask;
1962                  currMV->x=max_dx;          VECTOR pmv[3];
         if (currMV->x < min_dx)  
                 currMV->x=min_dx;  
         if (currMV->y > max_dy)  
                 currMV->y=max_dy;  
         if (currMV->y < min_dy)  
                 currMV->y=min_dy;  
1963    
1964  /***************** This is predictor SET A: only median prediction ******************/          *(Data->iMinSAD) = MV_MAX_ERROR;
1965            Data->predMV = get_pmv2(pMBs, pParam->mb_width, 0, x, y, 0);
1966            get_range(&Data->min_dx, &Data->max_dx, &Data->min_dy, &Data->max_dy, x, y, 16,
1967                                    pParam->width, pParam->height, Data->iFcode, pParam->m_quarterpel);
1968    
1969            Data->Cur = pCur + (x + y * pParam->edged_width) * 16;
1970            Data->Ref = pRef + (x + y * pParam->edged_width) * 16;
1971    
1972          iMinSAD = sad8( cur,          CheckCandidate = CheckCandidate16no4vI;
                 get_ref_mv(pRef, pRefH, pRefV, pRefHV, x, y, 8, currMV, iEdgedWidth),  
                 iEdgedWidth);  
         iMinSAD += calc_delta_8(currMV->x-pmv[0].x, currMV->y-pmv[0].y, (uint8_t)iFcode) * iQuant;  
1973    
1974            pmv[1].x = EVEN(pMB->mvs[0].x);
1975            pmv[1].y = EVEN(pMB->mvs[0].y);
1976            pmv[0].x = EVEN(Data->predMV.x);
1977            pmv[0].y = EVEN(Data->predMV.y);
1978            pmv[2].x = pmv[2].y = 0;
1979    
1980  // thresh1 is fixed to 256          CheckCandidate16no4vI(pmv[0].x, pmv[0].y, 255, &i, Data);
1981          if (iMinSAD < 256/4 )          if (!(mask = make_mask(pmv, 1)))
1982                  {                  CheckCandidate16no4vI(pmv[1].x, pmv[1].y, mask, &i, Data);
1983                          if (MotionFlags & PMV_QUICKSTOP8)          if (!(mask = make_mask(pmv, 2)))
1984                                  goto EPZS8_Terminate_without_Refine;                  CheckCandidate16no4vI(0, 0, mask, &i, Data);
1985                          if (MotionFlags & PMV_EARLYSTOP8)  
1986                                  goto EPZS8_Terminate_with_Refine;          DiamondSearch(Data->currentMV->x, Data->currentMV->y, Data, i);
1987    
1988            pMB->mvs[0] = *Data->currentMV;
1989            pMB->mode = MODE_INTER;
1990    
1991            return *(Data->iMinSAD);
1992                  }                  }
1993    
1994  /************** This is predictor SET B: (0,0), prev.frame MV, neighbours **************/  #define INTRA_THRESH    1350
1995    #define INTER_THRESH    900
1996    
1997  // previous frame MV  int
1998          CHECK_MV8_CANDIDATE(pMB->mvs[0].x,pMB->mvs[0].y);  MEanalysis(     const IMAGE * const pRef,
1999                            const IMAGE * const pCurrent,
2000                            MBParam * const pParam,
2001                            MACROBLOCK * const pMBs,
2002                            const uint32_t iFcode)
2003    {
2004            uint32_t x, y, intra = 0;
2005            int sSAD = 0;
2006    
2007  // MV=(0,0) is often a good choice          VECTOR currentMV;
2008            int32_t iMinSAD;
2009            SearchData Data;
2010            Data.iEdgedWidth = pParam->edged_width;
2011            Data.currentMV = &currentMV;
2012            Data.iMinSAD = &iMinSAD;
2013            Data.iFcode = iFcode;
2014    
2015          CHECK_MV8_ZERO;          if (sadInit) (*sadInit) ();
2016    
2017  /* Terminate if MinSAD <= T_2          for (y = 1; y < pParam->mb_height-1; y++) {
2018     Terminate if MV[t] == MV[t-1] and MinSAD[t] <= MinSAD[t-1]                  for (x = 1; x < pParam->mb_width-1; x++) {
2019  */                          int sad, dev;
2020                            MACROBLOCK *pMB = &pMBs[x + y * pParam->mb_width];
2021    
2022          if (iMinSAD < 512/4)    /* T_2 == 512/4 hardcoded */                          sad = MEanalyzeMB(pRef->y, pCurrent->y, x, y,
2023                  {                                                                  pParam, pMBs, pMB, &Data);
                         if (MotionFlags & PMV_QUICKSTOP8)  
                                 goto EPZS8_Terminate_without_Refine;  
                         if (MotionFlags & PMV_EARLYSTOP8)  
                                 goto EPZS8_Terminate_with_Refine;  
                 }  
2024    
2025  /************ (if Diamond Search)  **************/                          if (sad > INTRA_THRESH) {
2026                                    dev = dev16(pCurrent->y + (x + y * pParam->edged_width) * 16,
2027                                                              pParam->edged_width);
2028                                    if (dev + INTRA_THRESH < sad) { intra++; pMB->mode = MODE_INTRA; }
2029                                    if (intra > (pParam->mb_height-2)*(pParam->mb_width-2)/2) return 2;  // I frame
2030                                    }
2031                            sSAD += sad;
2032                    }
2033            }
2034            sSAD /= (pParam->mb_height-2)*(pParam->mb_width-2);
2035            if (sSAD > INTER_THRESH ) return 1; //P frame
2036            emms();
2037            return 0; // B frame
2038    
2039          backupMV = *currMV; /* save best prediction, actually only for EXTSEARCH */  }
2040    
2041          if (!(MotionFlags & PMV_HALFPELDIAMOND8))  int
2042                  iDiamondSize *= 2;  FindFcode(      const MBParam * const pParam,
2043                            const FRAMEINFO * const current)
2044    {
2045            uint32_t x, y;
2046            int max = 0, min = 0, i;
2047    
2048  /* default: use best prediction as starting point for one call of PMVfast_MainSearch */          for (y = 0; y < pParam->mb_height; y++) {
2049                    for (x = 0; x < pParam->mb_width; x++) {
2050    
2051  //      if (MotionFlags & PMV_USESQUARES8)                          MACROBLOCK *pMB = &current->mbs[x + y * pParam->mb_width];
2052  //              EPZSMainSearchPtr = Square8_MainSearch;                          for(i = 0; i < (pMB->mode == MODE_INTER4V ? 4:1); i++) {
2053  //      else                                  if (pMB->mvs[i].x > max) max = pMB->mvs[i].x;
2054                  EPZSMainSearchPtr = Diamond8_MainSearch;                                  if (pMB->mvs[i].y > max) max = pMB->mvs[i].y;
2055    
2056          iSAD = (*EPZSMainSearchPtr)(pRef, pRefH, pRefV, pRefHV, cur,                                  if (pMB->mvs[i].x < min) min = pMB->mvs[i].x;
2057                  x, y,                                  if (pMB->mvs[i].y < min) min = pMB->mvs[i].y;
2058                  currMV->x, currMV->y, iMinSAD, &newMV,                          }
2059                  pmv, min_dx, max_dx, min_dy, max_dy, iEdgedWidth,                  }
2060                  iDiamondSize, iFcode, iQuant, 00);          }
2061    
2062            min = -min;
2063            max += 1;
2064            if (min > max) max = min;
2065            if (pParam->m_quarterpel) max *= 2;
2066    
2067          if (iSAD < iMinSAD)          for (i = 1; (max > 32 << (i - 1)); i++);
2068          {          return i;
                 *currMV = newMV;  
                 iMinSAD = iSAD;  
2069          }          }
2070    
2071          if (MotionFlags & PMV_EXTSEARCH8)  static void
2072    CheckGMC(int x, int y, const int dir, int * iDirection,
2073                    const MACROBLOCK * const pMBs, uint32_t * bestcount, VECTOR * GMC,
2074                    const MBParam * const pParam)
2075          {          {
2076  /* extended mode: search (up to) two more times: orignal prediction and (0,0) */          uint32_t mx, my, a, count = 0;
2077    
2078                  if (!(MVequal(pmv[0],backupMV)) )          for (my = 1; my < pParam->mb_height-1; my++)
2079                  {                  for (mx = 1; mx < pParam->mb_width-1; mx++) {
2080                          iSAD = (*EPZSMainSearchPtr)(pRef, pRefH, pRefV, pRefHV, cur,                          VECTOR mv;
2081                                  x, y,                          const MACROBLOCK *pMB = &pMBs[mx + my * pParam->mb_width];
2082                          pmv[0].x, pmv[0].y, iMinSAD, &newMV,                          if (pMB->mode == MODE_INTRA || pMB->mode == MODE_NOT_CODED) continue;
2083                          pmv, min_dx, max_dx, min_dy, max_dy, iEdgedWidth, iDiamondSize, iFcode, iQuant, 0);                          mv = pMB->mvs[0];
2084                            a = ABS(mv.x - x) + ABS(mv.y - y);
2085                            if (a < 6) count += 6 - a;
2086                    }
2087    
2088                          if (iSAD < iMinSAD)          if (count > *bestcount) {
2089                          {                  *bestcount = count;
2090                                  *currMV = newMV;                  *iDirection = dir;
2091                                  iMinSAD = iSAD;                  GMC->x = x; GMC->y = y;
2092                          }                          }
2093                  }                  }
2094    
                 if ( (!(MVzero(pmv[0]))) && (!(MVzero(backupMV))) )  
                 {  
                         iSAD = (*EPZSMainSearchPtr)(pRef, pRefH, pRefV, pRefHV, cur,  
                                 x, y,  
                         0, 0, iMinSAD, &newMV,  
                         pmv, min_dx, max_dx, min_dy, max_dy, iEdgedWidth, iDiamondSize, iFcode, iQuant, 0);  
2095    
2096                          if (iSAD < iMinSAD)  static VECTOR
2097    GlobalMotionEst(const MACROBLOCK * const pMBs, const MBParam * const pParam, const uint32_t iFcode)
2098                          {                          {
2099                                  *currMV = newMV;  
2100                                  iMinSAD = iSAD;          uint32_t count, bestcount = 0;
2101            int x, y;
2102            VECTOR gmc = {0,0};
2103            int step, min_x, max_x, min_y, max_y;
2104            uint32_t mx, my;
2105            int iDirection, bDirection;
2106    
2107            min_x = min_y = -32<<iFcode;
2108            max_x = max_y = 32<<iFcode;
2109    
2110    //step1: let's find a rough camera panning
2111            for (step = 32; step >= 2; step /= 2) {
2112                    bestcount = 0;
2113                    for (y = min_y; y <= max_y; y += step)
2114                            for (x = min_x ; x <= max_x; x += step) {
2115                                    count = 0;
2116                                    //for all macroblocks
2117                                    for (my = 1; my < pParam->mb_height-1; my++)
2118                                            for (mx = 1; mx < pParam->mb_width-1; mx++) {
2119                                                    const MACROBLOCK *pMB = &pMBs[mx + my * pParam->mb_width];
2120                                                    VECTOR mv;
2121    
2122                                                    if (pMB->mode == MODE_INTRA || pMB->mode == MODE_NOT_CODED)
2123                                                            continue;
2124    
2125                                                    mv = pMB->mvs[0];
2126                                                    if ( ABS(mv.x - x) <= step && ABS(mv.y - y) <= step )   /* GMC translation is always halfpel-res */
2127                                                            count++;
2128                          }                          }
2129                                    if (count >= bestcount) { bestcount = count; gmc.x = x; gmc.y = y; }
2130                  }                  }
2131                    min_x = gmc.x - step;
2132                    max_x = gmc.x + step;
2133                    min_y = gmc.y - step;
2134                    max_y = gmc.y + step;
2135    
2136          }          }
2137    
2138  /***************        Choose best MV found     **************/          if (bestcount < (pParam->mb_height-2)*(pParam->mb_width-2)/10)
2139                    gmc.x = gmc.y = 0; //no camara pan, no GMC
2140    
2141  EPZS8_Terminate_with_Refine:  // step2: let's refine camera panning using gradiend-descent approach.
2142          if (MotionFlags & PMV_HALFPELREFINE8)           // perform final half-pel step  // TODO: more warping points may be evaluated here (like in interpolate mode search - two vectors in one diamond)
2143                  iMinSAD = Halfpel8_Refine( pRef, pRefH, pRefV, pRefHV, cur,          bestcount = 0;
2144                                  x, y,          CheckGMC(gmc.x, gmc.y, 255, &iDirection, pMBs, &bestcount, &gmc, pParam);
2145                                  currMV, iMinSAD,          do {
2146                                  pmv, min_dx, max_dx, min_dy, max_dy, iFcode, iQuant, iEdgedWidth);                  x = gmc.x; y = gmc.y;
2147                    bDirection = iDirection; iDirection = 0;
2148                    if (bDirection & 1) CheckGMC(x - 1, y, 1+4+8, &iDirection, pMBs, &bestcount, &gmc, pParam);
2149                    if (bDirection & 2) CheckGMC(x + 1, y, 2+4+8, &iDirection, pMBs, &bestcount, &gmc, pParam);
2150                    if (bDirection & 4) CheckGMC(x, y - 1, 1+2+4, &iDirection, pMBs, &bestcount, &gmc, pParam);
2151                    if (bDirection & 8) CheckGMC(x, y + 1, 1+2+8, &iDirection, pMBs, &bestcount, &gmc, pParam);
2152    
2153  EPZS8_Terminate_without_Refine:          } while (iDirection);
2154    
2155          currPMV->x = currMV->x - pmv[0].x;          if (pParam->m_quarterpel) {
2156          currPMV->y = currMV->y - pmv[0].y;                  gmc.x *= 2;
2157          return iMinSAD;                  gmc.y *= 2;     /* we store the halfpel value as pseudo-qpel to make comparison easier */
2158  }  }
2159    
2160            return gmc;
2161    }

Legend:
Removed from v.115  
changed lines
  Added in v.631

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