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