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