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