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