]> git.sesse.net Git - ffmpeg/blob - libavcodec/mpegvideo.c
slow but accurate integer dct from IJG (should be ok with the LGPL as the old DCT...
[ffmpeg] / libavcodec / mpegvideo.c
1 /*
2  * The simplest mpeg encoder (well, it was the simplest!)
3  * Copyright (c) 2000,2001 Fabrice Bellard.
4  *
5  * This library is free software; you can redistribute it and/or
6  * modify it under the terms of the GNU Lesser General Public
7  * License as published by the Free Software Foundation; either
8  * version 2 of the License, or (at your option) any later version.
9  *
10  * This library is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13  * Lesser General Public License for more details.
14  *
15  * You should have received a copy of the GNU Lesser General Public
16  * License along with this library; if not, write to the Free Software
17  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
18  *
19  * 4MV & hq & b-frame encoding stuff by Michael Niedermayer <michaelni@gmx.at>
20  */
21 #include "avcodec.h"
22 #include "dsputil.h"
23 #include "mpegvideo.h"
24
25 #ifdef USE_FASTMEMCPY
26 #include "fastmemcpy.h"
27 #endif
28
29 static void encode_picture(MpegEncContext *s, int picture_number);
30 static void dct_unquantize_mpeg1_c(MpegEncContext *s, 
31                                    DCTELEM *block, int n, int qscale);
32 static void dct_unquantize_mpeg2_c(MpegEncContext *s,
33                                    DCTELEM *block, int n, int qscale);
34 static void dct_unquantize_h263_c(MpegEncContext *s, 
35                                   DCTELEM *block, int n, int qscale);
36 static void draw_edges_c(UINT8 *buf, int wrap, int width, int height, int w);
37 static int dct_quantize_c(MpegEncContext *s, DCTELEM *block, int n, int qscale, int *overflow);
38
39 void (*draw_edges)(UINT8 *buf, int wrap, int width, int height, int w)= draw_edges_c;
40 static void emulated_edge_mc(MpegEncContext *s, UINT8 *src, int linesize, int block_w, int block_h, 
41                                     int src_x, int src_y, int w, int h);
42
43 #define EDGE_WIDTH 16
44
45 /* enable all paranoid tests for rounding, overflows, etc... */
46 //#define PARANOID
47
48 //#define DEBUG
49
50
51 /* for jpeg fast DCT */
52 #define CONST_BITS 14
53
54 static const unsigned short aanscales[64] = {
55     /* precomputed values scaled up by 14 bits */
56     16384, 22725, 21407, 19266, 16384, 12873,  8867,  4520,
57     22725, 31521, 29692, 26722, 22725, 17855, 12299,  6270,
58     21407, 29692, 27969, 25172, 21407, 16819, 11585,  5906,
59     19266, 26722, 25172, 22654, 19266, 15137, 10426,  5315,
60     16384, 22725, 21407, 19266, 16384, 12873,  8867,  4520,
61     12873, 17855, 16819, 15137, 12873, 10114,  6967,  3552,
62     8867, 12299, 11585, 10426,  8867,  6967,  4799,  2446,
63     4520,  6270,  5906,  5315,  4520,  3552,  2446,  1247
64 };
65
66 static UINT8 h263_chroma_roundtab[16] = {
67     0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2,
68 };
69
70 static UINT16 default_mv_penalty[MAX_FCODE+1][MAX_MV*2+1];
71 static UINT8 default_fcode_tab[MAX_MV*2+1];
72
73 extern UINT8 zigzag_end[64];
74
75 /* default motion estimation */
76 int motion_estimation_method = ME_EPZS;
77
78 static void convert_matrix(MpegEncContext *s, int (*qmat)[64], uint16_t (*qmat16)[64], uint16_t (*qmat16_bias)[64],
79                            const UINT16 *quant_matrix, int bias)
80 {
81     int qscale;
82
83     for(qscale=1; qscale<32; qscale++){
84         int i;
85         if (s->fdct == ff_jpeg_fdct_islow) {
86             for(i=0;i<64;i++) {
87                 const int j= block_permute_op(i);
88                 /* 16 <= qscale * quant_matrix[i] <= 7905 */
89                 /* 19952         <= aanscales[i] * qscale * quant_matrix[i]           <= 249205026 */
90                 /* (1<<36)/19952 >= (1<<36)/(aanscales[i] * qscale * quant_matrix[i]) >= (1<<36)/249205026 */
91                 /* 3444240       >= (1<<36)/(aanscales[i] * qscale * quant_matrix[i]) >= 275 */
92                 
93                 qmat[qscale][j] = (int)((UINT64_C(1) << (QMAT_SHIFT-3)) / 
94                                 (qscale * quant_matrix[j]));
95             }
96         } else if (s->fdct == fdct_ifast) {
97             for(i=0;i<64;i++) {
98                 const int j= block_permute_op(i);
99                 /* 16 <= qscale * quant_matrix[i] <= 7905 */
100                 /* 19952         <= aanscales[i] * qscale * quant_matrix[i]           <= 249205026 */
101                 /* (1<<36)/19952 >= (1<<36)/(aanscales[i] * qscale * quant_matrix[i]) >= (1<<36)/249205026 */
102                 /* 3444240       >= (1<<36)/(aanscales[i] * qscale * quant_matrix[i]) >= 275 */
103                 
104                 qmat[qscale][j] = (int)((UINT64_C(1) << (QMAT_SHIFT + 11)) / 
105                                 (aanscales[i] * qscale * quant_matrix[j]));
106             }
107         } else {
108             for(i=0;i<64;i++) {
109                 /* We can safely suppose that 16 <= quant_matrix[i] <= 255
110                    So 16           <= qscale * quant_matrix[i]             <= 7905
111                    so (1<<19) / 16 >= (1<<19) / (qscale * quant_matrix[i]) >= (1<<19) / 7905
112                    so 32768        >= (1<<19) / (qscale * quant_matrix[i]) >= 67
113                 */
114                 qmat  [qscale][i] = (1 << QMAT_SHIFT_MMX) / (qscale * quant_matrix[i]);
115                 qmat16[qscale][i] = (1 << QMAT_SHIFT_MMX) / (qscale * quant_matrix[block_permute_op(i)]);
116
117                 if(qmat16[qscale][i]==0 || qmat16[qscale][i]==128*256) qmat16[qscale][i]=128*256-1;
118
119                 qmat16_bias[qscale][i]= ROUNDED_DIV(bias<<(16-QUANT_BIAS_SHIFT), qmat16[qscale][i]);
120             }
121         }
122     }
123 }
124 // move into common.c perhaps 
125 #define CHECKED_ALLOCZ(p, size)\
126 {\
127     p= av_mallocz(size);\
128     if(p==NULL){\
129         perror("malloc");\
130         goto fail;\
131     }\
132 }
133
134 /* init common structure for both encoder and decoder */
135 int MPV_common_init(MpegEncContext *s)
136 {
137     int c_size, i;
138     UINT8 *pict;
139
140     s->dct_unquantize_h263 = dct_unquantize_h263_c;
141     s->dct_unquantize_mpeg1 = dct_unquantize_mpeg1_c;
142     s->dct_unquantize_mpeg2 = dct_unquantize_mpeg2_c;
143     s->dct_quantize= dct_quantize_c;
144
145     if(s->avctx->dct_algo==FF_DCT_FASTINT)
146         s->fdct = fdct_ifast;
147     else
148         s->fdct = ff_jpeg_fdct_islow;
149         
150 #ifdef HAVE_MMX
151     MPV_common_init_mmx(s);
152 #endif
153 #ifdef ARCH_ALPHA
154     MPV_common_init_axp(s);
155 #endif
156
157     s->mb_width = (s->width + 15) / 16;
158     s->mb_height = (s->height + 15) / 16;
159     
160     /* set default edge pos, will be overriden in decode_header if needed */
161     s->h_edge_pos= s->mb_width*16;
162     s->v_edge_pos= s->mb_height*16;
163
164     s->mb_num = s->mb_width * s->mb_height;
165     if(!(s->flags&CODEC_FLAG_DR1)){
166       s->linesize   = s->mb_width * 16 + 2 * EDGE_WIDTH;
167       s->uvlinesize = s->mb_width * 8  +     EDGE_WIDTH;
168
169       for(i=0;i<3;i++) {
170         int w, h, shift, pict_start;
171
172         w = s->linesize;
173         h = s->mb_height * 16 + 2 * EDGE_WIDTH;
174         shift = (i == 0) ? 0 : 1;
175         c_size = (s->linesize>>shift) * (h >> shift);
176         pict_start = (s->linesize>>shift) * (EDGE_WIDTH >> shift) + (EDGE_WIDTH >> shift);
177
178         CHECKED_ALLOCZ(pict, c_size)
179         s->last_picture_base[i] = pict;
180         s->last_picture[i] = pict + pict_start;
181         if(i>0) memset(s->last_picture_base[i], 128, c_size);
182     
183         CHECKED_ALLOCZ(pict, c_size)
184         s->next_picture_base[i] = pict;
185         s->next_picture[i] = pict + pict_start;
186         if(i>0) memset(s->next_picture_base[i], 128, c_size);
187         
188         if (s->has_b_frames || s->codec_id==CODEC_ID_MPEG4) {
189         /* Note the MPEG4 stuff is here cuz of buggy encoders which dont set the low_delay flag but 
190            do low-delay encoding, so we cant allways distinguish b-frame containing streams from low_delay streams */
191             CHECKED_ALLOCZ(pict, c_size)
192             s->aux_picture_base[i] = pict;
193             s->aux_picture[i] = pict + pict_start;
194             if(i>0) memset(s->aux_picture_base[i], 128, c_size);
195         }
196       }
197       s->ip_buffer_count= 2;
198     }
199     
200     CHECKED_ALLOCZ(s->edge_emu_buffer, (s->width+64)*2*17*2); //(width + edge + align)*interlaced*MBsize*tolerance
201     
202     if (s->encoding) {
203         int j;
204         int mv_table_size= (s->mb_width+2)*(s->mb_height+2);
205         
206         CHECKED_ALLOCZ(s->mb_var   , s->mb_num * sizeof(INT16))
207         CHECKED_ALLOCZ(s->mc_mb_var, s->mb_num * sizeof(INT16))
208
209         /* Allocate MV tables */
210         CHECKED_ALLOCZ(s->p_mv_table            , mv_table_size * 2 * sizeof(INT16))
211         CHECKED_ALLOCZ(s->b_forw_mv_table       , mv_table_size * 2 * sizeof(INT16))
212         CHECKED_ALLOCZ(s->b_back_mv_table       , mv_table_size * 2 * sizeof(INT16))
213         CHECKED_ALLOCZ(s->b_bidir_forw_mv_table , mv_table_size * 2 * sizeof(INT16))
214         CHECKED_ALLOCZ(s->b_bidir_back_mv_table , mv_table_size * 2 * sizeof(INT16))
215         CHECKED_ALLOCZ(s->b_direct_forw_mv_table, mv_table_size * 2 * sizeof(INT16))
216         CHECKED_ALLOCZ(s->b_direct_back_mv_table, mv_table_size * 2 * sizeof(INT16))
217         CHECKED_ALLOCZ(s->b_direct_mv_table     , mv_table_size * 2 * sizeof(INT16))
218
219         CHECKED_ALLOCZ(s->me_scratchpad,  s->linesize*16*3*sizeof(uint8_t))
220         
221         CHECKED_ALLOCZ(s->me_map      , ME_MAP_SIZE*sizeof(uint32_t))
222         CHECKED_ALLOCZ(s->me_score_map, ME_MAP_SIZE*sizeof(uint16_t))
223
224         if(s->max_b_frames){
225             for(j=0; j<REORDER_BUFFER_SIZE; j++){
226                 int i;
227                 for(i=0;i<3;i++) {
228                     int w, h, shift;
229
230                     w = s->linesize;
231                     h = s->mb_height * 16;
232                     shift = (i == 0) ? 0 : 1;
233                     c_size = (w >> shift) * (h >> shift);
234
235                     CHECKED_ALLOCZ(pict, c_size);
236                     s->picture_buffer[j][i] = pict;
237                 }
238             }
239         }
240
241         if(s->codec_id==CODEC_ID_MPEG4){
242             CHECKED_ALLOCZ(s->tex_pb_buffer, PB_BUFFER_SIZE);
243             CHECKED_ALLOCZ(   s->pb2_buffer, PB_BUFFER_SIZE);
244         }
245         
246         CHECKED_ALLOCZ(s->avctx->stats_out, 256);
247     }
248     
249     if (s->out_format == FMT_H263 || s->encoding) {
250         int size;
251         /* Allocate MB type table */
252         CHECKED_ALLOCZ(s->mb_type  , s->mb_num * sizeof(UINT8))
253
254         /* MV prediction */
255         size = (2 * s->mb_width + 2) * (2 * s->mb_height + 2);
256         CHECKED_ALLOCZ(s->motion_val, size * 2 * sizeof(INT16));
257         
258         /* 4mv direct mode decoding table */
259         CHECKED_ALLOCZ(s->non_b_mv4_table, size * sizeof(UINT8))
260     }
261
262     if (s->h263_pred || s->h263_plus) {
263         int y_size, c_size, i, size;
264         
265         /* dc values */
266
267         y_size = (2 * s->mb_width + 2) * (2 * s->mb_height + 2);
268         c_size = (s->mb_width + 2) * (s->mb_height + 2);
269         size = y_size + 2 * c_size;
270         CHECKED_ALLOCZ(s->dc_val[0], size * sizeof(INT16));
271         s->dc_val[1] = s->dc_val[0] + y_size;
272         s->dc_val[2] = s->dc_val[1] + c_size;
273         for(i=0;i<size;i++)
274             s->dc_val[0][i] = 1024;
275
276         /* ac values */
277         CHECKED_ALLOCZ(s->ac_val[0], size * sizeof(INT16) * 16);
278         s->ac_val[1] = s->ac_val[0] + y_size;
279         s->ac_val[2] = s->ac_val[1] + c_size;
280         
281         /* cbp values */
282         CHECKED_ALLOCZ(s->coded_block, y_size);
283         
284         /* divx501 bitstream reorder buffer */
285         CHECKED_ALLOCZ(s->bitstream_buffer, BITSTREAM_BUFFER_SIZE);
286         
287         /* cbp, ac_pred, pred_dir */
288         CHECKED_ALLOCZ(s->cbp_table  , s->mb_num * sizeof(UINT8))
289         CHECKED_ALLOCZ(s->pred_dir_table, s->mb_num * sizeof(UINT8))
290     }
291     CHECKED_ALLOCZ(s->qscale_table  , s->mb_num * sizeof(UINT8))
292     
293     /* which mb is a intra block */
294     CHECKED_ALLOCZ(s->mbintra_table, s->mb_num);
295     memset(s->mbintra_table, 1, s->mb_num);
296     
297     /* default structure is frame */
298     s->picture_structure = PICT_FRAME;
299     
300     /* init macroblock skip table */
301     CHECKED_ALLOCZ(s->mbskip_table, s->mb_num);
302     
303     s->block= s->blocks[0];
304
305     s->context_initialized = 1;
306     return 0;
307  fail:
308     MPV_common_end(s);
309     return -1;
310 }
311
312
313 //extern int sads;
314
315 /* init common structure for both encoder and decoder */
316 void MPV_common_end(MpegEncContext *s)
317 {
318     int i;
319
320     av_freep(&s->mb_type);
321     av_freep(&s->mb_var);
322     av_freep(&s->mc_mb_var);
323     av_freep(&s->p_mv_table);
324     av_freep(&s->b_forw_mv_table);
325     av_freep(&s->b_back_mv_table);
326     av_freep(&s->b_bidir_forw_mv_table);
327     av_freep(&s->b_bidir_back_mv_table);
328     av_freep(&s->b_direct_forw_mv_table);
329     av_freep(&s->b_direct_back_mv_table);
330     av_freep(&s->b_direct_mv_table);
331     av_freep(&s->motion_val);
332     av_freep(&s->dc_val[0]);
333     av_freep(&s->ac_val[0]);
334     av_freep(&s->coded_block);
335     av_freep(&s->mbintra_table);
336     av_freep(&s->cbp_table);
337     av_freep(&s->pred_dir_table);
338     av_freep(&s->qscale_table);
339     av_freep(&s->me_scratchpad);
340     av_freep(&s->me_map);
341     av_freep(&s->me_score_map);
342     
343     av_freep(&s->mbskip_table);
344     av_freep(&s->bitstream_buffer);
345     av_freep(&s->tex_pb_buffer);
346     av_freep(&s->pb2_buffer);
347     av_freep(&s->edge_emu_buffer);
348     av_freep(&s->non_b_mv4_table);
349     av_freep(&s->avctx->stats_out);
350     
351     for(i=0;i<3;i++) {
352         int j;
353         if(!(s->flags&CODEC_FLAG_DR1)){
354             av_freep(&s->last_picture_base[i]);
355             av_freep(&s->next_picture_base[i]);
356             av_freep(&s->aux_picture_base[i]);
357         }
358         s->last_picture_base[i]=
359         s->next_picture_base[i]=
360         s->aux_picture_base [i] = NULL;
361         s->last_picture[i]=
362         s->next_picture[i]=
363         s->aux_picture [i] = NULL;
364
365         for(j=0; j<REORDER_BUFFER_SIZE; j++){
366             av_freep(&s->picture_buffer[j][i]);
367         }
368     }
369     s->context_initialized = 0;
370 }
371
372 /* init video encoder */
373 int MPV_encode_init(AVCodecContext *avctx)
374 {
375     MpegEncContext *s = avctx->priv_data;
376     int i;
377
378     avctx->pix_fmt = PIX_FMT_YUV420P;
379
380     s->bit_rate = avctx->bit_rate;
381     s->bit_rate_tolerance = avctx->bit_rate_tolerance;
382     s->frame_rate = avctx->frame_rate;
383     s->width = avctx->width;
384     s->height = avctx->height;
385     if(avctx->gop_size > 600){
386         fprintf(stderr, "Warning keyframe interval too large! reducing it ...\n");
387         avctx->gop_size=600;
388     }
389     s->gop_size = avctx->gop_size;
390     s->rtp_mode = avctx->rtp_mode;
391     s->rtp_payload_size = avctx->rtp_payload_size;
392     if (avctx->rtp_callback)
393         s->rtp_callback = avctx->rtp_callback;
394     s->qmin= avctx->qmin;
395     s->qmax= avctx->qmax;
396     s->max_qdiff= avctx->max_qdiff;
397     s->qcompress= avctx->qcompress;
398     s->qblur= avctx->qblur;
399     s->avctx = avctx;
400     s->aspect_ratio_info= avctx->aspect_ratio_info;
401     if (avctx->aspect_ratio_info == FF_ASPECT_EXTENDED)
402     {
403         s->aspected_width = avctx->aspected_width;
404         s->aspected_height = avctx->aspected_height;
405     }
406     s->flags= avctx->flags;
407     s->max_b_frames= avctx->max_b_frames;
408     s->b_frame_strategy= avctx->b_frame_strategy;
409     s->codec_id= avctx->codec->id;
410     s->luma_elim_threshold  = avctx->luma_elim_threshold;
411     s->chroma_elim_threshold= avctx->chroma_elim_threshold;
412     s->strict_std_compliance= avctx->strict_std_compliance;
413     s->data_partitioning= avctx->flags & CODEC_FLAG_PART;
414     s->mpeg_quant= avctx->mpeg_quant;
415
416     if (s->gop_size <= 1) {
417         s->intra_only = 1;
418         s->gop_size = 12;
419     } else {
420         s->intra_only = 0;
421     }
422     
423     /* ME algorithm */
424     if (avctx->me_method == 0)
425         /* For compatibility */
426         s->me_method = motion_estimation_method;
427     else
428         s->me_method = avctx->me_method;
429         
430     /* Fixed QSCALE */
431     s->fixed_qscale = (avctx->flags & CODEC_FLAG_QSCALE);
432     
433     switch(avctx->codec->id) {
434     case CODEC_ID_MPEG1VIDEO:
435         s->out_format = FMT_MPEG1;
436         avctx->delay=0; //FIXME not sure, should check the spec
437         break;
438     case CODEC_ID_MJPEG:
439         s->out_format = FMT_MJPEG;
440         s->intra_only = 1; /* force intra only for jpeg */
441         s->mjpeg_write_tables = 1; /* write all tables */
442         s->mjpeg_data_only_frames = 0; /* write all the needed headers */
443         s->mjpeg_vsample[0] = 2; /* set up default sampling factors */
444         s->mjpeg_vsample[1] = 1; /* the only currently supported values */
445         s->mjpeg_vsample[2] = 1; 
446         s->mjpeg_hsample[0] = 2;
447         s->mjpeg_hsample[1] = 1; 
448         s->mjpeg_hsample[2] = 1; 
449         if (mjpeg_init(s) < 0)
450             return -1;
451         avctx->delay=0;
452         break;
453     case CODEC_ID_H263:
454         if (h263_get_picture_format(s->width, s->height) == 7) {
455             printf("Input picture size isn't suitable for h263 codec! try h263+\n");
456             return -1;
457         }
458         s->out_format = FMT_H263;
459         avctx->delay=0;
460         break;
461     case CODEC_ID_H263P:
462         s->out_format = FMT_H263;
463         s->rtp_mode = 1;
464         s->rtp_payload_size = 1200; 
465         s->h263_plus = 1;
466         s->unrestricted_mv = 1;
467         s->h263_aic = 1;
468         
469         /* These are just to be sure */
470         s->umvplus = 0;
471         s->umvplus_dec = 0;
472         avctx->delay=0;
473         break;
474     case CODEC_ID_RV10:
475         s->out_format = FMT_H263;
476         s->h263_rv10 = 1;
477         avctx->delay=0;
478         break;
479     case CODEC_ID_MPEG4:
480         s->out_format = FMT_H263;
481         s->h263_pred = 1;
482         s->unrestricted_mv = 1;
483         s->has_b_frames= s->max_b_frames ? 1 : 0;
484         s->low_delay=0;
485         avctx->delay= s->low_delay ? 0 : (s->max_b_frames + 1); 
486         break;
487     case CODEC_ID_MSMPEG4V1:
488         s->out_format = FMT_H263;
489         s->h263_msmpeg4 = 1;
490         s->h263_pred = 1;
491         s->unrestricted_mv = 1;
492         s->msmpeg4_version= 1;
493         avctx->delay=0;
494         break;
495     case CODEC_ID_MSMPEG4V2:
496         s->out_format = FMT_H263;
497         s->h263_msmpeg4 = 1;
498         s->h263_pred = 1;
499         s->unrestricted_mv = 1;
500         s->msmpeg4_version= 2;
501         avctx->delay=0;
502         break;
503     case CODEC_ID_MSMPEG4V3:
504         s->out_format = FMT_H263;
505         s->h263_msmpeg4 = 1;
506         s->h263_pred = 1;
507         s->unrestricted_mv = 1;
508         s->msmpeg4_version= 3;
509         avctx->delay=0;
510         break;
511     case CODEC_ID_WMV1:
512         s->out_format = FMT_H263;
513         s->h263_msmpeg4 = 1;
514         s->h263_pred = 1;
515         s->unrestricted_mv = 1;
516         s->msmpeg4_version= 4;
517         avctx->delay=0;
518         break;
519     case CODEC_ID_WMV2:
520         s->out_format = FMT_H263;
521         s->h263_msmpeg4 = 1;
522         s->h263_pred = 1;
523         s->unrestricted_mv = 1;
524         s->msmpeg4_version= 5;
525         avctx->delay=0;
526         break;
527     default:
528         return -1;
529     }
530     
531     { /* set up some save defaults, some codecs might override them later */
532         static int done=0;
533         if(!done){
534             int i;
535             done=1;
536             memset(default_mv_penalty, 0, sizeof(UINT16)*(MAX_FCODE+1)*(2*MAX_MV+1));
537             memset(default_fcode_tab , 0, sizeof(UINT8)*(2*MAX_MV+1));
538
539             for(i=-16; i<16; i++){
540                 default_fcode_tab[i + MAX_MV]= 1;
541             }
542         }
543     }
544     s->mv_penalty= default_mv_penalty;
545     s->fcode_tab= default_fcode_tab;
546     s->y_dc_scale_table=
547     s->c_dc_scale_table= ff_mpeg1_dc_scale_table;
548  
549     if (s->out_format == FMT_H263)
550         h263_encode_init(s);
551     else if (s->out_format == FMT_MPEG1)
552         ff_mpeg1_encode_init(s);
553     if(s->msmpeg4_version)
554         ff_msmpeg4_encode_init(s);
555
556     /* dont use mv_penalty table for crap MV as it would be confused */
557     if (s->me_method < ME_EPZS) s->mv_penalty = default_mv_penalty;
558
559     s->encoding = 1;
560
561     /* init */
562     if (MPV_common_init(s) < 0)
563         return -1;
564     
565     /* init default q matrix */
566     for(i=0;i<64;i++) {
567         if(s->codec_id==CODEC_ID_MPEG4 && s->mpeg_quant){
568             s->intra_matrix[i] = ff_mpeg4_default_intra_matrix[i];
569             s->inter_matrix[i] = ff_mpeg4_default_non_intra_matrix[i];
570         }else if(s->out_format == FMT_H263){
571             s->intra_matrix[i] =
572             s->inter_matrix[i] = ff_mpeg1_default_non_intra_matrix[i];
573         }else{ /* mpeg1 */
574             s->intra_matrix[i] = ff_mpeg1_default_intra_matrix[i];
575             s->inter_matrix[i] = ff_mpeg1_default_non_intra_matrix[i];
576         }
577     }
578
579     /* precompute matrix */
580     /* for mjpeg, we do include qscale in the matrix */
581     if (s->out_format != FMT_MJPEG) {
582         convert_matrix(s, s->q_intra_matrix, s->q_intra_matrix16, s->q_intra_matrix16_bias, 
583                        s->intra_matrix, s->intra_quant_bias);
584         convert_matrix(s, s->q_inter_matrix, s->q_inter_matrix16, s->q_inter_matrix16_bias, 
585                        s->inter_matrix, s->inter_quant_bias);
586     }
587
588     if(ff_rate_control_init(s) < 0)
589         return -1;
590
591     s->picture_number = 0;
592     s->picture_in_gop_number = 0;
593     s->fake_picture_number = 0;
594     /* motion detector init */
595     s->f_code = 1;
596     s->b_code = 1;
597
598     return 0;
599 }
600
601 int MPV_encode_end(AVCodecContext *avctx)
602 {
603     MpegEncContext *s = avctx->priv_data;
604
605 #ifdef STATS
606     print_stats();
607 #endif
608
609     ff_rate_control_uninit(s);
610
611     MPV_common_end(s);
612     if (s->out_format == FMT_MJPEG)
613         mjpeg_close(s);
614       
615     return 0;
616 }
617
618 /* draw the edges of width 'w' of an image of size width, height */
619 //FIXME check that this is ok for mpeg4 interlaced
620 static void draw_edges_c(UINT8 *buf, int wrap, int width, int height, int w)
621 {
622     UINT8 *ptr, *last_line;
623     int i;
624
625     last_line = buf + (height - 1) * wrap;
626     for(i=0;i<w;i++) {
627         /* top and bottom */
628         memcpy(buf - (i + 1) * wrap, buf, width);
629         memcpy(last_line + (i + 1) * wrap, last_line, width);
630     }
631     /* left and right */
632     ptr = buf;
633     for(i=0;i<height;i++) {
634         memset(ptr - w, ptr[0], w);
635         memset(ptr + width, ptr[width-1], w);
636         ptr += wrap;
637     }
638     /* corners */
639     for(i=0;i<w;i++) {
640         memset(buf - (i + 1) * wrap - w, buf[0], w); /* top left */
641         memset(buf - (i + 1) * wrap + width, buf[width-1], w); /* top right */
642         memset(last_line + (i + 1) * wrap - w, last_line[0], w); /* top left */
643         memset(last_line + (i + 1) * wrap + width, last_line[width-1], w); /* top right */
644     }
645 }
646
647 /* generic function for encode/decode called before a frame is coded/decoded */
648 void MPV_frame_start(MpegEncContext *s, AVCodecContext *avctx)
649 {
650     int i;
651     UINT8 *tmp;
652
653     s->mb_skiped = 0;
654     s->decoding_error=0;
655     avctx->mbskip_table= s->mbskip_table;
656
657     if(avctx->flags&CODEC_FLAG_DR1){
658         avctx->get_buffer_callback(avctx, s->width, s->height, s->pict_type);
659
660         s->linesize  = avctx->dr_stride;
661         s->uvlinesize= avctx->dr_uvstride;
662         s->ip_buffer_count= avctx->dr_ip_buffer_count;
663     }
664     avctx->dr_ip_buffer_count= s->ip_buffer_count;
665     
666     if (s->pict_type == B_TYPE) {
667         for(i=0;i<3;i++) {
668             if(avctx->flags&CODEC_FLAG_DR1)
669                 s->aux_picture[i]= avctx->dr_buffer[i];
670             
671             //FIXME the following should never be needed, the decoder should drop b frames if no reference is available
672             if(s->next_picture[i]==NULL)
673                 s->next_picture[i]= s->aux_picture[i];
674             if(s->last_picture[i]==NULL)
675                 s->last_picture[i]= s->next_picture[i];
676
677             s->current_picture[i] = s->aux_picture[i];
678         }
679     } else {
680         for(i=0;i<3;i++) {
681             /* swap next and last */
682             if(avctx->flags&CODEC_FLAG_DR1)
683                 tmp= avctx->dr_buffer[i];
684             else
685                 tmp = s->last_picture[i];
686
687             s->last_picture[i] = s->next_picture[i];
688             s->next_picture[i] = tmp;
689             s->current_picture[i] = tmp;
690
691             if(s->last_picture[i]==NULL)
692                 s->last_picture[i]= s->next_picture[i];
693
694             s->last_dr_opaque= s->next_dr_opaque;
695             s->next_dr_opaque= avctx->dr_opaque_frame;
696
697             if(s->has_b_frames && s->last_dr_opaque && s->codec_id!=CODEC_ID_SVQ1)
698                 avctx->dr_opaque_frame= s->last_dr_opaque;
699             else
700                 avctx->dr_opaque_frame= s->next_dr_opaque;
701         }
702     }
703     /* set dequantizer, we cant do it during init as it might change for mpeg4
704        and we cant do it in the header decode as init isnt called for mpeg4 there yet */
705     if(s->out_format == FMT_H263){
706         if(s->mpeg_quant)
707             s->dct_unquantize = s->dct_unquantize_mpeg2;
708         else
709             s->dct_unquantize = s->dct_unquantize_h263;
710     }else 
711         s->dct_unquantize = s->dct_unquantize_mpeg1;
712 }
713
714 /* generic function for encode/decode called after a frame has been coded/decoded */
715 void MPV_frame_end(MpegEncContext *s)
716 {
717 //    if((s->picture_number%100)==0 && s->encoding) printf("sads:%d //\n", sads);
718
719     /* draw edge for correct motion prediction if outside */
720     if (s->pict_type != B_TYPE && !s->intra_only && !(s->flags&CODEC_FLAG_EMU_EDGE)) {
721         draw_edges(s->current_picture[0], s->linesize  , s->h_edge_pos   , s->v_edge_pos   , EDGE_WIDTH  );
722         draw_edges(s->current_picture[1], s->uvlinesize, s->h_edge_pos>>1, s->v_edge_pos>>1, EDGE_WIDTH/2);
723         draw_edges(s->current_picture[2], s->uvlinesize, s->h_edge_pos>>1, s->v_edge_pos>>1, EDGE_WIDTH/2);
724     }
725     emms_c();
726     
727     s->last_pict_type    = s->pict_type;
728     if(s->pict_type!=B_TYPE){
729         s->last_non_b_pict_type= s->pict_type;
730         s->num_available_buffers++;
731         if(s->num_available_buffers>2) s->num_available_buffers= 2;
732     }
733 }
734
735 /* reorder input for encoding */
736 void reorder_input(MpegEncContext *s, AVPicture *pict)
737 {
738     int i, j, index;
739             
740     if(s->max_b_frames > FF_MAX_B_FRAMES) s->max_b_frames= FF_MAX_B_FRAMES;
741
742 //        delay= s->max_b_frames+1; (or 0 if no b frames cuz decoder diff)
743
744     for(j=0; j<REORDER_BUFFER_SIZE-1; j++){
745         s->coded_order[j]= s->coded_order[j+1];
746     }
747     s->coded_order[j].picture[0]= s->coded_order[j].picture[1]= s->coded_order[j].picture[2]= NULL; //catch uninitalized buffers
748     s->coded_order[j].pict_type=0;
749
750     switch(s->input_pict_type){
751     default: 
752     case I_TYPE:
753     case S_TYPE:
754     case P_TYPE:
755         index= s->max_b_frames - s->b_frames_since_non_b;
756         s->b_frames_since_non_b=0;
757         break;            
758     case B_TYPE:
759         index= s->max_b_frames + 1;
760         s->b_frames_since_non_b++;
761         break;          
762     }
763 //printf("index:%d type:%d strides: %d %d\n", index, s->input_pict_type, pict->linesize[0], s->linesize);
764     if(   (index==0 || (s->flags&CODEC_FLAG_INPUT_PRESERVED))
765        && pict->linesize[0] == s->linesize
766        && pict->linesize[1] == s->uvlinesize
767        && pict->linesize[2] == s->uvlinesize){
768 //printf("ptr\n");
769         for(i=0; i<3; i++){
770             s->coded_order[index].picture[i]= pict->data[i];
771         }
772     }else{
773 //printf("copy\n");
774         for(i=0; i<3; i++){
775             uint8_t *src = pict->data[i];
776             uint8_t *dest;
777             int src_wrap = pict->linesize[i];
778             int dest_wrap = s->linesize;
779             int w = s->width;
780             int h = s->height;
781
782             if(index==0) dest= s->last_picture[i]+16; //is current_picture indeed but the switch hapens after reordering
783             else         dest= s->picture_buffer[s->picture_buffer_index][i];
784
785             if (i >= 1) {
786                 dest_wrap >>= 1;
787                 w >>= 1;
788                 h >>= 1;
789             }
790
791             s->coded_order[index].picture[i]= dest;
792             for(j=0;j<h;j++) {
793                 memcpy(dest, src, w);
794                 dest += dest_wrap;
795                 src += src_wrap;
796             }
797         }
798         if(index!=0){
799             s->picture_buffer_index++;
800             if(s->picture_buffer_index >= REORDER_BUFFER_SIZE) s->picture_buffer_index=0;
801         }
802     }
803     s->coded_order[index].pict_type = s->input_pict_type;
804     s->coded_order[index].qscale    = s->input_qscale;
805     s->coded_order[index].force_type= s->force_input_type;
806     s->coded_order[index].picture_in_gop_number= s->input_picture_in_gop_number;
807     s->coded_order[index].picture_number= s->input_picture_number;
808
809     for(i=0; i<3; i++){
810         s->new_picture[i]= s->coded_order[0].picture[i];
811     }
812 }
813
814 int MPV_encode_picture(AVCodecContext *avctx,
815                        unsigned char *buf, int buf_size, void *data)
816 {
817     MpegEncContext *s = avctx->priv_data;
818     AVPicture *pict = data;
819
820     s->input_qscale = avctx->quality;
821
822     init_put_bits(&s->pb, buf, buf_size, NULL, NULL);
823
824     if(avctx->flags&CODEC_FLAG_TYPE){
825         s->input_pict_type=
826         s->force_input_type= avctx->key_frame ? I_TYPE : P_TYPE;
827     }else if(s->flags&CODEC_FLAG_PASS2){
828         s->input_pict_type=
829         s->force_input_type= s->rc_context.entry[s->input_picture_number].new_pict_type;
830     }else{
831         s->force_input_type=0;
832         if (!s->intra_only) {
833             /* first picture of GOP is intra */
834             if (s->input_picture_in_gop_number % s->gop_size==0){
835                 s->input_pict_type = I_TYPE;
836             }else if(s->max_b_frames==0){
837                 s->input_pict_type = P_TYPE;
838             }else{
839                 if(s->b_frames_since_non_b < s->max_b_frames) //FIXME more IQ
840                     s->input_pict_type = B_TYPE;
841                 else
842                     s->input_pict_type = P_TYPE;
843             }
844         } else {
845             s->input_pict_type = I_TYPE;
846         }
847     }
848
849     if(s->input_pict_type==I_TYPE)
850         s->input_picture_in_gop_number=0;
851     
852     reorder_input(s, pict);
853     
854     /* output? */
855     if(s->coded_order[0].picture[0]){
856
857         s->pict_type= s->coded_order[0].pict_type;
858         if (s->fixed_qscale) /* the ratecontrol needs the last qscale so we dont touch it for CBR */
859             s->qscale= s->coded_order[0].qscale;
860         s->force_type= s->coded_order[0].force_type;
861         s->picture_in_gop_number= s->coded_order[0].picture_in_gop_number;
862         s->picture_number= s->coded_order[0].picture_number;
863
864         MPV_frame_start(s, avctx);
865
866         encode_picture(s, s->picture_number);
867         avctx->key_frame   = (s->pict_type == I_TYPE);
868         avctx->pict_type   = s->pict_type;
869         avctx->real_pict_num  = s->picture_number;
870         avctx->header_bits = s->header_bits;
871         avctx->mv_bits     = s->mv_bits;
872         avctx->misc_bits   = s->misc_bits;
873         avctx->i_tex_bits  = s->i_tex_bits;
874         avctx->p_tex_bits  = s->p_tex_bits;
875         avctx->i_count     = s->i_count;
876         avctx->p_count     = s->p_count;
877         avctx->skip_count  = s->skip_count;
878
879         MPV_frame_end(s);
880
881         if (s->out_format == FMT_MJPEG)
882             mjpeg_picture_trailer(s);
883
884         avctx->quality = s->qscale;
885         
886         if(s->flags&CODEC_FLAG_PASS1)
887             ff_write_pass1_stats(s);
888     
889     }
890
891     s->input_picture_number++;
892     s->input_picture_in_gop_number++;
893
894     flush_put_bits(&s->pb);
895     s->frame_bits  = (pbBufPtr(&s->pb) - s->pb.buf) * 8;
896     
897     s->total_bits += s->frame_bits;
898     avctx->frame_bits  = s->frame_bits;
899 //printf("fcode: %d, type: %d, head: %d, mv: %d, misc: %d, frame: %d, itex: %d, ptex: %d\n", 
900 //s->f_code, avctx->key_frame, s->header_bits, s->mv_bits, s->misc_bits, s->frame_bits, s->i_tex_bits, s->p_tex_bits);
901 #if 0 //dump some stats to stats.txt for testing/debuging
902 if(s->max_b_frames==0)
903 {
904     static FILE *f=NULL;
905     if(!f) f= fopen("stats.txt", "wb");
906     get_psnr(pict->data, s->current_picture,
907              pict->linesize, s->linesize, avctx);
908     fprintf(f, "%7d, %7d, %2.4f\n", pbBufPtr(&s->pb) - s->pb.buf, s->qscale, avctx->psnr_y);
909 }
910 #endif
911
912     if (avctx->get_psnr) {
913         /* At this point pict->data should have the original frame   */
914         /* an s->current_picture should have the coded/decoded frame */
915         get_psnr(pict->data, s->current_picture,
916                  pict->linesize, s->linesize, avctx);
917 //        printf("%f\n", avctx->psnr_y);
918     }
919     return pbBufPtr(&s->pb) - s->pb.buf;
920 }
921
922 static inline void gmc1_motion(MpegEncContext *s,
923                                UINT8 *dest_y, UINT8 *dest_cb, UINT8 *dest_cr,
924                                int dest_offset,
925                                UINT8 **ref_picture, int src_offset,
926                                int h)
927 {
928     UINT8 *ptr;
929     int offset, src_x, src_y, linesize, uvlinesize;
930     int motion_x, motion_y;
931     int emu=0;
932
933     if(s->real_sprite_warping_points>1) printf("more than 1 warp point isnt supported\n");
934     motion_x= s->sprite_offset[0][0];
935     motion_y= s->sprite_offset[0][1];
936     src_x = s->mb_x * 16 + (motion_x >> (s->sprite_warping_accuracy+1));
937     src_y = s->mb_y * 16 + (motion_y >> (s->sprite_warping_accuracy+1));
938     motion_x<<=(3-s->sprite_warping_accuracy);
939     motion_y<<=(3-s->sprite_warping_accuracy);
940     src_x = clip(src_x, -16, s->width);
941     if (src_x == s->width)
942         motion_x =0;
943     src_y = clip(src_y, -16, s->height);
944     if (src_y == s->height)
945         motion_y =0;
946     
947     linesize = s->linesize;
948     uvlinesize = s->uvlinesize;
949     ptr = ref_picture[0] + (src_y * linesize) + src_x + src_offset;
950
951     dest_y+=dest_offset;
952     if(s->flags&CODEC_FLAG_EMU_EDGE){
953         if(src_x<0 || src_y<0 || src_x + (motion_x&15) + 16 > s->h_edge_pos
954                               || src_y + (motion_y&15) + h  > s->v_edge_pos){
955             emulated_edge_mc(s, ptr, linesize, 17, h+1, src_x, src_y, s->h_edge_pos, s->v_edge_pos);
956             ptr= s->edge_emu_buffer;
957             emu=1;
958         }
959     }
960     gmc1(dest_y  , ptr  , linesize, h, motion_x&15, motion_y&15, s->no_rounding);
961     gmc1(dest_y+8, ptr+8, linesize, h, motion_x&15, motion_y&15, s->no_rounding);
962
963     motion_x= s->sprite_offset[1][0];
964     motion_y= s->sprite_offset[1][1];
965     src_x = s->mb_x * 8 + (motion_x >> (s->sprite_warping_accuracy+1));
966     src_y = s->mb_y * 8 + (motion_y >> (s->sprite_warping_accuracy+1));
967     motion_x<<=(3-s->sprite_warping_accuracy);
968     motion_y<<=(3-s->sprite_warping_accuracy);
969     src_x = clip(src_x, -8, s->width>>1);
970     if (src_x == s->width>>1)
971         motion_x =0;
972     src_y = clip(src_y, -8, s->height>>1);
973     if (src_y == s->height>>1)
974         motion_y =0;
975
976     offset = (src_y * uvlinesize) + src_x + (src_offset>>1);
977     ptr = ref_picture[1] + offset;
978     if(emu){
979         emulated_edge_mc(s, ptr, uvlinesize, 9, (h>>1)+1, src_x, src_y, s->h_edge_pos>>1, s->v_edge_pos>>1);
980         ptr= s->edge_emu_buffer;
981     }
982     gmc1(dest_cb + (dest_offset>>1), ptr, uvlinesize, h>>1, motion_x&15, motion_y&15, s->no_rounding);
983     
984     ptr = ref_picture[2] + offset;
985     if(emu){
986         emulated_edge_mc(s, ptr, uvlinesize, 9, (h>>1)+1, src_x, src_y, s->h_edge_pos>>1, s->v_edge_pos>>1);
987         ptr= s->edge_emu_buffer;
988     }
989     gmc1(dest_cr + (dest_offset>>1), ptr, uvlinesize, h>>1, motion_x&15, motion_y&15, s->no_rounding);
990     
991     return;
992 }
993
994 static void emulated_edge_mc(MpegEncContext *s, UINT8 *src, int linesize, int block_w, int block_h, 
995                                     int src_x, int src_y, int w, int h){
996     int x, y;
997     int start_y, start_x, end_y, end_x;
998     UINT8 *buf= s->edge_emu_buffer;
999     
1000     if(src_y>= h){
1001         src+= (h-1-src_y)*linesize;
1002         src_y=h-1;
1003     }else if(src_y<=-block_h){
1004         src+= (1-block_h-src_y)*linesize;
1005         src_y=1-block_h;
1006     }
1007     if(src_x>= w){
1008         src+= (w-1-src_x);
1009         src_x=w-1;
1010     }else if(src_x<=-block_w){
1011         src+= (1-block_w-src_x);
1012         src_x=1-block_w;
1013     }
1014
1015     start_y= MAX(0, -src_y);
1016     start_x= MAX(0, -src_x);
1017     end_y= MIN(block_h, h-src_y);
1018     end_x= MIN(block_w, w-src_x);
1019
1020     // copy existing part
1021     for(y=start_y; y<end_y; y++){
1022         for(x=start_x; x<end_x; x++){
1023             buf[x + y*linesize]= src[x + y*linesize];
1024         }
1025     }
1026
1027     //top
1028     for(y=0; y<start_y; y++){
1029         for(x=start_x; x<end_x; x++){
1030             buf[x + y*linesize]= buf[x + start_y*linesize];
1031         }
1032     }
1033
1034     //bottom
1035     for(y=end_y; y<block_h; y++){
1036         for(x=start_x; x<end_x; x++){
1037             buf[x + y*linesize]= buf[x + (end_y-1)*linesize];
1038         }
1039     }
1040                                     
1041     for(y=0; y<block_h; y++){
1042        //left
1043         for(x=0; x<start_x; x++){
1044             buf[x + y*linesize]= buf[start_x + y*linesize];
1045         }
1046        
1047        //right
1048         for(x=end_x; x<block_w; x++){
1049             buf[x + y*linesize]= buf[end_x - 1 + y*linesize];
1050         }
1051     }
1052 }
1053
1054
1055 /* apply one mpeg motion vector to the three components */
1056 static inline void mpeg_motion(MpegEncContext *s,
1057                                UINT8 *dest_y, UINT8 *dest_cb, UINT8 *dest_cr,
1058                                int dest_offset,
1059                                UINT8 **ref_picture, int src_offset,
1060                                int field_based, op_pixels_func *pix_op,
1061                                int motion_x, int motion_y, int h)
1062 {
1063     UINT8 *ptr;
1064     int dxy, offset, mx, my, src_x, src_y, height, v_edge_pos, linesize, uvlinesize;
1065     int emu=0;
1066     
1067 if(s->quarter_sample)
1068 {
1069     motion_x>>=1;
1070     motion_y>>=1;
1071 }
1072     dxy = ((motion_y & 1) << 1) | (motion_x & 1);
1073     src_x = s->mb_x * 16 + (motion_x >> 1);
1074     src_y = s->mb_y * (16 >> field_based) + (motion_y >> 1);
1075                 
1076     /* WARNING: do no forget half pels */
1077     height = s->height >> field_based;
1078     v_edge_pos = s->v_edge_pos >> field_based;
1079     src_x = clip(src_x, -16, s->width);
1080     if (src_x == s->width)
1081         dxy &= ~1;
1082     src_y = clip(src_y, -16, height);
1083     if (src_y == height)
1084         dxy &= ~2;
1085     linesize   = s->linesize << field_based;
1086     uvlinesize = s->uvlinesize << field_based;
1087     ptr = ref_picture[0] + (src_y * linesize) + (src_x) + src_offset;
1088     dest_y += dest_offset;
1089
1090     if(s->flags&CODEC_FLAG_EMU_EDGE){
1091         if(src_x<0 || src_y<0 || src_x + (motion_x&1) + 16 > s->h_edge_pos
1092                               || src_y + (motion_y&1) + h  > v_edge_pos){
1093             emulated_edge_mc(s, ptr, linesize, 17, h+1, src_x, src_y, s->h_edge_pos, v_edge_pos);
1094             ptr= s->edge_emu_buffer;
1095             emu=1;
1096         }
1097     }
1098     pix_op[dxy](dest_y, ptr, linesize, h);
1099     pix_op[dxy](dest_y + 8, ptr + 8, linesize, h);
1100
1101     if(s->flags&CODEC_FLAG_GRAY) return;
1102
1103     if (s->out_format == FMT_H263) {
1104         dxy = 0;
1105         if ((motion_x & 3) != 0)
1106             dxy |= 1;
1107         if ((motion_y & 3) != 0)
1108             dxy |= 2;
1109         mx = motion_x >> 2;
1110         my = motion_y >> 2;
1111     } else {
1112         mx = motion_x / 2;
1113         my = motion_y / 2;
1114         dxy = ((my & 1) << 1) | (mx & 1);
1115         mx >>= 1;
1116         my >>= 1;
1117     }
1118     
1119     src_x = s->mb_x * 8 + mx;
1120     src_y = s->mb_y * (8 >> field_based) + my;
1121     src_x = clip(src_x, -8, s->width >> 1);
1122     if (src_x == (s->width >> 1))
1123         dxy &= ~1;
1124     src_y = clip(src_y, -8, height >> 1);
1125     if (src_y == (height >> 1))
1126         dxy &= ~2;
1127     offset = (src_y * uvlinesize) + src_x + (src_offset >> 1);
1128     ptr = ref_picture[1] + offset;
1129     if(emu){
1130         emulated_edge_mc(s, ptr, uvlinesize, 9, (h>>1)+1, src_x, src_y, s->h_edge_pos>>1, v_edge_pos>>1);
1131         ptr= s->edge_emu_buffer;
1132     }
1133     pix_op[dxy](dest_cb + (dest_offset >> 1), ptr, uvlinesize, h >> 1);
1134
1135     ptr = ref_picture[2] + offset;
1136     if(emu){
1137         emulated_edge_mc(s, ptr, uvlinesize, 9, (h>>1)+1, src_x, src_y, s->h_edge_pos>>1, v_edge_pos>>1);
1138         ptr= s->edge_emu_buffer;
1139     }
1140     pix_op[dxy](dest_cr + (dest_offset >> 1), ptr, uvlinesize, h >> 1);
1141 }
1142
1143 static inline void qpel_motion(MpegEncContext *s,
1144                                UINT8 *dest_y, UINT8 *dest_cb, UINT8 *dest_cr,
1145                                int dest_offset,
1146                                UINT8 **ref_picture, int src_offset,
1147                                int field_based, op_pixels_func *pix_op,
1148                                qpel_mc_func *qpix_op,
1149                                int motion_x, int motion_y, int h)
1150 {
1151     UINT8 *ptr;
1152     int dxy, offset, mx, my, src_x, src_y, height, v_edge_pos, linesize;
1153     int emu=0;
1154
1155     dxy = ((motion_y & 3) << 2) | (motion_x & 3);
1156     src_x = s->mb_x * 16 + (motion_x >> 2);
1157     src_y = s->mb_y * (16 >> field_based) + (motion_y >> 2);
1158
1159     height = s->height >> field_based;
1160     v_edge_pos = s->v_edge_pos >> field_based;
1161     src_x = clip(src_x, -16, s->width);
1162     if (src_x == s->width)
1163         dxy &= ~3;
1164     src_y = clip(src_y, -16, height);
1165     if (src_y == height)
1166         dxy &= ~12;
1167     linesize = s->linesize << field_based;
1168     ptr = ref_picture[0] + (src_y * linesize) + src_x + src_offset;
1169     dest_y += dest_offset;
1170 //printf("%d %d %d\n", src_x, src_y, dxy);
1171     
1172     if(s->flags&CODEC_FLAG_EMU_EDGE){
1173         if(src_x<0 || src_y<0 || src_x + (motion_x&3) + 16 > s->h_edge_pos
1174                               || src_y + (motion_y&3) + h  > v_edge_pos){
1175             emulated_edge_mc(s, ptr, linesize, 17, h+1, src_x, src_y, s->h_edge_pos, v_edge_pos);
1176             ptr= s->edge_emu_buffer;
1177             emu=1;
1178         }
1179     }
1180     qpix_op[dxy](dest_y                 , ptr                 , linesize, linesize, motion_x&3, motion_y&3);
1181     qpix_op[dxy](dest_y              + 8, ptr              + 8, linesize, linesize, motion_x&3, motion_y&3);
1182     qpix_op[dxy](dest_y + linesize*8    , ptr + linesize*8    , linesize, linesize, motion_x&3, motion_y&3);
1183     qpix_op[dxy](dest_y + linesize*8 + 8, ptr + linesize*8 + 8, linesize, linesize, motion_x&3, motion_y&3);
1184     
1185     if(s->flags&CODEC_FLAG_GRAY) return;
1186
1187     mx= (motion_x>>1) | (motion_x&1);
1188     my= (motion_y>>1) | (motion_y&1);
1189
1190     dxy = 0;
1191     if ((mx & 3) != 0)
1192         dxy |= 1;
1193     if ((my & 3) != 0)
1194         dxy |= 2;
1195     mx = mx >> 2;
1196     my = my >> 2;
1197     
1198     src_x = s->mb_x * 8 + mx;
1199     src_y = s->mb_y * (8 >> field_based) + my;
1200     src_x = clip(src_x, -8, s->width >> 1);
1201     if (src_x == (s->width >> 1))
1202         dxy &= ~1;
1203     src_y = clip(src_y, -8, height >> 1);
1204     if (src_y == (height >> 1))
1205         dxy &= ~2;
1206
1207     offset = (src_y * s->uvlinesize) + src_x + (src_offset >> 1);
1208     ptr = ref_picture[1] + offset;
1209     if(emu){
1210         emulated_edge_mc(s, ptr,  s->uvlinesize, 9, (h>>1)+1, src_x, src_y, s->h_edge_pos>>1, v_edge_pos>>1);
1211         ptr= s->edge_emu_buffer;
1212     }
1213     pix_op[dxy](dest_cb + (dest_offset >> 1), ptr,  s->uvlinesize, h >> 1);
1214     
1215     ptr = ref_picture[2] + offset;
1216     if(emu){
1217         emulated_edge_mc(s, ptr,  s->uvlinesize, 9, (h>>1)+1, src_x, src_y, s->h_edge_pos>>1, v_edge_pos>>1);
1218         ptr= s->edge_emu_buffer;
1219     }
1220     pix_op[dxy](dest_cr + (dest_offset >> 1), ptr,  s->uvlinesize, h >> 1);
1221 }
1222
1223
1224 static inline void MPV_motion(MpegEncContext *s, 
1225                               UINT8 *dest_y, UINT8 *dest_cb, UINT8 *dest_cr,
1226                               int dir, UINT8 **ref_picture, 
1227                               op_pixels_func *pix_op, qpel_mc_func *qpix_op)
1228 {
1229     int dxy, offset, mx, my, src_x, src_y, motion_x, motion_y;
1230     int mb_x, mb_y, i;
1231     UINT8 *ptr, *dest;
1232     int emu=0;
1233
1234     mb_x = s->mb_x;
1235     mb_y = s->mb_y;
1236
1237     switch(s->mv_type) {
1238     case MV_TYPE_16X16:
1239         if(s->mcsel){
1240 #if 0
1241             mpeg_motion(s, dest_y, dest_cb, dest_cr, 0,
1242                         ref_picture, 0,
1243                         0, pix_op,
1244                         s->sprite_offset[0][0]>>3,
1245                         s->sprite_offset[0][1]>>3,
1246                         16);
1247 #else
1248             gmc1_motion(s, dest_y, dest_cb, dest_cr, 0,
1249                         ref_picture, 0,
1250                         16);
1251 #endif
1252         }else if(s->quarter_sample && dir==0){ //FIXME
1253             qpel_motion(s, dest_y, dest_cb, dest_cr, 0,
1254                         ref_picture, 0,
1255                         0, pix_op, qpix_op,
1256                         s->mv[dir][0][0], s->mv[dir][0][1], 16);
1257         }else{
1258             mpeg_motion(s, dest_y, dest_cb, dest_cr, 0,
1259                         ref_picture, 0,
1260                         0, pix_op,
1261                         s->mv[dir][0][0], s->mv[dir][0][1], 16);
1262         }           
1263         break;
1264     case MV_TYPE_8X8:
1265         for(i=0;i<4;i++) {
1266             motion_x = s->mv[dir][i][0];
1267             motion_y = s->mv[dir][i][1];
1268
1269             dxy = ((motion_y & 1) << 1) | (motion_x & 1);
1270             src_x = mb_x * 16 + (motion_x >> 1) + (i & 1) * 8;
1271             src_y = mb_y * 16 + (motion_y >> 1) + (i >>1) * 8;
1272                     
1273             /* WARNING: do no forget half pels */
1274             src_x = clip(src_x, -16, s->width);
1275             if (src_x == s->width)
1276                 dxy &= ~1;
1277             src_y = clip(src_y, -16, s->height);
1278             if (src_y == s->height)
1279                 dxy &= ~2;
1280                     
1281             ptr = ref_picture[0] + (src_y * s->linesize) + (src_x);
1282             if(s->flags&CODEC_FLAG_EMU_EDGE){
1283                 if(src_x<0 || src_y<0 || src_x + (motion_x&1) + 8 > s->h_edge_pos
1284                                       || src_y + (motion_y&1) + 8 > s->v_edge_pos){
1285                     emulated_edge_mc(s, ptr, s->linesize, 9, 9, src_x, src_y, s->h_edge_pos, s->v_edge_pos);
1286                     ptr= s->edge_emu_buffer;
1287                 }
1288             }
1289             dest = dest_y + ((i & 1) * 8) + (i >> 1) * 8 * s->linesize;
1290             pix_op[dxy](dest, ptr, s->linesize, 8);
1291         }
1292     
1293         if(s->flags&CODEC_FLAG_GRAY) break;
1294         /* In case of 8X8, we construct a single chroma motion vector
1295            with a special rounding */
1296         mx = 0;
1297         my = 0;
1298         for(i=0;i<4;i++) {
1299             mx += s->mv[dir][i][0];
1300             my += s->mv[dir][i][1];
1301         }
1302         if (mx >= 0)
1303             mx = (h263_chroma_roundtab[mx & 0xf] + ((mx >> 3) & ~1));
1304         else {
1305             mx = -mx;
1306             mx = -(h263_chroma_roundtab[mx & 0xf] + ((mx >> 3) & ~1));
1307         }
1308         if (my >= 0)
1309             my = (h263_chroma_roundtab[my & 0xf] + ((my >> 3) & ~1));
1310         else {
1311             my = -my;
1312             my = -(h263_chroma_roundtab[my & 0xf] + ((my >> 3) & ~1));
1313         }
1314         dxy = ((my & 1) << 1) | (mx & 1);
1315         mx >>= 1;
1316         my >>= 1;
1317
1318         src_x = mb_x * 8 + mx;
1319         src_y = mb_y * 8 + my;
1320         src_x = clip(src_x, -8, s->width/2);
1321         if (src_x == s->width/2)
1322             dxy &= ~1;
1323         src_y = clip(src_y, -8, s->height/2);
1324         if (src_y == s->height/2)
1325             dxy &= ~2;
1326         
1327         offset = (src_y * (s->uvlinesize)) + src_x;
1328         ptr = ref_picture[1] + offset;
1329         if(s->flags&CODEC_FLAG_EMU_EDGE){
1330                 if(src_x<0 || src_y<0 || src_x + (dxy &1) + 8 > s->h_edge_pos>>1
1331                                       || src_y + (dxy>>1) + 8 > s->v_edge_pos>>1){
1332                     emulated_edge_mc(s, ptr, s->uvlinesize, 9, 9, src_x, src_y, s->h_edge_pos>>1, s->v_edge_pos>>1);
1333                     ptr= s->edge_emu_buffer;
1334                     emu=1;
1335                 }
1336             }
1337         pix_op[dxy](dest_cb, ptr, s->uvlinesize, 8);
1338
1339         ptr = ref_picture[2] + offset;
1340         if(emu){
1341             emulated_edge_mc(s, ptr, s->uvlinesize, 9, 9, src_x, src_y, s->h_edge_pos>>1, s->v_edge_pos>>1);
1342             ptr= s->edge_emu_buffer;
1343         }
1344         pix_op[dxy](dest_cr, ptr, s->uvlinesize, 8);
1345         break;
1346     case MV_TYPE_FIELD:
1347         if (s->picture_structure == PICT_FRAME) {
1348             /* top field */
1349             mpeg_motion(s, dest_y, dest_cb, dest_cr, 0,
1350                         ref_picture, s->field_select[dir][0] ? s->linesize : 0,
1351                         1, pix_op,
1352                         s->mv[dir][0][0], s->mv[dir][0][1], 8);
1353             /* bottom field */
1354             mpeg_motion(s, dest_y, dest_cb, dest_cr, s->linesize,
1355                         ref_picture, s->field_select[dir][1] ? s->linesize : 0,
1356                         1, pix_op,
1357                         s->mv[dir][1][0], s->mv[dir][1][1], 8);
1358         } else {
1359             
1360
1361         }
1362         break;
1363     }
1364 }
1365
1366
1367 /* put block[] to dest[] */
1368 static inline void put_dct(MpegEncContext *s, 
1369                            DCTELEM *block, int i, UINT8 *dest, int line_size)
1370 {
1371     if (!s->mpeg2)
1372         s->dct_unquantize(s, block, i, s->qscale);
1373     ff_idct_put (dest, line_size, block);
1374 }
1375
1376 /* add block[] to dest[] */
1377 static inline void add_dct(MpegEncContext *s, 
1378                            DCTELEM *block, int i, UINT8 *dest, int line_size)
1379 {
1380     if (s->block_last_index[i] >= 0) {
1381         ff_idct_add (dest, line_size, block);
1382     }
1383 }
1384
1385 static inline void add_dequant_dct(MpegEncContext *s, 
1386                            DCTELEM *block, int i, UINT8 *dest, int line_size)
1387 {
1388     if (s->block_last_index[i] >= 0) {
1389         s->dct_unquantize(s, block, i, s->qscale);
1390
1391         ff_idct_add (dest, line_size, block);
1392     }
1393 }
1394
1395 /**
1396  * cleans dc, ac, coded_block for the current non intra MB
1397  */
1398 void ff_clean_intra_table_entries(MpegEncContext *s)
1399 {
1400     int wrap = s->block_wrap[0];
1401     int xy = s->block_index[0];
1402     
1403     s->dc_val[0][xy           ] = 
1404     s->dc_val[0][xy + 1       ] = 
1405     s->dc_val[0][xy     + wrap] =
1406     s->dc_val[0][xy + 1 + wrap] = 1024;
1407     /* ac pred */
1408     memset(s->ac_val[0][xy       ], 0, 32 * sizeof(INT16));
1409     memset(s->ac_val[0][xy + wrap], 0, 32 * sizeof(INT16));
1410     if (s->msmpeg4_version>=3) {
1411         s->coded_block[xy           ] =
1412         s->coded_block[xy + 1       ] =
1413         s->coded_block[xy     + wrap] =
1414         s->coded_block[xy + 1 + wrap] = 0;
1415     }
1416     /* chroma */
1417     wrap = s->block_wrap[4];
1418     xy = s->mb_x + 1 + (s->mb_y + 1) * wrap;
1419     s->dc_val[1][xy] =
1420     s->dc_val[2][xy] = 1024;
1421     /* ac pred */
1422     memset(s->ac_val[1][xy], 0, 16 * sizeof(INT16));
1423     memset(s->ac_val[2][xy], 0, 16 * sizeof(INT16));
1424     
1425     s->mbintra_table[s->mb_x + s->mb_y*s->mb_width]= 0;
1426 }
1427
1428 /* generic function called after a macroblock has been parsed by the
1429    decoder or after it has been encoded by the encoder.
1430
1431    Important variables used:
1432    s->mb_intra : true if intra macroblock
1433    s->mv_dir   : motion vector direction
1434    s->mv_type  : motion vector type
1435    s->mv       : motion vector
1436    s->interlaced_dct : true if interlaced dct used (mpeg2)
1437  */
1438 void MPV_decode_mb(MpegEncContext *s, DCTELEM block[6][64])
1439 {
1440     int mb_x, mb_y;
1441     const int mb_xy = s->mb_y * s->mb_width + s->mb_x;
1442
1443     mb_x = s->mb_x;
1444     mb_y = s->mb_y;
1445
1446 #ifdef FF_POSTPROCESS
1447     /* Obsolete. Exists for compatibility with mplayer only. */
1448     quant_store[mb_y][mb_x]=s->qscale;
1449     //printf("[%02d][%02d] %d\n",mb_x,mb_y,s->qscale);
1450 #else
1451     /* even more obsolete, exists for mplayer xp only */
1452     if(s->avctx->quant_store) s->avctx->quant_store[mb_y*s->avctx->qstride+mb_x] = s->qscale;
1453 #endif
1454     s->qscale_table[mb_xy]= s->qscale;
1455
1456     /* update DC predictors for P macroblocks */
1457     if (!s->mb_intra) {
1458         if (s->h263_pred || s->h263_aic) {
1459             if(s->mbintra_table[mb_xy])
1460                 ff_clean_intra_table_entries(s);
1461         } else {
1462             s->last_dc[0] =
1463             s->last_dc[1] =
1464             s->last_dc[2] = 128 << s->intra_dc_precision;
1465         }
1466     }
1467     else if (s->h263_pred || s->h263_aic)
1468         s->mbintra_table[mb_xy]=1;
1469
1470     /* update motion predictor, not for B-frames as they need the motion_val from the last P/S-Frame */
1471     if (s->out_format == FMT_H263 && s->pict_type!=B_TYPE) { //FIXME move into h263.c if possible, format specific stuff shouldnt be here
1472         
1473         const int wrap = s->block_wrap[0];
1474         const int xy = s->block_index[0];
1475         if(s->mv_type == MV_TYPE_8X8){
1476             s->non_b_mv4_table[xy]=1;
1477         } else {
1478             int motion_x, motion_y;
1479             if (s->mb_intra) {
1480                 motion_x = 0;
1481                 motion_y = 0;
1482             } else if (s->mv_type == MV_TYPE_16X16) {
1483                 motion_x = s->mv[0][0][0];
1484                 motion_y = s->mv[0][0][1];
1485             } else /*if (s->mv_type == MV_TYPE_FIELD)*/ {
1486                 motion_x = s->mv[0][0][0] + s->mv[0][1][0];
1487                 motion_y = s->mv[0][0][1] + s->mv[0][1][1];
1488                 motion_x = (motion_x>>1) | (motion_x&1);
1489                 motion_y = (motion_y>>1) | (motion_y&1);
1490             }
1491             /* no update if 8X8 because it has been done during parsing */
1492             s->motion_val[xy][0] = motion_x;
1493             s->motion_val[xy][1] = motion_y;
1494             s->motion_val[xy + 1][0] = motion_x;
1495             s->motion_val[xy + 1][1] = motion_y;
1496             s->motion_val[xy + wrap][0] = motion_x;
1497             s->motion_val[xy + wrap][1] = motion_y;
1498             s->motion_val[xy + 1 + wrap][0] = motion_x;
1499             s->motion_val[xy + 1 + wrap][1] = motion_y;
1500             s->non_b_mv4_table[xy]=0;
1501         }
1502     }
1503     
1504     if (!(s->encoding && (s->intra_only || s->pict_type==B_TYPE))) {
1505         UINT8 *dest_y, *dest_cb, *dest_cr;
1506         int dct_linesize, dct_offset;
1507         op_pixels_func *op_pix;
1508         qpel_mc_func *op_qpix;
1509
1510         /* avoid copy if macroblock skipped in last frame too 
1511            dont touch it for B-frames as they need the skip info from the next p-frame */
1512         if (s->pict_type != B_TYPE) {
1513             UINT8 *mbskip_ptr = &s->mbskip_table[mb_xy];
1514             if (s->mb_skiped) {
1515                 s->mb_skiped = 0;
1516
1517                 (*mbskip_ptr) ++; /* indicate that this time we skiped it */
1518                 if(*mbskip_ptr >99) *mbskip_ptr= 99;
1519
1520                 /* if previous was skipped too, then nothing to do ! 
1521                    skip only during decoding as we might trash the buffers during encoding a bit */
1522                 if (*mbskip_ptr >= s->ip_buffer_count  && !s->encoding) 
1523                     goto the_end;
1524             } else {
1525                 *mbskip_ptr = 0; /* not skipped */
1526             }
1527         }
1528
1529         dest_y = s->current_picture [0] + (mb_y * 16* s->linesize  ) + mb_x * 16;
1530         dest_cb = s->current_picture[1] + (mb_y * 8 * s->uvlinesize) + mb_x * 8;
1531         dest_cr = s->current_picture[2] + (mb_y * 8 * s->uvlinesize) + mb_x * 8;
1532
1533         if (s->interlaced_dct) {
1534             dct_linesize = s->linesize * 2;
1535             dct_offset = s->linesize;
1536         } else {
1537             dct_linesize = s->linesize;
1538             dct_offset = s->linesize * 8;
1539         }
1540
1541         if (!s->mb_intra) {
1542             /* motion handling */
1543             /* decoding or more than one mb_type (MC was allready done otherwise) */
1544             if((!s->encoding) || (s->mb_type[mb_xy]&(s->mb_type[mb_xy]-1))){
1545                 if ((!s->no_rounding) || s->pict_type==B_TYPE){                
1546                     op_pix = put_pixels_tab;
1547                     op_qpix= qpel_mc_rnd_tab;
1548                 }else{
1549                     op_pix = put_no_rnd_pixels_tab;
1550                     op_qpix= qpel_mc_no_rnd_tab;
1551                 }
1552
1553                 if (s->mv_dir & MV_DIR_FORWARD) {
1554                     MPV_motion(s, dest_y, dest_cb, dest_cr, 0, s->last_picture, op_pix, op_qpix);
1555                     if ((!s->no_rounding) || s->pict_type==B_TYPE)
1556                         op_pix = avg_pixels_tab;
1557                     else
1558                         op_pix = avg_no_rnd_pixels_tab;
1559                 }
1560                 if (s->mv_dir & MV_DIR_BACKWARD) {
1561                     MPV_motion(s, dest_y, dest_cb, dest_cr, 1, s->next_picture, op_pix, op_qpix);
1562                 }
1563             }
1564
1565             /* skip dequant / idct if we are really late ;) */
1566             if(s->hurry_up>1) goto the_end;
1567
1568             /* add dct residue */
1569             if(s->encoding || !(s->mpeg2 || s->h263_msmpeg4 || (s->codec_id==CODEC_ID_MPEG4 && !s->mpeg_quant))){
1570                 add_dequant_dct(s, block[0], 0, dest_y, dct_linesize);
1571                 add_dequant_dct(s, block[1], 1, dest_y + 8, dct_linesize);
1572                 add_dequant_dct(s, block[2], 2, dest_y + dct_offset, dct_linesize);
1573                 add_dequant_dct(s, block[3], 3, dest_y + dct_offset + 8, dct_linesize);
1574
1575                 if(!(s->flags&CODEC_FLAG_GRAY)){
1576                     add_dequant_dct(s, block[4], 4, dest_cb, s->uvlinesize);
1577                     add_dequant_dct(s, block[5], 5, dest_cr, s->uvlinesize);
1578                 }
1579             } else {
1580                 add_dct(s, block[0], 0, dest_y, dct_linesize);
1581                 add_dct(s, block[1], 1, dest_y + 8, dct_linesize);
1582                 add_dct(s, block[2], 2, dest_y + dct_offset, dct_linesize);
1583                 add_dct(s, block[3], 3, dest_y + dct_offset + 8, dct_linesize);
1584
1585                 if(!(s->flags&CODEC_FLAG_GRAY)){
1586                     add_dct(s, block[4], 4, dest_cb, s->uvlinesize);
1587                     add_dct(s, block[5], 5, dest_cr, s->uvlinesize);
1588                 }
1589             }
1590         } else {
1591             /* dct only in intra block */
1592             put_dct(s, block[0], 0, dest_y, dct_linesize);
1593             put_dct(s, block[1], 1, dest_y + 8, dct_linesize);
1594             put_dct(s, block[2], 2, dest_y + dct_offset, dct_linesize);
1595             put_dct(s, block[3], 3, dest_y + dct_offset + 8, dct_linesize);
1596
1597             if(!(s->flags&CODEC_FLAG_GRAY)){
1598                 put_dct(s, block[4], 4, dest_cb, s->uvlinesize);
1599                 put_dct(s, block[5], 5, dest_cr, s->uvlinesize);
1600             }
1601         }
1602     }
1603  the_end:
1604     emms_c(); //FIXME remove
1605 }
1606
1607 static inline void dct_single_coeff_elimination(MpegEncContext *s, int n, int threshold)
1608 {
1609     static const char tab[64]=
1610         {3,2,2,1,1,1,1,1,
1611          1,1,1,1,1,1,1,1,
1612          1,1,1,1,1,1,1,1,
1613          0,0,0,0,0,0,0,0,
1614          0,0,0,0,0,0,0,0,
1615          0,0,0,0,0,0,0,0,
1616          0,0,0,0,0,0,0,0,
1617          0,0,0,0,0,0,0,0};
1618     int score=0;
1619     int run=0;
1620     int i;
1621     DCTELEM *block= s->block[n];
1622     const int last_index= s->block_last_index[n];
1623     int skip_dc;
1624
1625     if(threshold<0){
1626         skip_dc=0;
1627         threshold= -threshold;
1628     }else
1629         skip_dc=1;
1630
1631     /* are all which we could set to zero are allready zero? */
1632     if(last_index<=skip_dc - 1) return;
1633
1634     for(i=0; i<=last_index; i++){
1635         const int j = zigzag_direct[i];
1636         const int level = ABS(block[j]);
1637         if(level==1){
1638             if(skip_dc && i==0) continue;
1639             score+= tab[run];
1640             run=0;
1641         }else if(level>1){
1642             return;
1643         }else{
1644             run++;
1645         }
1646     }
1647     if(score >= threshold) return;
1648     for(i=skip_dc; i<=last_index; i++){
1649         const int j = zigzag_direct[i];
1650         block[j]=0;
1651     }
1652     if(block[0]) s->block_last_index[n]= 0;
1653     else         s->block_last_index[n]= -1;
1654 }
1655
1656 static inline void clip_coeffs(MpegEncContext *s, DCTELEM *block, int last_index)
1657 {
1658     int i;
1659     const int maxlevel= s->max_qcoeff;
1660     const int minlevel= s->min_qcoeff;
1661         
1662     for(i=0;i<=last_index; i++){
1663         const int j = zigzag_direct[i];
1664         int level = block[j];
1665        
1666         if     (level>maxlevel) level=maxlevel;
1667         else if(level<minlevel) level=minlevel;
1668         block[j]= level;
1669     }
1670 }
1671
1672 static void encode_mb(MpegEncContext *s, int motion_x, int motion_y)
1673 {
1674     const int mb_x= s->mb_x;
1675     const int mb_y= s->mb_y;
1676     int i;
1677     int skip_dct[6];
1678 #if 0
1679         if (s->interlaced_dct) {
1680             dct_linesize = s->linesize * 2;
1681             dct_offset = s->linesize;
1682         } else {
1683             dct_linesize = s->linesize;
1684             dct_offset = s->linesize * 8;
1685         }
1686 #endif
1687     for(i=0; i<6; i++) skip_dct[i]=0;
1688
1689     if (s->mb_intra) {
1690         UINT8 *ptr;
1691         int wrap;
1692         int emu=0;
1693
1694         wrap = s->linesize;
1695         ptr = s->new_picture[0] + (mb_y * 16 * wrap) + mb_x * 16;
1696         if(mb_x*16+16 > s->width || mb_y*16+16 > s->height){
1697             emulated_edge_mc(s, ptr, wrap, 16, 16, mb_x*16, mb_y*16, s->width, s->height);
1698             ptr= s->edge_emu_buffer;
1699             emu=1;
1700         }
1701         get_pixels(s->block[0], ptr               , wrap);
1702         get_pixels(s->block[1], ptr            + 8, wrap);
1703         get_pixels(s->block[2], ptr + 8 * wrap    , wrap);
1704         get_pixels(s->block[3], ptr + 8 * wrap + 8, wrap);
1705
1706         if(s->flags&CODEC_FLAG_GRAY){
1707             skip_dct[4]= 1;
1708             skip_dct[5]= 1;
1709         }else{
1710             wrap >>=1;
1711             ptr = s->new_picture[1] + (mb_y * 8 * wrap) + mb_x * 8;
1712             if(emu){
1713                 emulated_edge_mc(s, ptr, wrap, 8, 8, mb_x*8, mb_y*8, s->width>>1, s->height>>1);
1714                 ptr= s->edge_emu_buffer;
1715             }
1716             get_pixels(s->block[4], ptr, wrap);
1717
1718             ptr = s->new_picture[2] + (mb_y * 8 * wrap) + mb_x * 8;
1719             if(emu){
1720                 emulated_edge_mc(s, ptr, wrap, 8, 8, mb_x*8, mb_y*8, s->width>>1, s->height>>1);
1721                 ptr= s->edge_emu_buffer;
1722             }
1723             get_pixels(s->block[5], ptr, wrap);
1724         }
1725     }else{
1726         op_pixels_func *op_pix;
1727         qpel_mc_func *op_qpix;
1728         UINT8 *dest_y, *dest_cb, *dest_cr;
1729         UINT8 *ptr_y, *ptr_cb, *ptr_cr;
1730         int wrap_y, wrap_c;
1731         int emu=0;
1732
1733         dest_y  = s->current_picture[0] + (mb_y * 16 * s->linesize       ) + mb_x * 16;
1734         dest_cb = s->current_picture[1] + (mb_y * 8  * (s->uvlinesize)) + mb_x * 8;
1735         dest_cr = s->current_picture[2] + (mb_y * 8  * (s->uvlinesize)) + mb_x * 8;
1736         wrap_y = s->linesize;
1737         wrap_c = wrap_y>>1;
1738         ptr_y  = s->new_picture[0] + (mb_y * 16 * wrap_y) + mb_x * 16;
1739         ptr_cb = s->new_picture[1] + (mb_y * 8 * wrap_c) + mb_x * 8;
1740         ptr_cr = s->new_picture[2] + (mb_y * 8 * wrap_c) + mb_x * 8;
1741
1742         if ((!s->no_rounding) || s->pict_type==B_TYPE){
1743             op_pix = put_pixels_tab;
1744             op_qpix= qpel_mc_rnd_tab;
1745         }else{
1746             op_pix = put_no_rnd_pixels_tab;
1747             op_qpix= qpel_mc_no_rnd_tab;
1748         }
1749
1750         if (s->mv_dir & MV_DIR_FORWARD) {
1751             MPV_motion(s, dest_y, dest_cb, dest_cr, 0, s->last_picture, op_pix, op_qpix);
1752            if ((!s->no_rounding) || s->pict_type==B_TYPE)
1753                 op_pix = avg_pixels_tab;
1754             else
1755                 op_pix = avg_no_rnd_pixels_tab;
1756         }
1757         if (s->mv_dir & MV_DIR_BACKWARD) {
1758             MPV_motion(s, dest_y, dest_cb, dest_cr, 1, s->next_picture, op_pix, op_qpix);
1759         }
1760
1761         if(mb_x*16+16 > s->width || mb_y*16+16 > s->height){
1762             emulated_edge_mc(s, ptr_y, wrap_y, 16, 16, mb_x*16, mb_y*16, s->width, s->height);
1763             ptr_y= s->edge_emu_buffer;
1764             emu=1;
1765         }
1766         diff_pixels(s->block[0], ptr_y                 , dest_y                 , wrap_y);
1767         diff_pixels(s->block[1], ptr_y              + 8, dest_y              + 8, wrap_y);
1768         diff_pixels(s->block[2], ptr_y + 8 * wrap_y    , dest_y + 8 * wrap_y    , wrap_y);
1769         diff_pixels(s->block[3], ptr_y + 8 * wrap_y + 8, dest_y + 8 * wrap_y + 8, wrap_y);
1770         
1771         if(s->flags&CODEC_FLAG_GRAY){
1772             skip_dct[4]= 1;
1773             skip_dct[5]= 1;
1774         }else{
1775             if(emu){
1776                 emulated_edge_mc(s, ptr_cb, wrap_c, 8, 8, mb_x*8, mb_y*8, s->width>>1, s->height>>1);
1777                 ptr_cb= s->edge_emu_buffer;
1778             }
1779             diff_pixels(s->block[4], ptr_cb, dest_cb, wrap_c);
1780             if(emu){
1781                 emulated_edge_mc(s, ptr_cr, wrap_c, 8, 8, mb_x*8, mb_y*8, s->width>>1, s->height>>1);
1782                 ptr_cr= s->edge_emu_buffer;
1783             }
1784             diff_pixels(s->block[5], ptr_cr, dest_cr, wrap_c);
1785         }
1786
1787         /* pre quantization */         
1788         if(s->mc_mb_var[s->mb_width*mb_y+ mb_x]<2*s->qscale*s->qscale){
1789             if(pix_abs8x8(ptr_y               , dest_y               , wrap_y) < 20*s->qscale) skip_dct[0]= 1;
1790             if(pix_abs8x8(ptr_y            + 8, dest_y            + 8, wrap_y) < 20*s->qscale) skip_dct[1]= 1;
1791             if(pix_abs8x8(ptr_y + 8*wrap_y    , dest_y + 8*wrap_y    , wrap_y) < 20*s->qscale) skip_dct[2]= 1;
1792             if(pix_abs8x8(ptr_y + 8*wrap_y + 8, dest_y + 8*wrap_y + 8, wrap_y) < 20*s->qscale) skip_dct[3]= 1;
1793             if(pix_abs8x8(ptr_cb              , dest_cb              , wrap_y) < 20*s->qscale) skip_dct[4]= 1;
1794             if(pix_abs8x8(ptr_cr              , dest_cr              , wrap_y) < 20*s->qscale) skip_dct[5]= 1;
1795 #if 0
1796 {
1797  static int stat[7];
1798  int num=0;
1799  for(i=0; i<6; i++)
1800   if(skip_dct[i]) num++;
1801  stat[num]++;
1802  
1803  if(s->mb_x==0 && s->mb_y==0){
1804   for(i=0; i<7; i++){
1805    printf("%6d %1d\n", stat[i], i);
1806   }
1807  }
1808 }
1809 #endif
1810         }
1811
1812     }
1813             
1814 #if 0
1815             {
1816                 float adap_parm;
1817                 
1818                 adap_parm = ((s->avg_mb_var << 1) + s->mb_var[s->mb_width*mb_y+mb_x] + 1.0) /
1819                             ((s->mb_var[s->mb_width*mb_y+mb_x] << 1) + s->avg_mb_var + 1.0);
1820             
1821                 printf("\ntype=%c qscale=%2d adap=%0.2f dquant=%4.2f var=%4d avgvar=%4d", 
1822                         (s->mb_type[s->mb_width*mb_y+mb_x] > 0) ? 'I' : 'P', 
1823                         s->qscale, adap_parm, s->qscale*adap_parm,
1824                         s->mb_var[s->mb_width*mb_y+mb_x], s->avg_mb_var);
1825             }
1826 #endif
1827     /* DCT & quantize */
1828     if(s->out_format==FMT_MJPEG){
1829         for(i=0;i<6;i++) {
1830             int overflow;
1831             s->block_last_index[i] = s->dct_quantize(s, s->block[i], i, 8, &overflow);
1832             if (overflow) clip_coeffs(s, s->block[i], s->block_last_index[i]);
1833         }
1834     }else{
1835         for(i=0;i<6;i++) {
1836             if(!skip_dct[i]){
1837                 int overflow;
1838                 s->block_last_index[i] = s->dct_quantize(s, s->block[i], i, s->qscale, &overflow);
1839             // FIXME we could decide to change to quantizer instead of clipping
1840             // JS: I don't think that would be a good idea it could lower quality instead
1841             //     of improve it. Just INTRADC clipping deserves changes in quantizer
1842                 if (overflow) clip_coeffs(s, s->block[i], s->block_last_index[i]);
1843             }else
1844                 s->block_last_index[i]= -1;
1845         }
1846         if(s->luma_elim_threshold && !s->mb_intra)
1847             for(i=0; i<4; i++)
1848                 dct_single_coeff_elimination(s, i, s->luma_elim_threshold);
1849         if(s->chroma_elim_threshold && !s->mb_intra)
1850             for(i=4; i<6; i++)
1851                 dct_single_coeff_elimination(s, i, s->chroma_elim_threshold);
1852     }
1853
1854     if((s->flags&CODEC_FLAG_GRAY) && s->mb_intra){
1855         s->block_last_index[4]=
1856         s->block_last_index[5]= 0;
1857         s->block[4][0]=
1858         s->block[5][0]= 128;
1859     }
1860
1861     /* huffman encode */
1862     switch(s->out_format) {
1863     case FMT_MPEG1:
1864         mpeg1_encode_mb(s, s->block, motion_x, motion_y);
1865         break;
1866     case FMT_H263:
1867         if (s->h263_msmpeg4)
1868             msmpeg4_encode_mb(s, s->block, motion_x, motion_y);
1869         else if(s->h263_pred)
1870             mpeg4_encode_mb(s, s->block, motion_x, motion_y);
1871         else
1872             h263_encode_mb(s, s->block, motion_x, motion_y);
1873         break;
1874     case FMT_MJPEG:
1875         mjpeg_encode_mb(s, s->block);
1876         break;
1877     }
1878 }
1879
1880 void ff_copy_bits(PutBitContext *pb, UINT8 *src, int length)
1881 {
1882     int bytes= length>>4;
1883     int bits= length&15;
1884     int i;
1885
1886     if(length==0) return;
1887
1888     for(i=0; i<bytes; i++) put_bits(pb, 16, be2me_16(((uint16_t*)src)[i]));
1889     put_bits(pb, bits, be2me_16(((uint16_t*)src)[i])>>(16-bits));
1890 }
1891
1892 static inline void copy_context_before_encode(MpegEncContext *d, MpegEncContext *s, int type){
1893     int i;
1894
1895     memcpy(d->last_mv, s->last_mv, 2*2*2*sizeof(int)); //FIXME is memcpy faster then a loop?
1896
1897     /* mpeg1 */
1898     d->mb_incr= s->mb_incr;
1899     for(i=0; i<3; i++)
1900         d->last_dc[i]= s->last_dc[i];
1901     
1902     /* statistics */
1903     d->mv_bits= s->mv_bits;
1904     d->i_tex_bits= s->i_tex_bits;
1905     d->p_tex_bits= s->p_tex_bits;
1906     d->i_count= s->i_count;
1907     d->p_count= s->p_count;
1908     d->skip_count= s->skip_count;
1909     d->misc_bits= s->misc_bits;
1910     d->last_bits= 0;
1911
1912     d->mb_skiped= s->mb_skiped;
1913 }
1914
1915 static inline void copy_context_after_encode(MpegEncContext *d, MpegEncContext *s, int type){
1916     int i;
1917
1918     memcpy(d->mv, s->mv, 2*4*2*sizeof(int)); 
1919     memcpy(d->last_mv, s->last_mv, 2*2*2*sizeof(int)); //FIXME is memcpy faster then a loop?
1920     
1921     /* mpeg1 */
1922     d->mb_incr= s->mb_incr;
1923     for(i=0; i<3; i++)
1924         d->last_dc[i]= s->last_dc[i];
1925     
1926     /* statistics */
1927     d->mv_bits= s->mv_bits;
1928     d->i_tex_bits= s->i_tex_bits;
1929     d->p_tex_bits= s->p_tex_bits;
1930     d->i_count= s->i_count;
1931     d->p_count= s->p_count;
1932     d->skip_count= s->skip_count;
1933     d->misc_bits= s->misc_bits;
1934
1935     d->mb_intra= s->mb_intra;
1936     d->mb_skiped= s->mb_skiped;
1937     d->mv_type= s->mv_type;
1938     d->mv_dir= s->mv_dir;
1939     d->pb= s->pb;
1940     if(s->data_partitioning){
1941         d->pb2= s->pb2;
1942         d->tex_pb= s->tex_pb;
1943     }
1944     d->block= s->block;
1945     for(i=0; i<6; i++)
1946         d->block_last_index[i]= s->block_last_index[i];
1947 }
1948
1949 static inline void encode_mb_hq(MpegEncContext *s, MpegEncContext *backup, MpegEncContext *best, int type, 
1950                            PutBitContext pb[2], PutBitContext pb2[2], PutBitContext tex_pb[2],
1951                            int *dmin, int *next_block, int motion_x, int motion_y)
1952 {
1953     int bits_count;
1954     
1955     copy_context_before_encode(s, backup, type);
1956
1957     s->block= s->blocks[*next_block];
1958     s->pb= pb[*next_block];
1959     if(s->data_partitioning){
1960         s->pb2   = pb2   [*next_block];
1961         s->tex_pb= tex_pb[*next_block];
1962     }
1963
1964     encode_mb(s, motion_x, motion_y);
1965
1966     bits_count= get_bit_count(&s->pb);
1967     if(s->data_partitioning){
1968         bits_count+= get_bit_count(&s->pb2);
1969         bits_count+= get_bit_count(&s->tex_pb);
1970     }
1971
1972     if(bits_count<*dmin){
1973         *dmin= bits_count;
1974         *next_block^=1;
1975
1976         copy_context_after_encode(best, s, type);
1977     }
1978 }
1979
1980 static void encode_picture(MpegEncContext *s, int picture_number)
1981 {
1982     int mb_x, mb_y, last_gob, pdif = 0;
1983     int i;
1984     int bits;
1985     MpegEncContext best_s, backup_s;
1986     UINT8 bit_buf[2][3000];
1987     UINT8 bit_buf2[2][3000];
1988     UINT8 bit_buf_tex[2][3000];
1989     PutBitContext pb[2], pb2[2], tex_pb[2];
1990
1991     for(i=0; i<2; i++){
1992         init_put_bits(&pb    [i], bit_buf    [i], 3000, NULL, NULL);
1993         init_put_bits(&pb2   [i], bit_buf2   [i], 3000, NULL, NULL);
1994         init_put_bits(&tex_pb[i], bit_buf_tex[i], 3000, NULL, NULL);
1995     }
1996
1997     s->picture_number = picture_number;
1998
1999     s->block_wrap[0]=
2000     s->block_wrap[1]=
2001     s->block_wrap[2]=
2002     s->block_wrap[3]= s->mb_width*2 + 2;
2003     s->block_wrap[4]=
2004     s->block_wrap[5]= s->mb_width + 2;
2005     
2006     /* Reset the average MB variance */
2007     s->mb_var_sum = 0;
2008     s->mc_mb_var_sum = 0;
2009
2010     /* we need to initialize some time vars before we can encode b-frames */
2011     if (s->h263_pred && !s->h263_msmpeg4)
2012         ff_set_mpeg4_time(s, s->picture_number); 
2013
2014     s->scene_change_score=0;
2015
2016     /* Estimate motion for every MB */
2017     if(s->pict_type != I_TYPE){
2018         for(mb_y=0; mb_y < s->mb_height; mb_y++) {
2019             s->block_index[0]= s->block_wrap[0]*(mb_y*2 + 1) - 1;
2020             s->block_index[1]= s->block_wrap[0]*(mb_y*2 + 1);
2021             s->block_index[2]= s->block_wrap[0]*(mb_y*2 + 2) - 1;
2022             s->block_index[3]= s->block_wrap[0]*(mb_y*2 + 2);
2023             for(mb_x=0; mb_x < s->mb_width; mb_x++) {
2024                 s->mb_x = mb_x;
2025                 s->mb_y = mb_y;
2026                 s->block_index[0]+=2;
2027                 s->block_index[1]+=2;
2028                 s->block_index[2]+=2;
2029                 s->block_index[3]+=2;
2030
2031                 /* compute motion vector & mb_type and store in context */
2032                 if(s->pict_type==B_TYPE)
2033                     ff_estimate_b_frame_motion(s, mb_x, mb_y);
2034                 else
2035                     ff_estimate_p_frame_motion(s, mb_x, mb_y);
2036 //                s->mb_type[mb_y*s->mb_width + mb_x]=MB_TYPE_INTER;
2037             }
2038         }
2039         emms_c();
2040     }else /* if(s->pict_type == I_TYPE) */{
2041         /* I-Frame */
2042         //FIXME do we need to zero them?
2043         memset(s->motion_val[0], 0, sizeof(INT16)*(s->mb_width*2 + 2)*(s->mb_height*2 + 2)*2);
2044         memset(s->p_mv_table   , 0, sizeof(INT16)*(s->mb_width+2)*(s->mb_height+2)*2);
2045         memset(s->mb_type      , MB_TYPE_INTRA, sizeof(UINT8)*s->mb_width*s->mb_height);
2046         
2047         if(!s->fixed_qscale){
2048             /* finding spatial complexity for I-frame rate control */
2049             for(mb_y=0; mb_y < s->mb_height; mb_y++) {
2050                 for(mb_x=0; mb_x < s->mb_width; mb_x++) {
2051                     int xx = mb_x * 16;
2052                     int yy = mb_y * 16;
2053                     uint8_t *pix = s->new_picture[0] + (yy * s->linesize) + xx;
2054                     int varc;
2055                     int sum = pix_sum(pix, s->linesize);
2056     
2057                     sum= (sum+8)>>4;
2058                     varc = (pix_norm1(pix, s->linesize) - sum*sum + 500 + 128)>>8;
2059
2060                     s->mb_var[s->mb_width * mb_y + mb_x] = varc;
2061                     s->mb_var_sum    += varc;
2062                 }
2063             }
2064         }
2065     }
2066     if(s->scene_change_score > 0 && s->pict_type == P_TYPE){
2067         s->pict_type= I_TYPE;
2068         memset(s->mb_type   , MB_TYPE_INTRA, sizeof(UINT8)*s->mb_width*s->mb_height);
2069         if(s->max_b_frames==0){
2070             s->input_pict_type= I_TYPE;
2071             s->input_picture_in_gop_number=0;
2072         }
2073 //printf("Scene change detected, encoding as I Frame %d %d\n", s->mb_var_sum, s->mc_mb_var_sum);
2074     }
2075     
2076     if(s->pict_type==P_TYPE || s->pict_type==S_TYPE) 
2077         s->f_code= ff_get_best_fcode(s, s->p_mv_table, MB_TYPE_INTER);
2078         ff_fix_long_p_mvs(s);
2079     if(s->pict_type==B_TYPE){
2080         s->f_code= ff_get_best_fcode(s, s->b_forw_mv_table, MB_TYPE_FORWARD);
2081         s->b_code= ff_get_best_fcode(s, s->b_back_mv_table, MB_TYPE_BACKWARD);
2082
2083         ff_fix_long_b_mvs(s, s->b_forw_mv_table, s->f_code, MB_TYPE_FORWARD);
2084         ff_fix_long_b_mvs(s, s->b_back_mv_table, s->b_code, MB_TYPE_BACKWARD);
2085         ff_fix_long_b_mvs(s, s->b_bidir_forw_mv_table, s->f_code, MB_TYPE_BIDIR);
2086         ff_fix_long_b_mvs(s, s->b_bidir_back_mv_table, s->b_code, MB_TYPE_BIDIR);
2087     }
2088     
2089 //printf("f_code %d ///\n", s->f_code);
2090
2091 //    printf("%d %d\n", s->avg_mb_var, s->mc_mb_var);
2092     if (!s->fixed_qscale) 
2093         s->qscale = ff_rate_estimate_qscale(s);
2094
2095     if (s->out_format == FMT_MJPEG) {
2096         /* for mjpeg, we do include qscale in the matrix */
2097         s->intra_matrix[0] = ff_mpeg1_default_intra_matrix[0];
2098         for(i=1;i<64;i++)
2099             s->intra_matrix[i] = CLAMP_TO_8BIT((ff_mpeg1_default_intra_matrix[i] * s->qscale) >> 3);
2100         convert_matrix(s, s->q_intra_matrix, s->q_intra_matrix16, 
2101                        s->q_intra_matrix16_bias, s->intra_matrix, s->intra_quant_bias);
2102     }
2103
2104     s->last_bits= get_bit_count(&s->pb);
2105     switch(s->out_format) {
2106     case FMT_MJPEG:
2107         mjpeg_picture_header(s);
2108         break;
2109     case FMT_H263:
2110         if (s->h263_msmpeg4) 
2111             msmpeg4_encode_picture_header(s, picture_number);
2112         else if (s->h263_pred)
2113             mpeg4_encode_picture_header(s, picture_number);
2114         else if (s->h263_rv10) 
2115             rv10_encode_picture_header(s, picture_number);
2116         else
2117             h263_encode_picture_header(s, picture_number);
2118         break;
2119     case FMT_MPEG1:
2120         mpeg1_encode_picture_header(s, picture_number);
2121         break;
2122     }
2123     bits= get_bit_count(&s->pb);
2124     s->header_bits= bits - s->last_bits;
2125     s->last_bits= bits;
2126     s->mv_bits=0;
2127     s->misc_bits=0;
2128     s->i_tex_bits=0;
2129     s->p_tex_bits=0;
2130     s->i_count=0;
2131     s->p_count=0;
2132     s->skip_count=0;
2133
2134     /* init last dc values */
2135     /* note: quant matrix value (8) is implied here */
2136     s->last_dc[0] = 128;
2137     s->last_dc[1] = 128;
2138     s->last_dc[2] = 128;
2139     s->mb_incr = 1;
2140     s->last_mv[0][0][0] = 0;
2141     s->last_mv[0][0][1] = 0;
2142
2143     /* Get the GOB height based on picture height */
2144     if (s->out_format == FMT_H263 && !s->h263_pred && !s->h263_msmpeg4) {
2145         if (s->height <= 400)
2146             s->gob_index = 1;
2147         else if (s->height <= 800)
2148             s->gob_index = 2;
2149         else
2150             s->gob_index = 4;
2151     }else if(s->codec_id==CODEC_ID_MPEG4){
2152         s->gob_index = 1;
2153     }
2154
2155     if(s->codec_id==CODEC_ID_MPEG4 && s->data_partitioning && s->pict_type!=B_TYPE)
2156         ff_mpeg4_init_partitions(s);
2157
2158     s->resync_mb_x=0;
2159     s->resync_mb_y=0;
2160     for(mb_y=0; mb_y < s->mb_height; mb_y++) {
2161         /* Put GOB header based on RTP MTU for formats which support it per line (H263*)*/
2162         /* TODO: Put all this stuff in a separate generic function */
2163         if (s->rtp_mode) {
2164             if (!mb_y) {
2165                 s->ptr_lastgob = s->pb.buf;
2166                 s->ptr_last_mb_line = s->pb.buf;
2167             } else if (s->out_format == FMT_H263 && !s->h263_pred && !s->h263_msmpeg4 && !(mb_y % s->gob_index)) {
2168                 // MN: we could move the space check from h263 -> here, as its not h263 specific
2169                 last_gob = h263_encode_gob_header(s, mb_y);
2170                 if (last_gob) {
2171                     s->first_slice_line = 1;
2172                 }else{
2173                     /*MN: we reset it here instead at the end of each line cuz mpeg4 can have 
2174                           slice lines starting & ending in the middle*/
2175                     s->first_slice_line = 0;
2176                 }
2177             }
2178         }
2179
2180         s->y_dc_scale= s->y_dc_scale_table[ s->qscale ];
2181         s->c_dc_scale= s->c_dc_scale_table[ s->qscale ];
2182         
2183         s->block_index[0]= s->block_wrap[0]*(mb_y*2 + 1) - 1;
2184         s->block_index[1]= s->block_wrap[0]*(mb_y*2 + 1);
2185         s->block_index[2]= s->block_wrap[0]*(mb_y*2 + 2) - 1;
2186         s->block_index[3]= s->block_wrap[0]*(mb_y*2 + 2);
2187         s->block_index[4]= s->block_wrap[4]*(mb_y + 1)                    + s->block_wrap[0]*(s->mb_height*2 + 2);
2188         s->block_index[5]= s->block_wrap[4]*(mb_y + 1 + s->mb_height + 2) + s->block_wrap[0]*(s->mb_height*2 + 2);
2189         for(mb_x=0; mb_x < s->mb_width; mb_x++) {
2190             const int mb_type= s->mb_type[mb_y * s->mb_width + mb_x];
2191             const int xy= (mb_y+1) * (s->mb_width+2) + mb_x + 1;
2192 //            int d;
2193             int dmin=10000000;
2194
2195             s->mb_x = mb_x;
2196             s->mb_y = mb_y;
2197             s->block_index[0]+=2;
2198             s->block_index[1]+=2;
2199             s->block_index[2]+=2;
2200             s->block_index[3]+=2;
2201             s->block_index[4]++;
2202             s->block_index[5]++;
2203             
2204             /* write gob / video packet header for formats which support it at any MB (MPEG4) */
2205             if(s->rtp_mode && s->mb_y>0 && s->codec_id==CODEC_ID_MPEG4){
2206                 int pdif= pbBufPtr(&s->pb) - s->ptr_lastgob;
2207
2208                 //the *2 is there so we stay below the requested size
2209                 if(pdif + s->mb_line_avgsize/s->mb_width >= s->rtp_payload_size){ 
2210                     if(s->codec_id==CODEC_ID_MPEG4){
2211                         if(s->data_partitioning && s->pict_type!=B_TYPE){
2212                             ff_mpeg4_merge_partitions(s);
2213                             ff_mpeg4_init_partitions(s);
2214                         }
2215                         ff_mpeg4_encode_video_packet_header(s);
2216
2217                         if(s->flags&CODEC_FLAG_PASS1){
2218                             int bits= get_bit_count(&s->pb);
2219                             s->misc_bits+= bits - s->last_bits;
2220                             s->last_bits= bits;
2221                         }
2222                         ff_mpeg4_clean_buffers(s);
2223                     }
2224                     s->ptr_lastgob = pbBufPtr(&s->pb);
2225                     s->first_slice_line=1;
2226                     s->resync_mb_x=mb_x;
2227                     s->resync_mb_y=mb_y;
2228                 }
2229
2230                 if(  (s->resync_mb_x   == s->mb_x)
2231                    && s->resync_mb_y+1 == s->mb_y){
2232                     s->first_slice_line=0; 
2233                 }
2234             }
2235
2236             if(mb_type & (mb_type-1)){ // more than 1 MB type possible
2237                 int next_block=0;
2238                 int pb_bits_count, pb2_bits_count, tex_pb_bits_count;
2239
2240                 copy_context_before_encode(&backup_s, s, -1);
2241                 backup_s.pb= s->pb;
2242                 best_s.data_partitioning= s->data_partitioning;
2243                 if(s->data_partitioning){
2244                     backup_s.pb2= s->pb2;
2245                     backup_s.tex_pb= s->tex_pb;
2246                 }
2247
2248                 if(mb_type&MB_TYPE_INTER){
2249                     s->mv_dir = MV_DIR_FORWARD;
2250                     s->mv_type = MV_TYPE_16X16;
2251                     s->mb_intra= 0;
2252                     s->mv[0][0][0] = s->p_mv_table[xy][0];
2253                     s->mv[0][0][1] = s->p_mv_table[xy][1];
2254                     encode_mb_hq(s, &backup_s, &best_s, MB_TYPE_INTER, pb, pb2, tex_pb, 
2255                                  &dmin, &next_block, s->mv[0][0][0], s->mv[0][0][1]);
2256                 }
2257                 if(mb_type&MB_TYPE_INTER4V){                 
2258                     s->mv_dir = MV_DIR_FORWARD;
2259                     s->mv_type = MV_TYPE_8X8;
2260                     s->mb_intra= 0;
2261                     for(i=0; i<4; i++){
2262                         s->mv[0][i][0] = s->motion_val[s->block_index[i]][0];
2263                         s->mv[0][i][1] = s->motion_val[s->block_index[i]][1];
2264                     }
2265                     encode_mb_hq(s, &backup_s, &best_s, MB_TYPE_INTER4V, pb, pb2, tex_pb, 
2266                                  &dmin, &next_block, 0, 0);
2267                 }
2268                 if(mb_type&MB_TYPE_FORWARD){
2269                     s->mv_dir = MV_DIR_FORWARD;
2270                     s->mv_type = MV_TYPE_16X16;
2271                     s->mb_intra= 0;
2272                     s->mv[0][0][0] = s->b_forw_mv_table[xy][0];
2273                     s->mv[0][0][1] = s->b_forw_mv_table[xy][1];
2274                     encode_mb_hq(s, &backup_s, &best_s, MB_TYPE_FORWARD, pb, pb2, tex_pb, 
2275                                  &dmin, &next_block, s->mv[0][0][0], s->mv[0][0][1]);
2276                 }
2277                 if(mb_type&MB_TYPE_BACKWARD){
2278                     s->mv_dir = MV_DIR_BACKWARD;
2279                     s->mv_type = MV_TYPE_16X16;
2280                     s->mb_intra= 0;
2281                     s->mv[1][0][0] = s->b_back_mv_table[xy][0];
2282                     s->mv[1][0][1] = s->b_back_mv_table[xy][1];
2283                     encode_mb_hq(s, &backup_s, &best_s, MB_TYPE_BACKWARD, pb, pb2, tex_pb, 
2284                                  &dmin, &next_block, s->mv[1][0][0], s->mv[1][0][1]);
2285                 }
2286                 if(mb_type&MB_TYPE_BIDIR){
2287                     s->mv_dir = MV_DIR_FORWARD | MV_DIR_BACKWARD;
2288                     s->mv_type = MV_TYPE_16X16;
2289                     s->mb_intra= 0;
2290                     s->mv[0][0][0] = s->b_bidir_forw_mv_table[xy][0];
2291                     s->mv[0][0][1] = s->b_bidir_forw_mv_table[xy][1];
2292                     s->mv[1][0][0] = s->b_bidir_back_mv_table[xy][0];
2293                     s->mv[1][0][1] = s->b_bidir_back_mv_table[xy][1];
2294                     encode_mb_hq(s, &backup_s, &best_s, MB_TYPE_BIDIR, pb, pb2, tex_pb, 
2295                                  &dmin, &next_block, 0, 0);
2296                 }
2297                 if(mb_type&MB_TYPE_DIRECT){
2298                     s->mv_dir = MV_DIR_FORWARD | MV_DIR_BACKWARD | MV_DIRECT;
2299                     s->mv_type = MV_TYPE_16X16; //FIXME
2300                     s->mb_intra= 0;
2301                     s->mv[0][0][0] = s->b_direct_forw_mv_table[xy][0];
2302                     s->mv[0][0][1] = s->b_direct_forw_mv_table[xy][1];
2303                     s->mv[1][0][0] = s->b_direct_back_mv_table[xy][0];
2304                     s->mv[1][0][1] = s->b_direct_back_mv_table[xy][1];
2305                     encode_mb_hq(s, &backup_s, &best_s, MB_TYPE_DIRECT, pb, pb2, tex_pb, 
2306                                  &dmin, &next_block, s->b_direct_mv_table[xy][0], s->b_direct_mv_table[xy][1]);
2307                 }
2308                 if(mb_type&MB_TYPE_INTRA){
2309                     s->mv_dir = MV_DIR_FORWARD;
2310                     s->mv_type = MV_TYPE_16X16;
2311                     s->mb_intra= 1;
2312                     s->mv[0][0][0] = 0;
2313                     s->mv[0][0][1] = 0;
2314                     encode_mb_hq(s, &backup_s, &best_s, MB_TYPE_INTRA, pb, pb2, tex_pb, 
2315                                  &dmin, &next_block, 0, 0);
2316                     /* force cleaning of ac/dc pred stuff if needed ... */
2317                     if(s->h263_pred || s->h263_aic)
2318                         s->mbintra_table[mb_x + mb_y*s->mb_width]=1;
2319                 }
2320                 copy_context_after_encode(s, &best_s, -1);
2321                 
2322                 pb_bits_count= get_bit_count(&s->pb);
2323                 flush_put_bits(&s->pb);
2324                 ff_copy_bits(&backup_s.pb, bit_buf[next_block^1], pb_bits_count);
2325                 s->pb= backup_s.pb;
2326                 
2327                 if(s->data_partitioning){
2328                     pb2_bits_count= get_bit_count(&s->pb2);
2329                     flush_put_bits(&s->pb2);
2330                     ff_copy_bits(&backup_s.pb2, bit_buf2[next_block^1], pb2_bits_count);
2331                     s->pb2= backup_s.pb2;
2332                     
2333                     tex_pb_bits_count= get_bit_count(&s->tex_pb);
2334                     flush_put_bits(&s->tex_pb);
2335                     ff_copy_bits(&backup_s.tex_pb, bit_buf_tex[next_block^1], tex_pb_bits_count);
2336                     s->tex_pb= backup_s.tex_pb;
2337                 }
2338                 s->last_bits= get_bit_count(&s->pb);
2339             } else {
2340                 int motion_x, motion_y;
2341                 s->mv_type=MV_TYPE_16X16;
2342                 // only one MB-Type possible
2343                 switch(mb_type){
2344                 case MB_TYPE_INTRA:
2345                     s->mv_dir = MV_DIR_FORWARD;
2346                     s->mb_intra= 1;
2347                     motion_x= s->mv[0][0][0] = 0;
2348                     motion_y= s->mv[0][0][1] = 0;
2349                     break;
2350                 case MB_TYPE_INTER:
2351                     s->mv_dir = MV_DIR_FORWARD;
2352                     s->mb_intra= 0;
2353                     motion_x= s->mv[0][0][0] = s->p_mv_table[xy][0];
2354                     motion_y= s->mv[0][0][1] = s->p_mv_table[xy][1];
2355                     break;
2356                 case MB_TYPE_INTER4V:
2357                     s->mv_dir = MV_DIR_FORWARD;
2358                     s->mv_type = MV_TYPE_8X8;
2359                     s->mb_intra= 0;
2360                     for(i=0; i<4; i++){
2361                         s->mv[0][i][0] = s->motion_val[s->block_index[i]][0];
2362                         s->mv[0][i][1] = s->motion_val[s->block_index[i]][1];
2363                     }
2364                     motion_x= motion_y= 0;
2365                     break;
2366                 case MB_TYPE_DIRECT:
2367                     s->mv_dir = MV_DIR_FORWARD | MV_DIR_BACKWARD | MV_DIRECT;
2368                     s->mb_intra= 0;
2369                     motion_x=s->b_direct_mv_table[xy][0];
2370                     motion_y=s->b_direct_mv_table[xy][1];
2371                     s->mv[0][0][0] = s->b_direct_forw_mv_table[xy][0];
2372                     s->mv[0][0][1] = s->b_direct_forw_mv_table[xy][1];
2373                     s->mv[1][0][0] = s->b_direct_back_mv_table[xy][0];
2374                     s->mv[1][0][1] = s->b_direct_back_mv_table[xy][1];
2375                     break;
2376                 case MB_TYPE_BIDIR:
2377                     s->mv_dir = MV_DIR_FORWARD | MV_DIR_BACKWARD;
2378                     s->mb_intra= 0;
2379                     motion_x=0;
2380                     motion_y=0;
2381                     s->mv[0][0][0] = s->b_bidir_forw_mv_table[xy][0];
2382                     s->mv[0][0][1] = s->b_bidir_forw_mv_table[xy][1];
2383                     s->mv[1][0][0] = s->b_bidir_back_mv_table[xy][0];
2384                     s->mv[1][0][1] = s->b_bidir_back_mv_table[xy][1];
2385                     break;
2386                 case MB_TYPE_BACKWARD:
2387                     s->mv_dir = MV_DIR_BACKWARD;
2388                     s->mb_intra= 0;
2389                     motion_x= s->mv[1][0][0] = s->b_back_mv_table[xy][0];
2390                     motion_y= s->mv[1][0][1] = s->b_back_mv_table[xy][1];
2391                     break;
2392                 case MB_TYPE_FORWARD:
2393                     s->mv_dir = MV_DIR_FORWARD;
2394                     s->mb_intra= 0;
2395                     motion_x= s->mv[0][0][0] = s->b_forw_mv_table[xy][0];
2396                     motion_y= s->mv[0][0][1] = s->b_forw_mv_table[xy][1];
2397 //                    printf(" %d %d ", motion_x, motion_y);
2398                     break;
2399                 default:
2400                     motion_x=motion_y=0; //gcc warning fix
2401                     printf("illegal MB type\n");
2402                 }
2403                 encode_mb(s, motion_x, motion_y);
2404             }
2405             /* clean the MV table in IPS frames for direct mode in B frames */
2406             if(s->mb_intra /* && I,P,S_TYPE */){
2407                 s->p_mv_table[xy][0]=0;
2408                 s->p_mv_table[xy][1]=0;
2409             }
2410
2411             MPV_decode_mb(s, s->block);
2412 //printf("MB %d %d bits\n", s->mb_x+s->mb_y*s->mb_width, get_bit_count(&s->pb));
2413         }
2414
2415
2416         /* Obtain average GOB size for RTP */
2417         if (s->rtp_mode) {
2418             if (!mb_y)
2419                 s->mb_line_avgsize = pbBufPtr(&s->pb) - s->ptr_last_mb_line;
2420             else if (!(mb_y % s->gob_index)) {    
2421                 s->mb_line_avgsize = (s->mb_line_avgsize + pbBufPtr(&s->pb) - s->ptr_last_mb_line) >> 1;
2422                 s->ptr_last_mb_line = pbBufPtr(&s->pb);
2423             }
2424             //fprintf(stderr, "\nMB line: %d\tSize: %u\tAvg. Size: %u", s->mb_y, 
2425             //                    (s->pb.buf_ptr - s->ptr_last_mb_line), s->mb_line_avgsize);
2426             if(s->codec_id!=CODEC_ID_MPEG4) s->first_slice_line = 0; //FIXME clean
2427         }
2428     }
2429     emms_c();
2430
2431     if(s->codec_id==CODEC_ID_MPEG4 && s->data_partitioning && s->pict_type!=B_TYPE)
2432         ff_mpeg4_merge_partitions(s);
2433
2434     if (s->msmpeg4_version && s->msmpeg4_version<4 && s->pict_type == I_TYPE)
2435         msmpeg4_encode_ext_header(s);
2436
2437     if(s->codec_id==CODEC_ID_MPEG4) 
2438         ff_mpeg4_stuffing(&s->pb);
2439
2440     //if (s->gob_number)
2441     //    fprintf(stderr,"\nNumber of GOB: %d", s->gob_number);
2442     
2443     /* Send the last GOB if RTP */    
2444     if (s->rtp_mode) {
2445         flush_put_bits(&s->pb);
2446         pdif = pbBufPtr(&s->pb) - s->ptr_lastgob;
2447         /* Call the RTP callback to send the last GOB */
2448         if (s->rtp_callback)
2449             s->rtp_callback(s->ptr_lastgob, pdif, s->gob_number);
2450         s->ptr_lastgob = pbBufPtr(&s->pb);
2451         //fprintf(stderr,"\nGOB: %2d size: %d (last)", s->gob_number, pdif);
2452     }
2453 }
2454
2455 static int dct_quantize_c(MpegEncContext *s, 
2456                         DCTELEM *block, int n,
2457                         int qscale, int *overflow)
2458 {
2459     int i, j, level, last_non_zero, q;
2460     const int *qmat;
2461     int bias;
2462     int max=0;
2463     unsigned int threshold1, threshold2;
2464     
2465     s->fdct (block);
2466
2467     /* we need this permutation so that we correct the IDCT
2468        permutation. will be moved into DCT code */
2469     block_permute(block);
2470
2471     if (s->mb_intra) {
2472         if (!s->h263_aic) {
2473             if (n < 4)
2474                 q = s->y_dc_scale;
2475             else
2476                 q = s->c_dc_scale;
2477             q = q << 3;
2478         } else
2479             /* For AIC we skip quant/dequant of INTRADC */
2480             q = 1 << 3;
2481             
2482         /* note: block[0] is assumed to be positive */
2483         block[0] = (block[0] + (q >> 1)) / q;
2484         i = 1;
2485         last_non_zero = 0;
2486         qmat = s->q_intra_matrix[qscale];
2487         bias= s->intra_quant_bias<<(QMAT_SHIFT - 3 - QUANT_BIAS_SHIFT);
2488     } else {
2489         i = 0;
2490         last_non_zero = -1;
2491         qmat = s->q_inter_matrix[qscale];
2492         bias= s->inter_quant_bias<<(QMAT_SHIFT - 3 - QUANT_BIAS_SHIFT);
2493     }
2494     threshold1= (1<<(QMAT_SHIFT - 3)) - bias - 1;
2495     threshold2= threshold1<<1;
2496
2497     for(;i<64;i++) {
2498         j = zigzag_direct[i];
2499         level = block[j];
2500         level = level * qmat[j];
2501
2502 //        if(   bias+level >= (1<<(QMAT_SHIFT - 3))
2503 //           || bias-level >= (1<<(QMAT_SHIFT - 3))){
2504         if(((unsigned)(level+threshold1))>threshold2){
2505             if(level>0){
2506                 level= (bias + level)>>(QMAT_SHIFT - 3);
2507                 block[j]= level;
2508             }else{
2509                 level= (bias - level)>>(QMAT_SHIFT - 3);
2510                 block[j]= -level;
2511             }
2512             max |=level;
2513             last_non_zero = i;
2514         }else{
2515             block[j]=0;
2516         }
2517     }
2518     *overflow= s->max_qcoeff < max; //overflow might have happend
2519     
2520     return last_non_zero;
2521 }
2522
2523 static void dct_unquantize_mpeg1_c(MpegEncContext *s, 
2524                                    DCTELEM *block, int n, int qscale)
2525 {
2526     int i, level, nCoeffs;
2527     const UINT16 *quant_matrix;
2528
2529     if(s->alternate_scan) nCoeffs= 64;
2530     else nCoeffs= s->block_last_index[n]+1;
2531     
2532     if (s->mb_intra) {
2533         if (n < 4) 
2534             block[0] = block[0] * s->y_dc_scale;
2535         else
2536             block[0] = block[0] * s->c_dc_scale;
2537         /* XXX: only mpeg1 */
2538         quant_matrix = s->intra_matrix;
2539         for(i=1;i<nCoeffs;i++) {
2540             int j= zigzag_direct[i];
2541             level = block[j];
2542             if (level) {
2543                 if (level < 0) {
2544                     level = -level;
2545                     level = (int)(level * qscale * quant_matrix[j]) >> 3;
2546                     level = (level - 1) | 1;
2547                     level = -level;
2548                 } else {
2549                     level = (int)(level * qscale * quant_matrix[j]) >> 3;
2550                     level = (level - 1) | 1;
2551                 }
2552 #ifdef PARANOID
2553                 if (level < -2048 || level > 2047)
2554                     fprintf(stderr, "unquant error %d %d\n", i, level);
2555 #endif
2556                 block[j] = level;
2557             }
2558         }
2559     } else {
2560         i = 0;
2561         quant_matrix = s->inter_matrix;
2562         for(;i<nCoeffs;i++) {
2563             int j= zigzag_direct[i];
2564             level = block[j];
2565             if (level) {
2566                 if (level < 0) {
2567                     level = -level;
2568                     level = (((level << 1) + 1) * qscale *
2569                              ((int) (quant_matrix[j]))) >> 4;
2570                     level = (level - 1) | 1;
2571                     level = -level;
2572                 } else {
2573                     level = (((level << 1) + 1) * qscale *
2574                              ((int) (quant_matrix[j]))) >> 4;
2575                     level = (level - 1) | 1;
2576                 }
2577 #ifdef PARANOID
2578                 if (level < -2048 || level > 2047)
2579                     fprintf(stderr, "unquant error %d %d\n", i, level);
2580 #endif
2581                 block[j] = level;
2582             }
2583         }
2584     }
2585 }
2586
2587 static void dct_unquantize_mpeg2_c(MpegEncContext *s, 
2588                                    DCTELEM *block, int n, int qscale)
2589 {
2590     int i, level, nCoeffs;
2591     const UINT16 *quant_matrix;
2592
2593     if(s->alternate_scan) nCoeffs= 64;
2594     else nCoeffs= s->block_last_index[n]+1;
2595     
2596     if (s->mb_intra) {
2597         if (n < 4) 
2598             block[0] = block[0] * s->y_dc_scale;
2599         else
2600             block[0] = block[0] * s->c_dc_scale;
2601         quant_matrix = s->intra_matrix;
2602         for(i=1;i<nCoeffs;i++) {
2603             int j= zigzag_direct[i];
2604             level = block[j];
2605             if (level) {
2606                 if (level < 0) {
2607                     level = -level;
2608                     level = (int)(level * qscale * quant_matrix[j]) >> 3;
2609                     level = -level;
2610                 } else {
2611                     level = (int)(level * qscale * quant_matrix[j]) >> 3;
2612                 }
2613 #ifdef PARANOID
2614                 if (level < -2048 || level > 2047)
2615                     fprintf(stderr, "unquant error %d %d\n", i, level);
2616 #endif
2617                 block[j] = level;
2618             }
2619         }
2620     } else {
2621         int sum=-1;
2622         i = 0;
2623         quant_matrix = s->inter_matrix;
2624         for(;i<nCoeffs;i++) {
2625             int j= zigzag_direct[i];
2626             level = block[j];
2627             if (level) {
2628                 if (level < 0) {
2629                     level = -level;
2630                     level = (((level << 1) + 1) * qscale *
2631                              ((int) (quant_matrix[j]))) >> 4;
2632                     level = -level;
2633                 } else {
2634                     level = (((level << 1) + 1) * qscale *
2635                              ((int) (quant_matrix[j]))) >> 4;
2636                 }
2637 #ifdef PARANOID
2638                 if (level < -2048 || level > 2047)
2639                     fprintf(stderr, "unquant error %d %d\n", i, level);
2640 #endif
2641                 block[j] = level;
2642                 sum+=level;
2643             }
2644         }
2645         block[63]^=sum&1;
2646     }
2647 }
2648
2649
2650 static void dct_unquantize_h263_c(MpegEncContext *s, 
2651                                   DCTELEM *block, int n, int qscale)
2652 {
2653     int i, level, qmul, qadd;
2654     int nCoeffs;
2655     
2656     if (s->mb_intra) {
2657         if (!s->h263_aic) {
2658             if (n < 4) 
2659                 block[0] = block[0] * s->y_dc_scale;
2660             else
2661                 block[0] = block[0] * s->c_dc_scale;
2662         }
2663         i = 1;
2664         nCoeffs= 64; //does not allways use zigzag table 
2665     } else {
2666         i = 0;
2667         nCoeffs= zigzag_end[ s->block_last_index[n] ];
2668     }
2669
2670     qmul = s->qscale << 1;
2671     if (s->h263_aic && s->mb_intra)
2672         qadd = 0;
2673     else
2674         qadd = (s->qscale - 1) | 1;
2675
2676     for(;i<nCoeffs;i++) {
2677         level = block[i];
2678         if (level) {
2679             if (level < 0) {
2680                 level = level * qmul - qadd;
2681             } else {
2682                 level = level * qmul + qadd;
2683             }
2684 #ifdef PARANOID
2685                 if (level < -2048 || level > 2047)
2686                     fprintf(stderr, "unquant error %d %d\n", i, level);
2687 #endif
2688             block[i] = level;
2689         }
2690     }
2691 }
2692
2693 static void remove_ac(MpegEncContext *s, uint8_t *dest_y, uint8_t *dest_cb, uint8_t *dest_cr, int mb_x, int mb_y)
2694 {
2695     int dc, dcb, dcr, y, i;
2696     for(i=0; i<4; i++){
2697         dc= s->dc_val[0][mb_x*2+1 + (i&1) + (mb_y*2+1 + (i>>1))*(s->mb_width*2+2)];
2698         for(y=0; y<8; y++){
2699             int x;
2700             for(x=0; x<8; x++){
2701                 dest_y[x + (i&1)*8 + (y + (i>>1)*8)*s->linesize]= dc/8;
2702             }
2703         }
2704     }
2705     dcb = s->dc_val[1][mb_x+1 + (mb_y+1)*(s->mb_width+2)];
2706     dcr= s->dc_val[2][mb_x+1 + (mb_y+1)*(s->mb_width+2)];
2707     for(y=0; y<8; y++){
2708         int x;
2709         for(x=0; x<8; x++){
2710             dest_cb[x + y*(s->uvlinesize)]= dcb/8;
2711             dest_cr[x + y*(s->uvlinesize)]= dcr/8;
2712         }
2713     }
2714 }
2715
2716 /**
2717  * will conceal past errors, and allso drop b frames if needed
2718  *
2719  */
2720 void ff_conceal_past_errors(MpegEncContext *s, int unknown_pos)
2721 {
2722     int mb_x= s->mb_x;
2723     int mb_y= s->mb_y;
2724     int mb_dist=0;
2725     int i, intra_count=0, inter_count=0;
2726     int intra_conceal= s->msmpeg4_version ? 50 : 50; //FIXME finetune
2727     int inter_conceal= s->msmpeg4_version ? 50 : 50;
2728
2729     // for last block
2730     if(mb_x>=s->mb_width)  mb_x= s->mb_width -1;
2731     if(mb_y>=s->mb_height) mb_y= s->mb_height-1;
2732
2733     if(s->decoding_error==0 && unknown_pos){
2734         if(s->data_partitioning && s->pict_type!=B_TYPE)
2735                 s->decoding_error= DECODING_AC_LOST;
2736         else
2737                 s->decoding_error= DECODING_DESYNC;
2738     }
2739
2740     if(s->decoding_error==DECODING_DESYNC && s->pict_type!=B_TYPE) s->next_p_frame_damaged=1;
2741
2742     for(i=mb_x + mb_y*s->mb_width; i>=0; i--){
2743         if(s->mbintra_table[i]) intra_count++;
2744         else                    inter_count++;
2745     }
2746     
2747     if(s->decoding_error==DECODING_AC_LOST){
2748         intra_conceal*=2;
2749         inter_conceal*=2;
2750     }else if(s->decoding_error==DECODING_ACDC_LOST){
2751         intra_conceal*=2;
2752         inter_conceal*=2;
2753     }
2754
2755     if(unknown_pos && (intra_count<inter_count)){
2756         intra_conceal= inter_conceal= s->mb_num; 
2757 //        printf("%d %d\n",intra_count, inter_count);
2758     }
2759
2760     fprintf(stderr, "concealing errors\n");
2761
2762     /* for all MBs from the current one back until the last resync marker */
2763     for(; mb_y>=0 && mb_y>=s->resync_mb_y; mb_y--){
2764         for(; mb_x>=0; mb_x--){
2765             uint8_t *dest_y  = s->current_picture[0] + (mb_y * 16*  s->linesize      ) + mb_x * 16;
2766             uint8_t *dest_cb = s->current_picture[1] + (mb_y * 8 * (s->uvlinesize)) + mb_x * 8;
2767             uint8_t *dest_cr = s->current_picture[2] + (mb_y * 8 * (s->uvlinesize)) + mb_x * 8;
2768             int mb_x_backup= s->mb_x; //FIXME pass xy to mpeg_motion
2769             int mb_y_backup= s->mb_y;
2770             s->mb_x=mb_x;
2771             s->mb_y=mb_y;
2772             if(s->mbintra_table[mb_y*s->mb_width + mb_x] && mb_dist<intra_conceal){
2773                 if(s->decoding_error==DECODING_AC_LOST){
2774                     remove_ac(s, dest_y, dest_cb, dest_cr, mb_x, mb_y);
2775 //                    printf("remove ac to %d %d\n", mb_x, mb_y);
2776                 }else{
2777                     mpeg_motion(s, dest_y, dest_cb, dest_cr, 0, 
2778                                 s->last_picture, 0, 0, put_pixels_tab,
2779                                 0/*mx*/, 0/*my*/, 16);
2780                 }
2781             }
2782             else if(!s->mbintra_table[mb_y*s->mb_width + mb_x] && mb_dist<inter_conceal){
2783                 int mx=0;
2784                 int my=0;
2785
2786                 if(s->decoding_error!=DECODING_DESYNC){
2787                     int xy= mb_x*2+1 + (mb_y*2+1)*(s->mb_width*2+2);
2788                     mx= s->motion_val[ xy ][0];
2789                     my= s->motion_val[ xy ][1];
2790                 }
2791
2792                 mpeg_motion(s, dest_y, dest_cb, dest_cr, 0, 
2793                             s->last_picture, 0, 0, put_pixels_tab,
2794                             mx, my, 16);
2795             }
2796             s->mb_x= mb_x_backup;
2797             s->mb_y= mb_y_backup;
2798
2799             if(mb_x== s->resync_mb_x && mb_y== s->resync_mb_y) return;
2800             if(!s->mbskip_table[mb_x + mb_y*s->mb_width]) mb_dist++;
2801         }
2802         mb_x=s->mb_width-1;
2803     }
2804 }
2805
2806 AVCodec mpeg1video_encoder = {
2807     "mpeg1video",
2808     CODEC_TYPE_VIDEO,
2809     CODEC_ID_MPEG1VIDEO,
2810     sizeof(MpegEncContext),
2811     MPV_encode_init,
2812     MPV_encode_picture,
2813     MPV_encode_end,
2814 };
2815
2816 AVCodec h263_encoder = {
2817     "h263",
2818     CODEC_TYPE_VIDEO,
2819     CODEC_ID_H263,
2820     sizeof(MpegEncContext),
2821     MPV_encode_init,
2822     MPV_encode_picture,
2823     MPV_encode_end,
2824 };
2825
2826 AVCodec h263p_encoder = {
2827     "h263p",
2828     CODEC_TYPE_VIDEO,
2829     CODEC_ID_H263P,
2830     sizeof(MpegEncContext),
2831     MPV_encode_init,
2832     MPV_encode_picture,
2833     MPV_encode_end,
2834 };
2835
2836 AVCodec rv10_encoder = {
2837     "rv10",
2838     CODEC_TYPE_VIDEO,
2839     CODEC_ID_RV10,
2840     sizeof(MpegEncContext),
2841     MPV_encode_init,
2842     MPV_encode_picture,
2843     MPV_encode_end,
2844 };
2845
2846 AVCodec mjpeg_encoder = {
2847     "mjpeg",
2848     CODEC_TYPE_VIDEO,
2849     CODEC_ID_MJPEG,
2850     sizeof(MpegEncContext),
2851     MPV_encode_init,
2852     MPV_encode_picture,
2853     MPV_encode_end,
2854 };
2855
2856 AVCodec mpeg4_encoder = {
2857     "mpeg4",
2858     CODEC_TYPE_VIDEO,
2859     CODEC_ID_MPEG4,
2860     sizeof(MpegEncContext),
2861     MPV_encode_init,
2862     MPV_encode_picture,
2863     MPV_encode_end,
2864 };
2865
2866 AVCodec msmpeg4v1_encoder = {
2867     "msmpeg4v1",
2868     CODEC_TYPE_VIDEO,
2869     CODEC_ID_MSMPEG4V1,
2870     sizeof(MpegEncContext),
2871     MPV_encode_init,
2872     MPV_encode_picture,
2873     MPV_encode_end,
2874 };
2875
2876 AVCodec msmpeg4v2_encoder = {
2877     "msmpeg4v2",
2878     CODEC_TYPE_VIDEO,
2879     CODEC_ID_MSMPEG4V2,
2880     sizeof(MpegEncContext),
2881     MPV_encode_init,
2882     MPV_encode_picture,
2883     MPV_encode_end,
2884 };
2885
2886 AVCodec msmpeg4v3_encoder = {
2887     "msmpeg4",
2888     CODEC_TYPE_VIDEO,
2889     CODEC_ID_MSMPEG4V3,
2890     sizeof(MpegEncContext),
2891     MPV_encode_init,
2892     MPV_encode_picture,
2893     MPV_encode_end,
2894 };
2895
2896 AVCodec wmv1_encoder = {
2897     "wmv1",
2898     CODEC_TYPE_VIDEO,
2899     CODEC_ID_WMV1,
2900     sizeof(MpegEncContext),
2901     MPV_encode_init,
2902     MPV_encode_picture,
2903     MPV_encode_end,
2904 };
2905
2906 AVCodec wmv2_encoder = {
2907     "wmv2",
2908     CODEC_TYPE_VIDEO,
2909     CODEC_ID_WMV2,
2910     sizeof(MpegEncContext),
2911     MPV_encode_init,
2912     MPV_encode_picture,
2913     MPV_encode_end,
2914 };