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