]> git.sesse.net Git - x264/blob - encoder/me.c
r810 borked hpel_filter_sse2 on unaligned buffers
[x264] / encoder / me.c
1 /*****************************************************************************
2  * me.c: h264 encoder library (Motion Estimation)
3  *****************************************************************************
4  * Copyright (C) 2003 Laurent Aimar
5  * $Id: me.c,v 1.1 2004/06/03 19:27:08 fenrir Exp $
6  *
7  * Authors: Laurent Aimar <fenrir@via.ecp.fr>
8  *          Loren Merritt <lorenm@u.washington.edu>
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., 59 Temple Place - Suite 330, Boston, MA  02111, USA.
23  *****************************************************************************/
24
25 #include "common/common.h"
26 #include "me.h"
27
28 /* presets selected from good points on the speed-vs-quality curve of several test videos
29  * subpel_iters[i_subpel_refine] = { refine_hpel, refine_qpel, me_hpel, me_qpel }
30  * where me_* are the number of EPZS iterations run on all candidate block types,
31  * and refine_* are run only on the winner.
32  * the subme=7 values are much higher because any amount of satd search makes
33  * up its time by reducing the number of rd iterations. */
34 static const int subpel_iterations[][4] = 
35    {{1,0,0,0},
36     {1,1,0,0},
37     {0,1,1,0},
38     {0,2,1,0},
39     {0,2,1,1},
40     {0,2,1,2},
41     {0,0,2,2},
42     {0,0,4,10}};
43
44 /* (x-1)%6 */
45 static const int mod6m1[8] = {5,0,1,2,3,4,5,0};
46 /* radius 2 hexagon. repeated entries are to avoid having to compute mod6 every time. */
47 static const int hex2[8][2] = {{-1,-2}, {-2,0}, {-1,2}, {1,2}, {2,0}, {1,-2}, {-1,-2}, {-2,0}};
48 static const int square1[8][2] = {{0,-1}, {0,1}, {-1,0}, {1,0}, {-1,-1}, {1,1}, {-1,1}, {1,-1}};
49
50 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 );
51
52 #define BITS_MVD( mx, my )\
53     (p_cost_mvx[(mx)<<2] + p_cost_mvy[(my)<<2])
54
55 #define COST_MV( mx, my )\
56 {\
57     int cost = h->pixf.fpelcmp[i_pixel]( m->p_fenc[0], FENC_STRIDE,\
58                    &p_fref[(my)*m->i_stride[0]+(mx)], m->i_stride[0] )\
59              + BITS_MVD(mx,my);\
60     COPY3_IF_LT( bcost, cost, bmx, mx, bmy, my );\
61 }
62
63 #define COST_MV_HPEL( mx, my ) \
64 { \
65     int stride = 16; \
66     uint8_t *src = h->mc.get_ref( pix, &stride, m->p_fref, m->i_stride[0], mx, my, bw, bh ); \
67     int cost = h->pixf.fpelcmp[i_pixel]( m->p_fenc[0], FENC_STRIDE, src, stride ) \
68              + p_cost_mvx[ mx ] + p_cost_mvy[ my ]; \
69     COPY3_IF_LT( bpred_cost, cost, bpred_mx, mx, bpred_my, my ); \
70 }
71
72 #define COST_MV_X3_DIR( m0x, m0y, m1x, m1y, m2x, m2y, costs )\
73 {\
74     uint8_t *pix_base = p_fref + bmx + bmy*m->i_stride[0];\
75     h->pixf.fpelcmp_x3[i_pixel]( m->p_fenc[0],\
76         pix_base + (m0x) + (m0y)*m->i_stride[0],\
77         pix_base + (m1x) + (m1y)*m->i_stride[0],\
78         pix_base + (m2x) + (m2y)*m->i_stride[0],\
79         m->i_stride[0], costs );\
80     (costs)[0] += BITS_MVD( bmx+(m0x), bmy+(m0y) );\
81     (costs)[1] += BITS_MVD( bmx+(m1x), bmy+(m1y) );\
82     (costs)[2] += BITS_MVD( bmx+(m2x), bmy+(m2y) );\
83 }
84
85 #define COST_MV_X4( m0x, m0y, m1x, m1y, m2x, m2y, m3x, m3y )\
86 {\
87     uint8_t *pix_base = p_fref + omx + omy*m->i_stride[0];\
88     h->pixf.fpelcmp_x4[i_pixel]( m->p_fenc[0],\
89         pix_base + (m0x) + (m0y)*m->i_stride[0],\
90         pix_base + (m1x) + (m1y)*m->i_stride[0],\
91         pix_base + (m2x) + (m2y)*m->i_stride[0],\
92         pix_base + (m3x) + (m3y)*m->i_stride[0],\
93         m->i_stride[0], costs );\
94     costs[0] += BITS_MVD( omx+(m0x), omy+(m0y) );\
95     costs[1] += BITS_MVD( omx+(m1x), omy+(m1y) );\
96     costs[2] += BITS_MVD( omx+(m2x), omy+(m2y) );\
97     costs[3] += BITS_MVD( omx+(m3x), omy+(m3y) );\
98     COPY3_IF_LT( bcost, costs[0], bmx, omx+(m0x), bmy, omy+(m0y) );\
99     COPY3_IF_LT( bcost, costs[1], bmx, omx+(m1x), bmy, omy+(m1y) );\
100     COPY3_IF_LT( bcost, costs[2], bmx, omx+(m2x), bmy, omy+(m2y) );\
101     COPY3_IF_LT( bcost, costs[3], bmx, omx+(m3x), bmy, omy+(m3y) );\
102 }
103
104 #define COST_MV_X3_ABS( m0x, m0y, m1x, m1y, m2x, m2y )\
105 {\
106     h->pixf.fpelcmp_x3[i_pixel]( m->p_fenc[0],\
107         p_fref + (m0x) + (m0y)*m->i_stride[0],\
108         p_fref + (m1x) + (m1y)*m->i_stride[0],\
109         p_fref + (m2x) + (m2y)*m->i_stride[0],\
110         m->i_stride[0], costs );\
111     costs[0] += p_cost_mvx[(m0x)<<2]; /* no cost_mvy */\
112     costs[1] += p_cost_mvx[(m1x)<<2];\
113     costs[2] += p_cost_mvx[(m2x)<<2];\
114     COPY3_IF_LT( bcost, costs[0], bmx, m0x, bmy, m0y );\
115     COPY3_IF_LT( bcost, costs[1], bmx, m1x, bmy, m1y );\
116     COPY3_IF_LT( bcost, costs[2], bmx, m2x, bmy, m2y );\
117 }
118
119 /*  1  */
120 /* 101 */
121 /*  1  */
122 #define DIA1_ITER( mx, my )\
123 {\
124     omx = mx; omy = my;\
125     COST_MV_X4( 0,-1, 0,1, -1,0, 1,0 );\
126 }
127
128 #define CROSS( start, x_max, y_max )\
129 {\
130     i = start;\
131     if( x_max <= X264_MIN(mv_x_max-omx, omx-mv_x_min) )\
132         for( ; i < x_max-2; i+=4 )\
133             COST_MV_X4( i,0, -i,0, i+2,0, -i-2,0 );\
134     for( ; i < x_max; i+=2 )\
135     {\
136         if( omx+i <= mv_x_max )\
137             COST_MV( omx+i, omy );\
138         if( omx-i >= mv_x_min )\
139             COST_MV( omx-i, omy );\
140     }\
141     i = start;\
142     if( y_max <= X264_MIN(mv_y_max-omy, omy-mv_y_min) )\
143         for( ; i < y_max-2; i+=4 )\
144             COST_MV_X4( 0,i, 0,-i, 0,i+2, 0,-i-2 );\
145     for( ; i < y_max; i+=2 )\
146     {\
147         if( omy+i <= mv_y_max )\
148             COST_MV( omx, omy+i );\
149         if( omy-i >= mv_y_min )\
150             COST_MV( omx, omy-i );\
151     }\
152 }
153
154 void x264_me_search_ref( x264_t *h, x264_me_t *m, int (*mvc)[2], int i_mvc, int *p_halfpel_thresh )
155 {
156     const int bw = x264_pixel_size[m->i_pixel].w;
157     const int bh = x264_pixel_size[m->i_pixel].h;
158     const int i_pixel = m->i_pixel;
159     int i_me_range = h->param.analyse.i_me_range;
160     int bmx, bmy, bcost;
161     int bpred_mx = 0, bpred_my = 0, bpred_cost = COST_MAX;
162     int omx, omy, pmx, pmy;
163     uint8_t *p_fref = m->p_fref[0];
164     DECLARE_ALIGNED_16( uint8_t pix[16*16] );
165     
166     int i, j;
167     int dir;
168     int costs[6];
169
170     int mv_x_min = h->mb.mv_min_fpel[0];
171     int mv_y_min = h->mb.mv_min_fpel[1];
172     int mv_x_max = h->mb.mv_max_fpel[0];
173     int mv_y_max = h->mb.mv_max_fpel[1];
174
175 #define CHECK_MVRANGE(mx,my) ( mx >= mv_x_min && mx <= mv_x_max && my >= mv_y_min && my <= mv_y_max )
176
177     const int16_t *p_cost_mvx = m->p_cost_mv - m->mvp[0];
178     const int16_t *p_cost_mvy = m->p_cost_mv - m->mvp[1];
179
180     bmx = x264_clip3( m->mvp[0], mv_x_min*4, mv_x_max*4 );
181     bmy = x264_clip3( m->mvp[1], mv_y_min*4, mv_y_max*4 );
182     pmx = ( bmx + 2 ) >> 2;
183     pmy = ( bmy + 2 ) >> 2;
184     bcost = COST_MAX;
185
186     /* try extra predictors if provided */
187     if( h->mb.i_subpel_refine >= 3 )
188     {
189         COST_MV_HPEL( bmx, bmy );
190         for( i = 0; i < i_mvc; i++ )
191         {
192             int mx = mvc[i][0];
193             int my = mvc[i][1];
194             if( (mx | my) && ((mx-bmx) | (my-bmy)) )
195             {
196                 mx = x264_clip3( mx, mv_x_min*4, mv_x_max*4 );
197                 my = x264_clip3( my, mv_y_min*4, mv_y_max*4 );
198                 COST_MV_HPEL( mx, my );
199             }
200         }
201         bmx = ( bpred_mx + 2 ) >> 2;
202         bmy = ( bpred_my + 2 ) >> 2;
203         COST_MV( bmx, bmy );
204     }
205     else
206     {
207         /* check the MVP */
208         COST_MV( pmx, pmy );
209         /* I don't know why this helps */
210         bcost -= BITS_MVD(bmx,bmy);
211         
212         for( i = 0; i < i_mvc; i++ )
213         {
214             int mx = (mvc[i][0] + 2) >> 2;
215             int my = (mvc[i][1] + 2) >> 2;
216             if( (mx | my) && ((mx-bmx) | (my-bmy)) )
217             {
218                 mx = x264_clip3( mx, mv_x_min, mv_x_max );
219                 my = x264_clip3( my, mv_y_min, mv_y_max );
220                 COST_MV( mx, my );
221             }
222         }
223     }
224     
225     COST_MV( 0, 0 );
226
227     switch( h->mb.i_me_method )
228     {
229     case X264_ME_DIA:
230         /* diamond search, radius 1 */
231         for( i = 0; i < i_me_range; i++ )
232         {
233             DIA1_ITER( bmx, bmy );
234             if( bmx == omx && bmy == omy )
235                 break;
236             if( !CHECK_MVRANGE(bmx, bmy) )
237                 break;
238         }
239         break;
240
241     case X264_ME_HEX:
242 me_hex2:
243         /* hexagon search, radius 2 */
244 #if 0
245         for( i = 0; i < i_me_range/2; i++ )
246         {
247             omx = bmx; omy = bmy;
248             COST_MV( omx-2, omy   );
249             COST_MV( omx-1, omy+2 );
250             COST_MV( omx+1, omy+2 );
251             COST_MV( omx+2, omy   );
252             COST_MV( omx+1, omy-2 );
253             COST_MV( omx-1, omy-2 );
254             if( bmx == omx && bmy == omy )
255                 break;
256             if( !CHECK_MVRANGE(bmx, bmy) )
257                 break;
258         }
259 #else
260         /* equivalent to the above, but eliminates duplicate candidates */
261         dir = -2;
262
263         /* hexagon */
264         COST_MV_X3_DIR( -2,0, -1, 2,  1, 2, costs   );
265         COST_MV_X3_DIR(  2,0,  1,-2, -1,-2, costs+3 );
266         COPY2_IF_LT( bcost, costs[0], dir, 0 );
267         COPY2_IF_LT( bcost, costs[1], dir, 1 );
268         COPY2_IF_LT( bcost, costs[2], dir, 2 );
269         COPY2_IF_LT( bcost, costs[3], dir, 3 );
270         COPY2_IF_LT( bcost, costs[4], dir, 4 );
271         COPY2_IF_LT( bcost, costs[5], dir, 5 );
272
273         if( dir != -2 )
274         {
275             bmx += hex2[dir+1][0];
276             bmy += hex2[dir+1][1];
277             /* half hexagon, not overlapping the previous iteration */
278             for( i = 1; i < i_me_range/2 && CHECK_MVRANGE(bmx, bmy); i++ )
279             {
280                 const int odir = mod6m1[dir+1];
281                 COST_MV_X3_DIR( hex2[odir+0][0], hex2[odir+0][1],
282                                 hex2[odir+1][0], hex2[odir+1][1],
283                                 hex2[odir+2][0], hex2[odir+2][1],
284                                 costs );
285                 dir = -2;
286                 COPY2_IF_LT( bcost, costs[0], dir, odir-1 );
287                 COPY2_IF_LT( bcost, costs[1], dir, odir   );
288                 COPY2_IF_LT( bcost, costs[2], dir, odir+1 );
289                 if( dir == -2 )
290                     break;
291                 bmx += hex2[dir+1][0];
292                 bmy += hex2[dir+1][1];
293             }
294         }
295 #endif
296         /* square refine */
297         omx = bmx; omy = bmy;
298         COST_MV_X4(  0,-1,  0,1, -1,0, 1,0 );
299         COST_MV_X4( -1,-1, -1,1, 1,-1, 1,1 );
300         break;
301
302     case X264_ME_UMH:
303         {
304             /* Uneven-cross Multi-Hexagon-grid Search
305              * as in JM, except with different early termination */
306
307             static const int x264_pixel_size_shift[7] = { 0, 1, 1, 2, 3, 3, 4 };
308
309             int ucost1, ucost2;
310             int cross_start = 1;
311
312             /* refine predictors */
313             ucost1 = bcost;
314             DIA1_ITER( pmx, pmy );
315             if( pmx | pmy )
316                 DIA1_ITER( 0, 0 );
317
318             if(i_pixel == PIXEL_4x4)
319                 goto me_hex2;
320
321             ucost2 = bcost;
322             if( (bmx | bmy) && ((bmx-pmx) | (bmy-pmy)) )
323                 DIA1_ITER( bmx, bmy );
324             if( bcost == ucost2 )
325                 cross_start = 3;
326             omx = bmx; omy = bmy;
327
328             /* early termination */
329 #define SAD_THRESH(v) ( bcost < ( v >> x264_pixel_size_shift[i_pixel] ) )
330             if( bcost == ucost2 && SAD_THRESH(2000) )
331             {
332                 COST_MV_X4( 0,-2, -1,-1, 1,-1, -2,0 );
333                 COST_MV_X4( 2, 0, -1, 1, 1, 1,  0,2 );
334                 if( bcost == ucost1 && SAD_THRESH(500) )
335                     break;
336                 if( bcost == ucost2 )
337                 {
338                     int range = (i_me_range>>1) | 1;
339                     CROSS( 3, range, range );
340                     COST_MV_X4( -1,-2, 1,-2, -2,-1, 2,-1 );
341                     COST_MV_X4( -2, 1, 2, 1, -1, 2, 1, 2 );
342                     if( bcost == ucost2 )
343                         break;
344                     cross_start = range + 2;
345                 }
346             }
347
348             /* adaptive search range */
349             if( i_mvc )
350             {
351                 /* range multipliers based on casual inspection of some statistics of
352                  * average distance between current predictor and final mv found by ESA.
353                  * these have not been tuned much by actual encoding. */
354                 static const int range_mul[4][4] =
355                 {
356                     { 3, 3, 4, 4 },
357                     { 3, 4, 4, 4 },
358                     { 4, 4, 4, 5 },
359                     { 4, 4, 5, 6 },
360                 };
361                 int mvd;
362                 int sad_ctx, mvd_ctx;
363                 int denom = 1;
364
365                 if( i_mvc == 1 )
366                 {
367                     if( i_pixel == PIXEL_16x16 )
368                         /* mvc is probably the same as mvp, so the difference isn't meaningful.
369                          * but prediction usually isn't too bad, so just use medium range */
370                         mvd = 25;
371                     else
372                         mvd = abs( m->mvp[0] - mvc[0][0] )
373                             + abs( m->mvp[1] - mvc[0][1] );
374                 }
375                 else
376                 {
377                     /* calculate the degree of agreement between predictors. */
378                     /* in 16x16, mvc includes all the neighbors used to make mvp,
379                      * so don't count mvp separately. */
380                     denom = i_mvc - 1;
381                     mvd = 0;
382                     if( i_pixel != PIXEL_16x16 )
383                     {
384                         mvd = abs( m->mvp[0] - mvc[0][0] )
385                             + abs( m->mvp[1] - mvc[0][1] );
386                         denom++;
387                     }
388                     for( i = 0; i < i_mvc-1; i++ )
389                         mvd += abs( mvc[i][0] - mvc[i+1][0] )
390                              + abs( mvc[i][1] - mvc[i+1][1] );
391                 }
392
393                 sad_ctx = SAD_THRESH(1000) ? 0
394                         : SAD_THRESH(2000) ? 1
395                         : SAD_THRESH(4000) ? 2 : 3;
396                 mvd_ctx = mvd < 10*denom ? 0
397                         : mvd < 20*denom ? 1
398                         : mvd < 40*denom ? 2 : 3;
399
400                 i_me_range = i_me_range * range_mul[mvd_ctx][sad_ctx] / 4;
401             }
402
403             /* FIXME if the above DIA2/OCT2/CROSS found a new mv, it has not updated omx/omy.
404              * we are still centered on the same place as the DIA2. is this desirable? */
405             CROSS( cross_start, i_me_range, i_me_range/2 );
406
407             COST_MV_X4( -2,-2, -2,2, 2,-2, 2,2 );
408
409             /* hexagon grid */
410             omx = bmx; omy = bmy;
411             for( i = 1; i <= i_me_range/4; i++ )
412             {
413                 static const int hex4[16][2] = {
414                     {-4, 2}, {-4, 1}, {-4, 0}, {-4,-1}, {-4,-2},
415                     { 4,-2}, { 4,-1}, { 4, 0}, { 4, 1}, { 4, 2},
416                     { 2, 3}, { 0, 4}, {-2, 3},
417                     {-2,-3}, { 0,-4}, { 2,-3},
418                 };
419
420                 if( 4*i > X264_MIN4( mv_x_max-omx, omx-mv_x_min,
421                                      mv_y_max-omy, omy-mv_y_min ) )
422                 {
423                     for( j = 0; j < 16; j++ )
424                     {
425                         int mx = omx + hex4[j][0]*i;
426                         int my = omy + hex4[j][1]*i;
427                         if( CHECK_MVRANGE(mx, my) )
428                             COST_MV( mx, my );
429                     }
430                 }
431                 else
432                 {
433                     COST_MV_X4( -4*i, 2*i, -4*i, 1*i, -4*i, 0*i, -4*i,-1*i );
434                     COST_MV_X4( -4*i,-2*i,  4*i,-2*i,  4*i,-1*i,  4*i, 0*i );
435                     COST_MV_X4(  4*i, 1*i,  4*i, 2*i,  2*i, 3*i,  0*i, 4*i );
436                     COST_MV_X4( -2*i, 3*i, -2*i,-3*i,  0*i,-4*i,  2*i,-3*i );
437                 }
438             }
439             if( bmy <= mv_y_max )
440                 goto me_hex2;
441             break;
442         }
443
444     case X264_ME_ESA:
445     case X264_ME_TESA:
446         {
447             const int min_x = X264_MAX( bmx - i_me_range, mv_x_min );
448             const int min_y = X264_MAX( bmy - i_me_range, mv_y_min );
449             const int max_x = X264_MIN( bmx + i_me_range, mv_x_max );
450             const int max_y = X264_MIN( bmy + i_me_range, mv_y_max );
451             /* SEA is fastest in multiples of 4 */
452             const int width = (max_x - min_x + 3) & ~3;
453             int my;
454 #if 0
455             /* plain old exhaustive search */
456             int mx;
457             for( my = min_y; my <= max_y; my++ )
458                 for( mx = min_x; mx <= max_x; mx++ )
459                     COST_MV( mx, my );
460 #else
461             /* successive elimination by comparing DC before a full SAD,
462              * because sum(abs(diff)) >= abs(diff(sum)). */
463             const int stride = m->i_stride[0];
464             uint16_t *sums_base = m->integral;
465             DECLARE_ALIGNED_16( static uint8_t zero[16*16] );
466             DECLARE_ALIGNED_16( int enc_dc[4] );
467             int sad_size = i_pixel <= PIXEL_8x8 ? PIXEL_8x8 : PIXEL_4x4;
468             int delta = x264_pixel_size[sad_size].w;
469             int16_t xs_buf[64];
470             int16_t *xs = width<=64 ? xs_buf : x264_malloc( (width+15)*sizeof(int16_t) );
471             int xn;
472             uint16_t *cost_fpel_mvx = x264_cost_mv_fpel[h->mb.i_qp][-m->mvp[0]&3] + (-m->mvp[0]>>2);
473
474             h->pixf.sad_x4[sad_size]( zero, m->p_fenc[0], m->p_fenc[0]+delta,
475                 m->p_fenc[0]+delta*FENC_STRIDE, m->p_fenc[0]+delta+delta*FENC_STRIDE,
476                 FENC_STRIDE, enc_dc );
477             if( delta == 4 )
478                 sums_base += stride * (h->fenc->i_lines[0] + PADV*2);
479             if( i_pixel == PIXEL_16x16 || i_pixel == PIXEL_8x16 || i_pixel == PIXEL_4x8 )
480                 delta *= stride;
481             if( i_pixel == PIXEL_8x16 || i_pixel == PIXEL_4x8 )
482                 enc_dc[1] = enc_dc[2];
483
484             if( h->mb.i_me_method == X264_ME_TESA )
485             {
486                 // ADS threshold, then SAD threshold, then keep the best few SADs, then SATD
487                 typedef struct {
488                     int sad;
489                     int16_t mx, my;
490                 } mvsad_t;
491                 mvsad_t *mvsads = x264_malloc( width*(max_y-min_y+1)*sizeof(mvsad_t) );
492                 int nmvsad = 0, limit;
493                 int sad_thresh = i_me_range <= 16 ? 10 : i_me_range <= 24 ? 11 : 12;
494                 int bsad = h->pixf.sad[i_pixel]( m->p_fenc[0], FENC_STRIDE, p_fref+bmy*stride+bmx, stride )
495                          + BITS_MVD( bmx, bmy );
496                 for( my = min_y; my <= max_y; my++ )
497                 {
498                     int ycost = p_cost_mvy[my<<2];
499                     bsad -= ycost;
500                     xn = h->pixf.ads[i_pixel]( enc_dc, sums_base + min_x + my * stride, delta,
501                                                cost_fpel_mvx+min_x, xs, width, X264_MAX(bsad,0)*17/16 );
502                     for( i=0; i<xn-2; i+=3 )
503                     {
504                         uint8_t *ref = p_fref+min_x+my*stride;
505                         int sads[3];
506                         h->pixf.sad_x3[i_pixel]( m->p_fenc[0], ref+xs[i], ref+xs[i+1], ref+xs[i+2], stride, sads );
507                         for( j=0; j<3; j++ )
508                         {
509                             int sad = sads[j] + cost_fpel_mvx[xs[i+j]];
510                             if( sad < bsad*sad_thresh>>3 )
511                             {
512                                 COPY1_IF_LT( bsad, sad );
513                                 mvsads[nmvsad].sad = sad + ycost;
514                                 mvsads[nmvsad].mx = min_x+xs[i+j];
515                                 mvsads[nmvsad].my = my;
516                                 nmvsad++;
517                             }
518                         }
519                     }
520                     for( ; i<xn; i++ )
521                     {
522                         int mx = min_x+xs[i];
523                         int sad = h->pixf.sad[i_pixel]( m->p_fenc[0], FENC_STRIDE, p_fref+mx+my*stride, stride )
524                                 + cost_fpel_mvx[xs[i]];
525                         if( sad < bsad*sad_thresh>>3 )
526                         {
527                             COPY1_IF_LT( bsad, sad );
528                             mvsads[nmvsad].sad = sad + ycost;
529                             mvsads[nmvsad].mx = mx;
530                             mvsads[nmvsad].my = my;
531                             nmvsad++;
532                         }
533                     }
534                     bsad += ycost;
535                 }
536
537                 limit = i_me_range / 2;
538                 if( nmvsad > limit*2 )
539                 {
540                     // halve the range if the domain is too large... eh, close enough
541                     bsad = bsad*(sad_thresh+8)>>4;
542                     for( i=0; i<nmvsad && mvsads[i].sad <= bsad; i++ );
543                     for( j=i; j<nmvsad; j++ )
544                         if( mvsads[j].sad <= bsad )
545                             mvsads[i++] = mvsads[j];
546                     nmvsad = i;
547                 }
548                 if( nmvsad > limit )
549                 {
550                     for( i=0; i<limit; i++ )
551                     {
552                         int bj = i;
553                         int bsad = mvsads[bj].sad;
554                         for( j=i+1; j<nmvsad; j++ )
555                             COPY2_IF_LT( bsad, mvsads[j].sad, bj, j );
556                         if( bj > i )
557                             XCHG( mvsad_t, mvsads[i], mvsads[bj] );
558                     }
559                     nmvsad = limit;
560                 }
561                 for( i=0; i<nmvsad; i++ )
562                     COST_MV( mvsads[i].mx, mvsads[i].my );
563                 x264_free( mvsads );
564             }
565             else
566             {
567                 // just ADS and SAD
568                 for( my = min_y; my <= max_y; my++ )
569                 {
570                     bcost -= p_cost_mvy[my<<2];
571                     xn = h->pixf.ads[i_pixel]( enc_dc, sums_base + min_x + my * stride, delta,
572                                                cost_fpel_mvx+min_x, xs, width, X264_MAX(bcost,0) );
573                     for( i=0; i<xn-2; i+=3 )
574                         COST_MV_X3_ABS( min_x+xs[i],my, min_x+xs[i+1],my, min_x+xs[i+2],my );
575                     bcost += p_cost_mvy[my<<2];
576                     for( ; i<xn; i++ )
577                         COST_MV( min_x+xs[i], my );
578                 }
579             }
580
581             if( xs != xs_buf )
582                 x264_free( xs );
583 #endif
584         }
585         break;
586     }
587
588     /* -> qpel mv */
589     if( bpred_cost < bcost )
590     {
591         m->mv[0] = bpred_mx;
592         m->mv[1] = bpred_my;
593         m->cost = bpred_cost;
594     }
595     else
596     {
597         m->mv[0] = bmx << 2;
598         m->mv[1] = bmy << 2;
599         m->cost = bcost;
600     }
601
602     /* compute the real cost */
603     m->cost_mv = p_cost_mvx[ m->mv[0] ] + p_cost_mvy[ m->mv[1] ];
604     if( bmx == pmx && bmy == pmy && h->mb.i_subpel_refine < 3 )
605         m->cost += m->cost_mv;
606
607     /* subpel refine */
608     if( h->mb.i_subpel_refine >= 2 )
609     {
610         int hpel = subpel_iterations[h->mb.i_subpel_refine][2];
611         int qpel = subpel_iterations[h->mb.i_subpel_refine][3];
612         refine_subpel( h, m, hpel, qpel, p_halfpel_thresh, 0 );
613     }
614     else if( m->mv[1] > h->mb.mv_max_spel[1] )
615         m->mv[1] = h->mb.mv_max_spel[1];
616 }
617 #undef COST_MV
618
619 void x264_me_refine_qpel( x264_t *h, x264_me_t *m )
620 {
621     int hpel = subpel_iterations[h->mb.i_subpel_refine][0];
622     int qpel = subpel_iterations[h->mb.i_subpel_refine][1];
623
624     if( m->i_pixel <= PIXEL_8x8 && h->sh.i_type == SLICE_TYPE_P )
625         m->cost -= m->i_ref_cost;
626         
627     refine_subpel( h, m, hpel, qpel, NULL, 1 );
628 }
629
630 #define COST_MV_SAD( mx, my ) \
631 { \
632     int stride = 16; \
633     uint8_t *src = h->mc.get_ref( pix[0], &stride, m->p_fref, m->i_stride[0], mx, my, bw, bh ); \
634     int cost = h->pixf.fpelcmp[i_pixel]( m->p_fenc[0], FENC_STRIDE, src, stride ) \
635              + p_cost_mvx[ mx ] + p_cost_mvy[ my ]; \
636     COPY3_IF_LT( bcost, cost, bmx, mx, bmy, my ); \
637 }
638
639 #define COST_MV_SATD( mx, my, dir ) \
640 if( b_refine_qpel || (dir^1) != odir ) \
641 { \
642     int stride = 16; \
643     uint8_t *src = h->mc.get_ref( pix[0], &stride, m->p_fref, m->i_stride[0], mx, my, bw, bh ); \
644     int cost = h->pixf.mbcmp[i_pixel]( m->p_fenc[0], FENC_STRIDE, src, stride ) \
645              + p_cost_mvx[ mx ] + p_cost_mvy[ my ]; \
646     if( b_chroma_me && cost < bcost ) \
647     { \
648         h->mc.mc_chroma( pix[0], 8, m->p_fref[4], m->i_stride[1], mx, my, bw/2, bh/2 ); \
649         cost += h->pixf.mbcmp[i_pixel+3]( m->p_fenc[1], FENC_STRIDE, pix[0], 8 ); \
650         if( cost < bcost ) \
651         { \
652             h->mc.mc_chroma( pix[0], 8, m->p_fref[5], m->i_stride[1], mx, my, bw/2, bh/2 ); \
653             cost += h->pixf.mbcmp[i_pixel+3]( m->p_fenc[2], FENC_STRIDE, pix[0], 8 ); \
654         } \
655     } \
656     if( cost < bcost ) \
657     {                  \
658         bcost = cost;  \
659         bmx = mx;      \
660         bmy = my;      \
661         bdir = dir;    \
662     } \
663 }
664
665 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 )
666 {
667     const int bw = x264_pixel_size[m->i_pixel].w;
668     const int bh = x264_pixel_size[m->i_pixel].h;
669     const int16_t *p_cost_mvx = m->p_cost_mv - m->mvp[0];
670     const int16_t *p_cost_mvy = m->p_cost_mv - m->mvp[1];
671     const int i_pixel = m->i_pixel;
672     const int b_chroma_me = h->mb.b_chroma_me && i_pixel <= PIXEL_8x8;
673
674     DECLARE_ALIGNED_16( uint8_t pix[2][32*18] ); // really 17x17, but round up for alignment
675     int omx, omy;
676     int i;
677
678     int bmx = m->mv[0];
679     int bmy = m->mv[1];
680     int bcost = m->cost;
681     int odir = -1, bdir;
682
683
684     /* try the subpel component of the predicted mv */
685     if( hpel_iters && h->mb.i_subpel_refine < 3 )
686     {
687         int mx = x264_clip3( m->mvp[0], h->mb.mv_min_spel[0], h->mb.mv_max_spel[0] );
688         int my = x264_clip3( m->mvp[1], h->mb.mv_min_spel[1], h->mb.mv_max_spel[1] );
689         if( mx != bmx || my != bmy )
690             COST_MV_SAD( mx, my );
691     }
692
693     /* halfpel diamond search */
694     for( i = hpel_iters; i > 0; i-- )
695     {
696         int omx = bmx, omy = bmy;
697         int costs[4];
698         int stride = 32; // candidates are either all hpel or all qpel, so one stride is enough
699         uint8_t *src0, *src1, *src2, *src3;
700         src0 = h->mc.get_ref( pix[0], &stride, m->p_fref, m->i_stride[0], omx, omy-2, bw, bh+1 );
701         src2 = h->mc.get_ref( pix[1], &stride, m->p_fref, m->i_stride[0], omx-2, omy, bw+4, bh );
702         src1 = src0 + stride;
703         src3 = src2 + 1;
704         h->pixf.fpelcmp_x4[i_pixel]( m->p_fenc[0], src0, src1, src2, src3, stride, costs );
705         COPY2_IF_LT( bcost, costs[0] + p_cost_mvx[omx  ] + p_cost_mvy[omy-2], bmy, omy-2 );
706         COPY2_IF_LT( bcost, costs[1] + p_cost_mvx[omx  ] + p_cost_mvy[omy+2], bmy, omy+2 );
707         COPY3_IF_LT( bcost, costs[2] + p_cost_mvx[omx-2] + p_cost_mvy[omy  ], bmx, omx-2, bmy, omy );
708         COPY3_IF_LT( bcost, costs[3] + p_cost_mvx[omx+2] + p_cost_mvy[omy  ], bmx, omx+2, bmy, omy );
709         if( bmx == omx && bmy == omy )
710             break;
711     }
712
713     if( !b_refine_qpel )
714     {
715         /* check for mvrange */
716         if( bmy > h->mb.mv_max_spel[1] )
717             bmy = h->mb.mv_max_spel[1];
718         bcost = COST_MAX;
719         COST_MV_SATD( bmx, bmy, -1 );
720     }
721
722     /* early termination when examining multiple reference frames */
723     if( p_halfpel_thresh )
724     {
725         if( (bcost*7)>>3 > *p_halfpel_thresh )
726         {
727             m->cost = bcost;
728             m->mv[0] = bmx;
729             m->mv[1] = bmy;
730             // don't need cost_mv
731             return;
732         }
733         else if( bcost < *p_halfpel_thresh )
734             *p_halfpel_thresh = bcost;
735     }
736
737     /* quarterpel diamond search */
738     bdir = -1;
739     for( i = qpel_iters; i > 0; i-- )
740     {
741         odir = bdir;
742         omx = bmx;
743         omy = bmy;
744         COST_MV_SATD( omx, omy - 1, 0 );
745         COST_MV_SATD( omx, omy + 1, 1 );
746         COST_MV_SATD( omx - 1, omy, 2 );
747         COST_MV_SATD( omx + 1, omy, 3 );
748         if( bmx == omx && bmy == omy )
749             break;
750     }
751
752     /* check for mvrange */
753     if( bmy > h->mb.mv_max_spel[1] )
754     {
755         bmy = h->mb.mv_max_spel[1];
756         bcost = COST_MAX;
757         COST_MV_SATD( bmx, bmy, -1 );
758     }
759
760     m->cost = bcost;
761     m->mv[0] = bmx;
762     m->mv[1] = bmy;
763     m->cost_mv = p_cost_mvx[ bmx ] + p_cost_mvy[ bmy ];
764 }
765
766 #define BIME_CACHE( dx, dy ) \
767 { \
768     int i = 4 + 3*dx + dy; \
769     h->mc.mc_luma( pix0[i], bw, m0->p_fref, m0->i_stride[0], om0x+dx, om0y+dy, bw, bh ); \
770     h->mc.mc_luma( pix1[i], bw, m1->p_fref, m1->i_stride[0], om1x+dx, om1y+dy, bw, bh ); \
771 }
772
773 #define BIME_CACHE2(a,b) \
774     BIME_CACHE(a,b) \
775     BIME_CACHE(-(a),-(b))
776
777 #define COST_BIMV_SATD( m0x, m0y, m1x, m1y ) \
778 if( pass == 0 || !visited[(m0x)&7][(m0y)&7][(m1x)&7][(m1y)&7] ) \
779 { \
780     int cost; \
781     int i0 = 4 + 3*(m0x-om0x) + (m0y-om0y); \
782     int i1 = 4 + 3*(m1x-om1x) + (m1y-om1y); \
783     visited[(m0x)&7][(m0y)&7][(m1x)&7][(m1y)&7] = 1; \
784     memcpy( pix, pix0[i0], bs ); \
785     if( i_weight == 32 ) \
786         h->mc.avg[i_pixel]( pix, bw, pix1[i1], bw ); \
787     else \
788         h->mc.avg_weight[i_pixel]( pix, bw, pix1[i1], bw, i_weight ); \
789     cost = h->pixf.mbcmp[i_pixel]( m0->p_fenc[0], FENC_STRIDE, pix, bw ) \
790          + p_cost_m0x[ m0x ] + p_cost_m0y[ m0y ] \
791          + p_cost_m1x[ m1x ] + p_cost_m1y[ m1y ]; \
792     if( cost < bcost ) \
793     {                  \
794         bcost = cost;  \
795         bm0x = m0x;    \
796         bm0y = m0y;    \
797         bm1x = m1x;    \
798         bm1y = m1y;    \
799     } \
800 }
801
802 #define CHECK_BIDIR(a,b,c,d) \
803     COST_BIMV_SATD(om0x+a, om0y+b, om1x+c, om1y+d)
804
805 #define CHECK_BIDIR2(a,b,c,d) \
806     CHECK_BIDIR(a,b,c,d) \
807     CHECK_BIDIR(-(a),-(b),-(c),-(d))
808
809 #define CHECK_BIDIR8(a,b,c,d) \
810     CHECK_BIDIR2(a,b,c,d) \
811     CHECK_BIDIR2(b,c,d,a) \
812     CHECK_BIDIR2(c,d,a,b) \
813     CHECK_BIDIR2(d,a,b,c)
814
815 int x264_me_refine_bidir( x264_t *h, x264_me_t *m0, x264_me_t *m1, int i_weight )
816 {
817     const int i_pixel = m0->i_pixel;
818     const int bw = x264_pixel_size[i_pixel].w;
819     const int bh = x264_pixel_size[i_pixel].h;
820     const int bs = bw*bh;
821     const int16_t *p_cost_m0x = m0->p_cost_mv - x264_clip3( m0->mvp[0], h->mb.mv_min_spel[0], h->mb.mv_max_spel[0] );
822     const int16_t *p_cost_m0y = m0->p_cost_mv - x264_clip3( m0->mvp[1], h->mb.mv_min_spel[0], h->mb.mv_max_spel[0] );
823     const int16_t *p_cost_m1x = m1->p_cost_mv - x264_clip3( m1->mvp[0], h->mb.mv_min_spel[0], h->mb.mv_max_spel[0] );
824     const int16_t *p_cost_m1y = m1->p_cost_mv - x264_clip3( m1->mvp[1], h->mb.mv_min_spel[0], h->mb.mv_max_spel[0] );
825     DECLARE_ALIGNED_16( uint8_t pix0[9][16*16] );
826     DECLARE_ALIGNED_16( uint8_t pix1[9][16*16] );
827     DECLARE_ALIGNED_16( uint8_t pix[16*16] );
828     int bm0x = m0->mv[0], om0x = bm0x;
829     int bm0y = m0->mv[1], om0y = bm0y;
830     int bm1x = m1->mv[0], om1x = bm1x;
831     int bm1y = m1->mv[1], om1y = bm1y;
832     int bcost = COST_MAX;
833     int pass = 0;
834     uint8_t visited[8][8][8][8];
835     memset( visited, 0, sizeof(visited) );
836
837     BIME_CACHE( 0, 0 );
838     CHECK_BIDIR( 0, 0, 0, 0 );
839
840     if( bm0y > h->mb.mv_max_spel[1] - 8 ||
841         bm1y > h->mb.mv_max_spel[1] - 8 )
842         return bcost;
843
844     for( pass = 0; pass < 8; pass++ )
845     {
846         /* check all mv pairs that differ in at most 2 components from the current mvs. */
847         /* doesn't do chroma ME. this probably doesn't matter, as the gains
848          * from bidir ME are the same with and without chroma ME. */
849
850         BIME_CACHE2( 1, 0 );
851         BIME_CACHE2( 0, 1 );
852         BIME_CACHE2( 1, 1 );
853         BIME_CACHE2( 1,-1 );
854
855         CHECK_BIDIR8( 0, 0, 0, 1 );
856         CHECK_BIDIR8( 0, 0, 1, 1 );
857         CHECK_BIDIR2( 0, 1, 0, 1 );
858         CHECK_BIDIR2( 1, 0, 1, 0 );
859         CHECK_BIDIR8( 0, 0,-1, 1 );
860         CHECK_BIDIR2( 0,-1, 0, 1 );
861         CHECK_BIDIR2(-1, 0, 1, 0 );
862
863         if( om0x == bm0x && om0y == bm0y && om1x == bm1x && om1y == bm1y )
864             break;
865
866         om0x = bm0x;
867         om0y = bm0y;
868         om1x = bm1x;
869         om1y = bm1y;
870         BIME_CACHE( 0, 0 );
871     }
872
873     m0->mv[0] = bm0x;
874     m0->mv[1] = bm0y;
875     m1->mv[0] = bm1x;
876     m1->mv[1] = bm1y;
877     return bcost;
878 }
879
880 #undef COST_MV_SATD
881 #define COST_MV_SATD( mx, my, dst ) \
882 { \
883     int stride = 16; \
884     uint8_t *src = h->mc.get_ref( pix, &stride, m->p_fref, m->i_stride[0], mx, my, bw*4, bh*4 ); \
885     dst = h->pixf.mbcmp[i_pixel]( m->p_fenc[0], FENC_STRIDE, src, stride ) \
886         + p_cost_mvx[mx] + p_cost_mvy[my]; \
887     COPY1_IF_LT( bsatd, dst ); \
888 }
889
890 #define COST_MV_RD( mx, my, satd, do_dir, mdir ) \
891 { \
892     if( satd <= bsatd * SATD_THRESH )\
893     { \
894         int cost; \
895         cache_mv[0] = cache_mv2[0] = mx; \
896         cache_mv[1] = cache_mv2[1] = my; \
897         cost = x264_rd_cost_part( h, i_lambda2, i8, m->i_pixel ); \
898         COPY4_IF_LT( bcost, cost, bmx, mx, bmy, my, dir, do_dir?mdir:dir ); \
899     } \
900 }
901
902 #define SATD_THRESH 17/16
903
904 void x264_me_refine_qpel_rd( x264_t *h, x264_me_t *m, int i_lambda2, int i8 )
905 {
906     // don't have to fill the whole mv cache rectangle
907     static const int pixel_mv_offs[] = { 0, 4, 4*8, 0 };
908     int16_t *cache_mv = h->mb.cache.mv[0][x264_scan8[i8*4]];
909     int16_t *cache_mv2 = cache_mv + pixel_mv_offs[m->i_pixel];
910     const int16_t *p_cost_mvx, *p_cost_mvy;
911     const int bw = x264_pixel_size[m->i_pixel].w>>2;
912     const int bh = x264_pixel_size[m->i_pixel].h>>2;
913     const int i_pixel = m->i_pixel;
914
915     DECLARE_ALIGNED_16( uint8_t pix[16*16] );
916     int bcost = m->i_pixel == PIXEL_16x16 ? m->cost : COST_MAX;
917     int bmx = m->mv[0];
918     int bmy = m->mv[1];
919     int omx = bmx;
920     int omy = bmy;
921     int pmx, pmy, i, j;
922     unsigned bsatd;
923     int satd = 0;
924     int dir = -2;
925     int satds[8];
926
927     if( m->i_pixel != PIXEL_16x16 && i8 != 0 )
928         x264_mb_predict_mv( h, 0, i8*4, bw, m->mvp );
929     pmx = m->mvp[0];
930     pmy = m->mvp[1];
931     p_cost_mvx = m->p_cost_mv - pmx;
932     p_cost_mvy = m->p_cost_mv - pmy;
933     COST_MV_SATD( bmx, bmy, bsatd );
934     COST_MV_RD( bmx, bmy, 0, 0, 0);
935
936     /* check the predicted mv */
937     if( (bmx != pmx || bmy != pmy)
938         && pmx >= h->mb.mv_min_spel[0] && pmx <= h->mb.mv_max_spel[0]
939         && pmy >= h->mb.mv_min_spel[1] && pmy <= h->mb.mv_max_spel[1] )
940     {
941         COST_MV_SATD( pmx, pmy, satd );
942         COST_MV_RD( pmx, pmy, satd, 0,0 );
943     }
944
945     /* subpel hex search, same pattern as ME HEX. */
946     dir = -2;
947     omx = bmx;
948     omy = bmy;
949     for( j=0; j<6; j++ ) COST_MV_SATD( omx + hex2[j+1][0], omy + hex2[j+1][1], satds[j] );
950     for( j=0; j<6; j++ ) COST_MV_RD  ( omx + hex2[j+1][0], omy + hex2[j+1][1], satds[j], 1,j );
951     if( dir != -2 )
952     {
953         /* half hexagon, not overlapping the previous iteration */
954         for( i = 1; i < 10; i++ )
955         {
956             const int odir = mod6m1[dir+1];
957             if( bmy > h->mb.mv_max_spel[1] - 2 ||
958                 bmy < h->mb.mv_min_spel[1] - 2 )
959                 break;
960             dir = -2;
961             omx = bmx;
962             omy = bmy;
963             for( j=0; j<3; j++ ) COST_MV_SATD( omx + hex2[odir+j][0], omy + hex2[odir+j][1], satds[j] );
964             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 );
965             if( dir == -2 )
966                 break;
967         }
968     }
969
970     /* square refine, same as pattern as ME HEX. */
971     omx = bmx;
972     omy = bmy;
973     for( i=0; i<8; i++ ) COST_MV_SATD( omx + square1[i][0], omy  + square1[i][1], satds[i] );
974     for( i=0; i<8; i++ ) COST_MV_RD  ( omx + square1[i][0], omy  + square1[i][1], satds[i], 0,0 );
975
976     bmy = x264_clip3( bmy, h->mb.mv_min_spel[1],  h->mb.mv_max_spel[1] );
977     m->cost = bcost;
978     m->mv[0] = bmx;
979     m->mv[1] = bmy;
980     x264_macroblock_cache_mv ( h, 2*(i8&1), i8&2, bw, bh, 0, bmx, bmy );
981     x264_macroblock_cache_mvd( h, 2*(i8&1), i8&2, bw, bh, 0, bmx - pmx, bmy - pmy );
982 }
983