]> git.sesse.net Git - ffmpeg/blob - libavcodec/motion_est.c
1ba246ae5cdc06fed9118802f246c0972b7dff3c
[ffmpeg] / libavcodec / motion_est.c
1 /*
2  * Motion estimation 
3  * Copyright (c) 2000,2001 Gerard Lantau.
4  * 
5  *
6  * This program is free software; you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License as published by
8  * the Free Software Foundation; either version 2 of the License, or
9  * (at your option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with this program; if not, write to the Free Software
18  * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
19  *
20  * new Motion Estimation (X1/EPZS) by Michael Niedermayer <michaelni@gmx.at>
21  */
22 #include <stdlib.h>
23 #include <stdio.h>
24 #include "avcodec.h"
25 #include "dsputil.h"
26 #include "mpegvideo.h"
27
28 #define ABS(a) ((a)>0 ? (a) : -(a))
29 #define MAX(a,b) ((a) > (b) ? (a) : (b))
30 #define INTER_BIAS      257
31
32 static int halfpel_motion_search(MpegEncContext * s,
33                                   int *mx_ptr, int *my_ptr, int dmin,
34                                   int xmin, int ymin, int xmax, int ymax,
35                                   int pred_x, int pred_y, uint8_t *ref_picture);
36
37 static int pix_sum(UINT8 * pix, int line_size)
38 {
39     int s, i, j;
40
41     s = 0;
42     for (i = 0; i < 16; i++) {
43         for (j = 0; j < 16; j += 8) {
44             s += pix[0];
45             s += pix[1];
46             s += pix[2];
47             s += pix[3];
48             s += pix[4];
49             s += pix[5];
50             s += pix[6];
51             s += pix[7];
52             pix += 8;
53         }
54         pix += line_size - 16;
55     }
56     return s;
57 }
58
59 static int pix_dev(UINT8 * pix, int line_size, int mean)
60 {
61     int s, i, j;
62
63     s = 0;
64     for (i = 0; i < 16; i++) {
65         for (j = 0; j < 16; j += 8) {
66             s += ABS(pix[0]-mean);
67             s += ABS(pix[1]-mean);
68             s += ABS(pix[2]-mean);
69             s += ABS(pix[3]-mean);
70             s += ABS(pix[4]-mean);
71             s += ABS(pix[5]-mean);
72             s += ABS(pix[6]-mean);
73             s += ABS(pix[7]-mean);
74             pix += 8;
75         }
76         pix += line_size - 16;
77     }
78     return s;
79 }
80
81 static int pix_norm1(UINT8 * pix, int line_size)
82 {
83     int s, i, j;
84     UINT32 *sq = squareTbl + 256;
85
86     s = 0;
87     for (i = 0; i < 16; i++) {
88         for (j = 0; j < 16; j += 8) {
89             s += sq[pix[0]];
90             s += sq[pix[1]];
91             s += sq[pix[2]];
92             s += sq[pix[3]];
93             s += sq[pix[4]];
94             s += sq[pix[5]];
95             s += sq[pix[6]];
96             s += sq[pix[7]];
97             pix += 8;
98         }
99         pix += line_size - 16;
100     }
101     return s;
102 }
103
104 static int pix_norm(UINT8 * pix1, UINT8 * pix2, int line_size)
105 {
106     int s, i, j;
107     UINT32 *sq = squareTbl + 256;
108
109     s = 0;
110     for (i = 0; i < 16; i++) {
111         for (j = 0; j < 16; j += 8) {
112             s += sq[pix1[0] - pix2[0]];
113             s += sq[pix1[1] - pix2[1]];
114             s += sq[pix1[2] - pix2[2]];
115             s += sq[pix1[3] - pix2[3]];
116             s += sq[pix1[4] - pix2[4]];
117             s += sq[pix1[5] - pix2[5]];
118             s += sq[pix1[6] - pix2[6]];
119             s += sq[pix1[7] - pix2[7]];
120             pix1 += 8;
121             pix2 += 8;
122         }
123         pix1 += line_size - 16;
124         pix2 += line_size - 16;
125     }
126     return s;
127 }
128
129 static void no_motion_search(MpegEncContext * s,
130                              int *mx_ptr, int *my_ptr)
131 {
132     *mx_ptr = 16 * s->mb_x;
133     *my_ptr = 16 * s->mb_y;
134 }
135
136 static int full_motion_search(MpegEncContext * s,
137                               int *mx_ptr, int *my_ptr, int range,
138                               int xmin, int ymin, int xmax, int ymax, uint8_t *ref_picture)
139 {
140     int x1, y1, x2, y2, xx, yy, x, y;
141     int mx, my, dmin, d;
142     UINT8 *pix;
143
144     xx = 16 * s->mb_x;
145     yy = 16 * s->mb_y;
146     x1 = xx - range + 1;        /* we loose one pixel to avoid boundary pb with half pixel pred */
147     if (x1 < xmin)
148         x1 = xmin;
149     x2 = xx + range - 1;
150     if (x2 > xmax)
151         x2 = xmax;
152     y1 = yy - range + 1;
153     if (y1 < ymin)
154         y1 = ymin;
155     y2 = yy + range - 1;
156     if (y2 > ymax)
157         y2 = ymax;
158     pix = s->new_picture[0] + (yy * s->linesize) + xx;
159     dmin = 0x7fffffff;
160     mx = 0;
161     my = 0;
162     for (y = y1; y <= y2; y++) {
163         for (x = x1; x <= x2; x++) {
164             d = pix_abs16x16(pix, ref_picture + (y * s->linesize) + x,
165                              s->linesize);
166             if (d < dmin ||
167                 (d == dmin &&
168                  (abs(x - xx) + abs(y - yy)) <
169                  (abs(mx - xx) + abs(my - yy)))) {
170                 dmin = d;
171                 mx = x;
172                 my = y;
173             }
174         }
175     }
176
177     *mx_ptr = mx;
178     *my_ptr = my;
179
180 #if 0
181     if (*mx_ptr < -(2 * range) || *mx_ptr >= (2 * range) ||
182         *my_ptr < -(2 * range) || *my_ptr >= (2 * range)) {
183         fprintf(stderr, "error %d %d\n", *mx_ptr, *my_ptr);
184     }
185 #endif
186     return dmin;
187 }
188
189
190 static int log_motion_search(MpegEncContext * s,
191                              int *mx_ptr, int *my_ptr, int range,
192                              int xmin, int ymin, int xmax, int ymax, uint8_t *ref_picture)
193 {
194     int x1, y1, x2, y2, xx, yy, x, y;
195     int mx, my, dmin, d;
196     UINT8 *pix;
197
198     xx = s->mb_x << 4;
199     yy = s->mb_y << 4;
200
201     /* Left limit */
202     x1 = xx - range;
203     if (x1 < xmin)
204         x1 = xmin;
205
206     /* Right limit */
207     x2 = xx + range;
208     if (x2 > xmax)
209         x2 = xmax;
210
211     /* Upper limit */
212     y1 = yy - range;
213     if (y1 < ymin)
214         y1 = ymin;
215
216     /* Lower limit */
217     y2 = yy + range;
218     if (y2 > ymax)
219         y2 = ymax;
220
221     pix = s->new_picture[0] + (yy * s->linesize) + xx;
222     dmin = 0x7fffffff;
223     mx = 0;
224     my = 0;
225
226     do {
227         for (y = y1; y <= y2; y += range) {
228             for (x = x1; x <= x2; x += range) {
229                 d = pix_abs16x16(pix, ref_picture + (y * s->linesize) + x, s->linesize);
230                 if (d < dmin || (d == dmin && (abs(x - xx) + abs(y - yy)) < (abs(mx - xx) + abs(my - yy)))) {
231                     dmin = d;
232                     mx = x;
233                     my = y;
234                 }
235             }
236         }
237
238         range = range >> 1;
239
240         x1 = mx - range;
241         if (x1 < xmin)
242             x1 = xmin;
243
244         x2 = mx + range;
245         if (x2 > xmax)
246             x2 = xmax;
247
248         y1 = my - range;
249         if (y1 < ymin)
250             y1 = ymin;
251
252         y2 = my + range;
253         if (y2 > ymax)
254             y2 = ymax;
255
256     } while (range >= 1);
257
258 #ifdef DEBUG
259     fprintf(stderr, "log       - MX: %d\tMY: %d\n", mx, my);
260 #endif
261     *mx_ptr = mx;
262     *my_ptr = my;
263     return dmin;
264 }
265
266 static int phods_motion_search(MpegEncContext * s,
267                                int *mx_ptr, int *my_ptr, int range,
268                                int xmin, int ymin, int xmax, int ymax, uint8_t *ref_picture)
269 {
270     int x1, y1, x2, y2, xx, yy, x, y, lastx, d;
271     int mx, my, dminx, dminy;
272     UINT8 *pix;
273
274     xx = s->mb_x << 4;
275     yy = s->mb_y << 4;
276
277     /* Left limit */
278     x1 = xx - range;
279     if (x1 < xmin)
280         x1 = xmin;
281
282     /* Right limit */
283     x2 = xx + range;
284     if (x2 > xmax)
285         x2 = xmax;
286
287     /* Upper limit */
288     y1 = yy - range;
289     if (y1 < ymin)
290         y1 = ymin;
291
292     /* Lower limit */
293     y2 = yy + range;
294     if (y2 > ymax)
295         y2 = ymax;
296
297     pix = s->new_picture[0] + (yy * s->linesize) + xx;
298     mx = 0;
299     my = 0;
300
301     x = xx;
302     y = yy;
303     do {
304         dminx = 0x7fffffff;
305         dminy = 0x7fffffff;
306
307         lastx = x;
308         for (x = x1; x <= x2; x += range) {
309             d = pix_abs16x16(pix, ref_picture + (y * s->linesize) + x, s->linesize);
310             if (d < dminx || (d == dminx && (abs(x - xx) + abs(y - yy)) < (abs(mx - xx) + abs(my - yy)))) {
311                 dminx = d;
312                 mx = x;
313             }
314         }
315
316         x = lastx;
317         for (y = y1; y <= y2; y += range) {
318             d = pix_abs16x16(pix, ref_picture + (y * s->linesize) + x, s->linesize);
319             if (d < dminy || (d == dminy && (abs(x - xx) + abs(y - yy)) < (abs(mx - xx) + abs(my - yy)))) {
320                 dminy = d;
321                 my = y;
322             }
323         }
324
325         range = range >> 1;
326
327         x = mx;
328         y = my;
329         x1 = mx - range;
330         if (x1 < xmin)
331             x1 = xmin;
332
333         x2 = mx + range;
334         if (x2 > xmax)
335             x2 = xmax;
336
337         y1 = my - range;
338         if (y1 < ymin)
339             y1 = ymin;
340
341         y2 = my + range;
342         if (y2 > ymax)
343             y2 = ymax;
344
345     } while (range >= 1);
346
347 #ifdef DEBUG
348     fprintf(stderr, "phods     - MX: %d\tMY: %d\n", mx, my);
349 #endif
350
351     /* half pixel search */
352     *mx_ptr = mx;
353     *my_ptr = my;
354     return dminy;
355 }
356
357
358 #define Z_THRESHOLD 256
359
360 #define CHECK_MV(x,y)\
361 {\
362     d = pix_abs16x16(new_pic, old_pic + (x) + (y)*pic_stride, pic_stride);\
363     d += (mv_penalty[((x)<<shift)-pred_x] + mv_penalty[((y)<<shift)-pred_y])*quant;\
364     if(d<dmin){\
365         best[0]=x;\
366         best[1]=y;\
367         dmin=d;\
368     }\
369 }
370
371 #define CHECK_MV_DIR(x,y,new_dir)\
372 {\
373     d = pix_abs16x16(new_pic, old_pic + (x) + (y)*pic_stride, pic_stride);\
374     d += (mv_penalty[((x)<<shift)-pred_x] + mv_penalty[((y)<<shift)-pred_y])*quant;\
375     if(d<dmin){\
376         best[0]=x;\
377         best[1]=y;\
378         dmin=d;\
379         next_dir= new_dir;\
380     }\
381 }
382
383 #define CHECK_MV4(x,y)\
384 {\
385     d = pix_abs8x8(new_pic, old_pic + (x) + (y)*pic_stride, pic_stride);\
386     d += (mv_penalty[((x)<<shift)-pred_x] + mv_penalty[((y)<<shift)-pred_y])*quant;\
387     if(d<dmin){\
388         best[0]=x;\
389         best[1]=y;\
390         dmin=d;\
391     }\
392 }
393
394 #define CHECK_MV4_DIR(x,y,new_dir)\
395 {\
396     d = pix_abs8x8(new_pic, old_pic + (x) + (y)*pic_stride, pic_stride);\
397     d += (mv_penalty[((x)<<shift)-pred_x] + mv_penalty[((y)<<shift)-pred_y])*quant;\
398     if(d<dmin){\
399         best[0]=x;\
400         best[1]=y;\
401         dmin=d;\
402         next_dir= new_dir;\
403     }\
404 }
405
406
407 #define check(x,y,S,v)\
408 if( (x)<(xmin<<(S)) ) printf("%d %d %d %d xmin" #v, (x), (y), s->mb_x, s->mb_y);\
409 if( (x)>(xmax<<(S)) ) printf("%d %d %d %d xmax" #v, (x), (y), s->mb_x, s->mb_y);\
410 if( (y)<(ymin<<(S)) ) printf("%d %d %d %d ymin" #v, (x), (y), s->mb_x, s->mb_y);\
411 if( (y)>(ymax<<(S)) ) printf("%d %d %d %d ymax" #v, (x), (y), s->mb_x, s->mb_y);\
412
413
414 static inline int small_diamond_search(MpegEncContext * s, int *best, int dmin,
415                                        UINT8 *new_pic, UINT8 *old_pic, int pic_stride,
416                                        int pred_x, int pred_y, UINT16 *mv_penalty, int quant,
417                                        int xmin, int ymin, int xmax, int ymax, int shift)
418 {
419     int next_dir=-1;
420
421     for(;;){
422         int d;
423         const int dir= next_dir;
424         const int x= best[0];
425         const int y= best[1];
426         next_dir=-1;
427
428 //printf("%d", dir);
429         if(dir!=2 && x>xmin) CHECK_MV_DIR(x-1, y  , 0)
430         if(dir!=3 && y>ymin) CHECK_MV_DIR(x  , y-1, 1)
431         if(dir!=0 && x<xmax) CHECK_MV_DIR(x+1, y  , 2)
432         if(dir!=1 && y<ymax) CHECK_MV_DIR(x  , y+1, 3)
433
434         if(next_dir==-1){
435             return dmin;
436         }
437     }
438
439 /*    for(;;){
440         int d;
441         const int x= best[0];
442         const int y= best[1];
443         const int last_min=dmin;
444         if(x>xmin) CHECK_MV(x-1, y  )
445         if(y>xmin) CHECK_MV(x  , y-1)
446         if(x<xmax) CHECK_MV(x+1, y  )
447         if(y<xmax) CHECK_MV(x  , y+1)
448         if(x>xmin && y>ymin) CHECK_MV(x-1, y-1)
449         if(x>xmin && y<ymax) CHECK_MV(x-1, y+1)
450         if(x<xmax && y>ymin) CHECK_MV(x+1, y-1)
451         if(x<xmax && y<ymax) CHECK_MV(x+1, y+1)
452         if(x-1>xmin) CHECK_MV(x-2, y  )
453         if(y-1>xmin) CHECK_MV(x  , y-2)
454         if(x+1<xmax) CHECK_MV(x+2, y  )
455         if(y+1<xmax) CHECK_MV(x  , y+2)
456         if(x-1>xmin && y-1>ymin) CHECK_MV(x-2, y-2)
457         if(x-1>xmin && y+1<ymax) CHECK_MV(x-2, y+2)
458         if(x+1<xmax && y-1>ymin) CHECK_MV(x+2, y-2)
459         if(x+1<xmax && y+1<ymax) CHECK_MV(x+2, y+2)
460         if(dmin==last_min) return dmin;
461     }
462     */
463 }
464
465 static inline int small_diamond_search4MV(MpegEncContext * s, int *best, int dmin,
466                                        UINT8 *new_pic, UINT8 *old_pic, int pic_stride,
467                                        int pred_x, int pred_y, UINT16 *mv_penalty, int quant,
468                                        int xmin, int ymin, int xmax, int ymax, int shift)
469 {
470     int next_dir=-1;
471
472     for(;;){
473         int d;
474         const int dir= next_dir;
475         const int x= best[0];
476         const int y= best[1];
477         next_dir=-1;
478
479 //printf("%d", dir);
480         if(dir!=2 && x>xmin) CHECK_MV4_DIR(x-1, y  , 0)
481         if(dir!=3 && y>ymin) CHECK_MV4_DIR(x  , y-1, 1)
482         if(dir!=0 && x<xmax) CHECK_MV4_DIR(x+1, y  , 2)
483         if(dir!=1 && y<ymax) CHECK_MV4_DIR(x  , y+1, 3)
484
485         if(next_dir==-1){
486             return dmin;
487         }
488     }
489 }
490
491 static inline int snake_search(MpegEncContext * s, int *best, int dmin,
492                                        UINT8 *new_pic, UINT8 *old_pic, int pic_stride,
493                                        int pred_x, int pred_y, UINT16 *mv_penalty, int quant,
494                                        int xmin, int ymin, int xmax, int ymax, int shift)
495 {
496     int dir=0;
497     int c=1;
498     static int x_dir[8]= {1,1,0,-1,-1,-1, 0, 1};
499     static int y_dir[8]= {0,1,1, 1, 0,-1,-1,-1};
500     int fails=0;
501     int last_d[2]={dmin, dmin};
502
503 /*static int good=0;
504 static int bad=0;
505 static int point=0;
506
507 point++;
508 if(256*256*256*64%point==0)
509 {
510     printf("%d %d %d\n", good, bad, point);
511 }*/
512
513     for(;;){
514         int x= best[0];
515         int y= best[1];
516         int d;
517         x+=x_dir[dir];
518         y+=y_dir[dir];
519         if(x>=xmin && x<=xmax && y>=ymin && y<=ymax){
520             d = pix_abs16x16(new_pic, old_pic + (x) + (y)*pic_stride, pic_stride);
521             d += (mv_penalty[((x)<<shift)-pred_x] + mv_penalty[((y)<<shift)-pred_y])*quant;
522         }else{
523             d = dmin + 10000; //FIXME smarter boundary handling
524         }
525         if(d<dmin){
526             best[0]=x;
527             best[1]=y;
528             dmin=d;
529
530             if(last_d[1] - last_d[0] > last_d[0] - d) c= -c;
531             dir+=c;
532
533             fails=0;
534 //good++;
535             last_d[1]=last_d[0];
536             last_d[0]=d;
537         }else{
538 //bad++;
539             if(fails){
540                 if(fails>=3) return dmin;
541             }else{
542                 c= -c;
543             }
544             dir+=c*2;
545             fails++;
546         }
547         dir&=7;
548     }
549 }
550
551 static int epzs_motion_search(MpegEncContext * s,
552                              int *mx_ptr, int *my_ptr,
553                              int P[5][2], int pred_x, int pred_y,
554                              int xmin, int ymin, int xmax, int ymax, uint8_t * ref_picture)
555 {
556     int best[2]={0, 0};
557     int d, dmin; 
558     UINT8 *new_pic, *old_pic;
559     const int pic_stride= s->linesize;
560     const int pic_xy= (s->mb_y*pic_stride + s->mb_x)*16;
561     UINT16 *mv_penalty= s->mv_penalty[s->f_code] + MAX_MV; // f_code of the prev frame
562     int quant= s->qscale; // qscale of the prev frame
563     const int shift= 1+s->quarter_sample;
564
565     new_pic = s->new_picture[0] + pic_xy;
566     old_pic = ref_picture + pic_xy;
567    
568     dmin = pix_abs16x16(new_pic, old_pic, pic_stride);
569     if(dmin<Z_THRESHOLD){
570         *mx_ptr= 0;
571         *my_ptr= 0;
572 //printf("Z");
573         return dmin;
574     }
575
576     /* first line */
577     if ((s->mb_y == 0 || s->first_slice_line || s->first_gob_line)) {
578         CHECK_MV(P[1][0]>>shift, P[1][1]>>shift)
579     }else{
580         CHECK_MV(P[4][0]>>shift, P[4][1]>>shift)
581         if(dmin<Z_THRESHOLD){
582             *mx_ptr= P[4][0]>>shift;
583             *my_ptr= P[4][1]>>shift;
584 //printf("M\n");
585             return dmin;
586         }
587         CHECK_MV(P[1][0]>>shift, P[1][1]>>shift)
588         CHECK_MV(P[2][0]>>shift, P[2][1]>>shift)
589         CHECK_MV(P[3][0]>>shift, P[3][1]>>shift)
590     }
591     CHECK_MV(P[0][0]>>shift, P[0][1]>>shift)
592
593 //check(best[0],best[1],0, b0)
594     if(s->me_method==ME_EPZS)
595         dmin= small_diamond_search(s, best, dmin, new_pic, old_pic, pic_stride, 
596                                    pred_x, pred_y, mv_penalty, quant, xmin, ymin, xmax, ymax, shift);
597     else
598         dmin=         snake_search(s, best, dmin, new_pic, old_pic, pic_stride, 
599                                    pred_x, pred_y, mv_penalty, quant, xmin, ymin, xmax, ymax, shift);
600 //check(best[0],best[1],0, b1)
601     *mx_ptr= best[0];
602     *my_ptr= best[1];    
603
604 //    printf("%d %d %d \n", best[0], best[1], dmin);
605     return dmin;
606 }
607
608 static int epzs_motion_search4(MpegEncContext * s, int block,
609                              int *mx_ptr, int *my_ptr,
610                              int P[6][2], int pred_x, int pred_y,
611                              int xmin, int ymin, int xmax, int ymax, uint8_t *ref_picture)
612 {
613     int best[2]={0, 0};
614     int d, dmin; 
615     UINT8 *new_pic, *old_pic;
616     const int pic_stride= s->linesize;
617     const int pic_xy= ((s->mb_y*2 + (block>>1))*pic_stride + s->mb_x*2 + (block&1))*8;
618     UINT16 *mv_penalty= s->mv_penalty[s->f_code] + MAX_MV; // f_code of the prev frame
619     int quant= s->qscale; // qscale of the prev frame
620     const int shift= 1+s->quarter_sample;
621
622     new_pic = s->new_picture[0] + pic_xy;
623     old_pic = ref_picture + pic_xy;
624    
625     dmin = pix_abs8x8(new_pic, old_pic, pic_stride);
626
627     /* first line */
628     if ((s->mb_y == 0 || s->first_slice_line || s->first_gob_line) && block<2) {
629         CHECK_MV4(P[1][0]>>shift, P[1][1]>>shift)
630     }else{
631         CHECK_MV4(P[4][0]>>shift, P[4][1]>>shift)
632         if(dmin<Z_THRESHOLD){
633             *mx_ptr= P[4][0]>>shift;
634             *my_ptr= P[4][1]>>shift;
635 //printf("M\n");
636             return dmin;
637         }
638         CHECK_MV4(P[1][0]>>shift, P[1][1]>>shift)
639         CHECK_MV4(P[2][0]>>shift, P[2][1]>>shift)
640         CHECK_MV4(P[3][0]>>shift, P[3][1]>>shift)
641     }
642     CHECK_MV4(P[0][0]>>shift, P[0][1]>>shift)
643     CHECK_MV4(P[5][0]>>shift, P[5][1]>>shift)
644
645 //check(best[0],best[1],0, b0)
646     dmin= small_diamond_search4MV(s, best, dmin, new_pic, old_pic, pic_stride, 
647                                    pred_x, pred_y, mv_penalty, quant, xmin, ymin, xmax, ymax, shift);
648 //check(best[0],best[1],0, b1)
649     *mx_ptr= best[0];
650     *my_ptr= best[1];    
651
652 //    printf("%d %d %d \n", best[0], best[1], dmin);
653     return dmin;
654 }
655
656 #define CHECK_HALF_MV(suffix, x, y) \
657     d= pix_abs16x16_ ## suffix(pix, ptr+((x)>>1), s->linesize);\
658     d += (mv_penalty[pen_x + x] + mv_penalty[pen_y + y])*quant;\
659     if(d<dminh){\
660         dminh= d;\
661         mx= mx1 + x;\
662         my= my1 + y;\
663     }
664
665 #define CHECK_HALF_MV4(suffix, x, y) \
666     d= pix_abs8x8_ ## suffix(pix, ptr+((x)>>1), s->linesize);\
667     d += (mv_penalty[pen_x + x] + mv_penalty[pen_y + y])*quant;\
668     if(d<dminh){\
669         dminh= d;\
670         mx= mx1 + x;\
671         my= my1 + y;\
672     }
673     
674 /* The idea would be to make half pel ME after Inter/Intra decision to 
675    save time. */
676 static inline int halfpel_motion_search(MpegEncContext * s,
677                                   int *mx_ptr, int *my_ptr, int dmin,
678                                   int xmin, int ymin, int xmax, int ymax,
679                                   int pred_x, int pred_y, uint8_t *ref_picture)
680 {
681     UINT16 *mv_penalty= s->mv_penalty[s->f_code] + MAX_MV; // f_code of the prev frame
682     const int quant= s->qscale;
683     int pen_x, pen_y;
684     int mx, my, mx1, my1, d, xx, yy, dminh;
685     UINT8 *pix, *ptr;
686
687     mx = *mx_ptr;
688     my = *my_ptr;
689     ptr = ref_picture + (my * s->linesize) + mx;
690
691     xx = 16 * s->mb_x;
692     yy = 16 * s->mb_y;
693     pix =  s->new_picture[0] + (yy * s->linesize) + xx;
694     
695     dminh = dmin;
696
697     if (mx > xmin && mx < xmax && 
698         my > ymin && my < ymax) {
699
700         mx= mx1= 2*(mx - xx);
701         my= my1= 2*(my - yy);
702         if(dmin < Z_THRESHOLD && mx==0 && my==0){
703             *mx_ptr = 0;
704             *my_ptr = 0;
705             return dmin;
706         }
707         
708         pen_x= pred_x + mx;
709         pen_y= pred_y + my;
710
711         ptr-= s->linesize;
712         CHECK_HALF_MV(xy2, -1, -1)
713         CHECK_HALF_MV(y2 ,  0, -1)
714         CHECK_HALF_MV(xy2, +1, -1)
715         
716         ptr+= s->linesize;
717         CHECK_HALF_MV(x2 , -1,  0)
718         CHECK_HALF_MV(x2 , +1,  0)
719         CHECK_HALF_MV(xy2, -1, +1)
720         CHECK_HALF_MV(y2 ,  0, +1)
721         CHECK_HALF_MV(xy2, +1, +1)
722
723     }else{
724         mx= 2*(mx - xx);
725         my= 2*(my - yy);
726     }
727
728     *mx_ptr = mx;
729     *my_ptr = my;
730     return dminh;
731 }
732
733 static inline void halfpel_motion_search4(MpegEncContext * s,
734                                   int *mx_ptr, int *my_ptr, int dmin,
735                                   int xmin, int ymin, int xmax, int ymax,
736                                   int pred_x, int pred_y, int block_x, int block_y,
737                                   uint8_t *ref_picture)
738 {
739     UINT16 *mv_penalty= s->mv_penalty[s->f_code] + MAX_MV; // f_code of the prev frame
740     const int quant= s->qscale;
741     int pen_x, pen_y;
742     int mx, my, mx1, my1, d, xx, yy, dminh;
743     UINT8 *pix, *ptr;
744
745     xx = 8 * block_x;
746     yy = 8 * block_y;
747     pix =  s->new_picture[0] + (yy * s->linesize) + xx;
748     
749     mx = *mx_ptr;
750     my = *my_ptr;
751     ptr = ref_picture + ((yy+my) * s->linesize) + xx + mx;
752
753     dminh = dmin;
754
755     if (mx > xmin && mx < xmax && 
756         my > ymin && my < ymax) {
757
758         mx= mx1= 2*mx;
759         my= my1= 2*my;
760         if(dmin < Z_THRESHOLD && mx==0 && my==0){
761             *mx_ptr = 0;
762             *my_ptr = 0;
763             return;
764         }
765         
766         pen_x= pred_x + mx;
767         pen_y= pred_y + my;
768
769         ptr-= s->linesize;
770         CHECK_HALF_MV4(xy2, -1, -1)
771         CHECK_HALF_MV4(y2 ,  0, -1)
772         CHECK_HALF_MV4(xy2, +1, -1)
773         
774         ptr+= s->linesize;
775         CHECK_HALF_MV4(x2 , -1,  0)
776         CHECK_HALF_MV4(x2 , +1,  0)
777         CHECK_HALF_MV4(xy2, -1, +1)
778         CHECK_HALF_MV4(y2 ,  0, +1)
779         CHECK_HALF_MV4(xy2, +1, +1)
780
781     }else{
782         mx*=2;
783         my*=2;
784     }
785
786     *mx_ptr = mx;
787     *my_ptr = my;
788 }
789
790 static inline void set_p_mv_tables(MpegEncContext * s, int mx, int my)
791 {
792     const int xy= s->mb_x + 1 + (s->mb_y + 1)*(s->mb_width + 2);
793     
794     s->p_mv_table[xy][0] = mx;
795     s->p_mv_table[xy][1] = my;
796
797     /* has allready been set to the 4 MV if 4MV is done */
798     if(!(s->flags&CODEC_FLAG_4MV)){
799         int mot_xy= s->block_index[0];
800
801         s->motion_val[mot_xy  ][0]= mx;
802         s->motion_val[mot_xy  ][1]= my;
803         s->motion_val[mot_xy+1][0]= mx;
804         s->motion_val[mot_xy+1][1]= my;
805
806         mot_xy += s->block_wrap[0];
807         s->motion_val[mot_xy  ][0]= mx;
808         s->motion_val[mot_xy  ][1]= my;
809         s->motion_val[mot_xy+1][0]= mx;
810         s->motion_val[mot_xy+1][1]= my;
811     }
812 }
813
814 static inline void get_limits(MpegEncContext *s, int *range, int *xmin, int *ymin, int *xmax, int *ymax, int f_code)
815 {
816     *range = 8 * (1 << (f_code - 1));
817     /* XXX: temporary kludge to avoid overflow for msmpeg4 */
818     if (s->out_format == FMT_H263 && !s->h263_msmpeg4)
819         *range *= 2;
820
821     if (s->unrestricted_mv) {
822         *xmin = -16;
823         *ymin = -16;
824         if (s->h263_plus)
825             *range *= 2;
826         if(s->avctx==NULL || s->avctx->codec->id!=CODEC_ID_MPEG4){
827             *xmax = s->mb_width*16;
828             *ymax = s->mb_height*16;
829         }else {
830             /* XXX: dunno if this is correct but ffmpeg4 decoder wont like it otherwise 
831                     (cuz the drawn edge isnt large enough))*/
832             *xmax = s->width;
833             *ymax = s->height;
834         }
835     } else {
836         *xmin = 0;
837         *ymin = 0;
838         *xmax = s->mb_width*16 - 16;
839         *ymax = s->mb_height*16 - 16;
840     }
841 }
842
843 void ff_estimate_p_frame_motion(MpegEncContext * s,
844                                 int mb_x, int mb_y)
845 {
846     UINT8 *pix, *ppix;
847     int sum, varc, vard, mx, my, range, dmin, xx, yy;
848     int xmin, ymin, xmax, ymax;
849     int rel_xmin, rel_ymin, rel_xmax, rel_ymax;
850     int pred_x=0, pred_y=0;
851     int P[6][2];
852     const int shift= 1+s->quarter_sample;
853     int mb_type=0;
854     uint8_t *ref_picture= s->last_picture[0];
855
856     get_limits(s, &range, &xmin, &ymin, &xmax, &ymax, s->f_code);
857
858     switch(s->me_method) {
859     case ME_ZERO:
860     default:
861         no_motion_search(s, &mx, &my);
862         dmin = 0;
863         break;
864     case ME_FULL:
865         dmin = full_motion_search(s, &mx, &my, range, xmin, ymin, xmax, ymax, ref_picture);
866         break;
867     case ME_LOG:
868         dmin = log_motion_search(s, &mx, &my, range / 2, xmin, ymin, xmax, ymax, ref_picture);
869         break;
870     case ME_PHODS:
871         dmin = phods_motion_search(s, &mx, &my, range / 2, xmin, ymin, xmax, ymax, ref_picture);
872         break;
873     case ME_X1:
874     case ME_EPZS:
875        {
876             const int mot_stride = s->block_wrap[0];
877             const int mot_xy = s->block_index[0];
878
879             rel_xmin= xmin - mb_x*16;
880             rel_xmax= xmax - mb_x*16;
881             rel_ymin= ymin - mb_y*16;
882             rel_ymax= ymax - mb_y*16;
883
884             P[0][0] = s->motion_val[mot_xy    ][0];
885             P[0][1] = s->motion_val[mot_xy    ][1];
886             P[1][0] = s->motion_val[mot_xy - 1][0];
887             P[1][1] = s->motion_val[mot_xy - 1][1];
888             if(P[1][0] > (rel_xmax<<shift)) P[1][0]= (rel_xmax<<shift);
889
890             /* special case for first line */
891             if ((mb_y == 0 || s->first_slice_line || s->first_gob_line)) {
892                 P[4][0] = P[1][0];
893                 P[4][1] = P[1][1];
894             } else {
895                 P[2][0] = s->motion_val[mot_xy - mot_stride             ][0];
896                 P[2][1] = s->motion_val[mot_xy - mot_stride             ][1];
897                 P[3][0] = s->motion_val[mot_xy - mot_stride + 2         ][0];
898                 P[3][1] = s->motion_val[mot_xy - mot_stride + 2         ][1];
899                 if(P[2][1] > (rel_ymax<<shift)) P[2][1]= (rel_ymax<<shift);
900                 if(P[3][0] < (rel_xmin<<shift)) P[3][0]= (rel_xmin<<shift);
901                 if(P[3][1] > (rel_ymax<<shift)) P[3][1]= (rel_ymax<<shift);
902         
903                 P[4][0]= mid_pred(P[1][0], P[2][0], P[3][0]);
904                 P[4][1]= mid_pred(P[1][1], P[2][1], P[3][1]);
905             }
906             if(s->out_format == FMT_H263){
907                 pred_x = P[4][0];
908                 pred_y = P[4][1];
909             }else { /* mpeg1 at least */
910                 pred_x= P[1][0];
911                 pred_y= P[1][1];
912             }
913         }
914         dmin = epzs_motion_search(s, &mx, &my, P, pred_x, pred_y, rel_xmin, rel_ymin, rel_xmax, rel_ymax, ref_picture);
915  
916         mx+= mb_x*16;
917         my+= mb_y*16;
918         break;
919     }
920     
921     if(s->flags&CODEC_FLAG_4MV){
922         int block;
923
924         mb_type|= MB_TYPE_INTER4V;
925
926         for(block=0; block<4; block++){
927             int mx4, my4;
928             int pred_x4, pred_y4;
929             int dmin4;
930             static const int off[4]= {2, 1, 1, -1};
931             const int mot_stride = s->block_wrap[0];
932             const int mot_xy = s->block_index[block];
933             const int block_x= mb_x*2 + (block&1);
934             const int block_y= mb_y*2 + (block>>1);
935
936             const int rel_xmin4= xmin - block_x*8;
937             const int rel_xmax4= xmax - block_x*8 + 8;
938             const int rel_ymin4= ymin - block_y*8;
939             const int rel_ymax4= ymax - block_y*8 + 8;
940
941             P[0][0] = s->motion_val[mot_xy    ][0];
942             P[0][1] = s->motion_val[mot_xy    ][1];
943             P[1][0] = s->motion_val[mot_xy - 1][0];
944             P[1][1] = s->motion_val[mot_xy - 1][1];
945             if(P[1][0] > (rel_xmax4<<shift)) P[1][0]= (rel_xmax4<<shift);
946
947             /* special case for first line */
948             if ((mb_y == 0 || s->first_slice_line || s->first_gob_line) && block<2) {
949                 P[4][0] = P[1][0];
950                 P[4][1] = P[1][1];
951             } else {
952                 P[2][0] = s->motion_val[mot_xy - mot_stride             ][0];
953                 P[2][1] = s->motion_val[mot_xy - mot_stride             ][1];
954                 P[3][0] = s->motion_val[mot_xy - mot_stride + off[block]][0];
955                 P[3][1] = s->motion_val[mot_xy - mot_stride + off[block]][1];
956                 if(P[2][1] > (rel_ymax4<<shift)) P[2][1]= (rel_ymax4<<shift);
957                 if(P[3][0] < (rel_xmin4<<shift)) P[3][0]= (rel_xmin4<<shift);
958                 if(P[3][0] > (rel_xmax4<<shift)) P[3][0]= (rel_xmax4<<shift);
959                 if(P[3][1] > (rel_ymax4<<shift)) P[3][1]= (rel_ymax4<<shift);
960         
961                 P[4][0]= mid_pred(P[1][0], P[2][0], P[3][0]);
962                 P[4][1]= mid_pred(P[1][1], P[2][1], P[3][1]);
963             }
964             if(s->out_format == FMT_H263){
965                 pred_x4 = P[4][0];
966                 pred_y4 = P[4][1];
967             }else { /* mpeg1 at least */
968                 pred_x4= P[1][0];
969                 pred_y4= P[1][1];
970             }
971             P[5][0]= mx - mb_x*16;
972             P[5][1]= my - mb_y*16;
973
974             dmin4 = epzs_motion_search4(s, block, &mx4, &my4, P, pred_x4, pred_y4, rel_xmin4, rel_ymin4, rel_xmax4, rel_ymax4, ref_picture);
975
976             halfpel_motion_search4(s, &mx4, &my4, dmin4, rel_xmin4, rel_ymin4, rel_xmax4, rel_ymax4, 
977                                    pred_x4, pred_y4, block_x, block_y, ref_picture);
978      
979             s->motion_val[ s->block_index[block] ][0]= mx4;
980             s->motion_val[ s->block_index[block] ][1]= my4;
981         }
982     }
983
984     /* intra / predictive decision */
985     xx = mb_x * 16;
986     yy = mb_y * 16;
987
988     pix = s->new_picture[0] + (yy * s->linesize) + xx;
989     /* At this point (mx,my) are full-pell and the absolute displacement */
990     ppix = ref_picture + (my * s->linesize) + mx;
991     
992     sum = pix_sum(pix, s->linesize);
993 #if 0
994     varc = pix_dev(pix, s->linesize, (sum+128)>>8) + INTER_BIAS;
995     vard = pix_abs16x16(pix, ppix, s->linesize);
996 #else
997     sum= (sum+8)>>4;
998     varc = ((pix_norm1(pix, s->linesize) - sum*sum + 128 + 500)>>8);
999     vard = (pix_norm(pix, ppix, s->linesize)+128)>>8;
1000 #endif
1001
1002     s->mb_var[s->mb_width * mb_y + mb_x] = varc;
1003     s->avg_mb_var+= varc;
1004     s->mc_mb_var += vard;
1005
1006     
1007 #if 0
1008     printf("varc=%4d avg_var=%4d (sum=%4d) vard=%4d mx=%2d my=%2d\n",
1009            varc, s->avg_mb_var, sum, vard, mx - xx, my - yy);
1010 #endif
1011     if(s->flags&CODEC_FLAG_HQ){
1012         if (vard*2 + 200 > varc)
1013             mb_type|= MB_TYPE_INTRA;
1014         if (varc*2 + 200 > vard){
1015             mb_type|= MB_TYPE_INTER;
1016             halfpel_motion_search(s, &mx, &my, dmin, xmin, ymin, xmax, ymax, pred_x, pred_y, ref_picture);
1017         }else{
1018             mx = mx*2 - mb_x*32;
1019             my = my*2 - mb_y*32;
1020         }
1021     }else{
1022         if (vard <= 64 || vard < varc) {
1023             mb_type|= MB_TYPE_INTER;
1024             if (s->me_method != ME_ZERO) {
1025                 halfpel_motion_search(s, &mx, &my, dmin, xmin, ymin, xmax, ymax, pred_x, pred_y, ref_picture);
1026             } else {
1027                 mx -= 16 * mb_x;
1028                 my -= 16 * mb_y;
1029             }
1030 #if 0
1031             if (vard < 10) {
1032                 skip++;
1033                 fprintf(stderr,"\nEarly skip: %d vard: %2d varc: %5d dmin: %d", 
1034                                 skip, vard, varc, dmin);
1035             }
1036 #endif
1037         }else{
1038             mb_type|= MB_TYPE_INTRA;
1039             mx = 0;//mx*2 - 32 * mb_x;
1040             my = 0;//my*2 - 32 * mb_y;
1041         }
1042     }
1043
1044     s->mb_type[mb_y*s->mb_width + mb_x]= mb_type;
1045     set_p_mv_tables(s, mx, my);
1046 }
1047
1048 int ff_estimate_motion_b(MpegEncContext * s,
1049                        int mb_x, int mb_y, int16_t (*mv_table)[2], uint8_t *ref_picture, int f_code)
1050 {
1051     int mx, my, range, dmin;
1052     int xmin, ymin, xmax, ymax;
1053     int rel_xmin, rel_ymin, rel_xmax, rel_ymax;
1054     int pred_x=0, pred_y=0;
1055     int P[6][2];
1056     const int shift= 1+s->quarter_sample;
1057     const int mot_stride = s->mb_width + 2;
1058     const int mot_xy = (mb_y + 1)*mot_stride + mb_x + 1;
1059     
1060     get_limits(s, &range, &xmin, &ymin, &xmax, &ymax, f_code);
1061
1062     switch(s->me_method) {
1063     case ME_ZERO:
1064     default:
1065         no_motion_search(s, &mx, &my);
1066         dmin = 0;
1067         break;
1068     case ME_FULL:
1069         dmin = full_motion_search(s, &mx, &my, range, xmin, ymin, xmax, ymax, ref_picture);
1070         break;
1071     case ME_LOG:
1072         dmin = log_motion_search(s, &mx, &my, range / 2, xmin, ymin, xmax, ymax, ref_picture);
1073         break;
1074     case ME_PHODS:
1075         dmin = phods_motion_search(s, &mx, &my, range / 2, xmin, ymin, xmax, ymax, ref_picture);
1076         break;
1077     case ME_X1:
1078     case ME_EPZS:
1079        {
1080
1081             rel_xmin= xmin - mb_x*16;
1082             rel_xmax= xmax - mb_x*16;
1083             rel_ymin= ymin - mb_y*16;
1084             rel_ymax= ymax - mb_y*16;
1085
1086             P[0][0] = mv_table[mot_xy    ][0];
1087             P[0][1] = mv_table[mot_xy    ][1];
1088             P[1][0] = mv_table[mot_xy - 1][0];
1089             P[1][1] = mv_table[mot_xy - 1][1];
1090             if(P[1][0] > (rel_xmax<<shift)) P[1][0]= (rel_xmax<<shift);
1091
1092             /* special case for first line */
1093             if ((mb_y == 0 || s->first_slice_line || s->first_gob_line)) {
1094                 P[4][0] = P[1][0];
1095                 P[4][1] = P[1][1];
1096             } else {
1097                 P[2][0] = mv_table[mot_xy - mot_stride             ][0];
1098                 P[2][1] = mv_table[mot_xy - mot_stride             ][1];
1099                 P[3][0] = mv_table[mot_xy - mot_stride + 1         ][0];
1100                 P[3][1] = mv_table[mot_xy - mot_stride + 1         ][1];
1101                 if(P[2][1] > (rel_ymax<<shift)) P[2][1]= (rel_ymax<<shift);
1102                 if(P[3][0] < (rel_xmin<<shift)) P[3][0]= (rel_xmin<<shift);
1103                 if(P[3][1] > (rel_ymax<<shift)) P[3][1]= (rel_ymax<<shift);
1104         
1105                 P[4][0]= mid_pred(P[1][0], P[2][0], P[3][0]);
1106                 P[4][1]= mid_pred(P[1][1], P[2][1], P[3][1]);
1107             }
1108             pred_x= P[1][0];
1109             pred_y= P[1][1];
1110         }
1111         dmin = epzs_motion_search(s, &mx, &my, P, pred_x, pred_y, rel_xmin, rel_ymin, rel_xmax, rel_ymax, ref_picture);
1112  
1113         mx+= mb_x*16;
1114         my+= mb_y*16;
1115         break;
1116     }
1117     
1118     /* intra / predictive decision */
1119 //    xx = mb_x * 16;
1120 //    yy = mb_y * 16;
1121
1122 //    pix = s->new_picture[0] + (yy * s->linesize) + xx;
1123     /* At this point (mx,my) are full-pell and the absolute displacement */
1124 //    ppix = ref_picture + (my * s->linesize) + mx;
1125     
1126     dmin= halfpel_motion_search(s, &mx, &my, dmin, xmin, ymin, xmax, ymax, pred_x, pred_y, ref_picture);
1127
1128 //    s->mb_type[mb_y*s->mb_width + mb_x]= mb_type;
1129     mv_table[mot_xy][0]= mx;
1130     mv_table[mot_xy][1]= my;
1131     return dmin;
1132 }
1133
1134
1135 static inline int check_bidir_mv(MpegEncContext * s,
1136                    int mb_x, int mb_y,
1137                    int motion_fx, int motion_fy,
1138                    int motion_bx, int motion_by,
1139                    int pred_fx, int pred_fy,
1140                    int pred_bx, int pred_by)
1141 {
1142     //FIXME optimize?
1143     UINT16 *mv_penalty= s->mv_penalty[s->f_code] + MAX_MV; // f_code of the prev frame
1144     uint8_t *dest_y = s->me_scratchpad;
1145     uint8_t *ptr;
1146     int dxy;
1147     int src_x, src_y;
1148     int fbmin;
1149
1150     fbmin = (mv_penalty[motion_fx-pred_fx] + mv_penalty[motion_fy-pred_fy])*s->qscale;
1151
1152     dxy = ((motion_fy & 1) << 1) | (motion_fx & 1);
1153     src_x = mb_x * 16 + (motion_fx >> 1);
1154     src_y = mb_y * 16 + (motion_fy >> 1);
1155             
1156     ptr = s->last_picture[0] + (src_y * s->linesize) + src_x;
1157     put_pixels_tab[dxy](dest_y    , ptr    , s->linesize, 16);
1158     put_pixels_tab[dxy](dest_y + 8, ptr + 8, s->linesize, 16);
1159     
1160     fbmin += (mv_penalty[motion_bx-pred_bx] + mv_penalty[motion_by-pred_by])*s->qscale;
1161
1162     dxy = ((motion_by & 1) << 1) | (motion_bx & 1);
1163     src_x = mb_x * 16 + (motion_bx >> 1);
1164     src_y = mb_y * 16 + (motion_by >> 1);
1165             
1166     ptr = s->next_picture[0] + (src_y * s->linesize) + src_x;
1167     avg_pixels_tab[dxy](dest_y    , ptr    , s->linesize, 16);
1168     avg_pixels_tab[dxy](dest_y + 8, ptr + 8, s->linesize, 16);
1169     
1170     fbmin += pix_abs16x16(s->new_picture[0] + mb_x*16 + mb_y*16*s->linesize, dest_y, s->linesize);
1171     return fbmin;
1172 }
1173
1174 /* refine the bidir vectors in hq mode and return the score in both lq & hq mode*/
1175 static inline int bidir_refine(MpegEncContext * s,
1176                                   int mb_x, int mb_y)
1177 {
1178     const int mot_stride = s->mb_width + 2;
1179     const int xy = (mb_y + 1)*mot_stride + mb_x + 1;
1180     int fbmin;
1181     int pred_fx= s->b_bidir_forw_mv_table[xy-1][0];
1182     int pred_fy= s->b_bidir_forw_mv_table[xy-1][1];
1183     int pred_bx= s->b_bidir_back_mv_table[xy-1][0];
1184     int pred_by= s->b_bidir_back_mv_table[xy-1][1];
1185     int motion_fx= s->b_bidir_forw_mv_table[xy][0]= s->b_forw_mv_table[xy][0];
1186     int motion_fy= s->b_bidir_forw_mv_table[xy][1]= s->b_forw_mv_table[xy][1];
1187     int motion_bx= s->b_bidir_back_mv_table[xy][0]= s->b_back_mv_table[xy][0];
1188     int motion_by= s->b_bidir_back_mv_table[xy][1]= s->b_back_mv_table[xy][1];
1189
1190     //FIXME do refinement and add flag
1191     
1192     fbmin= check_bidir_mv(s, mb_x, mb_y, 
1193                           motion_fx, motion_fy,
1194                           motion_bx, motion_by,
1195                           pred_fx, pred_fy,
1196                           pred_bx, pred_by);
1197
1198    return fbmin;
1199 }
1200
1201 static inline int direct_search(MpegEncContext * s,
1202                                 int mb_x, int mb_y)
1203 {
1204     int P[6][2];
1205     const int mot_stride = s->mb_width + 2;
1206     const int mot_xy = (mb_y + 1)*mot_stride + mb_x + 1;
1207     int dmin, dmin2;
1208     int motion_fx, motion_fy, motion_bx, motion_by, motion_bx0, motion_by0;
1209     int motion_dx, motion_dy;
1210     const int motion_px= s->p_mv_table[mot_xy][0];
1211     const int motion_py= s->p_mv_table[mot_xy][1];
1212     const int time_pp= s->pp_time;
1213     const int time_bp= s->bp_time;
1214     const int time_pb= time_pp - time_bp;
1215     int bx, by;
1216     int mx, my, mx2, my2;
1217     uint8_t *ref_picture= s->me_scratchpad - (mb_x + 1 + (mb_y + 1)*s->linesize)*16;
1218     int16_t (*mv_table)[2]= s->b_direct_mv_table;
1219     uint16_t *mv_penalty= s->mv_penalty[s->f_code] + MAX_MV; // f_code of the prev frame
1220
1221     /* thanks to iso-mpeg the rounding is different for the zero vector, so we need to handle that ... */
1222     motion_fx= (motion_px*time_pb)/time_pp;
1223     motion_fy= (motion_py*time_pb)/time_pp;
1224     motion_bx0= (-motion_px*time_bp)/time_pp;
1225     motion_by0= (-motion_py*time_bp)/time_pp;
1226     motion_dx= motion_dy=0;
1227     dmin2= check_bidir_mv(s, mb_x, mb_y, 
1228                           motion_fx, motion_fy,
1229                           motion_bx0, motion_by0,
1230                           motion_fx, motion_fy,
1231                           motion_bx0, motion_by0) - s->qscale;
1232
1233     motion_bx= motion_fx - motion_px;
1234     motion_by= motion_fy - motion_py;
1235     for(by=-1; by<2; by++){
1236         for(bx=-1; bx<2; bx++){
1237             uint8_t *dest_y = s->me_scratchpad + (by+1)*s->linesize*16 + (bx+1)*16;
1238             uint8_t *ptr;
1239             int dxy;
1240             int src_x, src_y;
1241             const int width= s->width;
1242             const int height= s->height;
1243
1244             dxy = ((motion_fy & 1) << 1) | (motion_fx & 1);
1245             src_x = (mb_x + bx) * 16 + (motion_fx >> 1);
1246             src_y = (mb_y + by) * 16 + (motion_fy >> 1);
1247             src_x = clip(src_x, -16, width);
1248             if (src_x == width) dxy &= ~1;
1249             src_y = clip(src_y, -16, height);
1250             if (src_y == height) dxy &= ~2;
1251
1252             ptr = s->last_picture[0] + (src_y * s->linesize) + src_x;
1253             put_pixels_tab[dxy](dest_y    , ptr    , s->linesize, 16);
1254             put_pixels_tab[dxy](dest_y + 8, ptr + 8, s->linesize, 16);
1255
1256             dxy = ((motion_by & 1) << 1) | (motion_bx & 1);
1257             src_x = (mb_x + bx) * 16 + (motion_bx >> 1);
1258             src_y = (mb_y + by) * 16 + (motion_by >> 1);
1259             src_x = clip(src_x, -16, width);
1260             if (src_x == width) dxy &= ~1;
1261             src_y = clip(src_y, -16, height);
1262             if (src_y == height) dxy &= ~2;
1263
1264             avg_pixels_tab[dxy](dest_y    , ptr    , s->linesize, 16);
1265             avg_pixels_tab[dxy](dest_y + 8, ptr + 8, s->linesize, 16);
1266         }
1267     }
1268
1269     P[0][0] = mv_table[mot_xy    ][0];
1270     P[0][1] = mv_table[mot_xy    ][1];
1271     P[1][0] = mv_table[mot_xy - 1][0];
1272     P[1][1] = mv_table[mot_xy - 1][1];
1273
1274     /* special case for first line */
1275     if ((mb_y == 0 || s->first_slice_line || s->first_gob_line)) {
1276         P[4][0] = P[1][0];
1277         P[4][1] = P[1][1];
1278     } else {
1279         P[2][0] = mv_table[mot_xy - mot_stride             ][0];
1280         P[2][1] = mv_table[mot_xy - mot_stride             ][1];
1281         P[3][0] = mv_table[mot_xy - mot_stride + 1         ][0];
1282         P[3][1] = mv_table[mot_xy - mot_stride + 1         ][1];
1283     
1284         P[4][0]= mid_pred(P[1][0], P[2][0], P[3][0]);
1285         P[4][1]= mid_pred(P[1][1], P[2][1], P[3][1]);
1286     }
1287     dmin = epzs_motion_search(s, &mx, &my, P, 0, 0, -16, -16, 15, 15, ref_picture);
1288     if(mx==0 && my==0) dmin=99999999; // not representable, due to rounding stuff
1289     if(dmin2<dmin){ 
1290         dmin= dmin2;
1291         mx=0;
1292         my=0;
1293     }
1294 #if 1
1295     mx2= mx= mx*2; 
1296     my2= my= my*2;
1297     for(by=-1; by<2; by++){
1298         if(my2+by < -32) continue;
1299         for(bx=-1; bx<2; bx++){
1300             if(bx==0 && by==0) continue;
1301             if(mx2+bx < -32) continue;
1302             dmin2= check_bidir_mv(s, mb_x, mb_y, 
1303                           mx2+bx+motion_fx, my2+by+motion_fy,
1304                           mx2+bx+motion_bx, my2+by+motion_by,
1305                           mx2+bx+motion_fx, my2+by+motion_fy,
1306                           motion_bx, motion_by) - s->qscale;
1307             
1308             if(dmin2<dmin){
1309                 dmin=dmin2;
1310                 mx= mx2 + bx;
1311                 my= my2 + by;
1312             }
1313         }
1314     }
1315 #else
1316     mx*=2; my*=2;
1317 #endif
1318     if(mx==0 && my==0){
1319         motion_bx= motion_bx0;
1320         motion_by= motion_by0;
1321     }
1322
1323     s->b_direct_mv_table[mot_xy][0]= mx;
1324     s->b_direct_mv_table[mot_xy][1]= my;
1325     s->b_direct_forw_mv_table[mot_xy][0]= motion_fx + mx;
1326     s->b_direct_forw_mv_table[mot_xy][1]= motion_fy + my;
1327     s->b_direct_back_mv_table[mot_xy][0]= motion_bx + mx;
1328     s->b_direct_back_mv_table[mot_xy][1]= motion_by + my;
1329     return dmin;
1330 }
1331
1332 void ff_estimate_b_frame_motion(MpegEncContext * s,
1333                              int mb_x, int mb_y)
1334 {
1335     const int mot_stride = s->mb_width + 2;
1336     const int xy = (mb_y + 1)*mot_stride + mb_x + 1;
1337     const int quant= s->qscale;
1338     int fmin, bmin, dmin, fbmin;
1339     int type=0;
1340     int motion_fx, motion_fy, motion_bx, motion_by;
1341     
1342     dmin= direct_search(s, mb_x, mb_y);
1343
1344     fmin= ff_estimate_motion_b(s, mb_x, mb_y, s->b_forw_mv_table, s->last_picture[0], s->f_code);
1345     bmin= ff_estimate_motion_b(s, mb_x, mb_y, s->b_back_mv_table, s->next_picture[0], s->b_code) - quant;
1346 //printf(" %d %d ", s->b_forw_mv_table[xy][0], s->b_forw_mv_table[xy][1]);
1347
1348     fbmin= bidir_refine(s, mb_x, mb_y);
1349
1350     if(s->flags&CODEC_FLAG_HQ){
1351         type= MB_TYPE_FORWARD | MB_TYPE_BACKWARD | MB_TYPE_BIDIR | MB_TYPE_DIRECT;
1352     }else{
1353         int score= dmin;
1354         type=MB_TYPE_DIRECT;
1355         
1356         if(fmin<score){
1357             score=fmin;
1358             type= MB_TYPE_FORWARD; 
1359         }
1360         if(bmin<score){
1361             score=bmin;
1362             type= MB_TYPE_BACKWARD; 
1363         }
1364         if(fbmin<score){
1365             score=fbmin;
1366             type= MB_TYPE_BIDIR;
1367         }
1368         s->mc_mb_var += score;
1369     }
1370
1371     s->mb_type[mb_y*s->mb_width + mb_x]= type;
1372 }
1373
1374 /* find best f_code for ME which do unlimited searches */
1375 int ff_get_best_fcode(MpegEncContext * s, int16_t (*mv_table)[2], int type)
1376 {
1377     int f_code;
1378
1379     if(s->me_method>=ME_EPZS){
1380         int mv_num[8];
1381         int i, y;
1382         int loose=0;
1383         UINT8 * fcode_tab= s->fcode_tab;
1384
1385         for(i=0; i<8; i++) mv_num[i]=0;
1386
1387         for(y=0; y<s->mb_height; y++){
1388             int x;
1389             int xy= (y+1)* (s->mb_width+2) + 1;
1390             i= y*s->mb_width;
1391             for(x=0; x<s->mb_width; x++){
1392                 if(s->mb_type[i] & type){
1393                     mv_num[ fcode_tab[mv_table[xy][0] + MAX_MV] ]++;
1394                     mv_num[ fcode_tab[mv_table[xy][1] + MAX_MV] ]++;
1395 //printf("%d %d %d\n", s->mv_table[0][i], fcode_tab[s->mv_table[0][i] + MAX_MV], i);
1396                 }
1397                 i++;
1398                 xy++;
1399             }
1400         }
1401
1402         for(i=MAX_FCODE; i>1; i--){
1403             int threshold;
1404             loose+= mv_num[i];
1405
1406             if(s->pict_type==B_TYPE) threshold= 0;
1407             else                     threshold= s->mb_num/20; //FIXME 
1408             if(loose > threshold) break;
1409         }
1410 //    printf("fcode: %d type: %d\n", i, s->pict_type);
1411         return i;
1412 /*        for(i=0; i<=MAX_FCODE; i++){
1413             printf("%d ", mv_num[i]);
1414         }
1415         printf("\n");*/
1416     }else{
1417         return 1;
1418     }
1419 }
1420
1421 void ff_fix_long_p_mvs(MpegEncContext * s)
1422 {
1423     const int f_code= s->f_code;
1424     int y;
1425     UINT8 * fcode_tab= s->fcode_tab;
1426
1427     /* clip / convert to intra 16x16 type MVs */
1428     for(y=0; y<s->mb_height; y++){
1429         int x;
1430         int xy= (y+1)* (s->mb_width+2)+1;
1431         int i= y*s->mb_width;
1432         for(x=0; x<s->mb_width; x++){
1433             if(s->mb_type[i]&MB_TYPE_INTER){
1434                 if(   fcode_tab[s->p_mv_table[xy][0] + MAX_MV] > f_code
1435                    || fcode_tab[s->p_mv_table[xy][0] + MAX_MV] == 0
1436                    || fcode_tab[s->p_mv_table[xy][1] + MAX_MV] > f_code
1437                    || fcode_tab[s->p_mv_table[xy][1] + MAX_MV] == 0 ){
1438                     s->mb_type[i] &= ~MB_TYPE_INTER;
1439                     s->mb_type[i] |= MB_TYPE_INTRA;
1440                     s->p_mv_table[xy][0] = 0;
1441                     s->p_mv_table[xy][1] = 0;
1442                 }
1443             }
1444             xy++;
1445             i++;
1446         }
1447     }
1448
1449     if(s->flags&CODEC_FLAG_4MV){
1450         const int wrap= 2+ s->mb_width*2;
1451
1452         /* clip / convert to intra 8x8 type MVs */
1453         for(y=0; y<s->mb_height; y++){
1454             int xy= (y*2 + 1)*wrap + 1;
1455             int i= y*s->mb_width;
1456             int x;
1457
1458             for(x=0; x<s->mb_width; x++){
1459                 if(s->mb_type[i]&MB_TYPE_INTER4V){
1460                     int block;
1461                     for(block=0; block<4; block++){
1462                         int off= (block& 1) + (block>>1)*wrap;
1463                         int mx= s->motion_val[ xy + off ][0];
1464                         int my= s->motion_val[ xy + off ][1];
1465
1466                         if(   fcode_tab[mx + MAX_MV] > f_code
1467                            || fcode_tab[mx + MAX_MV] == 0
1468                            || fcode_tab[my + MAX_MV] > f_code
1469                            || fcode_tab[my + MAX_MV] == 0 ){
1470                             s->mb_type[i] &= ~MB_TYPE_INTER4V;
1471                             s->mb_type[i] |= MB_TYPE_INTRA;
1472                         }
1473                     }
1474                     xy+=2;
1475                     i++;
1476                 }
1477             }
1478         }
1479     }
1480 }
1481
1482 void ff_fix_long_b_mvs(MpegEncContext * s, int16_t (*mv_table)[2], int f_code, int type)
1483 {
1484     int y;
1485     UINT8 * fcode_tab= s->fcode_tab;
1486
1487     /* clip / convert to intra 16x16 type MVs */
1488     for(y=0; y<s->mb_height; y++){
1489         int x;
1490         int xy= (y+1)* (s->mb_width+2)+1;
1491         int i= y*s->mb_width;
1492         for(x=0; x<s->mb_width; x++){
1493             if(s->mb_type[i]&type){
1494                 if(   fcode_tab[mv_table[xy][0] + MAX_MV] > f_code
1495                    || fcode_tab[mv_table[xy][0] + MAX_MV] == 0
1496                    || fcode_tab[mv_table[xy][1] + MAX_MV] > f_code
1497                    || fcode_tab[mv_table[xy][1] + MAX_MV] == 0 ){
1498                     if(s->mb_type[i]&(~type)) s->mb_type[i] &= ~type;
1499                     else{
1500                         mv_table[xy][0] = 0;
1501                         mv_table[xy][1] = 0;
1502                         //this is certainly bad FIXME            
1503                     }
1504                 }
1505             }
1506             xy++;
1507             i++;
1508         }
1509     }
1510 }