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