]> git.sesse.net Git - x264/blob - encoder/me.c
Cosmetics: fix some signedness issues found by -Wsign-compare
[x264] / encoder / me.c
1 /*****************************************************************************
2  * me.c: motion estimation
3  *****************************************************************************
4  * Copyright (C) 2003-2011 x264 project
5  *
6  * Authors: Loren Merritt <lorenm@u.washington.edu>
7  *          Laurent Aimar <fenrir@via.ecp.fr>
8  *          Fiona Glaser <fiona@x264.com>
9  *
10  * This program is free software; you can redistribute it and/or modify
11  * it under the terms of the GNU General Public License as published by
12  * the Free Software Foundation; either version 2 of the License, or
13  * (at your option) any later version.
14  *
15  * This program is distributed in the hope that it will be useful,
16  * but WITHOUT ANY WARRANTY; without even the implied warranty of
17  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18  * GNU General Public License for more details.
19  *
20  * You should have received a copy of the GNU General Public License
21  * along with this program; if not, write to the Free Software
22  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02111, USA.
23  *
24  * This program is also available under a commercial proprietary license.
25  * For more information, contact us at licensing@x264.com.
26  *****************************************************************************/
27
28 #include "common/common.h"
29 #include "macroblock.h"
30 #include "me.h"
31
32 /* presets selected from good points on the speed-vs-quality curve of several test videos
33  * subpel_iters[i_subpel_refine] = { refine_hpel, refine_qpel, me_hpel, me_qpel }
34  * where me_* are the number of EPZS iterations run on all candidate block types,
35  * and refine_* are run only on the winner.
36  * the subme=8,9 values are much higher because any amount of satd search makes
37  * up its time by reducing the number of qpel-rd iterations. */
38 static const uint8_t subpel_iterations[][4] =
39    {{0,0,0,0},
40     {1,1,0,0},
41     {0,1,1,0},
42     {0,2,1,0},
43     {0,2,1,1},
44     {0,2,1,2},
45     {0,0,2,2},
46     {0,0,2,2},
47     {0,0,4,10},
48     {0,0,4,10},
49     {0,0,4,10}};
50
51 /* (x-1)%6 */
52 static const uint8_t mod6m1[8] = {5,0,1,2,3,4,5,0};
53 /* radius 2 hexagon. repeated entries are to avoid having to compute mod6 every time. */
54 static const int8_t hex2[8][2] = {{-1,-2}, {-2,0}, {-1,2}, {1,2}, {2,0}, {1,-2}, {-1,-2}, {-2,0}};
55 static const int8_t square1[9][2] = {{0,0}, {0,-1}, {0,1}, {-1,0}, {1,0}, {-1,-1}, {-1,1}, {1,-1}, {1,1}};
56
57 static void refine_subpel( x264_t *h, x264_me_t *m, int hpel_iters, int qpel_iters, int *p_halfpel_thresh, int b_refine_qpel );
58
59 #define BITS_MVD( mx, my )\
60     (p_cost_mvx[(mx)<<2] + p_cost_mvy[(my)<<2])
61
62 #define COST_MV( mx, my )\
63 {\
64     int cost = h->pixf.fpelcmp[i_pixel]( p_fenc, FENC_STRIDE,\
65                    &p_fref_w[(my)*stride+(mx)], stride )\
66              + BITS_MVD(mx,my);\
67     COPY3_IF_LT( bcost, cost, bmx, mx, bmy, my );\
68 }
69
70 #define COST_MV_HPEL( mx, my ) \
71 { \
72     int stride2 = 16; \
73     pixel *src = h->mc.get_ref( pix, &stride2, m->p_fref, stride, mx, my, bw, bh, &m->weight[0] ); \
74     int cost = h->pixf.fpelcmp[i_pixel]( p_fenc, FENC_STRIDE, src, stride2 ) \
75              + p_cost_mvx[ mx ] + p_cost_mvy[ my ]; \
76     COPY3_IF_LT( bpred_cost, cost, bpred_mx, mx, bpred_my, my ); \
77 }
78
79 #define COST_MV_X3_DIR( m0x, m0y, m1x, m1y, m2x, m2y, costs )\
80 {\
81     pixel *pix_base = p_fref_w + bmx + bmy*stride;\
82     h->pixf.fpelcmp_x3[i_pixel]( p_fenc,\
83         pix_base + (m0x) + (m0y)*stride,\
84         pix_base + (m1x) + (m1y)*stride,\
85         pix_base + (m2x) + (m2y)*stride,\
86         stride, costs );\
87     (costs)[0] += BITS_MVD( bmx+(m0x), bmy+(m0y) );\
88     (costs)[1] += BITS_MVD( bmx+(m1x), bmy+(m1y) );\
89     (costs)[2] += BITS_MVD( bmx+(m2x), bmy+(m2y) );\
90 }
91
92 #define COST_MV_X4_DIR( m0x, m0y, m1x, m1y, m2x, m2y, m3x, m3y, costs )\
93 {\
94     pixel *pix_base = p_fref_w + bmx + bmy*stride;\
95     h->pixf.fpelcmp_x4[i_pixel]( p_fenc,\
96         pix_base + (m0x) + (m0y)*stride,\
97         pix_base + (m1x) + (m1y)*stride,\
98         pix_base + (m2x) + (m2y)*stride,\
99         pix_base + (m3x) + (m3y)*stride,\
100         stride, costs );\
101     (costs)[0] += BITS_MVD( bmx+(m0x), bmy+(m0y) );\
102     (costs)[1] += BITS_MVD( bmx+(m1x), bmy+(m1y) );\
103     (costs)[2] += BITS_MVD( bmx+(m2x), bmy+(m2y) );\
104     (costs)[3] += BITS_MVD( bmx+(m3x), bmy+(m3y) );\
105 }
106
107 #define COST_MV_X4( m0x, m0y, m1x, m1y, m2x, m2y, m3x, m3y )\
108 {\
109     pixel *pix_base = p_fref_w + omx + omy*stride;\
110     h->pixf.fpelcmp_x4[i_pixel]( p_fenc,\
111         pix_base + (m0x) + (m0y)*stride,\
112         pix_base + (m1x) + (m1y)*stride,\
113         pix_base + (m2x) + (m2y)*stride,\
114         pix_base + (m3x) + (m3y)*stride,\
115         stride, costs );\
116     costs[0] += BITS_MVD( omx+(m0x), omy+(m0y) );\
117     costs[1] += BITS_MVD( omx+(m1x), omy+(m1y) );\
118     costs[2] += BITS_MVD( omx+(m2x), omy+(m2y) );\
119     costs[3] += BITS_MVD( omx+(m3x), omy+(m3y) );\
120     COPY3_IF_LT( bcost, costs[0], bmx, omx+(m0x), bmy, omy+(m0y) );\
121     COPY3_IF_LT( bcost, costs[1], bmx, omx+(m1x), bmy, omy+(m1y) );\
122     COPY3_IF_LT( bcost, costs[2], bmx, omx+(m2x), bmy, omy+(m2y) );\
123     COPY3_IF_LT( bcost, costs[3], bmx, omx+(m3x), bmy, omy+(m3y) );\
124 }
125
126 #define COST_MV_X3_ABS( m0x, m0y, m1x, m1y, m2x, m2y )\
127 {\
128     h->pixf.fpelcmp_x3[i_pixel]( p_fenc,\
129         p_fref_w + (m0x) + (m0y)*stride,\
130         p_fref_w + (m1x) + (m1y)*stride,\
131         p_fref_w + (m2x) + (m2y)*stride,\
132         stride, costs );\
133     costs[0] += p_cost_mvx[(m0x)<<2]; /* no cost_mvy */\
134     costs[1] += p_cost_mvx[(m1x)<<2];\
135     costs[2] += p_cost_mvx[(m2x)<<2];\
136     COPY3_IF_LT( bcost, costs[0], bmx, m0x, bmy, m0y );\
137     COPY3_IF_LT( bcost, costs[1], bmx, m1x, bmy, m1y );\
138     COPY3_IF_LT( bcost, costs[2], bmx, m2x, bmy, m2y );\
139 }
140
141 /*  1  */
142 /* 101 */
143 /*  1  */
144 #define DIA1_ITER( mx, my )\
145 {\
146     omx = mx; omy = my;\
147     COST_MV_X4( 0,-1, 0,1, -1,0, 1,0 );\
148 }
149
150 #define CROSS( start, x_max, y_max )\
151 {\
152     int i = start;\
153     if( (x_max) <= X264_MIN(mv_x_max-omx, omx-mv_x_min) )\
154         for( ; i < (x_max)-2; i+=4 )\
155             COST_MV_X4( i,0, -i,0, i+2,0, -i-2,0 );\
156     for( ; i < (x_max); i+=2 )\
157     {\
158         if( omx+i <= mv_x_max )\
159             COST_MV( omx+i, omy );\
160         if( omx-i >= mv_x_min )\
161             COST_MV( omx-i, omy );\
162     }\
163     i = start;\
164     if( (y_max) <= X264_MIN(mv_y_max-omy, omy-mv_y_min) )\
165         for( ; i < (y_max)-2; i+=4 )\
166             COST_MV_X4( 0,i, 0,-i, 0,i+2, 0,-i-2 );\
167     for( ; i < (y_max); i+=2 )\
168     {\
169         if( omy+i <= mv_y_max )\
170             COST_MV( omx, omy+i );\
171         if( omy-i >= mv_y_min )\
172             COST_MV( omx, omy-i );\
173     }\
174 }
175
176 void x264_me_search_ref( x264_t *h, x264_me_t *m, int16_t (*mvc)[2], int i_mvc, int *p_halfpel_thresh )
177 {
178     const int bw = x264_pixel_size[m->i_pixel].w;
179     const int bh = x264_pixel_size[m->i_pixel].h;
180     const int i_pixel = m->i_pixel;
181     const int stride = m->i_stride[0];
182     int i_me_range = h->param.analyse.i_me_range;
183     int bmx, bmy, bcost;
184     int bpred_mx = 0, bpred_my = 0, bpred_cost = COST_MAX;
185     int omx, omy, pmx, pmy;
186     pixel *p_fenc = m->p_fenc[0];
187     pixel *p_fref_w = m->p_fref_w;
188     ALIGNED_ARRAY_16( pixel, pix,[16*16] );
189
190     int costs[16];
191
192     int mv_x_min = h->mb.mv_min_fpel[0];
193     int mv_y_min = h->mb.mv_min_fpel[1];
194     int mv_x_max = h->mb.mv_max_fpel[0];
195     int mv_y_max = h->mb.mv_max_fpel[1];
196     int mv_x_min_qpel = mv_x_min << 2;
197     int mv_y_min_qpel = mv_y_min << 2;
198     int mv_x_max_qpel = mv_x_max << 2;
199     int mv_y_max_qpel = mv_y_max << 2;
200 /* Special version of pack to allow shortcuts in CHECK_MVRANGE */
201 #define pack16to32_mask2(mx,my) ((mx<<16)|(my&0x7FFF))
202     uint32_t mv_min = pack16to32_mask2( -mv_x_min, -mv_y_min );
203     uint32_t mv_max = pack16to32_mask2( mv_x_max, mv_y_max )|0x8000;
204
205 #define CHECK_MVRANGE(mx,my) (!(((pack16to32_mask2(mx,my) + mv_min) | (mv_max - pack16to32_mask2(mx,my))) & 0x80004000))
206
207     const uint16_t *p_cost_mvx = m->p_cost_mv - m->mvp[0];
208     const uint16_t *p_cost_mvy = m->p_cost_mv - m->mvp[1];
209
210     uint32_t pmv;
211     bmx = x264_clip3( m->mvp[0], mv_x_min_qpel, mv_x_max_qpel );
212     bmy = x264_clip3( m->mvp[1], mv_y_min_qpel, mv_y_max_qpel );
213     pmx = ( bmx + 2 ) >> 2;
214     pmy = ( bmy + 2 ) >> 2;
215     bcost = COST_MAX;
216
217     /* try extra predictors if provided */
218     if( h->mb.i_subpel_refine >= 3 )
219     {
220         pmv = pack16to32_mask(bmx,bmy);
221         if( i_mvc )
222             COST_MV_HPEL( bmx, bmy );
223         for( int i = 0; i < i_mvc; i++ )
224         {
225             if( M32( mvc[i] ) && (pmv != M32( mvc[i] )) )
226             {
227                 int mx = x264_clip3( mvc[i][0], mv_x_min_qpel, mv_x_max_qpel );
228                 int my = x264_clip3( mvc[i][1], mv_y_min_qpel, mv_y_max_qpel );
229                 COST_MV_HPEL( mx, my );
230             }
231         }
232         bmx = ( bpred_mx + 2 ) >> 2;
233         bmy = ( bpred_my + 2 ) >> 2;
234         COST_MV( bmx, bmy );
235     }
236     else
237     {
238         /* check the MVP */
239         bmx = pmx;
240         bmy = pmy;
241         /* Because we are rounding the predicted motion vector to fullpel, there will be
242          * an extra MV cost in 15 out of 16 cases.  However, when the predicted MV is
243          * chosen as the best predictor, it is often the case that the subpel search will
244          * result in a vector at or next to the predicted motion vector.  Therefore, it is
245          * sensible to omit the cost of the MV from the rounded MVP to avoid unfairly
246          * biasing against use of the predicted motion vector. */
247         bcost = h->pixf.fpelcmp[i_pixel]( p_fenc, FENC_STRIDE, &p_fref_w[bmy*stride+bmx], stride );
248         pmv = pack16to32_mask( bmx, bmy );
249         if( i_mvc > 0 )
250         {
251             ALIGNED_ARRAY_8( int16_t, mvc_fpel,[16],[2] );
252             x264_predictor_roundclip( mvc_fpel, mvc, i_mvc, mv_x_min, mv_x_max, mv_y_min, mv_y_max );
253             bcost <<= 4;
254             for( int i = 1; i <= i_mvc; i++ )
255             {
256                 if( M32( mvc_fpel[i-1] ) && (pmv != M32( mvc[i-1] )) )
257                 {
258                     int mx = mvc_fpel[i-1][0];
259                     int my = mvc_fpel[i-1][1];
260                     int cost = h->pixf.fpelcmp[i_pixel]( p_fenc, FENC_STRIDE, &p_fref_w[my*stride+mx], stride ) + BITS_MVD( mx, my );
261                     cost = (cost << 4) + i;
262                     COPY1_IF_LT( bcost, cost );
263                 }
264             }
265             if( bcost&15 )
266             {
267                 bmx = mvc_fpel[(bcost&15)-1][0];
268                 bmy = mvc_fpel[(bcost&15)-1][1];
269             }
270             bcost >>= 4;
271         }
272     }
273
274     if( pmv )
275         COST_MV( 0, 0 );
276
277     switch( h->mb.i_me_method )
278     {
279         case X264_ME_DIA:
280         {
281             /* diamond search, radius 1 */
282             bcost <<= 4;
283             int i = i_me_range;
284             do
285             {
286                 COST_MV_X4_DIR( 0,-1, 0,1, -1,0, 1,0, costs );
287                 COPY1_IF_LT( bcost, (costs[0]<<4)+1 );
288                 COPY1_IF_LT( bcost, (costs[1]<<4)+3 );
289                 COPY1_IF_LT( bcost, (costs[2]<<4)+4 );
290                 COPY1_IF_LT( bcost, (costs[3]<<4)+12 );
291                 if( !(bcost&15) )
292                     break;
293                 bmx -= (bcost<<28)>>30;
294                 bmy -= (bcost<<30)>>30;
295                 bcost &= ~15;
296             } while( --i && CHECK_MVRANGE(bmx, bmy) );
297             bcost >>= 4;
298             break;
299         }
300
301         case X264_ME_HEX:
302         {
303     me_hex2:
304             /* hexagon search, radius 2 */
305     #if 0
306             for( int i = 0; i < i_me_range/2; i++ )
307             {
308                 omx = bmx; omy = bmy;
309                 COST_MV( omx-2, omy   );
310                 COST_MV( omx-1, omy+2 );
311                 COST_MV( omx+1, omy+2 );
312                 COST_MV( omx+2, omy   );
313                 COST_MV( omx+1, omy-2 );
314                 COST_MV( omx-1, omy-2 );
315                 if( bmx == omx && bmy == omy )
316                     break;
317                 if( !CHECK_MVRANGE(bmx, bmy) )
318                     break;
319             }
320     #else
321             /* equivalent to the above, but eliminates duplicate candidates */
322
323             /* hexagon */
324             COST_MV_X3_DIR( -2,0, -1, 2,  1, 2, costs   );
325             COST_MV_X3_DIR(  2,0,  1,-2, -1,-2, costs+3 );
326             bcost <<= 3;
327             COPY1_IF_LT( bcost, (costs[0]<<3)+2 );
328             COPY1_IF_LT( bcost, (costs[1]<<3)+3 );
329             COPY1_IF_LT( bcost, (costs[2]<<3)+4 );
330             COPY1_IF_LT( bcost, (costs[3]<<3)+5 );
331             COPY1_IF_LT( bcost, (costs[4]<<3)+6 );
332             COPY1_IF_LT( bcost, (costs[5]<<3)+7 );
333
334             if( bcost&7 )
335             {
336                 int dir = (bcost&7)-2;
337                 bmx += hex2[dir+1][0];
338                 bmy += hex2[dir+1][1];
339
340                 /* half hexagon, not overlapping the previous iteration */
341                 for( int i = (i_me_range>>1) - 1; i > 0 && CHECK_MVRANGE(bmx, bmy); i-- )
342                 {
343                     COST_MV_X3_DIR( hex2[dir+0][0], hex2[dir+0][1],
344                                     hex2[dir+1][0], hex2[dir+1][1],
345                                     hex2[dir+2][0], hex2[dir+2][1],
346                                     costs );
347                     bcost &= ~7;
348                     COPY1_IF_LT( bcost, (costs[0]<<3)+1 );
349                     COPY1_IF_LT( bcost, (costs[1]<<3)+2 );
350                     COPY1_IF_LT( bcost, (costs[2]<<3)+3 );
351                     if( !(bcost&7) )
352                         break;
353                     dir += (bcost&7)-2;
354                     dir = mod6m1[dir+1];
355                     bmx += hex2[dir+1][0];
356                     bmy += hex2[dir+1][1];
357                 }
358             }
359             bcost >>= 3;
360     #endif
361             /* square refine */
362             int dir = 0;
363             COST_MV_X4_DIR(  0,-1,  0,1, -1,0, 1,0, costs );
364             COPY2_IF_LT( bcost, costs[0], dir, 1 );
365             COPY2_IF_LT( bcost, costs[1], dir, 2 );
366             COPY2_IF_LT( bcost, costs[2], dir, 3 );
367             COPY2_IF_LT( bcost, costs[3], dir, 4 );
368             COST_MV_X4_DIR( -1,-1, -1,1, 1,-1, 1,1, costs );
369             COPY2_IF_LT( bcost, costs[0], dir, 5 );
370             COPY2_IF_LT( bcost, costs[1], dir, 6 );
371             COPY2_IF_LT( bcost, costs[2], dir, 7 );
372             COPY2_IF_LT( bcost, costs[3], dir, 8 );
373             bmx += square1[dir][0];
374             bmy += square1[dir][1];
375             break;
376         }
377
378         case X264_ME_UMH:
379         {
380             /* Uneven-cross Multi-Hexagon-grid Search
381              * as in JM, except with different early termination */
382
383             static const uint8_t x264_pixel_size_shift[7] = { 0, 1, 1, 2, 3, 3, 4 };
384
385             int ucost1, ucost2;
386             int cross_start = 1;
387
388             /* refine predictors */
389             ucost1 = bcost;
390             DIA1_ITER( pmx, pmy );
391             if( pmx | pmy )
392                 DIA1_ITER( 0, 0 );
393
394             if( i_pixel == PIXEL_4x4 )
395                 goto me_hex2;
396
397             ucost2 = bcost;
398             if( (bmx | bmy) && ((bmx-pmx) | (bmy-pmy)) )
399                 DIA1_ITER( bmx, bmy );
400             if( bcost == ucost2 )
401                 cross_start = 3;
402             omx = bmx; omy = bmy;
403
404             /* early termination */
405 #define SAD_THRESH(v) ( bcost < ( v >> x264_pixel_size_shift[i_pixel] ) )
406             if( bcost == ucost2 && SAD_THRESH(2000) )
407             {
408                 COST_MV_X4( 0,-2, -1,-1, 1,-1, -2,0 );
409                 COST_MV_X4( 2, 0, -1, 1, 1, 1,  0,2 );
410                 if( bcost == ucost1 && SAD_THRESH(500) )
411                     break;
412                 if( bcost == ucost2 )
413                 {
414                     int range = (i_me_range>>1) | 1;
415                     CROSS( 3, range, range );
416                     COST_MV_X4( -1,-2, 1,-2, -2,-1, 2,-1 );
417                     COST_MV_X4( -2, 1, 2, 1, -1, 2, 1, 2 );
418                     if( bcost == ucost2 )
419                         break;
420                     cross_start = range + 2;
421                 }
422             }
423
424             /* adaptive search range */
425             if( i_mvc )
426             {
427                 /* range multipliers based on casual inspection of some statistics of
428                  * average distance between current predictor and final mv found by ESA.
429                  * these have not been tuned much by actual encoding. */
430                 static const uint8_t range_mul[4][4] =
431                 {
432                     { 3, 3, 4, 4 },
433                     { 3, 4, 4, 4 },
434                     { 4, 4, 4, 5 },
435                     { 4, 4, 5, 6 },
436                 };
437                 int mvd;
438                 int sad_ctx, mvd_ctx;
439                 int denom = 1;
440
441                 if( i_mvc == 1 )
442                 {
443                     if( i_pixel == PIXEL_16x16 )
444                         /* mvc is probably the same as mvp, so the difference isn't meaningful.
445                          * but prediction usually isn't too bad, so just use medium range */
446                         mvd = 25;
447                     else
448                         mvd = abs( m->mvp[0] - mvc[0][0] )
449                             + abs( m->mvp[1] - mvc[0][1] );
450                 }
451                 else
452                 {
453                     /* calculate the degree of agreement between predictors. */
454                     /* in 16x16, mvc includes all the neighbors used to make mvp,
455                      * so don't count mvp separately. */
456                     denom = i_mvc - 1;
457                     mvd = 0;
458                     if( i_pixel != PIXEL_16x16 )
459                     {
460                         mvd = abs( m->mvp[0] - mvc[0][0] )
461                             + abs( m->mvp[1] - mvc[0][1] );
462                         denom++;
463                     }
464                     mvd += x264_predictor_difference( mvc, i_mvc );
465                 }
466
467                 sad_ctx = SAD_THRESH(1000) ? 0
468                         : SAD_THRESH(2000) ? 1
469                         : SAD_THRESH(4000) ? 2 : 3;
470                 mvd_ctx = mvd < 10*denom ? 0
471                         : mvd < 20*denom ? 1
472                         : mvd < 40*denom ? 2 : 3;
473
474                 i_me_range = i_me_range * range_mul[mvd_ctx][sad_ctx] >> 2;
475             }
476
477             /* FIXME if the above DIA2/OCT2/CROSS found a new mv, it has not updated omx/omy.
478              * we are still centered on the same place as the DIA2. is this desirable? */
479             CROSS( cross_start, i_me_range, i_me_range>>1 );
480
481             COST_MV_X4( -2,-2, -2,2, 2,-2, 2,2 );
482
483             /* hexagon grid */
484             omx = bmx; omy = bmy;
485             const uint16_t *p_cost_omvx = p_cost_mvx + omx*4;
486             const uint16_t *p_cost_omvy = p_cost_mvy + omy*4;
487             int i = 1;
488             do
489             {
490                 static const int8_t hex4[16][2] = {
491                     { 0,-4}, { 0, 4}, {-2,-3}, { 2,-3},
492                     {-4,-2}, { 4,-2}, {-4,-1}, { 4,-1},
493                     {-4, 0}, { 4, 0}, {-4, 1}, { 4, 1},
494                     {-4, 2}, { 4, 2}, {-2, 3}, { 2, 3},
495                 };
496
497                 if( 4*i > X264_MIN4( mv_x_max-omx, omx-mv_x_min,
498                                      mv_y_max-omy, omy-mv_y_min ) )
499                 {
500                     for( int j = 0; j < 16; j++ )
501                     {
502                         int mx = omx + hex4[j][0]*i;
503                         int my = omy + hex4[j][1]*i;
504                         if( CHECK_MVRANGE(mx, my) )
505                             COST_MV( mx, my );
506                     }
507                 }
508                 else
509                 {
510                     int dir = 0;
511                     pixel *pix_base = p_fref_w + omx + (omy-4*i)*stride;
512                     int dy = i*stride;
513 #define SADS(k,x0,y0,x1,y1,x2,y2,x3,y3)\
514                     h->pixf.fpelcmp_x4[i_pixel]( p_fenc,\
515                             pix_base x0*i+(y0-2*k+4)*dy,\
516                             pix_base x1*i+(y1-2*k+4)*dy,\
517                             pix_base x2*i+(y2-2*k+4)*dy,\
518                             pix_base x3*i+(y3-2*k+4)*dy,\
519                             stride, costs+4*k );\
520                     pix_base += 2*dy;
521 #define ADD_MVCOST(k,x,y) costs[k] += p_cost_omvx[x*4*i] + p_cost_omvy[y*4*i]
522 #define MIN_MV(k,x,y)     COPY2_IF_LT( bcost, costs[k], dir, x*16+(y&15) )
523                     SADS( 0, +0,-4, +0,+4, -2,-3, +2,-3 );
524                     SADS( 1, -4,-2, +4,-2, -4,-1, +4,-1 );
525                     SADS( 2, -4,+0, +4,+0, -4,+1, +4,+1 );
526                     SADS( 3, -4,+2, +4,+2, -2,+3, +2,+3 );
527                     ADD_MVCOST(  0, 0,-4 );
528                     ADD_MVCOST(  1, 0, 4 );
529                     ADD_MVCOST(  2,-2,-3 );
530                     ADD_MVCOST(  3, 2,-3 );
531                     ADD_MVCOST(  4,-4,-2 );
532                     ADD_MVCOST(  5, 4,-2 );
533                     ADD_MVCOST(  6,-4,-1 );
534                     ADD_MVCOST(  7, 4,-1 );
535                     ADD_MVCOST(  8,-4, 0 );
536                     ADD_MVCOST(  9, 4, 0 );
537                     ADD_MVCOST( 10,-4, 1 );
538                     ADD_MVCOST( 11, 4, 1 );
539                     ADD_MVCOST( 12,-4, 2 );
540                     ADD_MVCOST( 13, 4, 2 );
541                     ADD_MVCOST( 14,-2, 3 );
542                     ADD_MVCOST( 15, 2, 3 );
543                     MIN_MV(  0, 0,-4 );
544                     MIN_MV(  1, 0, 4 );
545                     MIN_MV(  2,-2,-3 );
546                     MIN_MV(  3, 2,-3 );
547                     MIN_MV(  4,-4,-2 );
548                     MIN_MV(  5, 4,-2 );
549                     MIN_MV(  6,-4,-1 );
550                     MIN_MV(  7, 4,-1 );
551                     MIN_MV(  8,-4, 0 );
552                     MIN_MV(  9, 4, 0 );
553                     MIN_MV( 10,-4, 1 );
554                     MIN_MV( 11, 4, 1 );
555                     MIN_MV( 12,-4, 2 );
556                     MIN_MV( 13, 4, 2 );
557                     MIN_MV( 14,-2, 3 );
558                     MIN_MV( 15, 2, 3 );
559 #undef SADS
560 #undef ADD_MVCOST
561 #undef MIN_MV
562                     if(dir)
563                     {
564                         bmx = omx + i*(dir>>4);
565                         bmy = omy + i*((dir<<28)>>28);
566                     }
567                 }
568             } while( ++i <= i_me_range>>2 );
569             if( bmy <= mv_y_max && bmy >= mv_y_min && bmx <= mv_x_max && bmx >= mv_x_min )
570                 goto me_hex2;
571             break;
572         }
573
574         case X264_ME_ESA:
575         case X264_ME_TESA:
576         {
577             const int min_x = X264_MAX( bmx - i_me_range, mv_x_min );
578             const int min_y = X264_MAX( bmy - i_me_range, mv_y_min );
579             const int max_x = X264_MIN( bmx + i_me_range, mv_x_max );
580             const int max_y = X264_MIN( bmy + i_me_range, mv_y_max );
581             /* SEA is fastest in multiples of 4 */
582             const int width = (max_x - min_x + 3) & ~3;
583 #if 0
584             /* plain old exhaustive search */
585             for( int my = min_y; my <= max_y; my++ )
586                 for( int mx = min_x; mx < min_x + width; mx++ )
587                     COST_MV( mx, my );
588 #else
589             /* successive elimination by comparing DC before a full SAD,
590              * because sum(abs(diff)) >= abs(diff(sum)). */
591             uint16_t *sums_base = m->integral;
592             ALIGNED_16( static pixel zero[8*FENC_STRIDE] ) = {0};
593             ALIGNED_ARRAY_16( int, enc_dc,[4] );
594             int sad_size = i_pixel <= PIXEL_8x8 ? PIXEL_8x8 : PIXEL_4x4;
595             int delta = x264_pixel_size[sad_size].w;
596             int16_t *xs = h->scratch_buffer;
597             int xn;
598             uint16_t *cost_fpel_mvx = h->cost_mv_fpel[h->mb.i_qp][-m->mvp[0]&3] + (-m->mvp[0]>>2);
599
600             h->pixf.sad_x4[sad_size]( zero, p_fenc, p_fenc+delta,
601                 p_fenc+delta*FENC_STRIDE, p_fenc+delta+delta*FENC_STRIDE,
602                 FENC_STRIDE, enc_dc );
603             if( delta == 4 )
604                 sums_base += stride * (h->fenc->i_lines[0] + PADV*2);
605             if( i_pixel == PIXEL_16x16 || i_pixel == PIXEL_8x16 || i_pixel == PIXEL_4x8 )
606                 delta *= stride;
607             if( i_pixel == PIXEL_8x16 || i_pixel == PIXEL_4x8 )
608                 enc_dc[1] = enc_dc[2];
609
610             if( h->mb.i_me_method == X264_ME_TESA )
611             {
612                 // ADS threshold, then SAD threshold, then keep the best few SADs, then SATD
613                 mvsad_t *mvsads = (mvsad_t *)(xs + ((width+15)&~15) + 4);
614                 int nmvsad = 0, limit;
615                 int sad_thresh = i_me_range <= 16 ? 10 : i_me_range <= 24 ? 11 : 12;
616                 int bsad = h->pixf.sad[i_pixel]( p_fenc, FENC_STRIDE, p_fref_w+bmy*stride+bmx, stride )
617                          + BITS_MVD( bmx, bmy );
618                 for( int my = min_y; my <= max_y; my++ )
619                 {
620                     int i;
621                     int ycost = p_cost_mvy[my<<2];
622                     if( bsad <= ycost )
623                         continue;
624                     bsad -= ycost;
625                     xn = h->pixf.ads[i_pixel]( enc_dc, sums_base + min_x + my * stride, delta,
626                                                cost_fpel_mvx+min_x, xs, width, bsad * 17 >> 4 );
627                     for( i = 0; i < xn-2; i += 3 )
628                     {
629                         pixel *ref = p_fref_w+min_x+my*stride;
630                         int sads[3];
631                         h->pixf.sad_x3[i_pixel]( p_fenc, ref+xs[i], ref+xs[i+1], ref+xs[i+2], stride, sads );
632                         for( int j = 0; j < 3; j++ )
633                         {
634                             int sad = sads[j] + cost_fpel_mvx[xs[i+j]];
635                             if( sad < bsad*sad_thresh>>3 )
636                             {
637                                 COPY1_IF_LT( bsad, sad );
638                                 mvsads[nmvsad].sad = sad + ycost;
639                                 mvsads[nmvsad].mv[0] = min_x+xs[i+j];
640                                 mvsads[nmvsad].mv[1] = my;
641                                 nmvsad++;
642                             }
643                         }
644                     }
645                     for( ; i < xn; i++ )
646                     {
647                         int mx = min_x+xs[i];
648                         int sad = h->pixf.sad[i_pixel]( p_fenc, FENC_STRIDE, p_fref_w+mx+my*stride, stride )
649                                 + cost_fpel_mvx[xs[i]];
650                         if( sad < bsad*sad_thresh>>3 )
651                         {
652                             COPY1_IF_LT( bsad, sad );
653                             mvsads[nmvsad].sad = sad + ycost;
654                             mvsads[nmvsad].mv[0] = mx;
655                             mvsads[nmvsad].mv[1] = my;
656                             nmvsad++;
657                         }
658                     }
659                     bsad += ycost;
660                 }
661
662                 limit = i_me_range >> 1;
663                 sad_thresh = bsad*sad_thresh>>3;
664                 while( nmvsad > limit*2 && sad_thresh > bsad )
665                 {
666                     int i;
667                     // halve the range if the domain is too large... eh, close enough
668                     sad_thresh = (sad_thresh + bsad) >> 1;
669                     for( i = 0; i < nmvsad && mvsads[i].sad <= sad_thresh; i++ );
670                     for( int j = i; j < nmvsad; j++ )
671                     {
672                         uint32_t sad;
673                         if( WORD_SIZE == 8 && sizeof(mvsad_t) == 8 )
674                         {
675                             uint64_t mvsad = M64( &mvsads[i] ) = M64( &mvsads[j] );
676 #if WORDS_BIGENDIAN
677                             mvsad >>= 32;
678 #endif
679                             sad = mvsad;
680                         }
681                         else
682                         {
683                             sad = mvsads[j].sad;
684                             CP32( mvsads[i].mv, mvsads[j].mv );
685                             mvsads[i].sad = sad;
686                         }
687                         i += (sad - (sad_thresh+1)) >> 31;
688                     }
689                     nmvsad = i;
690                 }
691                 while( nmvsad > limit )
692                 {
693                     int bi = 0;
694                     for( int i = 1; i < nmvsad; i++ )
695                         if( mvsads[i].sad > mvsads[bi].sad )
696                             bi = i;
697                     nmvsad--;
698                     if( sizeof( mvsad_t ) == sizeof( uint64_t ) )
699                         CP64( &mvsads[bi], &mvsads[nmvsad] );
700                     else
701                         mvsads[bi] = mvsads[nmvsad];
702                 }
703                 for( int i = 0; i < nmvsad; i++ )
704                     COST_MV( mvsads[i].mv[0], mvsads[i].mv[1] );
705             }
706             else
707             {
708                 // just ADS and SAD
709                 for( int my = min_y; my <= max_y; my++ )
710                 {
711                     int i;
712                     int ycost = p_cost_mvy[my<<2];
713                     if( bcost <= ycost )
714                         continue;
715                     bcost -= ycost;
716                     xn = h->pixf.ads[i_pixel]( enc_dc, sums_base + min_x + my * stride, delta,
717                                                cost_fpel_mvx+min_x, xs, width, bcost );
718                     for( i = 0; i < xn-2; i += 3 )
719                         COST_MV_X3_ABS( min_x+xs[i],my, min_x+xs[i+1],my, min_x+xs[i+2],my );
720                     bcost += ycost;
721                     for( ; i < xn; i++ )
722                         COST_MV( min_x+xs[i], my );
723                 }
724             }
725 #endif
726         }
727         break;
728     }
729
730     /* -> qpel mv */
731     if( bpred_cost < bcost )
732     {
733         m->mv[0] = bpred_mx;
734         m->mv[1] = bpred_my;
735         m->cost = bpred_cost;
736     }
737     else
738     {
739         m->mv[0] = bmx << 2;
740         m->mv[1] = bmy << 2;
741         m->cost = bcost;
742     }
743
744     /* compute the real cost */
745     m->cost_mv = p_cost_mvx[ m->mv[0] ] + p_cost_mvy[ m->mv[1] ];
746     if( bmx == pmx && bmy == pmy && h->mb.i_subpel_refine < 3 )
747         m->cost += m->cost_mv;
748
749     /* subpel refine */
750     if( h->mb.i_subpel_refine >= 2 )
751     {
752         int hpel = subpel_iterations[h->mb.i_subpel_refine][2];
753         int qpel = subpel_iterations[h->mb.i_subpel_refine][3];
754         refine_subpel( h, m, hpel, qpel, p_halfpel_thresh, 0 );
755     }
756 }
757 #undef COST_MV
758
759 void x264_me_refine_qpel( x264_t *h, x264_me_t *m )
760 {
761     int hpel = subpel_iterations[h->mb.i_subpel_refine][0];
762     int qpel = subpel_iterations[h->mb.i_subpel_refine][1];
763
764     if( m->i_pixel <= PIXEL_8x8 )
765         m->cost -= m->i_ref_cost;
766
767     refine_subpel( h, m, hpel, qpel, NULL, 1 );
768 }
769
770 void x264_me_refine_qpel_refdupe( x264_t *h, x264_me_t *m, int *p_halfpel_thresh )
771 {
772     refine_subpel( h, m, 0, X264_MIN( 2, subpel_iterations[h->mb.i_subpel_refine][3] ), p_halfpel_thresh, 0 );
773 }
774
775 #define COST_MV_SAD( mx, my ) \
776 { \
777     int stride = 16; \
778     pixel *src = h->mc.get_ref( pix, &stride, m->p_fref, m->i_stride[0], mx, my, bw, bh, &m->weight[0] ); \
779     int cost = h->pixf.fpelcmp[i_pixel]( m->p_fenc[0], FENC_STRIDE, src, stride ) \
780              + p_cost_mvx[ mx ] + p_cost_mvy[ my ]; \
781     COPY3_IF_LT( bcost, cost, bmx, mx, bmy, my ); \
782 }
783
784 #define COST_MV_SATD( mx, my, dir ) \
785 if( b_refine_qpel || (dir^1) != odir ) \
786 { \
787     int stride = 16; \
788     pixel *src = h->mc.get_ref( pix, &stride, m->p_fref, m->i_stride[0], mx, my, bw, bh, &m->weight[0] ); \
789     int cost = h->pixf.mbcmp_unaligned[i_pixel]( m->p_fenc[0], FENC_STRIDE, src, stride ) \
790              + p_cost_mvx[ mx ] + p_cost_mvy[ my ]; \
791     if( b_chroma_me && cost < bcost ) \
792     { \
793         h->mc.mc_chroma( pix, pix+8, 16, m->p_fref[4], m->i_stride[1], mx, my + mvy_offset, bw>>1, bh>>1 ); \
794         if( m->weight[1].weightfn ) \
795             m->weight[1].weightfn[x264_pixel_size[i_pixel].w>>3]( pix, 16, pix, 16, \
796                                                                   &m->weight[1], x264_pixel_size[i_pixel].h>>1 ); \
797         cost += h->pixf.mbcmp[i_pixel+3]( m->p_fenc[1], FENC_STRIDE, pix, 16 ); \
798         if( cost < bcost ) \
799         { \
800             if( m->weight[2].weightfn ) \
801                 m->weight[2].weightfn[x264_pixel_size[i_pixel].w>>3]( pix+8, 16, pix+8, 16, \
802                                                                       &m->weight[2], x264_pixel_size[i_pixel].h>>1 ); \
803             cost += h->pixf.mbcmp[i_pixel+3]( m->p_fenc[2], FENC_STRIDE, pix+8, 16 ); \
804         } \
805     } \
806     COPY4_IF_LT( bcost, cost, bmx, mx, bmy, my, bdir, dir ); \
807 }
808
809 static void refine_subpel( x264_t *h, x264_me_t *m, int hpel_iters, int qpel_iters, int *p_halfpel_thresh, int b_refine_qpel )
810 {
811     const int bw = x264_pixel_size[m->i_pixel].w;
812     const int bh = x264_pixel_size[m->i_pixel].h;
813     const uint16_t *p_cost_mvx = m->p_cost_mv - m->mvp[0];
814     const uint16_t *p_cost_mvy = m->p_cost_mv - m->mvp[1];
815     const int i_pixel = m->i_pixel;
816     const int b_chroma_me = h->mb.b_chroma_me && i_pixel <= PIXEL_8x8;
817     const int mvy_offset = h->mb.b_interlaced & m->i_ref ? (h->mb.i_mb_y & 1)*4 - 2 : 0;
818
819     ALIGNED_ARRAY_16( pixel, pix,[64*18] ); // really 17x17x2, but round up for alignment
820
821     int bmx = m->mv[0];
822     int bmy = m->mv[1];
823     int bcost = m->cost;
824     int odir = -1, bdir;
825
826     /* try the subpel component of the predicted mv */
827     if( hpel_iters && h->mb.i_subpel_refine < 3 )
828     {
829         int mx = x264_clip3( m->mvp[0], h->mb.mv_min_spel[0]+2, h->mb.mv_max_spel[0]-2 );
830         int my = x264_clip3( m->mvp[1], h->mb.mv_min_spel[1]+2, h->mb.mv_max_spel[1]-2 );
831         if( (mx-bmx)|(my-bmy) )
832             COST_MV_SAD( mx, my );
833     }
834
835     /* halfpel diamond search */
836     for( int i = hpel_iters; i > 0; i-- )
837     {
838         int omx = bmx, omy = bmy;
839         int costs[4];
840         int stride = 64; // candidates are either all hpel or all qpel, so one stride is enough
841         pixel *src0, *src1, *src2, *src3;
842         src0 = h->mc.get_ref( pix,    &stride, m->p_fref, m->i_stride[0], omx, omy-2, bw, bh+1, &m->weight[0] );
843         src2 = h->mc.get_ref( pix+32, &stride, m->p_fref, m->i_stride[0], omx-2, omy, bw+4, bh, &m->weight[0] );
844         src1 = src0 + stride;
845         src3 = src2 + 1;
846         h->pixf.fpelcmp_x4[i_pixel]( m->p_fenc[0], src0, src1, src2, src3, stride, costs );
847         COPY2_IF_LT( bcost, costs[0] + p_cost_mvx[omx  ] + p_cost_mvy[omy-2], bmy, omy-2 );
848         COPY2_IF_LT( bcost, costs[1] + p_cost_mvx[omx  ] + p_cost_mvy[omy+2], bmy, omy+2 );
849         COPY3_IF_LT( bcost, costs[2] + p_cost_mvx[omx-2] + p_cost_mvy[omy  ], bmx, omx-2, bmy, omy );
850         COPY3_IF_LT( bcost, costs[3] + p_cost_mvx[omx+2] + p_cost_mvy[omy  ], bmx, omx+2, bmy, omy );
851         if( (bmx == omx) & (bmy == omy) )
852             break;
853     }
854
855     if( !b_refine_qpel && (h->pixf.mbcmp_unaligned[0] != h->pixf.fpelcmp[0] || b_chroma_me) )
856     {
857         bcost = COST_MAX;
858         COST_MV_SATD( bmx, bmy, -1 );
859     }
860
861     /* early termination when examining multiple reference frames */
862     if( p_halfpel_thresh )
863     {
864         if( (bcost*7)>>3 > *p_halfpel_thresh )
865         {
866             m->cost = bcost;
867             m->mv[0] = bmx;
868             m->mv[1] = bmy;
869             // don't need cost_mv
870             return;
871         }
872         else if( bcost < *p_halfpel_thresh )
873             *p_halfpel_thresh = bcost;
874     }
875
876     /* quarterpel diamond search */
877     if( h->mb.i_subpel_refine != 1 )
878     {
879         bdir = -1;
880         for( int i = qpel_iters; i > 0; i-- )
881         {
882             if( bmy <= h->mb.mv_min_spel[1] || bmy >= h->mb.mv_max_spel[1] || bmx <= h->mb.mv_min_spel[0] || bmx >= h->mb.mv_max_spel[0] )
883                 break;
884             odir = bdir;
885             int omx = bmx, omy = bmy;
886             COST_MV_SATD( omx, omy - 1, 0 );
887             COST_MV_SATD( omx, omy + 1, 1 );
888             COST_MV_SATD( omx - 1, omy, 2 );
889             COST_MV_SATD( omx + 1, omy, 3 );
890             if( (bmx == omx) & (bmy == omy) )
891                 break;
892         }
893     }
894     /* Special simplified case for subme=1 */
895     else if( bmy > h->mb.mv_min_spel[1] && bmy < h->mb.mv_max_spel[1] && bmx > h->mb.mv_min_spel[0] && bmx < h->mb.mv_max_spel[0] )
896     {
897         int costs[4];
898         int omx = bmx, omy = bmy;
899         /* We have to use mc_luma because all strides must be the same to use fpelcmp_x4 */
900         h->mc.mc_luma( pix   , 64, m->p_fref, m->i_stride[0], omx, omy-1, bw, bh, &m->weight[0] );
901         h->mc.mc_luma( pix+16, 64, m->p_fref, m->i_stride[0], omx, omy+1, bw, bh, &m->weight[0] );
902         h->mc.mc_luma( pix+32, 64, m->p_fref, m->i_stride[0], omx-1, omy, bw, bh, &m->weight[0] );
903         h->mc.mc_luma( pix+48, 64, m->p_fref, m->i_stride[0], omx+1, omy, bw, bh, &m->weight[0] );
904         h->pixf.fpelcmp_x4[i_pixel]( m->p_fenc[0], pix, pix+16, pix+32, pix+48, 64, costs );
905         COPY2_IF_LT( bcost, costs[0] + p_cost_mvx[omx  ] + p_cost_mvy[omy-1], bmy, omy-1 );
906         COPY2_IF_LT( bcost, costs[1] + p_cost_mvx[omx  ] + p_cost_mvy[omy+1], bmy, omy+1 );
907         COPY3_IF_LT( bcost, costs[2] + p_cost_mvx[omx-1] + p_cost_mvy[omy  ], bmx, omx-1, bmy, omy );
908         COPY3_IF_LT( bcost, costs[3] + p_cost_mvx[omx+1] + p_cost_mvy[omy  ], bmx, omx+1, bmy, omy );
909     }
910
911     m->cost = bcost;
912     m->mv[0] = bmx;
913     m->mv[1] = bmy;
914     m->cost_mv = p_cost_mvx[bmx] + p_cost_mvy[bmy];
915 }
916
917 #define BIME_CACHE( dx, dy, list )\
918 {\
919     x264_me_t *m = m##list;\
920     int i = 4 + 3*dx + dy;\
921     int mvx = bm##list##x+dx;\
922     int mvy = bm##list##y+dy;\
923     stride[list][i] = bw;\
924     src[list][i] = h->mc.get_ref( pixy_buf[list][i], &stride[list][i], m->p_fref, m->i_stride[0], mvx, mvy, bw, bh, weight_none );\
925     if( rd )\
926         h->mc.mc_chroma( pixu_buf[list][i], pixv_buf[list][i], 8, m->p_fref[4], m->i_stride[1], mvx, mvy + mv##list##y_offset, bw>>1, bh>>1 );\
927 }
928
929 #define SATD_THRESH 17/16
930
931 /* Don't unroll the BIME_CACHE loop. I couldn't find any way to force this
932  * other than making its iteration count not a compile-time constant. */
933 int x264_iter_kludge = 0;
934
935 static void ALWAYS_INLINE x264_me_refine_bidir( x264_t *h, x264_me_t *m0, x264_me_t *m1, int i_weight, int i8, int i_lambda2, int rd )
936 {
937     int x = i8&1;
938     int y = i8>>1;
939     int s8 = X264_SCAN8_0 + 2*x + 16*y;
940     int16_t *cache0_mv = h->mb.cache.mv[0][s8];
941     int16_t *cache1_mv = h->mb.cache.mv[1][s8];
942     const int i_pixel = m0->i_pixel;
943     const int bw = x264_pixel_size[i_pixel].w;
944     const int bh = x264_pixel_size[i_pixel].h;
945     ALIGNED_ARRAY_16( pixel, pixy_buf,[2],[9][16*16] );
946     ALIGNED_ARRAY_16( pixel, pixu_buf,[2],[9][8*8] );
947     ALIGNED_ARRAY_16( pixel, pixv_buf,[2],[9][8*8] );
948     pixel *src[2][9];
949     pixel *pix  = &h->mb.pic.p_fdec[0][8*x + 8*y*FDEC_STRIDE];
950     pixel *pixu = &h->mb.pic.p_fdec[1][4*x + 4*y*FDEC_STRIDE];
951     pixel *pixv = &h->mb.pic.p_fdec[2][4*x + 4*y*FDEC_STRIDE];
952     int ref0 = h->mb.cache.ref[0][s8];
953     int ref1 = h->mb.cache.ref[1][s8];
954     const int mv0y_offset = h->mb.b_interlaced & ref0 ? (h->mb.i_mb_y & 1)*4 - 2 : 0;
955     const int mv1y_offset = h->mb.b_interlaced & ref1 ? (h->mb.i_mb_y & 1)*4 - 2 : 0;
956     int stride[2][9];
957     int bm0x = m0->mv[0];
958     int bm0y = m0->mv[1];
959     int bm1x = m1->mv[0];
960     int bm1y = m1->mv[1];
961     int bcost = COST_MAX;
962     int mc_list0 = 1, mc_list1 = 1;
963     uint64_t bcostrd = COST_MAX64;
964     uint16_t amvd;
965     /* each byte of visited represents 8 possible m1y positions, so a 4D array isn't needed */
966     ALIGNED_ARRAY_16( uint8_t, visited,[8],[8][8] );
967     /* all permutations of an offset in up to 2 of the dimensions */
968     ALIGNED_4( static const int8_t dia4d[33][4] ) =
969     {
970         {0,0,0,0},
971         {0,0,0,1}, {0,0,0,-1}, {0,0,1,0}, {0,0,-1,0},
972         {0,1,0,0}, {0,-1,0,0}, {1,0,0,0}, {-1,0,0,0},
973         {0,0,1,1}, {0,0,-1,-1},{0,1,1,0}, {0,-1,-1,0},
974         {1,1,0,0}, {-1,-1,0,0},{1,0,0,1}, {-1,0,0,-1},
975         {0,1,0,1}, {0,-1,0,-1},{1,0,1,0}, {-1,0,-1,0},
976         {0,0,-1,1},{0,0,1,-1}, {0,-1,1,0},{0,1,-1,0},
977         {-1,1,0,0},{1,-1,0,0}, {1,0,0,-1},{-1,0,0,1},
978         {0,-1,0,1},{0,1,0,-1}, {-1,0,1,0},{1,0,-1,0},
979     };
980
981     if( bm0y < h->mb.mv_min_spel[1] + 8 || bm1y < h->mb.mv_min_spel[1] + 8 ||
982         bm0y > h->mb.mv_max_spel[1] - 8 || bm1y > h->mb.mv_max_spel[1] - 8 ||
983         bm0x < h->mb.mv_min_spel[0] + 8 || bm1x < h->mb.mv_min_spel[0] + 8 ||
984         bm0x > h->mb.mv_max_spel[0] - 8 || bm1x > h->mb.mv_max_spel[0] - 8 )
985         return;
986
987     if( rd && m0->i_pixel != PIXEL_16x16 && i8 != 0 )
988     {
989         x264_mb_predict_mv( h, 0, i8<<2, bw>>2, m0->mvp );
990         x264_mb_predict_mv( h, 1, i8<<2, bw>>2, m1->mvp );
991     }
992
993     const uint16_t *p_cost_m0x = m0->p_cost_mv - m0->mvp[0];
994     const uint16_t *p_cost_m0y = m0->p_cost_mv - m0->mvp[1];
995     const uint16_t *p_cost_m1x = m1->p_cost_mv - m1->mvp[0];
996     const uint16_t *p_cost_m1y = m1->p_cost_mv - m1->mvp[1];
997
998     h->mc.memzero_aligned( visited, sizeof(uint8_t[8][8][8]) );
999
1000     for( int pass = 0; pass < 8; pass++ )
1001     {
1002         int bestj = 0;
1003         /* check all mv pairs that differ in at most 2 components from the current mvs. */
1004         /* doesn't do chroma ME. this probably doesn't matter, as the gains
1005          * from bidir ME are the same with and without chroma ME. */
1006
1007         if( mc_list0 )
1008             for( int j = x264_iter_kludge; j < 9; j++ )
1009                 BIME_CACHE( square1[j][0], square1[j][1], 0 );
1010
1011         if( mc_list1 )
1012             for( int j = x264_iter_kludge; j < 9; j++ )
1013                 BIME_CACHE( square1[j][0], square1[j][1], 1 );
1014
1015         for( int j = !!pass; j < 33; j++ )
1016         {
1017             int m0x = dia4d[j][0] + bm0x;
1018             int m0y = dia4d[j][1] + bm0y;
1019             int m1x = dia4d[j][2] + bm1x;
1020             int m1y = dia4d[j][3] + bm1y;
1021             if( !pass || !((visited[(m0x)&7][(m0y)&7][(m1x)&7] & (1<<((m1y)&7)))) )
1022             {
1023                 int i0 = 4 + 3*dia4d[j][0] + dia4d[j][1];
1024                 int i1 = 4 + 3*dia4d[j][2] + dia4d[j][3];
1025                 visited[(m0x)&7][(m0y)&7][(m1x)&7] |= (1<<((m1y)&7));
1026                 h->mc.avg[i_pixel]( pix, FDEC_STRIDE, src[0][i0], stride[0][i0], src[1][i1], stride[1][i1], i_weight );
1027                 int cost = h->pixf.mbcmp[i_pixel]( m0->p_fenc[0], FENC_STRIDE, pix, FDEC_STRIDE )
1028                          + p_cost_m0x[m0x] + p_cost_m0y[m0y] + p_cost_m1x[m1x] + p_cost_m1y[m1y];
1029                 if( rd )
1030                 {
1031                     if( cost < bcost * SATD_THRESH )
1032                     {
1033                         bcost = X264_MIN( cost, bcost );
1034                         M32( cache0_mv ) = pack16to32_mask(m0x,m0y);
1035                         M32( cache1_mv ) = pack16to32_mask(m1x,m1y);
1036                         h->mc.avg[i_pixel+3]( pixu, FDEC_STRIDE, pixu_buf[0][i0], 8, pixu_buf[1][i1], 8, i_weight );
1037                         h->mc.avg[i_pixel+3]( pixv, FDEC_STRIDE, pixv_buf[0][i0], 8, pixv_buf[1][i1], 8, i_weight );
1038                         uint64_t costrd = x264_rd_cost_part( h, i_lambda2, i8*4, m0->i_pixel );
1039                         COPY2_IF_LT( bcostrd, costrd, bestj, j );
1040                     }
1041                 }
1042                 else
1043                     COPY2_IF_LT( bcost, cost, bestj, j );
1044             }
1045         }
1046
1047         if( !bestj )
1048             break;
1049
1050         bm0x += dia4d[bestj][0];
1051         bm0y += dia4d[bestj][1];
1052         bm1x += dia4d[bestj][2];
1053         bm1y += dia4d[bestj][3];
1054
1055         mc_list0 = M16( &dia4d[bestj][0] );
1056         mc_list1 = M16( &dia4d[bestj][2] );
1057     }
1058
1059     if( rd )
1060     {
1061         x264_macroblock_cache_mv ( h, 2*x, 2*y, bw>>2, bh>>2, 0, pack16to32_mask(bm0x, bm0y) );
1062         amvd = pack8to16( X264_MIN(abs(bm0x - m0->mvp[0]),33), X264_MIN(abs(bm0y - m0->mvp[1]),33) );
1063         x264_macroblock_cache_mvd( h, 2*x, 2*y, bw>>2, bh>>2, 0, amvd );
1064
1065         x264_macroblock_cache_mv ( h, 2*x, 2*y, bw>>2, bh>>2, 1, pack16to32_mask(bm1x, bm1y) );
1066         amvd = pack8to16( X264_MIN(abs(bm1x - m1->mvp[0]),33), X264_MIN(abs(bm1y - m1->mvp[1]),33) );
1067         x264_macroblock_cache_mvd( h, 2*x, 2*y, bw>>2, bh>>2, 1, amvd );
1068     }
1069
1070     m0->mv[0] = bm0x;
1071     m0->mv[1] = bm0y;
1072     m1->mv[0] = bm1x;
1073     m1->mv[1] = bm1y;
1074 }
1075
1076 void x264_me_refine_bidir_satd( x264_t *h, x264_me_t *m0, x264_me_t *m1, int i_weight )
1077 {
1078     x264_me_refine_bidir( h, m0, m1, i_weight, 0, 0, 0 );
1079 }
1080
1081 void x264_me_refine_bidir_rd( x264_t *h, x264_me_t *m0, x264_me_t *m1, int i_weight, int i8, int i_lambda2 )
1082 {
1083     /* Motion compensation is done as part of bidir_rd; don't repeat
1084      * it in encoding. */
1085     h->mb.b_skip_mc = 1;
1086     x264_me_refine_bidir( h, m0, m1, i_weight, i8, i_lambda2, 1 );
1087     h->mb.b_skip_mc = 0;
1088 }
1089
1090 #undef COST_MV_SATD
1091 #define COST_MV_SATD( mx, my, dst, avoid_mvp ) \
1092 { \
1093     if( !avoid_mvp || !(mx == pmx && my == pmy) ) \
1094     { \
1095         h->mc.mc_luma( pix, FDEC_STRIDE, m->p_fref, m->i_stride[0], mx, my, bw, bh, &m->weight[0] ); \
1096         dst = h->pixf.mbcmp[i_pixel]( m->p_fenc[0], FENC_STRIDE, pix, FDEC_STRIDE ) \
1097             + p_cost_mvx[mx] + p_cost_mvy[my]; \
1098         COPY1_IF_LT( bsatd, dst ); \
1099     } \
1100     else \
1101         dst = COST_MAX; \
1102 }
1103
1104 #define COST_MV_RD( mx, my, satd, do_dir, mdir ) \
1105 { \
1106     if( satd <= bsatd * SATD_THRESH ) \
1107     { \
1108         uint64_t cost; \
1109         M32( cache_mv ) = pack16to32_mask(mx,my); \
1110         if( m->i_pixel <= PIXEL_8x8 ) \
1111         { \
1112             h->mc.mc_chroma( pixu, pixv, FDEC_STRIDE, m->p_fref[4], m->i_stride[1], mx, my + mvy_offset, bw>>1, bh>>1 ); \
1113             if( m->weight[1].weightfn ) \
1114                 m->weight[1].weightfn[x264_pixel_size[i_pixel].w>>3]( pixu, FDEC_STRIDE, pixu, FDEC_STRIDE, \
1115                                                                       &m->weight[1], x264_pixel_size[i_pixel].h>>1 ); \
1116             if( m->weight[2].weightfn ) \
1117                 m->weight[2].weightfn[x264_pixel_size[i_pixel].w>>3]( pixv, FDEC_STRIDE, pixv, FDEC_STRIDE, \
1118                                                                       &m->weight[2], x264_pixel_size[i_pixel].h>>1 ); \
1119         } \
1120         cost = x264_rd_cost_part( h, i_lambda2, i4, m->i_pixel ); \
1121         COPY4_IF_LT( bcost, cost, bmx, mx, bmy, my, dir, do_dir?mdir:dir ); \
1122     } \
1123 }
1124
1125 void x264_me_refine_qpel_rd( x264_t *h, x264_me_t *m, int i_lambda2, int i4, int i_list )
1126 {
1127     int16_t *cache_mv = h->mb.cache.mv[i_list][x264_scan8[i4]];
1128     const uint16_t *p_cost_mvx, *p_cost_mvy;
1129     const int bw = x264_pixel_size[m->i_pixel].w;
1130     const int bh = x264_pixel_size[m->i_pixel].h;
1131     const int i_pixel = m->i_pixel;
1132     const int mvy_offset = h->mb.b_interlaced & m->i_ref ? (h->mb.i_mb_y & 1)*4 - 2 : 0;
1133
1134     uint64_t bcost = COST_MAX64;
1135     int bmx = m->mv[0];
1136     int bmy = m->mv[1];
1137     int omx, omy, pmx, pmy;
1138     int satd, bsatd;
1139     int dir = -2;
1140     int i8 = i4>>2;
1141     uint16_t amvd;
1142
1143     pixel *pix  = &h->mb.pic.p_fdec[0][block_idx_xy_fdec[i4]];
1144     pixel *pixu = &h->mb.pic.p_fdec[1][(i8>>1)*4*FDEC_STRIDE+(i8&1)*4];
1145     pixel *pixv = &h->mb.pic.p_fdec[2][(i8>>1)*4*FDEC_STRIDE+(i8&1)*4];
1146
1147     h->mb.b_skip_mc = 1;
1148
1149     if( m->i_pixel != PIXEL_16x16 && i4 != 0 )
1150         x264_mb_predict_mv( h, i_list, i4, bw>>2, m->mvp );
1151     pmx = m->mvp[0];
1152     pmy = m->mvp[1];
1153     p_cost_mvx = m->p_cost_mv - pmx;
1154     p_cost_mvy = m->p_cost_mv - pmy;
1155     COST_MV_SATD( bmx, bmy, bsatd, 0 );
1156     if( m->i_pixel != PIXEL_16x16 )
1157         COST_MV_RD( bmx, bmy, 0, 0, 0 )
1158     else
1159         bcost = m->cost;
1160
1161     /* check the predicted mv */
1162     if( (bmx != pmx || bmy != pmy)
1163         && pmx >= h->mb.mv_min_spel[0] && pmx <= h->mb.mv_max_spel[0]
1164         && pmy >= h->mb.mv_min_spel[1] && pmy <= h->mb.mv_max_spel[1] )
1165     {
1166         COST_MV_SATD( pmx, pmy, satd, 0 );
1167         COST_MV_RD  ( pmx, pmy, satd, 0, 0 );
1168         /* The hex motion search is guaranteed to not repeat the center candidate,
1169          * so if pmv is chosen, set the "MV to avoid checking" to bmv instead. */
1170         if( bmx == pmx && bmy == pmy )
1171         {
1172             pmx = m->mv[0];
1173             pmy = m->mv[1];
1174         }
1175     }
1176
1177     if( bmy < h->mb.mv_min_spel[1] + 3 || bmy > h->mb.mv_max_spel[1] - 3 ||
1178         bmx < h->mb.mv_min_spel[0] + 3 || bmx > h->mb.mv_max_spel[0] - 3 )
1179     {
1180         h->mb.b_skip_mc = 0;
1181         return;
1182     }
1183
1184     /* subpel hex search, same pattern as ME HEX. */
1185     dir = -2;
1186     omx = bmx;
1187     omy = bmy;
1188     for( int j = 0; j < 6; j++ )
1189     {
1190         COST_MV_SATD( omx + hex2[j+1][0], omy + hex2[j+1][1], satd, 1 );
1191         COST_MV_RD  ( omx + hex2[j+1][0], omy + hex2[j+1][1], satd, 1, j );
1192     }
1193
1194     if( dir != -2 )
1195     {
1196         /* half hexagon, not overlapping the previous iteration */
1197         for( int i = 1; i < 10; i++ )
1198         {
1199             const int odir = mod6m1[dir+1];
1200             if( bmy < h->mb.mv_min_spel[1] + 3 ||
1201                 bmy > h->mb.mv_max_spel[1] - 3 )
1202                 break;
1203             dir = -2;
1204             omx = bmx;
1205             omy = bmy;
1206             for( int j = 0; j < 3; j++ )
1207             {
1208                 COST_MV_SATD( omx + hex2[odir+j][0], omy + hex2[odir+j][1], satd, 1 );
1209                 COST_MV_RD  ( omx + hex2[odir+j][0], omy + hex2[odir+j][1], satd, 1, odir-1+j );
1210             }
1211             if( dir == -2 )
1212                 break;
1213         }
1214     }
1215
1216     /* square refine, same pattern as ME HEX. */
1217     omx = bmx;
1218     omy = bmy;
1219     for( int i = 0; i < 8; i++ )
1220     {
1221         COST_MV_SATD( omx + square1[i+1][0], omy + square1[i+1][1], satd, 1 );
1222         COST_MV_RD  ( omx + square1[i+1][0], omy + square1[i+1][1], satd, 0, 0 );
1223     }
1224
1225     m->cost = bcost;
1226     m->mv[0] = bmx;
1227     m->mv[1] = bmy;
1228     x264_macroblock_cache_mv ( h, block_idx_x[i4], block_idx_y[i4], bw>>2, bh>>2, i_list, pack16to32_mask(bmx, bmy) );
1229     amvd = pack8to16( X264_MIN(abs(bmx - m->mvp[0]),33), X264_MIN(abs(bmy - m->mvp[1]),33) );
1230     x264_macroblock_cache_mvd( h, block_idx_x[i4], block_idx_y[i4], bw>>2, bh>>2, i_list, amvd );
1231     h->mb.b_skip_mc = 0;
1232 }