]> git.sesse.net Git - ffmpeg/blob - libavcodec/motion_est.c
dsputil: Drop unused functions copy_block{2|4|16}
[ffmpeg] / libavcodec / motion_est.c
1 /*
2  * Motion estimation
3  * Copyright (c) 2000,2001 Fabrice Bellard
4  * Copyright (c) 2002-2004 Michael Niedermayer
5  *
6  * new motion estimation (X1/EPZS) by Michael Niedermayer <michaelni@gmx.at>
7  *
8  * This file is part of Libav.
9  *
10  * Libav is free software; you can redistribute it and/or
11  * modify it under the terms of the GNU Lesser General Public
12  * License as published by the Free Software Foundation; either
13  * version 2.1 of the License, or (at your option) any later version.
14  *
15  * Libav 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 GNU
18  * Lesser General Public License for more details.
19  *
20  * You should have received a copy of the GNU Lesser General Public
21  * License along with Libav; if not, write to the Free Software
22  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
23  */
24
25 /**
26  * @file
27  * Motion estimation.
28  */
29
30 #include <stdlib.h>
31 #include <stdio.h>
32 #include <limits.h>
33
34 #include "avcodec.h"
35 #include "dsputil.h"
36 #include "mathops.h"
37 #include "mpegvideo.h"
38
39 #undef NDEBUG
40 #include <assert.h>
41
42 #define P_LEFT P[1]
43 #define P_TOP P[2]
44 #define P_TOPRIGHT P[3]
45 #define P_MEDIAN P[4]
46 #define P_MV1 P[9]
47
48 static int sad_hpel_motion_search(MpegEncContext * s,
49                                   int *mx_ptr, int *my_ptr, int dmin,
50                                   int src_index, int ref_index,
51                                   int size, int h);
52
53 static inline unsigned update_map_generation(MotionEstContext *c)
54 {
55     c->map_generation+= 1<<(ME_MAP_MV_BITS*2);
56     if(c->map_generation==0){
57         c->map_generation= 1<<(ME_MAP_MV_BITS*2);
58         memset(c->map, 0, sizeof(uint32_t)*ME_MAP_SIZE);
59     }
60     return c->map_generation;
61 }
62
63 /* shape adaptive search stuff */
64 typedef struct Minima{
65     int height;
66     int x, y;
67     int checked;
68 }Minima;
69
70 static int minima_cmp(const void *a, const void *b){
71     const Minima *da = (const Minima *) a;
72     const Minima *db = (const Minima *) b;
73
74     return da->height - db->height;
75 }
76
77 #define FLAG_QPEL   1 //must be 1
78 #define FLAG_CHROMA 2
79 #define FLAG_DIRECT 4
80
81 static inline void init_ref(MotionEstContext *c, uint8_t *src[3], uint8_t *ref[3], uint8_t *ref2[3], int x, int y, int ref_index){
82     const int offset[3]= {
83           y*c->  stride + x,
84         ((y*c->uvstride + x)>>1),
85         ((y*c->uvstride + x)>>1),
86     };
87     int i;
88     for(i=0; i<3; i++){
89         c->src[0][i]= src [i] + offset[i];
90         c->ref[0][i]= ref [i] + offset[i];
91     }
92     if(ref_index){
93         for(i=0; i<3; i++){
94             c->ref[ref_index][i]= ref2[i] + offset[i];
95         }
96     }
97 }
98
99 static int get_flags(MotionEstContext *c, int direct, int chroma){
100     return   ((c->avctx->flags&CODEC_FLAG_QPEL) ? FLAG_QPEL : 0)
101            + (direct ? FLAG_DIRECT : 0)
102            + (chroma ? FLAG_CHROMA : 0);
103 }
104
105 static av_always_inline int cmp_direct_inline(MpegEncContext *s, const int x, const int y, const int subx, const int suby,
106                       const int size, const int h, int ref_index, int src_index,
107                       me_cmp_func cmp_func, me_cmp_func chroma_cmp_func, int qpel){
108     MotionEstContext * const c= &s->me;
109     const int stride= c->stride;
110     const int hx= subx + (x<<(1+qpel));
111     const int hy= suby + (y<<(1+qpel));
112     uint8_t * const * const ref= c->ref[ref_index];
113     uint8_t * const * const src= c->src[src_index];
114     int d;
115     //FIXME check chroma 4mv, (no crashes ...)
116         assert(x >= c->xmin && hx <= c->xmax<<(qpel+1) && y >= c->ymin && hy <= c->ymax<<(qpel+1));
117         if(x >= c->xmin && hx <= c->xmax<<(qpel+1) && y >= c->ymin && hy <= c->ymax<<(qpel+1)){
118             const int time_pp= s->pp_time;
119             const int time_pb= s->pb_time;
120             const int mask= 2*qpel+1;
121             if(s->mv_type==MV_TYPE_8X8){
122                 int i;
123                 for(i=0; i<4; i++){
124                     int fx = c->direct_basis_mv[i][0] + hx;
125                     int fy = c->direct_basis_mv[i][1] + hy;
126                     int bx = hx ? fx - c->co_located_mv[i][0] : c->co_located_mv[i][0]*(time_pb - time_pp)/time_pp + ((i &1)<<(qpel+4));
127                     int by = hy ? fy - c->co_located_mv[i][1] : c->co_located_mv[i][1]*(time_pb - time_pp)/time_pp + ((i>>1)<<(qpel+4));
128                     int fxy= (fx&mask) + ((fy&mask)<<(qpel+1));
129                     int bxy= (bx&mask) + ((by&mask)<<(qpel+1));
130
131                     uint8_t *dst= c->temp + 8*(i&1) + 8*stride*(i>>1);
132                     if(qpel){
133                         c->qpel_put[1][fxy](dst, ref[0] + (fx>>2) + (fy>>2)*stride, stride);
134                         c->qpel_avg[1][bxy](dst, ref[8] + (bx>>2) + (by>>2)*stride, stride);
135                     }else{
136                         c->hpel_put[1][fxy](dst, ref[0] + (fx>>1) + (fy>>1)*stride, stride, 8);
137                         c->hpel_avg[1][bxy](dst, ref[8] + (bx>>1) + (by>>1)*stride, stride, 8);
138                     }
139                 }
140             }else{
141                 int fx = c->direct_basis_mv[0][0] + hx;
142                 int fy = c->direct_basis_mv[0][1] + hy;
143                 int bx = hx ? fx - c->co_located_mv[0][0] : (c->co_located_mv[0][0]*(time_pb - time_pp)/time_pp);
144                 int by = hy ? fy - c->co_located_mv[0][1] : (c->co_located_mv[0][1]*(time_pb - time_pp)/time_pp);
145                 int fxy= (fx&mask) + ((fy&mask)<<(qpel+1));
146                 int bxy= (bx&mask) + ((by&mask)<<(qpel+1));
147
148                 if(qpel){
149                     c->qpel_put[1][fxy](c->temp               , ref[0] + (fx>>2) + (fy>>2)*stride               , stride);
150                     c->qpel_put[1][fxy](c->temp + 8           , ref[0] + (fx>>2) + (fy>>2)*stride + 8           , stride);
151                     c->qpel_put[1][fxy](c->temp     + 8*stride, ref[0] + (fx>>2) + (fy>>2)*stride     + 8*stride, stride);
152                     c->qpel_put[1][fxy](c->temp + 8 + 8*stride, ref[0] + (fx>>2) + (fy>>2)*stride + 8 + 8*stride, stride);
153                     c->qpel_avg[1][bxy](c->temp               , ref[8] + (bx>>2) + (by>>2)*stride               , stride);
154                     c->qpel_avg[1][bxy](c->temp + 8           , ref[8] + (bx>>2) + (by>>2)*stride + 8           , stride);
155                     c->qpel_avg[1][bxy](c->temp     + 8*stride, ref[8] + (bx>>2) + (by>>2)*stride     + 8*stride, stride);
156                     c->qpel_avg[1][bxy](c->temp + 8 + 8*stride, ref[8] + (bx>>2) + (by>>2)*stride + 8 + 8*stride, stride);
157                 }else{
158                     assert((fx>>1) + 16*s->mb_x >= -16);
159                     assert((fy>>1) + 16*s->mb_y >= -16);
160                     assert((fx>>1) + 16*s->mb_x <= s->width);
161                     assert((fy>>1) + 16*s->mb_y <= s->height);
162                     assert((bx>>1) + 16*s->mb_x >= -16);
163                     assert((by>>1) + 16*s->mb_y >= -16);
164                     assert((bx>>1) + 16*s->mb_x <= s->width);
165                     assert((by>>1) + 16*s->mb_y <= s->height);
166
167                     c->hpel_put[0][fxy](c->temp, ref[0] + (fx>>1) + (fy>>1)*stride, stride, 16);
168                     c->hpel_avg[0][bxy](c->temp, ref[8] + (bx>>1) + (by>>1)*stride, stride, 16);
169                 }
170             }
171             d = cmp_func(s, c->temp, src[0], stride, 16);
172         }else
173             d= 256*256*256*32;
174     return d;
175 }
176
177 static av_always_inline int cmp_inline(MpegEncContext *s, const int x, const int y, const int subx, const int suby,
178                       const int size, const int h, int ref_index, int src_index,
179                       me_cmp_func cmp_func, me_cmp_func chroma_cmp_func, int qpel, int chroma){
180     MotionEstContext * const c= &s->me;
181     const int stride= c->stride;
182     const int uvstride= c->uvstride;
183     const int dxy= subx + (suby<<(1+qpel)); //FIXME log2_subpel?
184     const int hx= subx + (x<<(1+qpel));
185     const int hy= suby + (y<<(1+qpel));
186     uint8_t * const * const ref= c->ref[ref_index];
187     uint8_t * const * const src= c->src[src_index];
188     int d;
189     //FIXME check chroma 4mv, (no crashes ...)
190         int uvdxy;              /* no, it might not be used uninitialized */
191         if(dxy){
192             if(qpel){
193                 c->qpel_put[size][dxy](c->temp, ref[0] + x + y*stride, stride); //FIXME prototype (add h)
194                 if(chroma){
195                     int cx= hx/2;
196                     int cy= hy/2;
197                     cx= (cx>>1)|(cx&1);
198                     cy= (cy>>1)|(cy&1);
199                     uvdxy= (cx&1) + 2*(cy&1);
200                     //FIXME x/y wrong, but mpeg4 qpel is sick anyway, we should drop as much of it as possible in favor for h264
201                 }
202             }else{
203                 c->hpel_put[size][dxy](c->temp, ref[0] + x + y*stride, stride, h);
204                 if(chroma)
205                     uvdxy= dxy | (x&1) | (2*(y&1));
206             }
207             d = cmp_func(s, c->temp, src[0], stride, h);
208         }else{
209             d = cmp_func(s, src[0], ref[0] + x + y*stride, stride, h);
210             if(chroma)
211                 uvdxy= (x&1) + 2*(y&1);
212         }
213         if(chroma){
214             uint8_t * const uvtemp= c->temp + 16*stride;
215             c->hpel_put[size+1][uvdxy](uvtemp  , ref[1] + (x>>1) + (y>>1)*uvstride, uvstride, h>>1);
216             c->hpel_put[size+1][uvdxy](uvtemp+8, ref[2] + (x>>1) + (y>>1)*uvstride, uvstride, h>>1);
217             d += chroma_cmp_func(s, uvtemp  , src[1], uvstride, h>>1);
218             d += chroma_cmp_func(s, uvtemp+8, src[2], uvstride, h>>1);
219         }
220     return d;
221 }
222
223 static int cmp_simple(MpegEncContext *s, const int x, const int y,
224                       int ref_index, int src_index,
225                       me_cmp_func cmp_func, me_cmp_func chroma_cmp_func){
226     return cmp_inline(s,x,y,0,0,0,16,ref_index,src_index, cmp_func, chroma_cmp_func, 0, 0);
227 }
228
229 static int cmp_fpel_internal(MpegEncContext *s, const int x, const int y,
230                       const int size, const int h, int ref_index, int src_index,
231                       me_cmp_func cmp_func, me_cmp_func chroma_cmp_func, const int flags){
232     if(flags&FLAG_DIRECT){
233         return cmp_direct_inline(s,x,y,0,0,size,h,ref_index,src_index, cmp_func, chroma_cmp_func, flags&FLAG_QPEL);
234     }else{
235         return cmp_inline(s,x,y,0,0,size,h,ref_index,src_index, cmp_func, chroma_cmp_func, 0, flags&FLAG_CHROMA);
236     }
237 }
238
239 static int cmp_internal(MpegEncContext *s, const int x, const int y, const int subx, const int suby,
240                       const int size, const int h, int ref_index, int src_index,
241                       me_cmp_func cmp_func, me_cmp_func chroma_cmp_func, const int flags){
242     if(flags&FLAG_DIRECT){
243         return cmp_direct_inline(s,x,y,subx,suby,size,h,ref_index,src_index, cmp_func, chroma_cmp_func, flags&FLAG_QPEL);
244     }else{
245         return cmp_inline(s,x,y,subx,suby,size,h,ref_index,src_index, cmp_func, chroma_cmp_func, flags&FLAG_QPEL, flags&FLAG_CHROMA);
246     }
247 }
248
249 /** @brief compares a block (either a full macroblock or a partition thereof)
250     against a proposed motion-compensated prediction of that block
251  */
252 static av_always_inline int cmp(MpegEncContext *s, const int x, const int y, const int subx, const int suby,
253                       const int size, const int h, int ref_index, int src_index,
254                       me_cmp_func cmp_func, me_cmp_func chroma_cmp_func, const int flags){
255     if(av_builtin_constant_p(flags) && av_builtin_constant_p(h) && av_builtin_constant_p(size)
256        && av_builtin_constant_p(subx) && av_builtin_constant_p(suby)
257        && flags==0 && h==16 && size==0 && subx==0 && suby==0){
258         return cmp_simple(s,x,y,ref_index,src_index, cmp_func, chroma_cmp_func);
259     }else if(av_builtin_constant_p(subx) && av_builtin_constant_p(suby)
260        && subx==0 && suby==0){
261         return cmp_fpel_internal(s,x,y,size,h,ref_index,src_index, cmp_func, chroma_cmp_func,flags);
262     }else{
263         return cmp_internal(s,x,y,subx,suby,size,h,ref_index,src_index, cmp_func, chroma_cmp_func, flags);
264     }
265 }
266
267 static int cmp_hpel(MpegEncContext *s, const int x, const int y, const int subx, const int suby,
268                       const int size, const int h, int ref_index, int src_index,
269                       me_cmp_func cmp_func, me_cmp_func chroma_cmp_func, const int flags){
270     if(flags&FLAG_DIRECT){
271         return cmp_direct_inline(s,x,y,subx,suby,size,h,ref_index,src_index, cmp_func, chroma_cmp_func, 0);
272     }else{
273         return cmp_inline(s,x,y,subx,suby,size,h,ref_index,src_index, cmp_func, chroma_cmp_func, 0, flags&FLAG_CHROMA);
274     }
275 }
276
277 static int cmp_qpel(MpegEncContext *s, const int x, const int y, const int subx, const int suby,
278                       const int size, const int h, int ref_index, int src_index,
279                       me_cmp_func cmp_func, me_cmp_func chroma_cmp_func, const int flags){
280     if(flags&FLAG_DIRECT){
281         return cmp_direct_inline(s,x,y,subx,suby,size,h,ref_index,src_index, cmp_func, chroma_cmp_func, 1);
282     }else{
283         return cmp_inline(s,x,y,subx,suby,size,h,ref_index,src_index, cmp_func, chroma_cmp_func, 1, flags&FLAG_CHROMA);
284     }
285 }
286
287 #include "motion_est_template.c"
288
289 static int zero_cmp(void *s, uint8_t *a, uint8_t *b, int stride, int h){
290     return 0;
291 }
292
293 static void zero_hpel(uint8_t *a, const uint8_t *b, ptrdiff_t stride, int h){
294 }
295
296 int ff_init_me(MpegEncContext *s){
297     MotionEstContext * const c= &s->me;
298     int cache_size= FFMIN(ME_MAP_SIZE>>ME_MAP_SHIFT, 1<<ME_MAP_SHIFT);
299     int dia_size= FFMAX(FFABS(s->avctx->dia_size)&255, FFABS(s->avctx->pre_dia_size)&255);
300
301     if(FFMIN(s->avctx->dia_size, s->avctx->pre_dia_size) < -ME_MAP_SIZE){
302         av_log(s->avctx, AV_LOG_ERROR, "ME_MAP size is too small for SAB diamond\n");
303         return -1;
304     }
305     if (s->me_method != ME_ZERO &&
306         s->me_method != ME_EPZS &&
307         s->me_method != ME_X1) {
308         av_log(s->avctx, AV_LOG_ERROR, "me_method is only allowed to be set to zero and epzs; for hex,umh,full and others see dia_size\n");
309         return -1;
310     }
311
312     c->avctx= s->avctx;
313
314     if(cache_size < 2*dia_size && !c->stride){
315         av_log(s->avctx, AV_LOG_INFO, "ME_MAP size may be a little small for the selected diamond size\n");
316     }
317
318     ff_set_cmp(&s->dsp, s->dsp.me_pre_cmp, c->avctx->me_pre_cmp);
319     ff_set_cmp(&s->dsp, s->dsp.me_cmp, c->avctx->me_cmp);
320     ff_set_cmp(&s->dsp, s->dsp.me_sub_cmp, c->avctx->me_sub_cmp);
321     ff_set_cmp(&s->dsp, s->dsp.mb_cmp, c->avctx->mb_cmp);
322
323     c->flags    = get_flags(c, 0, c->avctx->me_cmp    &FF_CMP_CHROMA);
324     c->sub_flags= get_flags(c, 0, c->avctx->me_sub_cmp&FF_CMP_CHROMA);
325     c->mb_flags = get_flags(c, 0, c->avctx->mb_cmp    &FF_CMP_CHROMA);
326
327 /*FIXME s->no_rounding b_type*/
328     if(s->flags&CODEC_FLAG_QPEL){
329         c->sub_motion_search= qpel_motion_search;
330         c->qpel_avg= s->dsp.avg_qpel_pixels_tab;
331         if(s->no_rounding) c->qpel_put= s->dsp.put_no_rnd_qpel_pixels_tab;
332         else               c->qpel_put= s->dsp.put_qpel_pixels_tab;
333     }else{
334         if(c->avctx->me_sub_cmp&FF_CMP_CHROMA)
335             c->sub_motion_search= hpel_motion_search;
336         else if(   c->avctx->me_sub_cmp == FF_CMP_SAD
337                 && c->avctx->    me_cmp == FF_CMP_SAD
338                 && c->avctx->    mb_cmp == FF_CMP_SAD)
339             c->sub_motion_search= sad_hpel_motion_search; // 2050 vs. 2450 cycles
340         else
341             c->sub_motion_search= hpel_motion_search;
342     }
343     c->hpel_avg= s->dsp.avg_pixels_tab;
344     if(s->no_rounding) c->hpel_put= s->dsp.put_no_rnd_pixels_tab;
345     else               c->hpel_put= s->dsp.put_pixels_tab;
346
347     if(s->linesize){
348         c->stride  = s->linesize;
349         c->uvstride= s->uvlinesize;
350     }else{
351         c->stride  = 16*s->mb_width + 32;
352         c->uvstride=  8*s->mb_width + 16;
353     }
354
355     /* 8x8 fullpel search would need a 4x4 chroma compare, which we do
356      * not have yet, and even if we had, the motion estimation code
357      * does not expect it. */
358     if((c->avctx->me_cmp&FF_CMP_CHROMA)/* && !s->dsp.me_cmp[2]*/){
359         s->dsp.me_cmp[2]= zero_cmp;
360     }
361     if((c->avctx->me_sub_cmp&FF_CMP_CHROMA) && !s->dsp.me_sub_cmp[2]){
362         s->dsp.me_sub_cmp[2]= zero_cmp;
363     }
364     c->hpel_put[2][0]= c->hpel_put[2][1]=
365     c->hpel_put[2][2]= c->hpel_put[2][3]= zero_hpel;
366
367     if(s->codec_id == AV_CODEC_ID_H261){
368         c->sub_motion_search= no_sub_motion_search;
369     }
370
371     return 0;
372 }
373
374 #define CHECK_SAD_HALF_MV(suffix, x, y) \
375 {\
376     d= s->dsp.pix_abs[size][(x?1:0)+(y?2:0)](NULL, pix, ptr+((x)>>1), stride, h);\
377     d += (mv_penalty[pen_x + x] + mv_penalty[pen_y + y])*penalty_factor;\
378     COPY3_IF_LT(dminh, d, dx, x, dy, y)\
379 }
380
381 static int sad_hpel_motion_search(MpegEncContext * s,
382                                   int *mx_ptr, int *my_ptr, int dmin,
383                                   int src_index, int ref_index,
384                                   int size, int h)
385 {
386     MotionEstContext * const c= &s->me;
387     const int penalty_factor= c->sub_penalty_factor;
388     int mx, my, dminh;
389     uint8_t *pix, *ptr;
390     int stride= c->stride;
391     const int flags= c->sub_flags;
392     LOAD_COMMON
393
394     assert(flags == 0);
395
396     if(c->skip){
397         *mx_ptr = 0;
398         *my_ptr = 0;
399         return dmin;
400     }
401
402     pix = c->src[src_index][0];
403
404     mx = *mx_ptr;
405     my = *my_ptr;
406     ptr = c->ref[ref_index][0] + (my * stride) + mx;
407
408     dminh = dmin;
409
410     if (mx > xmin && mx < xmax &&
411         my > ymin && my < ymax) {
412         int dx=0, dy=0;
413         int d, pen_x, pen_y;
414         const int index= (my<<ME_MAP_SHIFT) + mx;
415         const int t= score_map[(index-(1<<ME_MAP_SHIFT))&(ME_MAP_SIZE-1)];
416         const int l= score_map[(index- 1               )&(ME_MAP_SIZE-1)];
417         const int r= score_map[(index+ 1               )&(ME_MAP_SIZE-1)];
418         const int b= score_map[(index+(1<<ME_MAP_SHIFT))&(ME_MAP_SIZE-1)];
419         mx<<=1;
420         my<<=1;
421
422
423         pen_x= pred_x + mx;
424         pen_y= pred_y + my;
425
426         ptr-= stride;
427         if(t<=b){
428             CHECK_SAD_HALF_MV(y2 , 0, -1)
429             if(l<=r){
430                 CHECK_SAD_HALF_MV(xy2, -1, -1)
431                 if(t+r<=b+l){
432                     CHECK_SAD_HALF_MV(xy2, +1, -1)
433                     ptr+= stride;
434                 }else{
435                     ptr+= stride;
436                     CHECK_SAD_HALF_MV(xy2, -1, +1)
437                 }
438                 CHECK_SAD_HALF_MV(x2 , -1,  0)
439             }else{
440                 CHECK_SAD_HALF_MV(xy2, +1, -1)
441                 if(t+l<=b+r){
442                     CHECK_SAD_HALF_MV(xy2, -1, -1)
443                     ptr+= stride;
444                 }else{
445                     ptr+= stride;
446                     CHECK_SAD_HALF_MV(xy2, +1, +1)
447                 }
448                 CHECK_SAD_HALF_MV(x2 , +1,  0)
449             }
450         }else{
451             if(l<=r){
452                 if(t+l<=b+r){
453                     CHECK_SAD_HALF_MV(xy2, -1, -1)
454                     ptr+= stride;
455                 }else{
456                     ptr+= stride;
457                     CHECK_SAD_HALF_MV(xy2, +1, +1)
458                 }
459                 CHECK_SAD_HALF_MV(x2 , -1,  0)
460                 CHECK_SAD_HALF_MV(xy2, -1, +1)
461             }else{
462                 if(t+r<=b+l){
463                     CHECK_SAD_HALF_MV(xy2, +1, -1)
464                     ptr+= stride;
465                 }else{
466                     ptr+= stride;
467                     CHECK_SAD_HALF_MV(xy2, -1, +1)
468                 }
469                 CHECK_SAD_HALF_MV(x2 , +1,  0)
470                 CHECK_SAD_HALF_MV(xy2, +1, +1)
471             }
472             CHECK_SAD_HALF_MV(y2 ,  0, +1)
473         }
474         mx+=dx;
475         my+=dy;
476
477     }else{
478         mx<<=1;
479         my<<=1;
480     }
481
482     *mx_ptr = mx;
483     *my_ptr = my;
484     return dminh;
485 }
486
487 static inline void set_p_mv_tables(MpegEncContext * s, int mx, int my, int mv4)
488 {
489     const int xy= s->mb_x + s->mb_y*s->mb_stride;
490
491     s->p_mv_table[xy][0] = mx;
492     s->p_mv_table[xy][1] = my;
493
494     /* has already been set to the 4 MV if 4MV is done */
495     if(mv4){
496         int mot_xy= s->block_index[0];
497
498         s->current_picture.f.motion_val[0][mot_xy    ][0] = mx;
499         s->current_picture.f.motion_val[0][mot_xy    ][1] = my;
500         s->current_picture.f.motion_val[0][mot_xy + 1][0] = mx;
501         s->current_picture.f.motion_val[0][mot_xy + 1][1] = my;
502
503         mot_xy += s->b8_stride;
504         s->current_picture.f.motion_val[0][mot_xy    ][0] = mx;
505         s->current_picture.f.motion_val[0][mot_xy    ][1] = my;
506         s->current_picture.f.motion_val[0][mot_xy + 1][0] = mx;
507         s->current_picture.f.motion_val[0][mot_xy + 1][1] = my;
508     }
509 }
510
511 /**
512  * get fullpel ME search limits.
513  */
514 static inline void get_limits(MpegEncContext *s, int x, int y)
515 {
516     MotionEstContext * const c= &s->me;
517     int range= c->avctx->me_range >> (1 + !!(c->flags&FLAG_QPEL));
518 /*
519     if(c->avctx->me_range) c->range= c->avctx->me_range >> 1;
520     else                   c->range= 16;
521 */
522     if (s->unrestricted_mv) {
523         c->xmin = - x - 16;
524         c->ymin = - y - 16;
525         c->xmax = - x + s->mb_width *16;
526         c->ymax = - y + s->mb_height*16;
527     } else if (s->out_format == FMT_H261){
528         // Search range of H261 is different from other codec standards
529         c->xmin = (x > 15) ? - 15 : 0;
530         c->ymin = (y > 15) ? - 15 : 0;
531         c->xmax = (x < s->mb_width * 16 - 16) ? 15 : 0;
532         c->ymax = (y < s->mb_height * 16 - 16) ? 15 : 0;
533     } else {
534         c->xmin = - x;
535         c->ymin = - y;
536         c->xmax = - x + s->mb_width *16 - 16;
537         c->ymax = - y + s->mb_height*16 - 16;
538     }
539     if(range){
540         c->xmin = FFMAX(c->xmin,-range);
541         c->xmax = FFMIN(c->xmax, range);
542         c->ymin = FFMAX(c->ymin,-range);
543         c->ymax = FFMIN(c->ymax, range);
544     }
545 }
546
547 static inline void init_mv4_ref(MotionEstContext *c){
548     const int stride= c->stride;
549
550     c->ref[1][0] = c->ref[0][0] + 8;
551     c->ref[2][0] = c->ref[0][0] + 8*stride;
552     c->ref[3][0] = c->ref[2][0] + 8;
553     c->src[1][0] = c->src[0][0] + 8;
554     c->src[2][0] = c->src[0][0] + 8*stride;
555     c->src[3][0] = c->src[2][0] + 8;
556 }
557
558 static inline int h263_mv4_search(MpegEncContext *s, int mx, int my, int shift)
559 {
560     MotionEstContext * const c= &s->me;
561     const int size= 1;
562     const int h=8;
563     int block;
564     int P[10][2];
565     int dmin_sum=0, mx4_sum=0, my4_sum=0;
566     int same=1;
567     const int stride= c->stride;
568     uint8_t *mv_penalty= c->current_mv_penalty;
569
570     init_mv4_ref(c);
571
572     for(block=0; block<4; block++){
573         int mx4, my4;
574         int pred_x4, pred_y4;
575         int dmin4;
576         static const int off[4]= {2, 1, 1, -1};
577         const int mot_stride = s->b8_stride;
578         const int mot_xy = s->block_index[block];
579
580         P_LEFT[0] = s->current_picture.f.motion_val[0][mot_xy - 1][0];
581         P_LEFT[1] = s->current_picture.f.motion_val[0][mot_xy - 1][1];
582
583         if(P_LEFT[0]       > (c->xmax<<shift)) P_LEFT[0]       = (c->xmax<<shift);
584
585         /* special case for first line */
586         if (s->first_slice_line && block<2) {
587             c->pred_x= pred_x4= P_LEFT[0];
588             c->pred_y= pred_y4= P_LEFT[1];
589         } else {
590             P_TOP[0]      = s->current_picture.f.motion_val[0][mot_xy - mot_stride             ][0];
591             P_TOP[1]      = s->current_picture.f.motion_val[0][mot_xy - mot_stride             ][1];
592             P_TOPRIGHT[0] = s->current_picture.f.motion_val[0][mot_xy - mot_stride + off[block]][0];
593             P_TOPRIGHT[1] = s->current_picture.f.motion_val[0][mot_xy - mot_stride + off[block]][1];
594             if(P_TOP[1]      > (c->ymax<<shift)) P_TOP[1]     = (c->ymax<<shift);
595             if(P_TOPRIGHT[0] < (c->xmin<<shift)) P_TOPRIGHT[0]= (c->xmin<<shift);
596             if(P_TOPRIGHT[0] > (c->xmax<<shift)) P_TOPRIGHT[0]= (c->xmax<<shift);
597             if(P_TOPRIGHT[1] > (c->ymax<<shift)) P_TOPRIGHT[1]= (c->ymax<<shift);
598
599             P_MEDIAN[0]= mid_pred(P_LEFT[0], P_TOP[0], P_TOPRIGHT[0]);
600             P_MEDIAN[1]= mid_pred(P_LEFT[1], P_TOP[1], P_TOPRIGHT[1]);
601
602             c->pred_x= pred_x4 = P_MEDIAN[0];
603             c->pred_y= pred_y4 = P_MEDIAN[1];
604         }
605         P_MV1[0]= mx;
606         P_MV1[1]= my;
607
608         dmin4 = epzs_motion_search4(s, &mx4, &my4, P, block, block, s->p_mv_table, (1<<16)>>shift);
609
610         dmin4= c->sub_motion_search(s, &mx4, &my4, dmin4, block, block, size, h);
611
612         if(s->dsp.me_sub_cmp[0] != s->dsp.mb_cmp[0]){
613             int dxy;
614             const int offset= ((block&1) + (block>>1)*stride)*8;
615             uint8_t *dest_y = c->scratchpad + offset;
616             if(s->quarter_sample){
617                 uint8_t *ref= c->ref[block][0] + (mx4>>2) + (my4>>2)*stride;
618                 dxy = ((my4 & 3) << 2) | (mx4 & 3);
619
620                 if(s->no_rounding)
621                     s->dsp.put_no_rnd_qpel_pixels_tab[1][dxy](dest_y   , ref    , stride);
622                 else
623                     s->dsp.put_qpel_pixels_tab       [1][dxy](dest_y   , ref    , stride);
624             }else{
625                 uint8_t *ref= c->ref[block][0] + (mx4>>1) + (my4>>1)*stride;
626                 dxy = ((my4 & 1) << 1) | (mx4 & 1);
627
628                 if(s->no_rounding)
629                     s->dsp.put_no_rnd_pixels_tab[1][dxy](dest_y    , ref    , stride, h);
630                 else
631                     s->dsp.put_pixels_tab       [1][dxy](dest_y    , ref    , stride, h);
632             }
633             dmin_sum+= (mv_penalty[mx4-pred_x4] + mv_penalty[my4-pred_y4])*c->mb_penalty_factor;
634         }else
635             dmin_sum+= dmin4;
636
637         if(s->quarter_sample){
638             mx4_sum+= mx4/2;
639             my4_sum+= my4/2;
640         }else{
641             mx4_sum+= mx4;
642             my4_sum+= my4;
643         }
644
645         s->current_picture.f.motion_val[0][s->block_index[block]][0] = mx4;
646         s->current_picture.f.motion_val[0][s->block_index[block]][1] = my4;
647
648         if(mx4 != mx || my4 != my) same=0;
649     }
650
651     if(same)
652         return INT_MAX;
653
654     if(s->dsp.me_sub_cmp[0] != s->dsp.mb_cmp[0]){
655         dmin_sum += s->dsp.mb_cmp[0](s, s->new_picture.f.data[0] + s->mb_x*16 + s->mb_y*16*stride, c->scratchpad, stride, 16);
656     }
657
658     if(c->avctx->mb_cmp&FF_CMP_CHROMA){
659         int dxy;
660         int mx, my;
661         int offset;
662
663         mx= ff_h263_round_chroma(mx4_sum);
664         my= ff_h263_round_chroma(my4_sum);
665         dxy = ((my & 1) << 1) | (mx & 1);
666
667         offset= (s->mb_x*8 + (mx>>1)) + (s->mb_y*8 + (my>>1))*s->uvlinesize;
668
669         if(s->no_rounding){
670             s->dsp.put_no_rnd_pixels_tab[1][dxy](c->scratchpad    , s->last_picture.f.data[1] + offset, s->uvlinesize, 8);
671             s->dsp.put_no_rnd_pixels_tab[1][dxy](c->scratchpad + 8, s->last_picture.f.data[2] + offset, s->uvlinesize, 8);
672         }else{
673             s->dsp.put_pixels_tab       [1][dxy](c->scratchpad    , s->last_picture.f.data[1] + offset, s->uvlinesize, 8);
674             s->dsp.put_pixels_tab       [1][dxy](c->scratchpad + 8, s->last_picture.f.data[2] + offset, s->uvlinesize, 8);
675         }
676
677         dmin_sum += s->dsp.mb_cmp[1](s, s->new_picture.f.data[1] + s->mb_x*8 + s->mb_y*8*s->uvlinesize, c->scratchpad  , s->uvlinesize, 8);
678         dmin_sum += s->dsp.mb_cmp[1](s, s->new_picture.f.data[2] + s->mb_x*8 + s->mb_y*8*s->uvlinesize, c->scratchpad+8, s->uvlinesize, 8);
679     }
680
681     c->pred_x= mx;
682     c->pred_y= my;
683
684     switch(c->avctx->mb_cmp&0xFF){
685     /*case FF_CMP_SSE:
686         return dmin_sum+ 32*s->qscale*s->qscale;*/
687     case FF_CMP_RD:
688         return dmin_sum;
689     default:
690         return dmin_sum+ 11*c->mb_penalty_factor;
691     }
692 }
693
694 static inline void init_interlaced_ref(MpegEncContext *s, int ref_index){
695     MotionEstContext * const c= &s->me;
696
697     c->ref[1+ref_index][0] = c->ref[0+ref_index][0] + s->linesize;
698     c->src[1][0] = c->src[0][0] + s->linesize;
699     if(c->flags & FLAG_CHROMA){
700         c->ref[1+ref_index][1] = c->ref[0+ref_index][1] + s->uvlinesize;
701         c->ref[1+ref_index][2] = c->ref[0+ref_index][2] + s->uvlinesize;
702         c->src[1][1] = c->src[0][1] + s->uvlinesize;
703         c->src[1][2] = c->src[0][2] + s->uvlinesize;
704     }
705 }
706
707 static int interlaced_search(MpegEncContext *s, int ref_index,
708                              int16_t (*mv_tables[2][2])[2], uint8_t *field_select_tables[2], int mx, int my, int user_field_select)
709 {
710     MotionEstContext * const c= &s->me;
711     const int size=0;
712     const int h=8;
713     int block;
714     int P[10][2];
715     uint8_t * const mv_penalty= c->current_mv_penalty;
716     int same=1;
717     const int stride= 2*s->linesize;
718     int dmin_sum= 0;
719     const int mot_stride= s->mb_stride;
720     const int xy= s->mb_x + s->mb_y*mot_stride;
721
722     c->ymin>>=1;
723     c->ymax>>=1;
724     c->stride<<=1;
725     c->uvstride<<=1;
726     init_interlaced_ref(s, ref_index);
727
728     for(block=0; block<2; block++){
729         int field_select;
730         int best_dmin= INT_MAX;
731         int best_field= -1;
732
733         for(field_select=0; field_select<2; field_select++){
734             int dmin, mx_i, my_i;
735             int16_t (*mv_table)[2]= mv_tables[block][field_select];
736
737             if(user_field_select){
738                 assert(field_select==0 || field_select==1);
739                 assert(field_select_tables[block][xy]==0 || field_select_tables[block][xy]==1);
740                 if(field_select_tables[block][xy] != field_select)
741                     continue;
742             }
743
744             P_LEFT[0] = mv_table[xy - 1][0];
745             P_LEFT[1] = mv_table[xy - 1][1];
746             if(P_LEFT[0]       > (c->xmax<<1)) P_LEFT[0]       = (c->xmax<<1);
747
748             c->pred_x= P_LEFT[0];
749             c->pred_y= P_LEFT[1];
750
751             if(!s->first_slice_line){
752                 P_TOP[0]      = mv_table[xy - mot_stride][0];
753                 P_TOP[1]      = mv_table[xy - mot_stride][1];
754                 P_TOPRIGHT[0] = mv_table[xy - mot_stride + 1][0];
755                 P_TOPRIGHT[1] = mv_table[xy - mot_stride + 1][1];
756                 if(P_TOP[1]      > (c->ymax<<1)) P_TOP[1]     = (c->ymax<<1);
757                 if(P_TOPRIGHT[0] < (c->xmin<<1)) P_TOPRIGHT[0]= (c->xmin<<1);
758                 if(P_TOPRIGHT[0] > (c->xmax<<1)) P_TOPRIGHT[0]= (c->xmax<<1);
759                 if(P_TOPRIGHT[1] > (c->ymax<<1)) P_TOPRIGHT[1]= (c->ymax<<1);
760
761                 P_MEDIAN[0]= mid_pred(P_LEFT[0], P_TOP[0], P_TOPRIGHT[0]);
762                 P_MEDIAN[1]= mid_pred(P_LEFT[1], P_TOP[1], P_TOPRIGHT[1]);
763             }
764             P_MV1[0]= mx; //FIXME not correct if block != field_select
765             P_MV1[1]= my / 2;
766
767             dmin = epzs_motion_search2(s, &mx_i, &my_i, P, block, field_select+ref_index, mv_table, (1<<16)>>1);
768
769             dmin= c->sub_motion_search(s, &mx_i, &my_i, dmin, block, field_select+ref_index, size, h);
770
771             mv_table[xy][0]= mx_i;
772             mv_table[xy][1]= my_i;
773
774             if(s->dsp.me_sub_cmp[0] != s->dsp.mb_cmp[0]){
775                 int dxy;
776
777                 //FIXME chroma ME
778                 uint8_t *ref= c->ref[field_select+ref_index][0] + (mx_i>>1) + (my_i>>1)*stride;
779                 dxy = ((my_i & 1) << 1) | (mx_i & 1);
780
781                 if(s->no_rounding){
782                     s->dsp.put_no_rnd_pixels_tab[size][dxy](c->scratchpad, ref    , stride, h);
783                 }else{
784                     s->dsp.put_pixels_tab       [size][dxy](c->scratchpad, ref    , stride, h);
785                 }
786                 dmin= s->dsp.mb_cmp[size](s, c->src[block][0], c->scratchpad, stride, h);
787                 dmin+= (mv_penalty[mx_i-c->pred_x] + mv_penalty[my_i-c->pred_y] + 1)*c->mb_penalty_factor;
788             }else
789                 dmin+= c->mb_penalty_factor; //field_select bits
790
791             dmin += field_select != block; //slightly prefer same field
792
793             if(dmin < best_dmin){
794                 best_dmin= dmin;
795                 best_field= field_select;
796             }
797         }
798         {
799             int16_t (*mv_table)[2]= mv_tables[block][best_field];
800
801             if(mv_table[xy][0] != mx) same=0; //FIXME check if these checks work and are any good at all
802             if(mv_table[xy][1]&1) same=0;
803             if(mv_table[xy][1]*2 != my) same=0;
804             if(best_field != block) same=0;
805         }
806
807         field_select_tables[block][xy]= best_field;
808         dmin_sum += best_dmin;
809     }
810
811     c->ymin<<=1;
812     c->ymax<<=1;
813     c->stride>>=1;
814     c->uvstride>>=1;
815
816     if(same)
817         return INT_MAX;
818
819     switch(c->avctx->mb_cmp&0xFF){
820     /*case FF_CMP_SSE:
821         return dmin_sum+ 32*s->qscale*s->qscale;*/
822     case FF_CMP_RD:
823         return dmin_sum;
824     default:
825         return dmin_sum+ 11*c->mb_penalty_factor;
826     }
827 }
828
829 static void clip_input_mv(MpegEncContext * s, int16_t *mv, int interlaced){
830     int ymax= s->me.ymax>>interlaced;
831     int ymin= s->me.ymin>>interlaced;
832
833     if(mv[0] < s->me.xmin) mv[0] = s->me.xmin;
834     if(mv[0] > s->me.xmax) mv[0] = s->me.xmax;
835     if(mv[1] <       ymin) mv[1] =       ymin;
836     if(mv[1] >       ymax) mv[1] =       ymax;
837 }
838
839 static inline int check_input_motion(MpegEncContext * s, int mb_x, int mb_y, int p_type){
840     MotionEstContext * const c= &s->me;
841     Picture *p= s->current_picture_ptr;
842     int mb_xy= mb_x + mb_y*s->mb_stride;
843     int xy= 2*mb_x + 2*mb_y*s->b8_stride;
844     int mb_type= s->current_picture.f.mb_type[mb_xy];
845     int flags= c->flags;
846     int shift= (flags&FLAG_QPEL) + 1;
847     int mask= (1<<shift)-1;
848     int x, y, i;
849     int d=0;
850     me_cmp_func cmpf= s->dsp.sse[0];
851     me_cmp_func chroma_cmpf= s->dsp.sse[1];
852
853     if(p_type && USES_LIST(mb_type, 1)){
854         av_log(c->avctx, AV_LOG_ERROR, "backward motion vector in P frame\n");
855         return INT_MAX/2;
856     }
857     assert(IS_INTRA(mb_type) || USES_LIST(mb_type,0) || USES_LIST(mb_type,1));
858
859     for(i=0; i<4; i++){
860         int xy= s->block_index[i];
861         clip_input_mv(s, p->f.motion_val[0][xy], !!IS_INTERLACED(mb_type));
862         clip_input_mv(s, p->f.motion_val[1][xy], !!IS_INTERLACED(mb_type));
863     }
864
865     if(IS_INTERLACED(mb_type)){
866         int xy2= xy  + s->b8_stride;
867         s->mb_type[mb_xy]=CANDIDATE_MB_TYPE_INTRA;
868         c->stride<<=1;
869         c->uvstride<<=1;
870
871         if(!(s->flags & CODEC_FLAG_INTERLACED_ME)){
872             av_log(c->avctx, AV_LOG_ERROR, "Interlaced macroblock selected but interlaced motion estimation disabled\n");
873             return INT_MAX/2;
874         }
875
876         if(USES_LIST(mb_type, 0)){
877             int field_select0= p->f.ref_index[0][4*mb_xy  ];
878             int field_select1= p->f.ref_index[0][4*mb_xy+2];
879             assert(field_select0==0 ||field_select0==1);
880             assert(field_select1==0 ||field_select1==1);
881             init_interlaced_ref(s, 0);
882
883             if(p_type){
884                 s->p_field_select_table[0][mb_xy]= field_select0;
885                 s->p_field_select_table[1][mb_xy]= field_select1;
886                 *(uint32_t*)s->p_field_mv_table[0][field_select0][mb_xy] = *(uint32_t*)p->f.motion_val[0][xy ];
887                 *(uint32_t*)s->p_field_mv_table[1][field_select1][mb_xy] = *(uint32_t*)p->f.motion_val[0][xy2];
888                 s->mb_type[mb_xy]=CANDIDATE_MB_TYPE_INTER_I;
889             }else{
890                 s->b_field_select_table[0][0][mb_xy]= field_select0;
891                 s->b_field_select_table[0][1][mb_xy]= field_select1;
892                 *(uint32_t*)s->b_field_mv_table[0][0][field_select0][mb_xy] = *(uint32_t*)p->f.motion_val[0][xy ];
893                 *(uint32_t*)s->b_field_mv_table[0][1][field_select1][mb_xy] = *(uint32_t*)p->f.motion_val[0][xy2];
894                 s->mb_type[mb_xy]= CANDIDATE_MB_TYPE_FORWARD_I;
895             }
896
897             x = p->f.motion_val[0][xy ][0];
898             y = p->f.motion_val[0][xy ][1];
899             d = cmp(s, x>>shift, y>>shift, x&mask, y&mask, 0, 8, field_select0, 0, cmpf, chroma_cmpf, flags);
900             x = p->f.motion_val[0][xy2][0];
901             y = p->f.motion_val[0][xy2][1];
902             d+= cmp(s, x>>shift, y>>shift, x&mask, y&mask, 0, 8, field_select1, 1, cmpf, chroma_cmpf, flags);
903         }
904         if(USES_LIST(mb_type, 1)){
905             int field_select0 = p->f.ref_index[1][4 * mb_xy    ];
906             int field_select1 = p->f.ref_index[1][4 * mb_xy + 2];
907             assert(field_select0==0 ||field_select0==1);
908             assert(field_select1==0 ||field_select1==1);
909             init_interlaced_ref(s, 2);
910
911             s->b_field_select_table[1][0][mb_xy]= field_select0;
912             s->b_field_select_table[1][1][mb_xy]= field_select1;
913             *(uint32_t*)s->b_field_mv_table[1][0][field_select0][mb_xy] = *(uint32_t*)p->f.motion_val[1][xy ];
914             *(uint32_t*)s->b_field_mv_table[1][1][field_select1][mb_xy] = *(uint32_t*)p->f.motion_val[1][xy2];
915             if(USES_LIST(mb_type, 0)){
916                 s->mb_type[mb_xy]= CANDIDATE_MB_TYPE_BIDIR_I;
917             }else{
918                 s->mb_type[mb_xy]= CANDIDATE_MB_TYPE_BACKWARD_I;
919             }
920
921             x = p->f.motion_val[1][xy ][0];
922             y = p->f.motion_val[1][xy ][1];
923             d = cmp(s, x>>shift, y>>shift, x&mask, y&mask, 0, 8, field_select0+2, 0, cmpf, chroma_cmpf, flags);
924             x = p->f.motion_val[1][xy2][0];
925             y = p->f.motion_val[1][xy2][1];
926             d+= cmp(s, x>>shift, y>>shift, x&mask, y&mask, 0, 8, field_select1+2, 1, cmpf, chroma_cmpf, flags);
927             //FIXME bidir scores
928         }
929         c->stride>>=1;
930         c->uvstride>>=1;
931     }else if(IS_8X8(mb_type)){
932         if(!(s->flags & CODEC_FLAG_4MV)){
933             av_log(c->avctx, AV_LOG_ERROR, "4MV macroblock selected but 4MV encoding disabled\n");
934             return INT_MAX/2;
935         }
936         cmpf= s->dsp.sse[1];
937         chroma_cmpf= s->dsp.sse[1];
938         init_mv4_ref(c);
939         for(i=0; i<4; i++){
940             xy= s->block_index[i];
941             x= p->f.motion_val[0][xy][0];
942             y= p->f.motion_val[0][xy][1];
943             d+= cmp(s, x>>shift, y>>shift, x&mask, y&mask, 1, 8, i, i, cmpf, chroma_cmpf, flags);
944         }
945         s->mb_type[mb_xy]=CANDIDATE_MB_TYPE_INTER4V;
946     }else{
947         if(USES_LIST(mb_type, 0)){
948             if(p_type){
949                 *(uint32_t*)s->p_mv_table[mb_xy] = *(uint32_t*)p->f.motion_val[0][xy];
950                 s->mb_type[mb_xy]=CANDIDATE_MB_TYPE_INTER;
951             }else if(USES_LIST(mb_type, 1)){
952                 *(uint32_t*)s->b_bidir_forw_mv_table[mb_xy] = *(uint32_t*)p->f.motion_val[0][xy];
953                 *(uint32_t*)s->b_bidir_back_mv_table[mb_xy] = *(uint32_t*)p->f.motion_val[1][xy];
954                 s->mb_type[mb_xy]=CANDIDATE_MB_TYPE_BIDIR;
955             }else{
956                 *(uint32_t*)s->b_forw_mv_table[mb_xy] = *(uint32_t*)p->f.motion_val[0][xy];
957                 s->mb_type[mb_xy]=CANDIDATE_MB_TYPE_FORWARD;
958             }
959             x = p->f.motion_val[0][xy][0];
960             y = p->f.motion_val[0][xy][1];
961             d = cmp(s, x>>shift, y>>shift, x&mask, y&mask, 0, 16, 0, 0, cmpf, chroma_cmpf, flags);
962         }else if(USES_LIST(mb_type, 1)){
963             *(uint32_t*)s->b_back_mv_table[mb_xy] = *(uint32_t*)p->f.motion_val[1][xy];
964             s->mb_type[mb_xy]=CANDIDATE_MB_TYPE_BACKWARD;
965
966             x = p->f.motion_val[1][xy][0];
967             y = p->f.motion_val[1][xy][1];
968             d = cmp(s, x>>shift, y>>shift, x&mask, y&mask, 0, 16, 2, 0, cmpf, chroma_cmpf, flags);
969         }else
970             s->mb_type[mb_xy]=CANDIDATE_MB_TYPE_INTRA;
971     }
972     return d;
973 }
974
975 static inline int get_penalty_factor(int lambda, int lambda2, int type){
976     switch(type&0xFF){
977     default:
978     case FF_CMP_SAD:
979         return lambda>>FF_LAMBDA_SHIFT;
980     case FF_CMP_DCT:
981         return (3*lambda)>>(FF_LAMBDA_SHIFT+1);
982     case FF_CMP_SATD:
983     case FF_CMP_DCT264:
984         return (2*lambda)>>FF_LAMBDA_SHIFT;
985     case FF_CMP_RD:
986     case FF_CMP_PSNR:
987     case FF_CMP_SSE:
988     case FF_CMP_NSSE:
989         return lambda2>>FF_LAMBDA_SHIFT;
990     case FF_CMP_BIT:
991         return 1;
992     }
993 }
994
995 void ff_estimate_p_frame_motion(MpegEncContext * s,
996                                 int mb_x, int mb_y)
997 {
998     MotionEstContext * const c= &s->me;
999     uint8_t *pix, *ppix;
1000     int sum, mx, my, dmin;
1001     int varc;            ///< the variance of the block (sum of squared (p[y][x]-average))
1002     int vard;            ///< sum of squared differences with the estimated motion vector
1003     int P[10][2];
1004     const int shift= 1+s->quarter_sample;
1005     int mb_type=0;
1006     Picture * const pic= &s->current_picture;
1007
1008     init_ref(c, s->new_picture.f.data, s->last_picture.f.data, NULL, 16*mb_x, 16*mb_y, 0);
1009
1010     assert(s->quarter_sample==0 || s->quarter_sample==1);
1011     assert(s->linesize == c->stride);
1012     assert(s->uvlinesize == c->uvstride);
1013
1014     c->penalty_factor    = get_penalty_factor(s->lambda, s->lambda2, c->avctx->me_cmp);
1015     c->sub_penalty_factor= get_penalty_factor(s->lambda, s->lambda2, c->avctx->me_sub_cmp);
1016     c->mb_penalty_factor = get_penalty_factor(s->lambda, s->lambda2, c->avctx->mb_cmp);
1017     c->current_mv_penalty= c->mv_penalty[s->f_code] + MAX_MV;
1018
1019     get_limits(s, 16*mb_x, 16*mb_y);
1020     c->skip=0;
1021
1022     /* intra / predictive decision */
1023     pix = c->src[0][0];
1024     sum = s->dsp.pix_sum(pix, s->linesize);
1025     varc = s->dsp.pix_norm1(pix, s->linesize) - (((unsigned)sum*sum)>>8) + 500;
1026
1027     pic->mb_mean[s->mb_stride * mb_y + mb_x] = (sum+128)>>8;
1028     pic->mb_var [s->mb_stride * mb_y + mb_x] = (varc+128)>>8;
1029     c->mb_var_sum_temp += (varc+128)>>8;
1030
1031     if(c->avctx->me_threshold){
1032         vard= check_input_motion(s, mb_x, mb_y, 1);
1033
1034         if((vard+128)>>8 < c->avctx->me_threshold){
1035             int p_score= FFMIN(vard, varc-500+(s->lambda2>>FF_LAMBDA_SHIFT)*100);
1036             int i_score= varc-500+(s->lambda2>>FF_LAMBDA_SHIFT)*20;
1037             pic->mc_mb_var[s->mb_stride * mb_y + mb_x] = (vard+128)>>8;
1038             c->mc_mb_var_sum_temp += (vard+128)>>8;
1039             c->scene_change_score+= ff_sqrt(p_score) - ff_sqrt(i_score);
1040             return;
1041         }
1042         if((vard+128)>>8 < c->avctx->mb_threshold)
1043             mb_type= s->mb_type[mb_x + mb_y*s->mb_stride];
1044     }
1045
1046     switch(s->me_method) {
1047     case ME_ZERO:
1048     default:
1049         mx   = 0;
1050         my   = 0;
1051         dmin = 0;
1052         break;
1053     case ME_X1:
1054     case ME_EPZS:
1055        {
1056             const int mot_stride = s->b8_stride;
1057             const int mot_xy = s->block_index[0];
1058
1059             P_LEFT[0] = s->current_picture.f.motion_val[0][mot_xy - 1][0];
1060             P_LEFT[1] = s->current_picture.f.motion_val[0][mot_xy - 1][1];
1061
1062             if(P_LEFT[0]       > (c->xmax<<shift)) P_LEFT[0]       = (c->xmax<<shift);
1063
1064             if(!s->first_slice_line) {
1065                 P_TOP[0]      = s->current_picture.f.motion_val[0][mot_xy - mot_stride    ][0];
1066                 P_TOP[1]      = s->current_picture.f.motion_val[0][mot_xy - mot_stride    ][1];
1067                 P_TOPRIGHT[0] = s->current_picture.f.motion_val[0][mot_xy - mot_stride + 2][0];
1068                 P_TOPRIGHT[1] = s->current_picture.f.motion_val[0][mot_xy - mot_stride + 2][1];
1069                 if(P_TOP[1]      > (c->ymax<<shift)) P_TOP[1]     = (c->ymax<<shift);
1070                 if(P_TOPRIGHT[0] < (c->xmin<<shift)) P_TOPRIGHT[0]= (c->xmin<<shift);
1071                 if(P_TOPRIGHT[1] > (c->ymax<<shift)) P_TOPRIGHT[1]= (c->ymax<<shift);
1072
1073                 P_MEDIAN[0]= mid_pred(P_LEFT[0], P_TOP[0], P_TOPRIGHT[0]);
1074                 P_MEDIAN[1]= mid_pred(P_LEFT[1], P_TOP[1], P_TOPRIGHT[1]);
1075
1076                 if(s->out_format == FMT_H263){
1077                     c->pred_x = P_MEDIAN[0];
1078                     c->pred_y = P_MEDIAN[1];
1079                 }else { /* mpeg1 at least */
1080                     c->pred_x= P_LEFT[0];
1081                     c->pred_y= P_LEFT[1];
1082                 }
1083             }else{
1084                 c->pred_x= P_LEFT[0];
1085                 c->pred_y= P_LEFT[1];
1086             }
1087
1088         }
1089         dmin = ff_epzs_motion_search(s, &mx, &my, P, 0, 0, s->p_mv_table, (1<<16)>>shift, 0, 16);
1090
1091         break;
1092     }
1093
1094     /* At this point (mx,my) are full-pell and the relative displacement */
1095     ppix = c->ref[0][0] + (my * s->linesize) + mx;
1096
1097     vard = s->dsp.sse[0](NULL, pix, ppix, s->linesize, 16);
1098
1099     pic->mc_mb_var[s->mb_stride * mb_y + mb_x] = (vard+128)>>8;
1100     c->mc_mb_var_sum_temp += (vard+128)>>8;
1101
1102     if(mb_type){
1103         int p_score= FFMIN(vard, varc-500+(s->lambda2>>FF_LAMBDA_SHIFT)*100);
1104         int i_score= varc-500+(s->lambda2>>FF_LAMBDA_SHIFT)*20;
1105         c->scene_change_score+= ff_sqrt(p_score) - ff_sqrt(i_score);
1106
1107         if(mb_type == CANDIDATE_MB_TYPE_INTER){
1108             c->sub_motion_search(s, &mx, &my, dmin, 0, 0, 0, 16);
1109             set_p_mv_tables(s, mx, my, 1);
1110         }else{
1111             mx <<=shift;
1112             my <<=shift;
1113         }
1114         if(mb_type == CANDIDATE_MB_TYPE_INTER4V){
1115             h263_mv4_search(s, mx, my, shift);
1116
1117             set_p_mv_tables(s, mx, my, 0);
1118         }
1119         if(mb_type == CANDIDATE_MB_TYPE_INTER_I){
1120             interlaced_search(s, 0, s->p_field_mv_table, s->p_field_select_table, mx, my, 1);
1121         }
1122     }else if(c->avctx->mb_decision > FF_MB_DECISION_SIMPLE){
1123         int p_score= FFMIN(vard, varc-500+(s->lambda2>>FF_LAMBDA_SHIFT)*100);
1124         int i_score= varc-500+(s->lambda2>>FF_LAMBDA_SHIFT)*20;
1125         c->scene_change_score+= ff_sqrt(p_score) - ff_sqrt(i_score);
1126
1127         if (vard*2 + 200*256 > varc)
1128             mb_type|= CANDIDATE_MB_TYPE_INTRA;
1129         if (varc*2 + 200*256 > vard || s->qscale > 24){
1130 //        if (varc*2 + 200*256 + 50*(s->lambda2>>FF_LAMBDA_SHIFT) > vard){
1131             mb_type|= CANDIDATE_MB_TYPE_INTER;
1132             c->sub_motion_search(s, &mx, &my, dmin, 0, 0, 0, 16);
1133             if(s->flags&CODEC_FLAG_MV0)
1134                 if(mx || my)
1135                     mb_type |= CANDIDATE_MB_TYPE_SKIPPED; //FIXME check difference
1136         }else{
1137             mx <<=shift;
1138             my <<=shift;
1139         }
1140         if((s->flags&CODEC_FLAG_4MV)
1141            && !c->skip && varc>50<<8 && vard>10<<8){
1142             if(h263_mv4_search(s, mx, my, shift) < INT_MAX)
1143                 mb_type|=CANDIDATE_MB_TYPE_INTER4V;
1144
1145             set_p_mv_tables(s, mx, my, 0);
1146         }else
1147             set_p_mv_tables(s, mx, my, 1);
1148         if((s->flags&CODEC_FLAG_INTERLACED_ME)
1149            && !c->skip){ //FIXME varc/d checks
1150             if(interlaced_search(s, 0, s->p_field_mv_table, s->p_field_select_table, mx, my, 0) < INT_MAX)
1151                 mb_type |= CANDIDATE_MB_TYPE_INTER_I;
1152         }
1153     }else{
1154         int intra_score, i;
1155         mb_type= CANDIDATE_MB_TYPE_INTER;
1156
1157         dmin= c->sub_motion_search(s, &mx, &my, dmin, 0, 0, 0, 16);
1158         if(c->avctx->me_sub_cmp != c->avctx->mb_cmp && !c->skip)
1159             dmin= get_mb_score(s, mx, my, 0, 0, 0, 16, 1);
1160
1161         if((s->flags&CODEC_FLAG_4MV)
1162            && !c->skip && varc>50<<8 && vard>10<<8){
1163             int dmin4= h263_mv4_search(s, mx, my, shift);
1164             if(dmin4 < dmin){
1165                 mb_type= CANDIDATE_MB_TYPE_INTER4V;
1166                 dmin=dmin4;
1167             }
1168         }
1169         if((s->flags&CODEC_FLAG_INTERLACED_ME)
1170            && !c->skip){ //FIXME varc/d checks
1171             int dmin_i= interlaced_search(s, 0, s->p_field_mv_table, s->p_field_select_table, mx, my, 0);
1172             if(dmin_i < dmin){
1173                 mb_type = CANDIDATE_MB_TYPE_INTER_I;
1174                 dmin= dmin_i;
1175             }
1176         }
1177
1178         set_p_mv_tables(s, mx, my, mb_type!=CANDIDATE_MB_TYPE_INTER4V);
1179
1180         /* get intra luma score */
1181         if((c->avctx->mb_cmp&0xFF)==FF_CMP_SSE){
1182             intra_score= varc - 500;
1183         }else{
1184             unsigned mean = (sum+128)>>8;
1185             mean*= 0x01010101;
1186
1187             for(i=0; i<16; i++){
1188                 *(uint32_t*)(&c->scratchpad[i*s->linesize+ 0]) = mean;
1189                 *(uint32_t*)(&c->scratchpad[i*s->linesize+ 4]) = mean;
1190                 *(uint32_t*)(&c->scratchpad[i*s->linesize+ 8]) = mean;
1191                 *(uint32_t*)(&c->scratchpad[i*s->linesize+12]) = mean;
1192             }
1193
1194             intra_score= s->dsp.mb_cmp[0](s, c->scratchpad, pix, s->linesize, 16);
1195         }
1196         intra_score += c->mb_penalty_factor*16;
1197
1198         if(intra_score < dmin){
1199             mb_type= CANDIDATE_MB_TYPE_INTRA;
1200             s->current_picture.f.mb_type[mb_y*s->mb_stride + mb_x] = CANDIDATE_MB_TYPE_INTRA; //FIXME cleanup
1201         }else
1202             s->current_picture.f.mb_type[mb_y*s->mb_stride + mb_x] = 0;
1203
1204         {
1205             int p_score= FFMIN(vard, varc-500+(s->lambda2>>FF_LAMBDA_SHIFT)*100);
1206             int i_score= varc-500+(s->lambda2>>FF_LAMBDA_SHIFT)*20;
1207             c->scene_change_score+= ff_sqrt(p_score) - ff_sqrt(i_score);
1208         }
1209     }
1210
1211     s->mb_type[mb_y*s->mb_stride + mb_x]= mb_type;
1212 }
1213
1214 int ff_pre_estimate_p_frame_motion(MpegEncContext * s,
1215                                     int mb_x, int mb_y)
1216 {
1217     MotionEstContext * const c= &s->me;
1218     int mx, my, dmin;
1219     int P[10][2];
1220     const int shift= 1+s->quarter_sample;
1221     const int xy= mb_x + mb_y*s->mb_stride;
1222     init_ref(c, s->new_picture.f.data, s->last_picture.f.data, NULL, 16*mb_x, 16*mb_y, 0);
1223
1224     assert(s->quarter_sample==0 || s->quarter_sample==1);
1225
1226     c->pre_penalty_factor    = get_penalty_factor(s->lambda, s->lambda2, c->avctx->me_pre_cmp);
1227     c->current_mv_penalty= c->mv_penalty[s->f_code] + MAX_MV;
1228
1229     get_limits(s, 16*mb_x, 16*mb_y);
1230     c->skip=0;
1231
1232     P_LEFT[0]       = s->p_mv_table[xy + 1][0];
1233     P_LEFT[1]       = s->p_mv_table[xy + 1][1];
1234
1235     if(P_LEFT[0]       < (c->xmin<<shift)) P_LEFT[0]       = (c->xmin<<shift);
1236
1237     /* special case for first line */
1238     if (s->first_slice_line) {
1239         c->pred_x= P_LEFT[0];
1240         c->pred_y= P_LEFT[1];
1241         P_TOP[0]= P_TOPRIGHT[0]= P_MEDIAN[0]=
1242         P_TOP[1]= P_TOPRIGHT[1]= P_MEDIAN[1]= 0; //FIXME
1243     } else {
1244         P_TOP[0]      = s->p_mv_table[xy + s->mb_stride    ][0];
1245         P_TOP[1]      = s->p_mv_table[xy + s->mb_stride    ][1];
1246         P_TOPRIGHT[0] = s->p_mv_table[xy + s->mb_stride - 1][0];
1247         P_TOPRIGHT[1] = s->p_mv_table[xy + s->mb_stride - 1][1];
1248         if(P_TOP[1]      < (c->ymin<<shift)) P_TOP[1]     = (c->ymin<<shift);
1249         if(P_TOPRIGHT[0] > (c->xmax<<shift)) P_TOPRIGHT[0]= (c->xmax<<shift);
1250         if(P_TOPRIGHT[1] < (c->ymin<<shift)) P_TOPRIGHT[1]= (c->ymin<<shift);
1251
1252         P_MEDIAN[0]= mid_pred(P_LEFT[0], P_TOP[0], P_TOPRIGHT[0]);
1253         P_MEDIAN[1]= mid_pred(P_LEFT[1], P_TOP[1], P_TOPRIGHT[1]);
1254
1255         c->pred_x = P_MEDIAN[0];
1256         c->pred_y = P_MEDIAN[1];
1257     }
1258
1259     dmin = ff_epzs_motion_search(s, &mx, &my, P, 0, 0, s->p_mv_table, (1<<16)>>shift, 0, 16);
1260
1261     s->p_mv_table[xy][0] = mx<<shift;
1262     s->p_mv_table[xy][1] = my<<shift;
1263
1264     return dmin;
1265 }
1266
1267 static int ff_estimate_motion_b(MpegEncContext * s,
1268                        int mb_x, int mb_y, int16_t (*mv_table)[2], int ref_index, int f_code)
1269 {
1270     MotionEstContext * const c= &s->me;
1271     int mx, my, dmin;
1272     int P[10][2];
1273     const int shift= 1+s->quarter_sample;
1274     const int mot_stride = s->mb_stride;
1275     const int mot_xy = mb_y*mot_stride + mb_x;
1276     uint8_t * const mv_penalty= c->mv_penalty[f_code] + MAX_MV;
1277     int mv_scale;
1278
1279     c->penalty_factor    = get_penalty_factor(s->lambda, s->lambda2, c->avctx->me_cmp);
1280     c->sub_penalty_factor= get_penalty_factor(s->lambda, s->lambda2, c->avctx->me_sub_cmp);
1281     c->mb_penalty_factor = get_penalty_factor(s->lambda, s->lambda2, c->avctx->mb_cmp);
1282     c->current_mv_penalty= mv_penalty;
1283
1284     get_limits(s, 16*mb_x, 16*mb_y);
1285
1286     switch(s->me_method) {
1287     case ME_ZERO:
1288     default:
1289         mx   = 0;
1290         my   = 0;
1291         dmin = 0;
1292         break;
1293     case ME_X1:
1294     case ME_EPZS:
1295         P_LEFT[0] = mv_table[mot_xy - 1][0];
1296         P_LEFT[1] = mv_table[mot_xy - 1][1];
1297
1298         if (P_LEFT[0] > (c->xmax << shift)) P_LEFT[0] = (c->xmax << shift);
1299
1300         /* special case for first line */
1301         if (!s->first_slice_line) {
1302             P_TOP[0]      = mv_table[mot_xy - mot_stride    ][0];
1303             P_TOP[1]      = mv_table[mot_xy - mot_stride    ][1];
1304             P_TOPRIGHT[0] = mv_table[mot_xy - mot_stride + 1][0];
1305             P_TOPRIGHT[1] = mv_table[mot_xy - mot_stride + 1][1];
1306             if (P_TOP[1] > (c->ymax << shift)) P_TOP[1] = (c->ymax << shift);
1307             if (P_TOPRIGHT[0] < (c->xmin << shift)) P_TOPRIGHT[0] = (c->xmin << shift);
1308             if (P_TOPRIGHT[1] > (c->ymax << shift)) P_TOPRIGHT[1] = (c->ymax << shift);
1309
1310             P_MEDIAN[0] = mid_pred(P_LEFT[0], P_TOP[0], P_TOPRIGHT[0]);
1311             P_MEDIAN[1] = mid_pred(P_LEFT[1], P_TOP[1], P_TOPRIGHT[1]);
1312         }
1313         c->pred_x = P_LEFT[0];
1314         c->pred_y = P_LEFT[1];
1315
1316         if(mv_table == s->b_forw_mv_table){
1317             mv_scale= (s->pb_time<<16) / (s->pp_time<<shift);
1318         }else{
1319             mv_scale= ((s->pb_time - s->pp_time)<<16) / (s->pp_time<<shift);
1320         }
1321
1322         dmin = ff_epzs_motion_search(s, &mx, &my, P, 0, ref_index, s->p_mv_table, mv_scale, 0, 16);
1323
1324         break;
1325     }
1326
1327     dmin= c->sub_motion_search(s, &mx, &my, dmin, 0, ref_index, 0, 16);
1328
1329     if(c->avctx->me_sub_cmp != c->avctx->mb_cmp && !c->skip)
1330         dmin= get_mb_score(s, mx, my, 0, ref_index, 0, 16, 1);
1331
1332 //    s->mb_type[mb_y*s->mb_width + mb_x]= mb_type;
1333     mv_table[mot_xy][0]= mx;
1334     mv_table[mot_xy][1]= my;
1335
1336     return dmin;
1337 }
1338
1339 static inline int check_bidir_mv(MpegEncContext * s,
1340                    int motion_fx, int motion_fy,
1341                    int motion_bx, int motion_by,
1342                    int pred_fx, int pred_fy,
1343                    int pred_bx, int pred_by,
1344                    int size, int h)
1345 {
1346     //FIXME optimize?
1347     //FIXME better f_code prediction (max mv & distance)
1348     //FIXME pointers
1349     MotionEstContext * const c= &s->me;
1350     uint8_t * const mv_penalty_f= c->mv_penalty[s->f_code] + MAX_MV; // f_code of the prev frame
1351     uint8_t * const mv_penalty_b= c->mv_penalty[s->b_code] + MAX_MV; // f_code of the prev frame
1352     int stride= c->stride;
1353     uint8_t *dest_y = c->scratchpad;
1354     uint8_t *ptr;
1355     int dxy;
1356     int src_x, src_y;
1357     int fbmin;
1358     uint8_t **src_data= c->src[0];
1359     uint8_t **ref_data= c->ref[0];
1360     uint8_t **ref2_data= c->ref[2];
1361
1362     if(s->quarter_sample){
1363         dxy = ((motion_fy & 3) << 2) | (motion_fx & 3);
1364         src_x = motion_fx >> 2;
1365         src_y = motion_fy >> 2;
1366
1367         ptr = ref_data[0] + (src_y * stride) + src_x;
1368         s->dsp.put_qpel_pixels_tab[0][dxy](dest_y    , ptr    , stride);
1369
1370         dxy = ((motion_by & 3) << 2) | (motion_bx & 3);
1371         src_x = motion_bx >> 2;
1372         src_y = motion_by >> 2;
1373
1374         ptr = ref2_data[0] + (src_y * stride) + src_x;
1375         s->dsp.avg_qpel_pixels_tab[size][dxy](dest_y    , ptr    , stride);
1376     }else{
1377         dxy = ((motion_fy & 1) << 1) | (motion_fx & 1);
1378         src_x = motion_fx >> 1;
1379         src_y = motion_fy >> 1;
1380
1381         ptr = ref_data[0] + (src_y * stride) + src_x;
1382         s->dsp.put_pixels_tab[size][dxy](dest_y    , ptr    , stride, h);
1383
1384         dxy = ((motion_by & 1) << 1) | (motion_bx & 1);
1385         src_x = motion_bx >> 1;
1386         src_y = motion_by >> 1;
1387
1388         ptr = ref2_data[0] + (src_y * stride) + src_x;
1389         s->dsp.avg_pixels_tab[size][dxy](dest_y    , ptr    , stride, h);
1390     }
1391
1392     fbmin = (mv_penalty_f[motion_fx-pred_fx] + mv_penalty_f[motion_fy-pred_fy])*c->mb_penalty_factor
1393            +(mv_penalty_b[motion_bx-pred_bx] + mv_penalty_b[motion_by-pred_by])*c->mb_penalty_factor
1394            + s->dsp.mb_cmp[size](s, src_data[0], dest_y, stride, h); //FIXME new_pic
1395
1396     if(c->avctx->mb_cmp&FF_CMP_CHROMA){
1397     }
1398     //FIXME CHROMA !!!
1399
1400     return fbmin;
1401 }
1402
1403 /* refine the bidir vectors in hq mode and return the score in both lq & hq mode*/
1404 static inline int bidir_refine(MpegEncContext * s, int mb_x, int mb_y)
1405 {
1406     MotionEstContext * const c= &s->me;
1407     const int mot_stride = s->mb_stride;
1408     const int xy = mb_y *mot_stride + mb_x;
1409     int fbmin;
1410     int pred_fx= s->b_bidir_forw_mv_table[xy-1][0];
1411     int pred_fy= s->b_bidir_forw_mv_table[xy-1][1];
1412     int pred_bx= s->b_bidir_back_mv_table[xy-1][0];
1413     int pred_by= s->b_bidir_back_mv_table[xy-1][1];
1414     int motion_fx= s->b_bidir_forw_mv_table[xy][0]= s->b_forw_mv_table[xy][0];
1415     int motion_fy= s->b_bidir_forw_mv_table[xy][1]= s->b_forw_mv_table[xy][1];
1416     int motion_bx= s->b_bidir_back_mv_table[xy][0]= s->b_back_mv_table[xy][0];
1417     int motion_by= s->b_bidir_back_mv_table[xy][1]= s->b_back_mv_table[xy][1];
1418     const int flags= c->sub_flags;
1419     const int qpel= flags&FLAG_QPEL;
1420     const int shift= 1+qpel;
1421     const int xmin= c->xmin<<shift;
1422     const int ymin= c->ymin<<shift;
1423     const int xmax= c->xmax<<shift;
1424     const int ymax= c->ymax<<shift;
1425 #define HASH(fx,fy,bx,by) ((fx)+17*(fy)+63*(bx)+117*(by))
1426 #define HASH8(fx,fy,bx,by) ((uint8_t)HASH(fx,fy,bx,by))
1427     int hashidx= HASH(motion_fx,motion_fy, motion_bx, motion_by);
1428     uint8_t map[256] = { 0 };
1429
1430     map[hashidx&255] = 1;
1431
1432     fbmin= check_bidir_mv(s, motion_fx, motion_fy,
1433                           motion_bx, motion_by,
1434                           pred_fx, pred_fy,
1435                           pred_bx, pred_by,
1436                           0, 16);
1437
1438     if(s->avctx->bidir_refine){
1439         int end;
1440         static const uint8_t limittab[5]={0,8,32,64,80};
1441         const int limit= limittab[s->avctx->bidir_refine];
1442         static const int8_t vect[][4]={
1443 { 0, 0, 0, 1}, { 0, 0, 0,-1}, { 0, 0, 1, 0}, { 0, 0,-1, 0}, { 0, 1, 0, 0}, { 0,-1, 0, 0}, { 1, 0, 0, 0}, {-1, 0, 0, 0},
1444
1445 { 0, 0, 1, 1}, { 0, 0,-1,-1}, { 0, 1, 1, 0}, { 0,-1,-1, 0}, { 1, 1, 0, 0}, {-1,-1, 0, 0}, { 1, 0, 0, 1}, {-1, 0, 0,-1},
1446 { 0, 1, 0, 1}, { 0,-1, 0,-1}, { 1, 0, 1, 0}, {-1, 0,-1, 0},
1447 { 0, 0,-1, 1}, { 0, 0, 1,-1}, { 0,-1, 1, 0}, { 0, 1,-1, 0}, {-1, 1, 0, 0}, { 1,-1, 0, 0}, { 1, 0, 0,-1}, {-1, 0, 0, 1},
1448 { 0,-1, 0, 1}, { 0, 1, 0,-1}, {-1, 0, 1, 0}, { 1, 0,-1, 0},
1449
1450 { 0, 1, 1, 1}, { 0,-1,-1,-1}, { 1, 1, 1, 0}, {-1,-1,-1, 0}, { 1, 1, 0, 1}, {-1,-1, 0,-1}, { 1, 0, 1, 1}, {-1, 0,-1,-1},
1451 { 0,-1, 1, 1}, { 0, 1,-1,-1}, {-1, 1, 1, 0}, { 1,-1,-1, 0}, { 1, 1, 0,-1}, {-1,-1, 0, 1}, { 1, 0,-1, 1}, {-1, 0, 1,-1},
1452 { 0, 1,-1, 1}, { 0,-1, 1,-1}, { 1,-1, 1, 0}, {-1, 1,-1, 0}, {-1, 1, 0, 1}, { 1,-1, 0,-1}, { 1, 0, 1,-1}, {-1, 0,-1, 1},
1453 { 0, 1, 1,-1}, { 0,-1,-1, 1}, { 1, 1,-1, 0}, {-1,-1, 1, 0}, { 1,-1, 0, 1}, {-1, 1, 0,-1}, {-1, 0, 1, 1}, { 1, 0,-1,-1},
1454
1455 { 1, 1, 1, 1}, {-1,-1,-1,-1},
1456 { 1, 1, 1,-1}, {-1,-1,-1, 1}, { 1, 1,-1, 1}, {-1,-1, 1,-1}, { 1,-1, 1, 1}, {-1, 1,-1,-1}, {-1, 1, 1, 1}, { 1,-1,-1,-1},
1457 { 1, 1,-1,-1}, {-1,-1, 1, 1}, { 1,-1,-1, 1}, {-1, 1, 1,-1}, { 1,-1, 1,-1}, {-1, 1,-1, 1},
1458         };
1459         static const uint8_t hash[]={
1460 HASH8( 0, 0, 0, 1), HASH8( 0, 0, 0,-1), HASH8( 0, 0, 1, 0), HASH8( 0, 0,-1, 0), HASH8( 0, 1, 0, 0), HASH8( 0,-1, 0, 0), HASH8( 1, 0, 0, 0), HASH8(-1, 0, 0, 0),
1461
1462 HASH8( 0, 0, 1, 1), HASH8( 0, 0,-1,-1), HASH8( 0, 1, 1, 0), HASH8( 0,-1,-1, 0), HASH8( 1, 1, 0, 0), HASH8(-1,-1, 0, 0), HASH8( 1, 0, 0, 1), HASH8(-1, 0, 0,-1),
1463 HASH8( 0, 1, 0, 1), HASH8( 0,-1, 0,-1), HASH8( 1, 0, 1, 0), HASH8(-1, 0,-1, 0),
1464 HASH8( 0, 0,-1, 1), HASH8( 0, 0, 1,-1), HASH8( 0,-1, 1, 0), HASH8( 0, 1,-1, 0), HASH8(-1, 1, 0, 0), HASH8( 1,-1, 0, 0), HASH8( 1, 0, 0,-1), HASH8(-1, 0, 0, 1),
1465 HASH8( 0,-1, 0, 1), HASH8( 0, 1, 0,-1), HASH8(-1, 0, 1, 0), HASH8( 1, 0,-1, 0),
1466
1467 HASH8( 0, 1, 1, 1), HASH8( 0,-1,-1,-1), HASH8( 1, 1, 1, 0), HASH8(-1,-1,-1, 0), HASH8( 1, 1, 0, 1), HASH8(-1,-1, 0,-1), HASH8( 1, 0, 1, 1), HASH8(-1, 0,-1,-1),
1468 HASH8( 0,-1, 1, 1), HASH8( 0, 1,-1,-1), HASH8(-1, 1, 1, 0), HASH8( 1,-1,-1, 0), HASH8( 1, 1, 0,-1), HASH8(-1,-1, 0, 1), HASH8( 1, 0,-1, 1), HASH8(-1, 0, 1,-1),
1469 HASH8( 0, 1,-1, 1), HASH8( 0,-1, 1,-1), HASH8( 1,-1, 1, 0), HASH8(-1, 1,-1, 0), HASH8(-1, 1, 0, 1), HASH8( 1,-1, 0,-1), HASH8( 1, 0, 1,-1), HASH8(-1, 0,-1, 1),
1470 HASH8( 0, 1, 1,-1), HASH8( 0,-1,-1, 1), HASH8( 1, 1,-1, 0), HASH8(-1,-1, 1, 0), HASH8( 1,-1, 0, 1), HASH8(-1, 1, 0,-1), HASH8(-1, 0, 1, 1), HASH8( 1, 0,-1,-1),
1471
1472 HASH8( 1, 1, 1, 1), HASH8(-1,-1,-1,-1),
1473 HASH8( 1, 1, 1,-1), HASH8(-1,-1,-1, 1), HASH8( 1, 1,-1, 1), HASH8(-1,-1, 1,-1), HASH8( 1,-1, 1, 1), HASH8(-1, 1,-1,-1), HASH8(-1, 1, 1, 1), HASH8( 1,-1,-1,-1),
1474 HASH8( 1, 1,-1,-1), HASH8(-1,-1, 1, 1), HASH8( 1,-1,-1, 1), HASH8(-1, 1, 1,-1), HASH8( 1,-1, 1,-1), HASH8(-1, 1,-1, 1),
1475 };
1476
1477 #define CHECK_BIDIR(fx,fy,bx,by)\
1478     if( !map[(hashidx+HASH(fx,fy,bx,by))&255]\
1479        &&(fx<=0 || motion_fx+fx<=xmax) && (fy<=0 || motion_fy+fy<=ymax) && (bx<=0 || motion_bx+bx<=xmax) && (by<=0 || motion_by+by<=ymax)\
1480        &&(fx>=0 || motion_fx+fx>=xmin) && (fy>=0 || motion_fy+fy>=ymin) && (bx>=0 || motion_bx+bx>=xmin) && (by>=0 || motion_by+by>=ymin)){\
1481         int score;\
1482         map[(hashidx+HASH(fx,fy,bx,by))&255] = 1;\
1483         score= check_bidir_mv(s, motion_fx+fx, motion_fy+fy, motion_bx+bx, motion_by+by, pred_fx, pred_fy, pred_bx, pred_by, 0, 16);\
1484         if(score < fbmin){\
1485             hashidx += HASH(fx,fy,bx,by);\
1486             fbmin= score;\
1487             motion_fx+=fx;\
1488             motion_fy+=fy;\
1489             motion_bx+=bx;\
1490             motion_by+=by;\
1491             end=0;\
1492         }\
1493     }
1494 #define CHECK_BIDIR2(a,b,c,d)\
1495 CHECK_BIDIR(a,b,c,d)\
1496 CHECK_BIDIR(-(a),-(b),-(c),-(d))
1497
1498         do{
1499             int i;
1500             int borderdist=0;
1501             end=1;
1502
1503             CHECK_BIDIR2(0,0,0,1)
1504             CHECK_BIDIR2(0,0,1,0)
1505             CHECK_BIDIR2(0,1,0,0)
1506             CHECK_BIDIR2(1,0,0,0)
1507
1508             for(i=8; i<limit; i++){
1509                 int fx= motion_fx+vect[i][0];
1510                 int fy= motion_fy+vect[i][1];
1511                 int bx= motion_bx+vect[i][2];
1512                 int by= motion_by+vect[i][3];
1513                 if(borderdist<=0){
1514                     int a= (xmax - FFMAX(fx,bx))|(FFMIN(fx,bx) - xmin);
1515                     int b= (ymax - FFMAX(fy,by))|(FFMIN(fy,by) - ymin);
1516                     if((a|b) < 0)
1517                         map[(hashidx+hash[i])&255] = 1;
1518                 }
1519                 if(!map[(hashidx+hash[i])&255]){
1520                     int score;
1521                     map[(hashidx+hash[i])&255] = 1;
1522                     score= check_bidir_mv(s, fx, fy, bx, by, pred_fx, pred_fy, pred_bx, pred_by, 0, 16);
1523                     if(score < fbmin){
1524                         hashidx += hash[i];
1525                         fbmin= score;
1526                         motion_fx=fx;
1527                         motion_fy=fy;
1528                         motion_bx=bx;
1529                         motion_by=by;
1530                         end=0;
1531                         borderdist--;
1532                         if(borderdist<=0){
1533                             int a= FFMIN(xmax - FFMAX(fx,bx), FFMIN(fx,bx) - xmin);
1534                             int b= FFMIN(ymax - FFMAX(fy,by), FFMIN(fy,by) - ymin);
1535                             borderdist= FFMIN(a,b);
1536                         }
1537                     }
1538                 }
1539             }
1540         }while(!end);
1541     }
1542
1543     s->b_bidir_forw_mv_table[xy][0]= motion_fx;
1544     s->b_bidir_forw_mv_table[xy][1]= motion_fy;
1545     s->b_bidir_back_mv_table[xy][0]= motion_bx;
1546     s->b_bidir_back_mv_table[xy][1]= motion_by;
1547
1548     return fbmin;
1549 }
1550
1551 static inline int direct_search(MpegEncContext * s, int mb_x, int mb_y)
1552 {
1553     MotionEstContext * const c= &s->me;
1554     int P[10][2];
1555     const int mot_stride = s->mb_stride;
1556     const int mot_xy = mb_y*mot_stride + mb_x;
1557     const int shift= 1+s->quarter_sample;
1558     int dmin, i;
1559     const int time_pp= s->pp_time;
1560     const int time_pb= s->pb_time;
1561     int mx, my, xmin, xmax, ymin, ymax;
1562     int16_t (*mv_table)[2]= s->b_direct_mv_table;
1563
1564     c->current_mv_penalty= c->mv_penalty[1] + MAX_MV;
1565     ymin= xmin=(-32)>>shift;
1566     ymax= xmax=   31>>shift;
1567
1568     if (IS_8X8(s->next_picture.f.mb_type[mot_xy])) {
1569         s->mv_type= MV_TYPE_8X8;
1570     }else{
1571         s->mv_type= MV_TYPE_16X16;
1572     }
1573
1574     for(i=0; i<4; i++){
1575         int index= s->block_index[i];
1576         int min, max;
1577
1578         c->co_located_mv[i][0] = s->next_picture.f.motion_val[0][index][0];
1579         c->co_located_mv[i][1] = s->next_picture.f.motion_val[0][index][1];
1580         c->direct_basis_mv[i][0]= c->co_located_mv[i][0]*time_pb/time_pp + ((i& 1)<<(shift+3));
1581         c->direct_basis_mv[i][1]= c->co_located_mv[i][1]*time_pb/time_pp + ((i>>1)<<(shift+3));
1582 //        c->direct_basis_mv[1][i][0]= c->co_located_mv[i][0]*(time_pb - time_pp)/time_pp + ((i &1)<<(shift+3);
1583 //        c->direct_basis_mv[1][i][1]= c->co_located_mv[i][1]*(time_pb - time_pp)/time_pp + ((i>>1)<<(shift+3);
1584
1585         max= FFMAX(c->direct_basis_mv[i][0], c->direct_basis_mv[i][0] - c->co_located_mv[i][0])>>shift;
1586         min= FFMIN(c->direct_basis_mv[i][0], c->direct_basis_mv[i][0] - c->co_located_mv[i][0])>>shift;
1587         max+= 16*mb_x + 1; // +-1 is for the simpler rounding
1588         min+= 16*mb_x - 1;
1589         xmax= FFMIN(xmax, s->width - max);
1590         xmin= FFMAX(xmin, - 16     - min);
1591
1592         max= FFMAX(c->direct_basis_mv[i][1], c->direct_basis_mv[i][1] - c->co_located_mv[i][1])>>shift;
1593         min= FFMIN(c->direct_basis_mv[i][1], c->direct_basis_mv[i][1] - c->co_located_mv[i][1])>>shift;
1594         max+= 16*mb_y + 1; // +-1 is for the simpler rounding
1595         min+= 16*mb_y - 1;
1596         ymax= FFMIN(ymax, s->height - max);
1597         ymin= FFMAX(ymin, - 16      - min);
1598
1599         if(s->mv_type == MV_TYPE_16X16) break;
1600     }
1601
1602     assert(xmax <= 15 && ymax <= 15 && xmin >= -16 && ymin >= -16);
1603
1604     if(xmax < 0 || xmin >0 || ymax < 0 || ymin > 0){
1605         s->b_direct_mv_table[mot_xy][0]= 0;
1606         s->b_direct_mv_table[mot_xy][1]= 0;
1607
1608         return 256*256*256*64;
1609     }
1610
1611     c->xmin= xmin;
1612     c->ymin= ymin;
1613     c->xmax= xmax;
1614     c->ymax= ymax;
1615     c->flags     |= FLAG_DIRECT;
1616     c->sub_flags |= FLAG_DIRECT;
1617     c->pred_x=0;
1618     c->pred_y=0;
1619
1620     P_LEFT[0]        = av_clip(mv_table[mot_xy - 1][0], xmin<<shift, xmax<<shift);
1621     P_LEFT[1]        = av_clip(mv_table[mot_xy - 1][1], ymin<<shift, ymax<<shift);
1622
1623     /* special case for first line */
1624     if (!s->first_slice_line) { //FIXME maybe allow this over thread boundary as it is clipped
1625         P_TOP[0]      = av_clip(mv_table[mot_xy - mot_stride             ][0], xmin<<shift, xmax<<shift);
1626         P_TOP[1]      = av_clip(mv_table[mot_xy - mot_stride             ][1], ymin<<shift, ymax<<shift);
1627         P_TOPRIGHT[0] = av_clip(mv_table[mot_xy - mot_stride + 1         ][0], xmin<<shift, xmax<<shift);
1628         P_TOPRIGHT[1] = av_clip(mv_table[mot_xy - mot_stride + 1         ][1], ymin<<shift, ymax<<shift);
1629
1630         P_MEDIAN[0]= mid_pred(P_LEFT[0], P_TOP[0], P_TOPRIGHT[0]);
1631         P_MEDIAN[1]= mid_pred(P_LEFT[1], P_TOP[1], P_TOPRIGHT[1]);
1632     }
1633
1634     dmin = ff_epzs_motion_search(s, &mx, &my, P, 0, 0, mv_table, 1<<(16-shift), 0, 16);
1635     if(c->sub_flags&FLAG_QPEL)
1636         dmin = qpel_motion_search(s, &mx, &my, dmin, 0, 0, 0, 16);
1637     else
1638         dmin = hpel_motion_search(s, &mx, &my, dmin, 0, 0, 0, 16);
1639
1640     if(c->avctx->me_sub_cmp != c->avctx->mb_cmp && !c->skip)
1641         dmin= get_mb_score(s, mx, my, 0, 0, 0, 16, 1);
1642
1643     get_limits(s, 16*mb_x, 16*mb_y); //restore c->?min/max, maybe not needed
1644
1645     mv_table[mot_xy][0]= mx;
1646     mv_table[mot_xy][1]= my;
1647     c->flags     &= ~FLAG_DIRECT;
1648     c->sub_flags &= ~FLAG_DIRECT;
1649
1650     return dmin;
1651 }
1652
1653 void ff_estimate_b_frame_motion(MpegEncContext * s,
1654                              int mb_x, int mb_y)
1655 {
1656     MotionEstContext * const c= &s->me;
1657     const int penalty_factor= c->mb_penalty_factor;
1658     int fmin, bmin, dmin, fbmin, bimin, fimin;
1659     int type=0;
1660     const int xy = mb_y*s->mb_stride + mb_x;
1661     init_ref(c, s->new_picture.f.data, s->last_picture.f.data,
1662              s->next_picture.f.data, 16 * mb_x, 16 * mb_y, 2);
1663
1664     get_limits(s, 16*mb_x, 16*mb_y);
1665
1666     c->skip=0;
1667
1668     if (s->codec_id == AV_CODEC_ID_MPEG4 && s->next_picture.f.mbskip_table[xy]) {
1669         int score= direct_search(s, mb_x, mb_y); //FIXME just check 0,0
1670
1671         score= ((unsigned)(score*score + 128*256))>>16;
1672         c->mc_mb_var_sum_temp += score;
1673         s->current_picture.mc_mb_var[mb_y*s->mb_stride + mb_x] = score; //FIXME use SSE
1674         s->mb_type[mb_y*s->mb_stride + mb_x]= CANDIDATE_MB_TYPE_DIRECT0;
1675
1676         return;
1677     }
1678
1679     if(c->avctx->me_threshold){
1680         int vard= check_input_motion(s, mb_x, mb_y, 0);
1681
1682         if((vard+128)>>8 < c->avctx->me_threshold){
1683 //            pix = c->src[0][0];
1684 //            sum = s->dsp.pix_sum(pix, s->linesize);
1685 //            varc = s->dsp.pix_norm1(pix, s->linesize) - (((unsigned)(sum*sum))>>8) + 500;
1686
1687 //            pic->mb_var   [s->mb_stride * mb_y + mb_x] = (varc+128)>>8;
1688              s->current_picture.mc_mb_var[s->mb_stride * mb_y + mb_x] = (vard+128)>>8;
1689 /*            pic->mb_mean  [s->mb_stride * mb_y + mb_x] = (sum+128)>>8;
1690             c->mb_var_sum_temp    += (varc+128)>>8;*/
1691             c->mc_mb_var_sum_temp += (vard+128)>>8;
1692 /*            if (vard <= 64<<8 || vard < varc) {
1693                 c->scene_change_score+= ff_sqrt(vard) - ff_sqrt(varc);
1694             }else{
1695                 c->scene_change_score+= s->qscale * s->avctx->scenechange_factor;
1696             }*/
1697             return;
1698         }
1699         if((vard+128)>>8 < c->avctx->mb_threshold){
1700             type= s->mb_type[mb_y*s->mb_stride + mb_x];
1701             if(type == CANDIDATE_MB_TYPE_DIRECT){
1702                 direct_search(s, mb_x, mb_y);
1703             }
1704             if(type == CANDIDATE_MB_TYPE_FORWARD || type == CANDIDATE_MB_TYPE_BIDIR){
1705                 c->skip=0;
1706                 ff_estimate_motion_b(s, mb_x, mb_y, s->b_forw_mv_table, 0, s->f_code);
1707             }
1708             if(type == CANDIDATE_MB_TYPE_BACKWARD || type == CANDIDATE_MB_TYPE_BIDIR){
1709                 c->skip=0;
1710                 ff_estimate_motion_b(s, mb_x, mb_y, s->b_back_mv_table, 2, s->b_code);
1711             }
1712             if(type == CANDIDATE_MB_TYPE_FORWARD_I || type == CANDIDATE_MB_TYPE_BIDIR_I){
1713                 c->skip=0;
1714                 c->current_mv_penalty= c->mv_penalty[s->f_code] + MAX_MV;
1715                 interlaced_search(s, 0,
1716                                         s->b_field_mv_table[0], s->b_field_select_table[0],
1717                                         s->b_forw_mv_table[xy][0], s->b_forw_mv_table[xy][1], 1);
1718             }
1719             if(type == CANDIDATE_MB_TYPE_BACKWARD_I || type == CANDIDATE_MB_TYPE_BIDIR_I){
1720                 c->skip=0;
1721                 c->current_mv_penalty= c->mv_penalty[s->b_code] + MAX_MV;
1722                 interlaced_search(s, 2,
1723                                         s->b_field_mv_table[1], s->b_field_select_table[1],
1724                                         s->b_back_mv_table[xy][0], s->b_back_mv_table[xy][1], 1);
1725             }
1726             return;
1727         }
1728     }
1729
1730     if (s->codec_id == AV_CODEC_ID_MPEG4)
1731         dmin= direct_search(s, mb_x, mb_y);
1732     else
1733         dmin= INT_MAX;
1734 //FIXME penalty stuff for non mpeg4
1735     c->skip=0;
1736     fmin= ff_estimate_motion_b(s, mb_x, mb_y, s->b_forw_mv_table, 0, s->f_code) + 3*penalty_factor;
1737
1738     c->skip=0;
1739     bmin= ff_estimate_motion_b(s, mb_x, mb_y, s->b_back_mv_table, 2, s->b_code) + 2*penalty_factor;
1740     av_dlog(s, " %d %d ", s->b_forw_mv_table[xy][0], s->b_forw_mv_table[xy][1]);
1741
1742     c->skip=0;
1743     fbmin= bidir_refine(s, mb_x, mb_y) + penalty_factor;
1744     av_dlog(s, "%d %d %d %d\n", dmin, fmin, bmin, fbmin);
1745
1746     if(s->flags & CODEC_FLAG_INTERLACED_ME){
1747 //FIXME mb type penalty
1748         c->skip=0;
1749         c->current_mv_penalty= c->mv_penalty[s->f_code] + MAX_MV;
1750         fimin= interlaced_search(s, 0,
1751                                  s->b_field_mv_table[0], s->b_field_select_table[0],
1752                                  s->b_forw_mv_table[xy][0], s->b_forw_mv_table[xy][1], 0);
1753         c->current_mv_penalty= c->mv_penalty[s->b_code] + MAX_MV;
1754         bimin= interlaced_search(s, 2,
1755                                  s->b_field_mv_table[1], s->b_field_select_table[1],
1756                                  s->b_back_mv_table[xy][0], s->b_back_mv_table[xy][1], 0);
1757     }else
1758         fimin= bimin= INT_MAX;
1759
1760     {
1761         int score= fmin;
1762         type = CANDIDATE_MB_TYPE_FORWARD;
1763
1764         if (dmin <= score){
1765             score = dmin;
1766             type = CANDIDATE_MB_TYPE_DIRECT;
1767         }
1768         if(bmin<score){
1769             score=bmin;
1770             type= CANDIDATE_MB_TYPE_BACKWARD;
1771         }
1772         if(fbmin<score){
1773             score=fbmin;
1774             type= CANDIDATE_MB_TYPE_BIDIR;
1775         }
1776         if(fimin<score){
1777             score=fimin;
1778             type= CANDIDATE_MB_TYPE_FORWARD_I;
1779         }
1780         if(bimin<score){
1781             score=bimin;
1782             type= CANDIDATE_MB_TYPE_BACKWARD_I;
1783         }
1784
1785         score= ((unsigned)(score*score + 128*256))>>16;
1786         c->mc_mb_var_sum_temp += score;
1787         s->current_picture.mc_mb_var[mb_y*s->mb_stride + mb_x] = score; //FIXME use SSE
1788     }
1789
1790     if(c->avctx->mb_decision > FF_MB_DECISION_SIMPLE){
1791         type= CANDIDATE_MB_TYPE_FORWARD | CANDIDATE_MB_TYPE_BACKWARD | CANDIDATE_MB_TYPE_BIDIR | CANDIDATE_MB_TYPE_DIRECT;
1792         if(fimin < INT_MAX)
1793             type |= CANDIDATE_MB_TYPE_FORWARD_I;
1794         if(bimin < INT_MAX)
1795             type |= CANDIDATE_MB_TYPE_BACKWARD_I;
1796         if(fimin < INT_MAX && bimin < INT_MAX){
1797             type |= CANDIDATE_MB_TYPE_BIDIR_I;
1798         }
1799          //FIXME something smarter
1800         if(dmin>256*256*16) type&= ~CANDIDATE_MB_TYPE_DIRECT; //do not try direct mode if it is invalid for this MB
1801         if(s->codec_id == AV_CODEC_ID_MPEG4 && type&CANDIDATE_MB_TYPE_DIRECT && s->flags&CODEC_FLAG_MV0 && *(uint32_t*)s->b_direct_mv_table[xy])
1802             type |= CANDIDATE_MB_TYPE_DIRECT0;
1803     }
1804
1805     s->mb_type[mb_y*s->mb_stride + mb_x]= type;
1806 }
1807
1808 /* find best f_code for ME which do unlimited searches */
1809 int ff_get_best_fcode(MpegEncContext * s, int16_t (*mv_table)[2], int type)
1810 {
1811     if(s->me_method>=ME_EPZS){
1812         int score[8];
1813         int i, y, range= s->avctx->me_range ? s->avctx->me_range : (INT_MAX/2);
1814         uint8_t * fcode_tab= s->fcode_tab;
1815         int best_fcode=-1;
1816         int best_score=-10000000;
1817
1818         if(s->msmpeg4_version)
1819             range= FFMIN(range, 16);
1820         else if(s->codec_id == AV_CODEC_ID_MPEG2VIDEO && s->avctx->strict_std_compliance >= FF_COMPLIANCE_NORMAL)
1821             range= FFMIN(range, 256);
1822
1823         for(i=0; i<8; i++) score[i]= s->mb_num*(8-i);
1824
1825         for(y=0; y<s->mb_height; y++){
1826             int x;
1827             int xy= y*s->mb_stride;
1828             for(x=0; x<s->mb_width; x++){
1829                 if(s->mb_type[xy] & type){
1830                     int mx= mv_table[xy][0];
1831                     int my= mv_table[xy][1];
1832                     int fcode= FFMAX(fcode_tab[mx + MAX_MV],
1833                                      fcode_tab[my + MAX_MV]);
1834                     int j;
1835
1836                         if(mx >= range || mx < -range ||
1837                            my >= range || my < -range)
1838                             continue;
1839
1840                     for(j=0; j<fcode && j<8; j++){
1841                         if(s->pict_type==AV_PICTURE_TYPE_B || s->current_picture.mc_mb_var[xy] < s->current_picture.mb_var[xy])
1842                             score[j]-= 170;
1843                     }
1844                 }
1845                 xy++;
1846             }
1847         }
1848
1849         for(i=1; i<8; i++){
1850             if(score[i] > best_score){
1851                 best_score= score[i];
1852                 best_fcode= i;
1853             }
1854         }
1855
1856         return best_fcode;
1857     }else{
1858         return 1;
1859     }
1860 }
1861
1862 void ff_fix_long_p_mvs(MpegEncContext * s)
1863 {
1864     MotionEstContext * const c= &s->me;
1865     const int f_code= s->f_code;
1866     int y, range;
1867     assert(s->pict_type==AV_PICTURE_TYPE_P);
1868
1869     range = (((s->out_format == FMT_MPEG1 || s->msmpeg4_version) ? 8 : 16) << f_code);
1870
1871     assert(range <= 16 || !s->msmpeg4_version);
1872     assert(range <=256 || !(s->codec_id == AV_CODEC_ID_MPEG2VIDEO && s->avctx->strict_std_compliance >= FF_COMPLIANCE_NORMAL));
1873
1874     if(c->avctx->me_range && range > c->avctx->me_range) range= c->avctx->me_range;
1875
1876     if(s->flags&CODEC_FLAG_4MV){
1877         const int wrap= s->b8_stride;
1878
1879         /* clip / convert to intra 8x8 type MVs */
1880         for(y=0; y<s->mb_height; y++){
1881             int xy= y*2*wrap;
1882             int i= y*s->mb_stride;
1883             int x;
1884
1885             for(x=0; x<s->mb_width; x++){
1886                 if(s->mb_type[i]&CANDIDATE_MB_TYPE_INTER4V){
1887                     int block;
1888                     for(block=0; block<4; block++){
1889                         int off= (block& 1) + (block>>1)*wrap;
1890                         int mx = s->current_picture.f.motion_val[0][ xy + off ][0];
1891                         int my = s->current_picture.f.motion_val[0][ xy + off ][1];
1892
1893                         if(   mx >=range || mx <-range
1894                            || my >=range || my <-range){
1895                             s->mb_type[i] &= ~CANDIDATE_MB_TYPE_INTER4V;
1896                             s->mb_type[i] |= CANDIDATE_MB_TYPE_INTRA;
1897                             s->current_picture.f.mb_type[i] = CANDIDATE_MB_TYPE_INTRA;
1898                         }
1899                     }
1900                 }
1901                 xy+=2;
1902                 i++;
1903             }
1904         }
1905     }
1906 }
1907
1908 /**
1909  *
1910  * @param truncate 1 for truncation, 0 for using intra
1911  */
1912 void ff_fix_long_mvs(MpegEncContext * s, uint8_t *field_select_table, int field_select,
1913                      int16_t (*mv_table)[2], int f_code, int type, int truncate)
1914 {
1915     MotionEstContext * const c= &s->me;
1916     int y, h_range, v_range;
1917
1918     // RAL: 8 in MPEG-1, 16 in MPEG-4
1919     int range = (((s->out_format == FMT_MPEG1 || s->msmpeg4_version) ? 8 : 16) << f_code);
1920
1921     if(c->avctx->me_range && range > c->avctx->me_range) range= c->avctx->me_range;
1922
1923     h_range= range;
1924     v_range= field_select_table ? range>>1 : range;
1925
1926     /* clip / convert to intra 16x16 type MVs */
1927     for(y=0; y<s->mb_height; y++){
1928         int x;
1929         int xy= y*s->mb_stride;
1930         for(x=0; x<s->mb_width; x++){
1931             if (s->mb_type[xy] & type){    // RAL: "type" test added...
1932                 if(field_select_table==NULL || field_select_table[xy] == field_select){
1933                     if(   mv_table[xy][0] >=h_range || mv_table[xy][0] <-h_range
1934                        || mv_table[xy][1] >=v_range || mv_table[xy][1] <-v_range){
1935
1936                         if(truncate){
1937                             if     (mv_table[xy][0] > h_range-1) mv_table[xy][0]=  h_range-1;
1938                             else if(mv_table[xy][0] < -h_range ) mv_table[xy][0]= -h_range;
1939                             if     (mv_table[xy][1] > v_range-1) mv_table[xy][1]=  v_range-1;
1940                             else if(mv_table[xy][1] < -v_range ) mv_table[xy][1]= -v_range;
1941                         }else{
1942                             s->mb_type[xy] &= ~type;
1943                             s->mb_type[xy] |= CANDIDATE_MB_TYPE_INTRA;
1944                             mv_table[xy][0]=
1945                             mv_table[xy][1]= 0;
1946                         }
1947                     }
1948                 }
1949             }
1950             xy++;
1951         }
1952     }
1953 }