828e74a66870de9c34007e0f10de125f5380be03
[ffmpeg.git] / libavcodec / mpegvideo.c
1 /*
2  * The simplest mpeg encoder (well, it was the simplest!)
3  * Copyright (c) 2000,2001 Fabrice Bellard.
4  * Copyright (c) 2002-2004 Michael Niedermayer <michaelni@gmx.at>
5  *
6  * This library is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU Lesser General Public
8  * License as published by the Free Software Foundation; either
9  * version 2 of the License, or (at your option) any later version.
10  *
11  * This library is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14  * Lesser General Public License for more details.
15  *
16  * You should have received a copy of the GNU Lesser General Public
17  * License along with this library; if not, write to the Free Software
18  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
19  *
20  * 4MV & hq & b-frame encoding stuff by Michael Niedermayer <michaelni@gmx.at>
21  */
22  
23 /**
24  * @file mpegvideo.c
25  * The simplest mpeg encoder (well, it was the simplest!).
26  */ 
27  
28 #include <limits.h>
29 #include <math.h> //for PI
30 #include "avcodec.h"
31 #include "dsputil.h"
32 #include "mpegvideo.h"
33 #include "faandct.h"
34
35 #ifdef USE_FASTMEMCPY
36 #include "fastmemcpy.h"
37 #endif
38
39 //#undef NDEBUG
40 //#include <assert.h>
41
42 #ifdef CONFIG_ENCODERS
43 static void encode_picture(MpegEncContext *s, int picture_number);
44 #endif //CONFIG_ENCODERS
45 static void dct_unquantize_mpeg1_intra_c(MpegEncContext *s, 
46                                    DCTELEM *block, int n, int qscale);
47 static void dct_unquantize_mpeg1_inter_c(MpegEncContext *s, 
48                                    DCTELEM *block, int n, int qscale);
49 static void dct_unquantize_mpeg2_intra_c(MpegEncContext *s,
50                                    DCTELEM *block, int n, int qscale);
51 static void dct_unquantize_mpeg2_inter_c(MpegEncContext *s,
52                                    DCTELEM *block, int n, int qscale);
53 static void dct_unquantize_h263_intra_c(MpegEncContext *s, 
54                                   DCTELEM *block, int n, int qscale);
55 static void dct_unquantize_h263_inter_c(MpegEncContext *s, 
56                                   DCTELEM *block, int n, int qscale);
57 static void draw_edges_c(uint8_t *buf, int wrap, int width, int height, int w);
58 #ifdef CONFIG_ENCODERS
59 static int dct_quantize_c(MpegEncContext *s, DCTELEM *block, int n, int qscale, int *overflow);
60 static int dct_quantize_trellis_c(MpegEncContext *s, DCTELEM *block, int n, int qscale, int *overflow);
61 static int dct_quantize_refine(MpegEncContext *s, DCTELEM *block, int16_t *weight, DCTELEM *orig, int n, int qscale);
62 static int sse_mb(MpegEncContext *s);
63 static void  denoise_dct_c(MpegEncContext *s, DCTELEM *block);
64 #endif //CONFIG_ENCODERS
65
66 #ifdef HAVE_XVMC
67 extern int  XVMC_field_start(MpegEncContext*s, AVCodecContext *avctx);
68 extern void XVMC_field_end(MpegEncContext *s);
69 extern void XVMC_decode_mb(MpegEncContext *s);
70 #endif
71
72 void (*draw_edges)(uint8_t *buf, int wrap, int width, int height, int w)= draw_edges_c;
73
74
75 /* enable all paranoid tests for rounding, overflows, etc... */
76 //#define PARANOID
77
78 //#define DEBUG
79
80
81 /* for jpeg fast DCT */
82 #define CONST_BITS 14
83
84 static const uint16_t aanscales[64] = {
85     /* precomputed values scaled up by 14 bits */
86     16384, 22725, 21407, 19266, 16384, 12873,  8867,  4520,
87     22725, 31521, 29692, 26722, 22725, 17855, 12299,  6270,
88     21407, 29692, 27969, 25172, 21407, 16819, 11585,  5906,
89     19266, 26722, 25172, 22654, 19266, 15137, 10426,  5315,
90     16384, 22725, 21407, 19266, 16384, 12873,  8867,  4520,
91     12873, 17855, 16819, 15137, 12873, 10114,  6967,  3552,
92     8867 , 12299, 11585, 10426,  8867,  6967,  4799,  2446,
93     4520 ,  6270,  5906,  5315,  4520,  3552,  2446,  1247
94 };
95
96 static const uint8_t h263_chroma_roundtab[16] = {
97 //  0  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15
98     0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2,
99 };
100
101 static const uint8_t ff_default_chroma_qscale_table[32]={
102 //  0  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
103     0, 1, 2, 3, 4, 5, 6, 7, 8, 9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31
104 };
105
106 #ifdef CONFIG_ENCODERS
107 static uint8_t (*default_mv_penalty)[MAX_MV*2+1]=NULL;
108 static uint8_t default_fcode_tab[MAX_MV*2+1];
109
110 enum PixelFormat ff_yuv420p_list[2]= {PIX_FMT_YUV420P, -1};
111
112 static void convert_matrix(DSPContext *dsp, int (*qmat)[64], uint16_t (*qmat16)[2][64],
113                            const uint16_t *quant_matrix, int bias, int qmin, int qmax)
114 {
115     int qscale;
116
117     for(qscale=qmin; qscale<=qmax; qscale++){
118         int i;
119         if (dsp->fdct == ff_jpeg_fdct_islow 
120 #ifdef FAAN_POSTSCALE
121             || dsp->fdct == ff_faandct
122 #endif
123             ) {
124             for(i=0;i<64;i++) {
125                 const int j= dsp->idct_permutation[i];
126                 /* 16 <= qscale * quant_matrix[i] <= 7905 */
127                 /* 19952         <= aanscales[i] * qscale * quant_matrix[i]           <= 249205026 */
128                 /* (1<<36)/19952 >= (1<<36)/(aanscales[i] * qscale * quant_matrix[i]) >= (1<<36)/249205026 */
129                 /* 3444240       >= (1<<36)/(aanscales[i] * qscale * quant_matrix[i]) >= 275 */
130                 
131                 qmat[qscale][i] = (int)((uint64_t_C(1) << QMAT_SHIFT) / 
132                                 (qscale * quant_matrix[j]));
133             }
134         } else if (dsp->fdct == fdct_ifast
135 #ifndef FAAN_POSTSCALE
136                    || dsp->fdct == ff_faandct
137 #endif
138                    ) {
139             for(i=0;i<64;i++) {
140                 const int j= dsp->idct_permutation[i];
141                 /* 16 <= qscale * quant_matrix[i] <= 7905 */
142                 /* 19952         <= aanscales[i] * qscale * quant_matrix[i]           <= 249205026 */
143                 /* (1<<36)/19952 >= (1<<36)/(aanscales[i] * qscale * quant_matrix[i]) >= (1<<36)/249205026 */
144                 /* 3444240       >= (1<<36)/(aanscales[i] * qscale * quant_matrix[i]) >= 275 */
145                 
146                 qmat[qscale][i] = (int)((uint64_t_C(1) << (QMAT_SHIFT + 14)) / 
147                                 (aanscales[i] * qscale * quant_matrix[j]));
148             }
149         } else {
150             for(i=0;i<64;i++) {
151                 const int j= dsp->idct_permutation[i];
152                 /* We can safely suppose that 16 <= quant_matrix[i] <= 255
153                    So 16           <= qscale * quant_matrix[i]             <= 7905
154                    so (1<<19) / 16 >= (1<<19) / (qscale * quant_matrix[i]) >= (1<<19) / 7905
155                    so 32768        >= (1<<19) / (qscale * quant_matrix[i]) >= 67
156                 */
157                 qmat[qscale][i] = (int)((uint64_t_C(1) << QMAT_SHIFT) / (qscale * quant_matrix[j]));
158 //                qmat  [qscale][i] = (1 << QMAT_SHIFT_MMX) / (qscale * quant_matrix[i]);
159                 qmat16[qscale][0][i] = (1 << QMAT_SHIFT_MMX) / (qscale * quant_matrix[j]);
160
161                 if(qmat16[qscale][0][i]==0 || qmat16[qscale][0][i]==128*256) qmat16[qscale][0][i]=128*256-1;
162                 qmat16[qscale][1][i]= ROUNDED_DIV(bias<<(16-QUANT_BIAS_SHIFT), qmat16[qscale][0][i]);
163             }
164         }
165     }
166 }
167
168 static inline void update_qscale(MpegEncContext *s){
169     s->qscale= (s->lambda*139 + FF_LAMBDA_SCALE*64) >> (FF_LAMBDA_SHIFT + 7);
170     s->qscale= clip(s->qscale, s->avctx->qmin, s->avctx->qmax);
171     
172     s->lambda2= (s->lambda*s->lambda + FF_LAMBDA_SCALE/2) >> FF_LAMBDA_SHIFT;
173 }
174 #endif //CONFIG_ENCODERS
175
176 void ff_init_scantable(uint8_t *permutation, ScanTable *st, const uint8_t *src_scantable){
177     int i;
178     int end;
179     
180     st->scantable= src_scantable;
181
182     for(i=0; i<64; i++){
183         int j;
184         j = src_scantable[i];
185         st->permutated[i] = permutation[j];
186 #ifdef ARCH_POWERPC
187         st->inverse[j] = i;
188 #endif
189     }
190     
191     end=-1;
192     for(i=0; i<64; i++){
193         int j;
194         j = st->permutated[i];
195         if(j>end) end=j;
196         st->raster_end[i]= end;
197     }
198 }
199
200 #ifdef CONFIG_ENCODERS
201 void ff_write_quant_matrix(PutBitContext *pb, int16_t *matrix){
202     int i;
203
204     if(matrix){
205         put_bits(pb, 1, 1);
206         for(i=0;i<64;i++) {
207             put_bits(pb, 8, matrix[ ff_zigzag_direct[i] ]);
208         }
209     }else
210         put_bits(pb, 1, 0);
211 }
212 #endif //CONFIG_ENCODERS
213
214 /* init common dct for both encoder and decoder */
215 int DCT_common_init(MpegEncContext *s)
216 {
217     s->dct_unquantize_h263_intra = dct_unquantize_h263_intra_c;
218     s->dct_unquantize_h263_inter = dct_unquantize_h263_inter_c;
219     s->dct_unquantize_mpeg1_intra = dct_unquantize_mpeg1_intra_c;
220     s->dct_unquantize_mpeg1_inter = dct_unquantize_mpeg1_inter_c;
221     s->dct_unquantize_mpeg2_intra = dct_unquantize_mpeg2_intra_c;
222     s->dct_unquantize_mpeg2_inter = dct_unquantize_mpeg2_inter_c;
223
224 #ifdef CONFIG_ENCODERS
225     s->dct_quantize= dct_quantize_c;
226     s->denoise_dct= denoise_dct_c;
227 #endif
228         
229 #ifdef HAVE_MMX
230     MPV_common_init_mmx(s);
231 #endif
232 #ifdef ARCH_ALPHA
233     MPV_common_init_axp(s);
234 #endif
235 #ifdef HAVE_MLIB
236     MPV_common_init_mlib(s);
237 #endif
238 #ifdef HAVE_MMI
239     MPV_common_init_mmi(s);
240 #endif
241 #ifdef ARCH_ARMV4L
242     MPV_common_init_armv4l(s);
243 #endif
244 #ifdef ARCH_POWERPC
245     MPV_common_init_ppc(s);
246 #endif
247
248 #ifdef CONFIG_ENCODERS
249     s->fast_dct_quantize= s->dct_quantize;
250
251     if(s->flags&CODEC_FLAG_TRELLIS_QUANT){
252         s->dct_quantize= dct_quantize_trellis_c; //move before MPV_common_init_*
253     }
254
255 #endif //CONFIG_ENCODERS
256
257     /* load & permutate scantables
258        note: only wmv uses differnt ones 
259     */
260     if(s->alternate_scan){
261         ff_init_scantable(s->dsp.idct_permutation, &s->inter_scantable  , ff_alternate_vertical_scan);
262         ff_init_scantable(s->dsp.idct_permutation, &s->intra_scantable  , ff_alternate_vertical_scan);
263     }else{
264         ff_init_scantable(s->dsp.idct_permutation, &s->inter_scantable  , ff_zigzag_direct);
265         ff_init_scantable(s->dsp.idct_permutation, &s->intra_scantable  , ff_zigzag_direct);
266     }
267     ff_init_scantable(s->dsp.idct_permutation, &s->intra_h_scantable, ff_alternate_horizontal_scan);
268     ff_init_scantable(s->dsp.idct_permutation, &s->intra_v_scantable, ff_alternate_vertical_scan);
269
270     s->picture_structure= PICT_FRAME;
271     
272     return 0;
273 }
274
275 static void copy_picture(Picture *dst, Picture *src){
276     *dst = *src;
277     dst->type= FF_BUFFER_TYPE_COPY;
278 }
279
280 static void copy_picture_attributes(AVFrame *dst, AVFrame *src){
281     dst->pict_type              = src->pict_type;
282     dst->quality                = src->quality;
283     dst->coded_picture_number   = src->coded_picture_number;
284     dst->display_picture_number = src->display_picture_number;
285 //    dst->reference              = src->reference;
286     dst->pts                    = src->pts;
287     dst->interlaced_frame       = src->interlaced_frame;
288     dst->top_field_first        = src->top_field_first;
289 }
290
291 /**
292  * allocates a Picture
293  * The pixels are allocated/set by calling get_buffer() if shared=0
294  */
295 static int alloc_picture(MpegEncContext *s, Picture *pic, int shared){
296     const int big_mb_num= s->mb_stride*(s->mb_height+1) + 1; //the +1 is needed so memset(,,stride*height) doesnt sig11
297     const int mb_array_size= s->mb_stride*s->mb_height;
298     const int b8_array_size= s->b8_stride*s->mb_height*2;
299     const int b4_array_size= s->b4_stride*s->mb_height*4;
300     int i;
301     
302     if(shared){
303         assert(pic->data[0]);
304         assert(pic->type == 0 || pic->type == FF_BUFFER_TYPE_SHARED);
305         pic->type= FF_BUFFER_TYPE_SHARED;
306     }else{
307         int r;
308         
309         assert(!pic->data[0]);
310         
311         r= s->avctx->get_buffer(s->avctx, (AVFrame*)pic);
312         
313         if(r<0 || !pic->age || !pic->type || !pic->data[0]){
314             av_log(s->avctx, AV_LOG_ERROR, "get_buffer() failed (%d %d %d %p)\n", r, pic->age, pic->type, pic->data[0]);
315             return -1;
316         }
317
318         if(s->linesize && (s->linesize != pic->linesize[0] || s->uvlinesize != pic->linesize[1])){
319             av_log(s->avctx, AV_LOG_ERROR, "get_buffer() failed (stride changed)\n");
320             return -1;
321         }
322
323         if(pic->linesize[1] != pic->linesize[2]){
324             av_log(s->avctx, AV_LOG_ERROR, "get_buffer() failed (uv stride missmatch)\n");
325             return -1;
326         }
327
328         s->linesize  = pic->linesize[0];
329         s->uvlinesize= pic->linesize[1];
330     }
331     
332     if(pic->qscale_table==NULL){
333         if (s->encoding) {        
334             CHECKED_ALLOCZ(pic->mb_var   , mb_array_size * sizeof(int16_t))
335             CHECKED_ALLOCZ(pic->mc_mb_var, mb_array_size * sizeof(int16_t))
336             CHECKED_ALLOCZ(pic->mb_mean  , mb_array_size * sizeof(int8_t))
337         }
338
339         CHECKED_ALLOCZ(pic->mbskip_table , mb_array_size * sizeof(uint8_t)+2) //the +2 is for the slice end check
340         CHECKED_ALLOCZ(pic->qscale_table , mb_array_size * sizeof(uint8_t))
341         CHECKED_ALLOCZ(pic->mb_type_base , big_mb_num    * sizeof(uint32_t))
342         pic->mb_type= pic->mb_type_base + s->mb_stride+1;
343         if(s->out_format == FMT_H264){
344             for(i=0; i<2; i++){
345                 CHECKED_ALLOCZ(pic->motion_val_base[i], 2 * (b4_array_size+1)  * sizeof(int16_t))
346                 pic->motion_val[i]= pic->motion_val_base[i]+1;
347                 CHECKED_ALLOCZ(pic->ref_index[i] , b8_array_size * sizeof(uint8_t))
348             }
349             pic->motion_subsample_log2= 2;
350         }else if(s->out_format == FMT_H263 || s->encoding || (s->avctx->debug&FF_DEBUG_MV) || (s->avctx->debug_mv)){
351             for(i=0; i<2; i++){
352                 CHECKED_ALLOCZ(pic->motion_val_base[i], 2 * (b8_array_size+1) * sizeof(int16_t)*2) //FIXME
353                 pic->motion_val[i]= pic->motion_val_base[i]+1;
354             }
355             pic->motion_subsample_log2= 3;
356         }
357         if(s->avctx->debug&FF_DEBUG_DCT_COEFF) {
358             CHECKED_ALLOCZ(pic->dct_coeff, 64 * mb_array_size * sizeof(DCTELEM)*6)
359         }
360         pic->qstride= s->mb_stride;
361         CHECKED_ALLOCZ(pic->pan_scan , 1 * sizeof(AVPanScan))
362     }
363
364     //it might be nicer if the application would keep track of these but it would require a API change
365     memmove(s->prev_pict_types+1, s->prev_pict_types, PREV_PICT_TYPES_BUFFER_SIZE-1);
366     s->prev_pict_types[0]= s->pict_type;
367     if(pic->age < PREV_PICT_TYPES_BUFFER_SIZE && s->prev_pict_types[pic->age] == B_TYPE)
368         pic->age= INT_MAX; // skiped MBs in b frames are quite rare in mpeg1/2 and its a bit tricky to skip them anyway
369     
370     return 0;
371 fail: //for the CHECKED_ALLOCZ macro
372     return -1;
373 }
374
375 /**
376  * deallocates a picture
377  */
378 static void free_picture(MpegEncContext *s, Picture *pic){
379     int i;
380
381     if(pic->data[0] && pic->type!=FF_BUFFER_TYPE_SHARED){
382         s->avctx->release_buffer(s->avctx, (AVFrame*)pic);
383     }
384
385     av_freep(&pic->mb_var);
386     av_freep(&pic->mc_mb_var);
387     av_freep(&pic->mb_mean);
388     av_freep(&pic->mbskip_table);
389     av_freep(&pic->qscale_table);
390     av_freep(&pic->mb_type_base);
391     av_freep(&pic->dct_coeff);
392     av_freep(&pic->pan_scan);
393     pic->mb_type= NULL;
394     for(i=0; i<2; i++){
395         av_freep(&pic->motion_val_base[i]);
396         av_freep(&pic->ref_index[i]);
397     }
398     
399     if(pic->type == FF_BUFFER_TYPE_SHARED){
400         for(i=0; i<4; i++){
401             pic->base[i]=
402             pic->data[i]= NULL;
403         }
404         pic->type= 0;        
405     }
406 }
407
408 static int init_duplicate_context(MpegEncContext *s, MpegEncContext *base){
409     int i;
410
411     // edge emu needs blocksize + filter length - 1 (=17x17 for halfpel / 21x21 for h264) 
412     CHECKED_ALLOCZ(s->allocated_edge_emu_buffer, (s->width+64)*2*17*2); //(width + edge + align)*interlaced*MBsize*tolerance
413     s->edge_emu_buffer= s->allocated_edge_emu_buffer + (s->width+64)*2*17;
414
415      //FIXME should be linesize instead of s->width*2 but that isnt known before get_buffer()
416     CHECKED_ALLOCZ(s->me.scratchpad,  (s->width+64)*2*16*2*sizeof(uint8_t)) 
417     s->rd_scratchpad=   s->me.scratchpad;
418     s->b_scratchpad=    s->me.scratchpad;
419     s->obmc_scratchpad= s->me.scratchpad + 16;
420     if (s->encoding) {
421         CHECKED_ALLOCZ(s->me.map      , ME_MAP_SIZE*sizeof(uint32_t))
422         CHECKED_ALLOCZ(s->me.score_map, ME_MAP_SIZE*sizeof(uint32_t))
423         if(s->avctx->noise_reduction){
424             CHECKED_ALLOCZ(s->dct_error_sum, 2 * 64 * sizeof(int))
425         }
426     }   
427     CHECKED_ALLOCZ(s->blocks, 64*6*2 * sizeof(DCTELEM))
428     s->block= s->blocks[0];
429
430     for(i=0;i<12;i++){
431         s->pblocks[i] = (short *)(&s->block[i]);
432     }
433     return 0;
434 fail:
435     return -1; //free() through MPV_common_end()
436 }
437
438 static void free_duplicate_context(MpegEncContext *s){
439     if(s==NULL) return;
440
441     av_freep(&s->allocated_edge_emu_buffer); s->edge_emu_buffer= NULL;
442     av_freep(&s->me.scratchpad);
443     s->rd_scratchpad=   
444     s->b_scratchpad=    
445     s->obmc_scratchpad= NULL;
446     
447     av_freep(&s->dct_error_sum);
448     av_freep(&s->me.map);
449     av_freep(&s->me.score_map);
450     av_freep(&s->blocks);
451     s->block= NULL;
452 }
453
454 static void backup_duplicate_context(MpegEncContext *bak, MpegEncContext *src){
455 #define COPY(a) bak->a= src->a
456     COPY(allocated_edge_emu_buffer);
457     COPY(edge_emu_buffer);
458     COPY(me.scratchpad);
459     COPY(rd_scratchpad);
460     COPY(b_scratchpad);
461     COPY(obmc_scratchpad);
462     COPY(me.map);
463     COPY(me.score_map);
464     COPY(blocks);
465     COPY(block);
466     COPY(start_mb_y);
467     COPY(end_mb_y);
468     COPY(me.map_generation);
469     COPY(pb);
470     COPY(dct_error_sum);
471     COPY(dct_count[0]);
472     COPY(dct_count[1]);
473 #undef COPY
474 }
475
476 void ff_update_duplicate_context(MpegEncContext *dst, MpegEncContext *src){
477     MpegEncContext bak;
478     int i;
479     //FIXME copy only needed parts
480 //START_TIMER
481     backup_duplicate_context(&bak, dst);
482     memcpy(dst, src, sizeof(MpegEncContext));
483     backup_duplicate_context(dst, &bak);
484     for(i=0;i<12;i++){
485         dst->pblocks[i] = (short *)(&dst->block[i]);
486     }
487 //STOP_TIMER("update_duplicate_context") //about 10k cycles / 0.01 sec for 1000frames on 1ghz with 2 threads
488 }
489
490 static void update_duplicate_context_after_me(MpegEncContext *dst, MpegEncContext *src){
491 #define COPY(a) dst->a= src->a
492     COPY(pict_type);
493     COPY(current_picture);
494     COPY(f_code);
495     COPY(b_code);
496     COPY(qscale);
497     COPY(lambda);
498     COPY(lambda2);
499     COPY(picture_in_gop_number);
500     COPY(gop_picture_number);
501     COPY(frame_pred_frame_dct); //FIXME dont set in encode_header
502     COPY(progressive_frame); //FIXME dont set in encode_header
503     COPY(partitioned_frame); //FIXME dont set in encode_header
504 #undef COPY
505 }
506
507 /* init common structure for both encoder and decoder */
508 int MPV_common_init(MpegEncContext *s)
509 {
510     int y_size, c_size, yc_size, i, mb_array_size, mv_table_size, x, y;
511
512     dsputil_init(&s->dsp, s->avctx);
513     DCT_common_init(s);
514
515     s->flags= s->avctx->flags;
516     s->flags2= s->avctx->flags2;
517
518     s->mb_width  = (s->width  + 15) / 16;
519     s->mb_height = (s->height + 15) / 16;
520     s->mb_stride = s->mb_width + 1;
521     s->b8_stride = s->mb_width*2 + 1;
522     s->b4_stride = s->mb_width*4 + 1;
523     mb_array_size= s->mb_height * s->mb_stride;
524     mv_table_size= (s->mb_height+2) * s->mb_stride + 1;
525
526     /* set default edge pos, will be overriden in decode_header if needed */
527     s->h_edge_pos= s->mb_width*16;
528     s->v_edge_pos= s->mb_height*16;
529
530     s->mb_num = s->mb_width * s->mb_height;
531     
532     s->block_wrap[0]=
533     s->block_wrap[1]=
534     s->block_wrap[2]=
535     s->block_wrap[3]= s->mb_width*2 + 2;
536     s->block_wrap[4]=
537     s->block_wrap[5]= s->mb_width + 2;
538
539     s->y_dc_scale_table=
540     s->c_dc_scale_table= ff_mpeg1_dc_scale_table;
541     s->chroma_qscale_table= ff_default_chroma_qscale_table;
542     if (!s->encoding)
543         s->progressive_sequence= 1;
544     s->progressive_frame= 1;
545     s->coded_picture_number = 0;
546
547     y_size = (2 * s->mb_width + 2) * (2 * s->mb_height + 2);
548     c_size = (s->mb_width + 2) * (s->mb_height + 2);
549     yc_size = y_size + 2 * c_size;
550
551     /* convert fourcc to upper case */
552     s->avctx->codec_tag=   toupper( s->avctx->codec_tag     &0xFF)          
553                         + (toupper((s->avctx->codec_tag>>8 )&0xFF)<<8 )
554                         + (toupper((s->avctx->codec_tag>>16)&0xFF)<<16) 
555                         + (toupper((s->avctx->codec_tag>>24)&0xFF)<<24);
556
557     s->avctx->stream_codec_tag=   toupper( s->avctx->stream_codec_tag     &0xFF)          
558                                + (toupper((s->avctx->stream_codec_tag>>8 )&0xFF)<<8 )
559                                + (toupper((s->avctx->stream_codec_tag>>16)&0xFF)<<16) 
560                                + (toupper((s->avctx->stream_codec_tag>>24)&0xFF)<<24);
561
562     s->avctx->coded_frame= (AVFrame*)&s->current_picture;
563
564     CHECKED_ALLOCZ(s->mb_index2xy, (s->mb_num+1)*sizeof(int)) //error ressilience code looks cleaner with this
565     for(y=0; y<s->mb_height; y++){
566         for(x=0; x<s->mb_width; x++){
567             s->mb_index2xy[ x + y*s->mb_width ] = x + y*s->mb_stride;
568         }
569     }
570     s->mb_index2xy[ s->mb_height*s->mb_width ] = (s->mb_height-1)*s->mb_stride + s->mb_width; //FIXME really needed?
571     
572     if (s->encoding) {
573         /* Allocate MV tables */
574         CHECKED_ALLOCZ(s->p_mv_table_base            , mv_table_size * 2 * sizeof(int16_t))
575         CHECKED_ALLOCZ(s->b_forw_mv_table_base       , mv_table_size * 2 * sizeof(int16_t))
576         CHECKED_ALLOCZ(s->b_back_mv_table_base       , mv_table_size * 2 * sizeof(int16_t))
577         CHECKED_ALLOCZ(s->b_bidir_forw_mv_table_base , mv_table_size * 2 * sizeof(int16_t))
578         CHECKED_ALLOCZ(s->b_bidir_back_mv_table_base , mv_table_size * 2 * sizeof(int16_t))
579         CHECKED_ALLOCZ(s->b_direct_mv_table_base     , mv_table_size * 2 * sizeof(int16_t))
580         s->p_mv_table           = s->p_mv_table_base            + s->mb_stride + 1;
581         s->b_forw_mv_table      = s->b_forw_mv_table_base       + s->mb_stride + 1;
582         s->b_back_mv_table      = s->b_back_mv_table_base       + s->mb_stride + 1;
583         s->b_bidir_forw_mv_table= s->b_bidir_forw_mv_table_base + s->mb_stride + 1;
584         s->b_bidir_back_mv_table= s->b_bidir_back_mv_table_base + s->mb_stride + 1;
585         s->b_direct_mv_table    = s->b_direct_mv_table_base     + s->mb_stride + 1;
586
587         if(s->msmpeg4_version){
588             CHECKED_ALLOCZ(s->ac_stats, 2*2*(MAX_LEVEL+1)*(MAX_RUN+1)*2*sizeof(int));
589         }
590         CHECKED_ALLOCZ(s->avctx->stats_out, 256);
591
592         /* Allocate MB type table */
593         CHECKED_ALLOCZ(s->mb_type  , mb_array_size * sizeof(uint16_t)) //needed for encoding
594         
595         CHECKED_ALLOCZ(s->lambda_table, mb_array_size * sizeof(int))
596         
597         CHECKED_ALLOCZ(s->q_intra_matrix, 64*32 * sizeof(int))
598         CHECKED_ALLOCZ(s->q_inter_matrix, 64*32 * sizeof(int))
599         CHECKED_ALLOCZ(s->q_intra_matrix16, 64*32*2 * sizeof(uint16_t))
600         CHECKED_ALLOCZ(s->q_inter_matrix16, 64*32*2 * sizeof(uint16_t))
601         CHECKED_ALLOCZ(s->input_picture, MAX_PICTURE_COUNT * sizeof(Picture*))
602         CHECKED_ALLOCZ(s->reordered_input_picture, MAX_PICTURE_COUNT * sizeof(Picture*))
603         
604         if(s->avctx->noise_reduction){
605             CHECKED_ALLOCZ(s->dct_offset, 2 * 64 * sizeof(uint16_t))
606         }
607     }
608     CHECKED_ALLOCZ(s->picture, MAX_PICTURE_COUNT * sizeof(Picture))
609
610     CHECKED_ALLOCZ(s->error_status_table, mb_array_size*sizeof(uint8_t))
611     
612     if(s->codec_id==CODEC_ID_MPEG4 || (s->flags & CODEC_FLAG_INTERLACED_ME)){
613         /* interlaced direct mode decoding tables */
614             for(i=0; i<2; i++){
615                 int j, k;
616                 for(j=0; j<2; j++){
617                     for(k=0; k<2; k++){
618                         CHECKED_ALLOCZ(s->b_field_mv_table_base[i][j][k]     , mv_table_size * 2 * sizeof(int16_t))
619                         s->b_field_mv_table[i][j][k]    = s->b_field_mv_table_base[i][j][k]     + s->mb_stride + 1;
620                     }
621                     CHECKED_ALLOCZ(s->b_field_select_table[i][j]     , mb_array_size * 2 * sizeof(uint8_t))
622                     CHECKED_ALLOCZ(s->p_field_mv_table_base[i][j]     , mv_table_size * 2 * sizeof(int16_t))
623                     s->p_field_mv_table[i][j]    = s->p_field_mv_table_base[i][j]     + s->mb_stride + 1;
624                 }
625                 CHECKED_ALLOCZ(s->p_field_select_table[i]      , mb_array_size * 2 * sizeof(uint8_t))
626             }
627     }
628     if (s->out_format == FMT_H263) {
629         /* ac values */
630         CHECKED_ALLOCZ(s->ac_val[0], yc_size * sizeof(int16_t) * 16);
631         s->ac_val[1] = s->ac_val[0] + y_size;
632         s->ac_val[2] = s->ac_val[1] + c_size;
633         
634         /* cbp values */
635         CHECKED_ALLOCZ(s->coded_block, y_size);
636         
637         /* divx501 bitstream reorder buffer */
638         CHECKED_ALLOCZ(s->bitstream_buffer, BITSTREAM_BUFFER_SIZE);
639
640         /* cbp, ac_pred, pred_dir */
641         CHECKED_ALLOCZ(s->cbp_table  , mb_array_size * sizeof(uint8_t))
642         CHECKED_ALLOCZ(s->pred_dir_table, mb_array_size * sizeof(uint8_t))
643     }
644     
645     if (s->h263_pred || s->h263_plus || !s->encoding) {
646         /* dc values */
647         //MN: we need these for error resilience of intra-frames
648         CHECKED_ALLOCZ(s->dc_val[0], yc_size * sizeof(int16_t));
649         s->dc_val[1] = s->dc_val[0] + y_size;
650         s->dc_val[2] = s->dc_val[1] + c_size;
651         for(i=0;i<yc_size;i++)
652             s->dc_val[0][i] = 1024;
653     }
654
655     /* which mb is a intra block */
656     CHECKED_ALLOCZ(s->mbintra_table, mb_array_size);
657     memset(s->mbintra_table, 1, mb_array_size);
658     
659     /* default structure is frame */
660     s->picture_structure = PICT_FRAME;
661     
662     /* init macroblock skip table */
663     CHECKED_ALLOCZ(s->mbskip_table, mb_array_size+2);
664     //Note the +1 is for a quicker mpeg4 slice_end detection
665     CHECKED_ALLOCZ(s->prev_pict_types, PREV_PICT_TYPES_BUFFER_SIZE);
666     
667     s->parse_context.state= -1;
668     if((s->avctx->debug&(FF_DEBUG_VIS_QP|FF_DEBUG_VIS_MB_TYPE)) || (s->avctx->debug_mv)){
669        s->visualization_buffer[0] = av_malloc((s->mb_width*16 + 2*EDGE_WIDTH) * s->mb_height*16 + 2*EDGE_WIDTH);
670        s->visualization_buffer[1] = av_malloc((s->mb_width*8 + EDGE_WIDTH) * s->mb_height*8 + EDGE_WIDTH);
671        s->visualization_buffer[2] = av_malloc((s->mb_width*8 + EDGE_WIDTH) * s->mb_height*8 + EDGE_WIDTH);
672     }
673
674     s->context_initialized = 1;
675
676     s->thread_context[0]= s;
677     for(i=1; i<s->avctx->thread_count; i++){
678         s->thread_context[i]= av_malloc(sizeof(MpegEncContext));
679         memcpy(s->thread_context[i], s, sizeof(MpegEncContext));
680     }
681
682     for(i=0; i<s->avctx->thread_count; i++){
683         if(init_duplicate_context(s->thread_context[i], s) < 0)
684            goto fail;
685         s->thread_context[i]->start_mb_y= (s->mb_height*(i  ) + s->avctx->thread_count/2) / s->avctx->thread_count;
686         s->thread_context[i]->end_mb_y  = (s->mb_height*(i+1) + s->avctx->thread_count/2) / s->avctx->thread_count;
687     }
688
689     return 0;
690  fail:
691     MPV_common_end(s);
692     return -1;
693 }
694
695 /* init common structure for both encoder and decoder */
696 void MPV_common_end(MpegEncContext *s)
697 {
698     int i, j, k;
699
700     for(i=0; i<s->avctx->thread_count; i++){
701         free_duplicate_context(s->thread_context[i]);
702     }
703     for(i=1; i<s->avctx->thread_count; i++){
704         av_freep(&s->thread_context[i]);
705     }
706
707     av_freep(&s->parse_context.buffer);
708     s->parse_context.buffer_size=0;
709
710     av_freep(&s->mb_type);
711     av_freep(&s->p_mv_table_base);
712     av_freep(&s->b_forw_mv_table_base);
713     av_freep(&s->b_back_mv_table_base);
714     av_freep(&s->b_bidir_forw_mv_table_base);
715     av_freep(&s->b_bidir_back_mv_table_base);
716     av_freep(&s->b_direct_mv_table_base);
717     s->p_mv_table= NULL;
718     s->b_forw_mv_table= NULL;
719     s->b_back_mv_table= NULL;
720     s->b_bidir_forw_mv_table= NULL;
721     s->b_bidir_back_mv_table= NULL;
722     s->b_direct_mv_table= NULL;
723     for(i=0; i<2; i++){
724         for(j=0; j<2; j++){
725             for(k=0; k<2; k++){
726                 av_freep(&s->b_field_mv_table_base[i][j][k]);
727                 s->b_field_mv_table[i][j][k]=NULL;
728             }
729             av_freep(&s->b_field_select_table[i][j]);
730             av_freep(&s->p_field_mv_table_base[i][j]);
731             s->p_field_mv_table[i][j]=NULL;
732         }
733         av_freep(&s->p_field_select_table[i]);
734     }
735     
736     av_freep(&s->dc_val[0]);
737     av_freep(&s->ac_val[0]);
738     av_freep(&s->coded_block);
739     av_freep(&s->mbintra_table);
740     av_freep(&s->cbp_table);
741     av_freep(&s->pred_dir_table);
742     
743     av_freep(&s->mbskip_table);
744     av_freep(&s->prev_pict_types);
745     av_freep(&s->bitstream_buffer);
746     av_freep(&s->avctx->stats_out);
747     av_freep(&s->ac_stats);
748     av_freep(&s->error_status_table);
749     av_freep(&s->mb_index2xy);
750     av_freep(&s->lambda_table);
751     av_freep(&s->q_intra_matrix);
752     av_freep(&s->q_inter_matrix);
753     av_freep(&s->q_intra_matrix16);
754     av_freep(&s->q_inter_matrix16);
755     av_freep(&s->input_picture);
756     av_freep(&s->reordered_input_picture);
757     av_freep(&s->dct_offset);
758
759     if(s->picture){
760         for(i=0; i<MAX_PICTURE_COUNT; i++){
761             free_picture(s, &s->picture[i]);
762         }
763     }
764     av_freep(&s->picture);
765     avcodec_default_free_buffers(s->avctx);
766     s->context_initialized = 0;
767     s->last_picture_ptr=
768     s->next_picture_ptr=
769     s->current_picture_ptr= NULL;
770     for(i=0; i<3; i++)
771         if (s->visualization_buffer[i])
772             av_free(s->visualization_buffer[i]);
773 }
774
775 #ifdef CONFIG_ENCODERS
776
777 /* init video encoder */
778 int MPV_encode_init(AVCodecContext *avctx)
779 {
780     MpegEncContext *s = avctx->priv_data;
781     int i, dummy;
782     int chroma_h_shift, chroma_v_shift;
783
784     avctx->pix_fmt = PIX_FMT_YUV420P; // FIXME
785
786     s->bit_rate = avctx->bit_rate;
787     s->width = avctx->width;
788     s->height = avctx->height;
789     if(avctx->gop_size > 600){
790         av_log(avctx, AV_LOG_ERROR, "Warning keyframe interval too large! reducing it ...\n");
791         avctx->gop_size=600;
792     }
793     s->gop_size = avctx->gop_size;
794     s->avctx = avctx;
795     s->flags= avctx->flags;
796     s->flags2= avctx->flags2;
797     s->max_b_frames= avctx->max_b_frames;
798     s->codec_id= avctx->codec->id;
799     s->luma_elim_threshold  = avctx->luma_elim_threshold;
800     s->chroma_elim_threshold= avctx->chroma_elim_threshold;
801     s->strict_std_compliance= avctx->strict_std_compliance;
802     s->data_partitioning= avctx->flags & CODEC_FLAG_PART;
803     s->quarter_sample= (avctx->flags & CODEC_FLAG_QPEL)!=0;
804     s->mpeg_quant= avctx->mpeg_quant;
805     s->rtp_mode= !!avctx->rtp_payload_size;
806
807     if (s->gop_size <= 1) {
808         s->intra_only = 1;
809         s->gop_size = 12;
810     } else {
811         s->intra_only = 0;
812     }
813
814     s->me_method = avctx->me_method;
815
816     /* Fixed QSCALE */
817     s->fixed_qscale = !!(avctx->flags & CODEC_FLAG_QSCALE);
818     
819     s->adaptive_quant= (   s->avctx->lumi_masking
820                         || s->avctx->dark_masking
821                         || s->avctx->temporal_cplx_masking 
822                         || s->avctx->spatial_cplx_masking
823                         || s->avctx->p_masking
824                         || (s->flags&CODEC_FLAG_QP_RD))
825                        && !s->fixed_qscale;
826     
827     s->obmc= !!(s->flags & CODEC_FLAG_OBMC);
828     s->loop_filter= !!(s->flags & CODEC_FLAG_LOOP_FILTER);
829     s->alternate_scan= !!(s->flags & CODEC_FLAG_ALT_SCAN);
830
831     if(avctx->rc_max_rate && !avctx->rc_buffer_size){
832         av_log(avctx, AV_LOG_ERROR, "a vbv buffer size is needed, for encoding with a maximum bitrate\n");
833         return -1;
834     }    
835
836     if(avctx->rc_min_rate && avctx->rc_max_rate != avctx->rc_min_rate){
837         av_log(avctx, AV_LOG_INFO, "Warning min_rate > 0 but min_rate != max_rate isnt recommanded!\n");
838     }    
839         
840     if((s->flags & CODEC_FLAG_4MV) && s->codec_id != CODEC_ID_MPEG4 
841        && s->codec_id != CODEC_ID_H263 && s->codec_id != CODEC_ID_H263P && s->codec_id != CODEC_ID_FLV1){
842         av_log(avctx, AV_LOG_ERROR, "4MV not supported by codec\n");
843         return -1;
844     }
845         
846     if(s->obmc && s->avctx->mb_decision != FF_MB_DECISION_SIMPLE){
847         av_log(avctx, AV_LOG_ERROR, "OBMC is only supported with simple mb decission\n");
848         return -1;
849     }
850     
851     if(s->obmc && s->codec_id != CODEC_ID_H263 && s->codec_id != CODEC_ID_H263P){
852         av_log(avctx, AV_LOG_ERROR, "OBMC is only supported with H263(+)\n");
853         return -1;
854     }
855     
856     if(s->quarter_sample && s->codec_id != CODEC_ID_MPEG4){
857         av_log(avctx, AV_LOG_ERROR, "qpel not supported by codec\n");
858         return -1;
859     }
860
861     if(s->data_partitioning && s->codec_id != CODEC_ID_MPEG4){
862         av_log(avctx, AV_LOG_ERROR, "data partitioning not supported by codec\n");
863         return -1;
864     }
865     
866     if(s->max_b_frames && s->codec_id != CODEC_ID_MPEG4 && s->codec_id != CODEC_ID_MPEG1VIDEO && s->codec_id != CODEC_ID_MPEG2VIDEO){
867         av_log(avctx, AV_LOG_ERROR, "b frames not supported by codec\n");
868         return -1;
869     }
870     
871     if(s->mpeg_quant && s->codec_id != CODEC_ID_MPEG4){ //FIXME mpeg2 uses that too
872         av_log(avctx, AV_LOG_ERROR, "mpeg2 style quantization not supporetd by codec\n");
873         return -1;
874     }
875         
876     if((s->flags & CODEC_FLAG_CBP_RD) && !(s->flags & CODEC_FLAG_TRELLIS_QUANT)){
877         av_log(avctx, AV_LOG_ERROR, "CBP RD needs trellis quant\n");
878         return -1;
879     }
880
881     if((s->flags & CODEC_FLAG_QP_RD) && s->avctx->mb_decision != FF_MB_DECISION_RD){
882         av_log(avctx, AV_LOG_ERROR, "QP RD needs mbd=2\n");
883         return -1;
884     }
885     
886     if(s->avctx->scenechange_threshold < 1000000000 && (s->flags & CODEC_FLAG_CLOSED_GOP)){
887         av_log(avctx, AV_LOG_ERROR, "closed gop with scene change detection arent supported yet\n");
888         return -1;
889     }
890     
891     if(s->avctx->thread_count > 1 && s->codec_id != CODEC_ID_MPEG4 
892        && s->codec_id != CODEC_ID_MPEG1VIDEO && s->codec_id != CODEC_ID_MPEG2VIDEO 
893        && (s->codec_id != CODEC_ID_H263P || !(s->flags & CODEC_FLAG_H263P_SLICE_STRUCT))){
894         av_log(avctx, AV_LOG_ERROR, "multi threaded encoding not supported by codec\n");
895         return -1;
896     }
897     
898     if(s->avctx->thread_count > MAX_THREADS || 16*s->avctx->thread_count > s->height){
899         av_log(avctx, AV_LOG_ERROR, "too many threads\n");
900         return -1;
901     }
902     
903     if(s->avctx->thread_count > 1)
904         s->rtp_mode= 1;
905
906     i= ff_gcd(avctx->frame_rate, avctx->frame_rate_base);
907     if(i > 1){
908         av_log(avctx, AV_LOG_INFO, "removing common factors from framerate\n");
909         avctx->frame_rate /= i;
910         avctx->frame_rate_base /= i;
911 //        return -1;
912     }
913     
914     if(s->codec_id==CODEC_ID_MJPEG){
915         s->intra_quant_bias= 1<<(QUANT_BIAS_SHIFT-1); //(a + x/2)/x
916         s->inter_quant_bias= 0;
917     }else if(s->mpeg_quant || s->codec_id==CODEC_ID_MPEG1VIDEO || s->codec_id==CODEC_ID_MPEG2VIDEO){
918         s->intra_quant_bias= 3<<(QUANT_BIAS_SHIFT-3); //(a + x*3/8)/x
919         s->inter_quant_bias= 0;
920     }else{
921         s->intra_quant_bias=0;
922         s->inter_quant_bias=-(1<<(QUANT_BIAS_SHIFT-2)); //(a - x/4)/x
923     }
924     
925     if(avctx->intra_quant_bias != FF_DEFAULT_QUANT_BIAS)
926         s->intra_quant_bias= avctx->intra_quant_bias;
927     if(avctx->inter_quant_bias != FF_DEFAULT_QUANT_BIAS)
928         s->inter_quant_bias= avctx->inter_quant_bias;
929         
930     avcodec_get_chroma_sub_sample(avctx->pix_fmt, &chroma_h_shift, &chroma_v_shift);
931
932     av_reduce(&s->time_increment_resolution, &dummy, s->avctx->frame_rate, s->avctx->frame_rate_base, (1<<16)-1);
933     s->time_increment_bits = av_log2(s->time_increment_resolution - 1) + 1;
934
935     switch(avctx->codec->id) {
936     case CODEC_ID_MPEG1VIDEO:
937         s->out_format = FMT_MPEG1;
938         s->low_delay= 0; //s->max_b_frames ? 0 : 1;
939         avctx->delay= s->low_delay ? 0 : (s->max_b_frames + 1);
940         break;
941     case CODEC_ID_MPEG2VIDEO:
942         s->out_format = FMT_MPEG1;
943         s->low_delay= 0; //s->max_b_frames ? 0 : 1;
944         avctx->delay= s->low_delay ? 0 : (s->max_b_frames + 1);
945         s->rtp_mode= 1;
946         break;
947     case CODEC_ID_LJPEG:
948     case CODEC_ID_MJPEG:
949         s->out_format = FMT_MJPEG;
950         s->intra_only = 1; /* force intra only for jpeg */
951         s->mjpeg_write_tables = 1; /* write all tables */
952         s->mjpeg_data_only_frames = 0; /* write all the needed headers */
953         s->mjpeg_vsample[0] = 1<<chroma_v_shift;
954         s->mjpeg_vsample[1] = 1;
955         s->mjpeg_vsample[2] = 1; 
956         s->mjpeg_hsample[0] = 1<<chroma_h_shift;
957         s->mjpeg_hsample[1] = 1; 
958         s->mjpeg_hsample[2] = 1; 
959         if (mjpeg_init(s) < 0)
960             return -1;
961         avctx->delay=0;
962         s->low_delay=1;
963         break;
964 #ifdef CONFIG_RISKY
965     case CODEC_ID_H263:
966         if (h263_get_picture_format(s->width, s->height) == 7) {
967             av_log(avctx, AV_LOG_INFO, "Input picture size isn't suitable for h263 codec! try h263+\n");
968             return -1;
969         }
970         s->out_format = FMT_H263;
971         s->obmc= (avctx->flags & CODEC_FLAG_OBMC) ? 1:0;
972         avctx->delay=0;
973         s->low_delay=1;
974         break;
975     case CODEC_ID_H263P:
976         s->out_format = FMT_H263;
977         s->h263_plus = 1;
978         /* Fx */
979         s->umvplus = (avctx->flags & CODEC_FLAG_H263P_UMV) ? 1:0;
980         s->h263_aic= (avctx->flags & CODEC_FLAG_H263P_AIC) ? 1:0;
981         s->modified_quant= s->h263_aic;
982         s->alt_inter_vlc= (avctx->flags & CODEC_FLAG_H263P_AIV) ? 1:0;
983         s->obmc= (avctx->flags & CODEC_FLAG_OBMC) ? 1:0;
984         s->loop_filter= (avctx->flags & CODEC_FLAG_LOOP_FILTER) ? 1:0;
985         s->unrestricted_mv= s->obmc || s->loop_filter || s->umvplus;
986         s->h263_slice_structured= (s->flags & CODEC_FLAG_H263P_SLICE_STRUCT) ? 1:0;
987
988         /* /Fx */
989         /* These are just to be sure */
990         avctx->delay=0;
991         s->low_delay=1;
992         break;
993     case CODEC_ID_FLV1:
994         s->out_format = FMT_H263;
995         s->h263_flv = 2; /* format = 1; 11-bit codes */
996         s->unrestricted_mv = 1;
997         s->rtp_mode=0; /* don't allow GOB */
998         avctx->delay=0;
999         s->low_delay=1;
1000         break;
1001     case CODEC_ID_RV10:
1002         s->out_format = FMT_H263;
1003         avctx->delay=0;
1004         s->low_delay=1;
1005         break;
1006     case CODEC_ID_MPEG4:
1007         s->out_format = FMT_H263;
1008         s->h263_pred = 1;
1009         s->unrestricted_mv = 1;
1010         s->low_delay= s->max_b_frames ? 0 : 1;
1011         avctx->delay= s->low_delay ? 0 : (s->max_b_frames + 1);
1012         break;
1013     case CODEC_ID_MSMPEG4V1:
1014         s->out_format = FMT_H263;
1015         s->h263_msmpeg4 = 1;
1016         s->h263_pred = 1;
1017         s->unrestricted_mv = 1;
1018         s->msmpeg4_version= 1;
1019         avctx->delay=0;
1020         s->low_delay=1;
1021         break;
1022     case CODEC_ID_MSMPEG4V2:
1023         s->out_format = FMT_H263;
1024         s->h263_msmpeg4 = 1;
1025         s->h263_pred = 1;
1026         s->unrestricted_mv = 1;
1027         s->msmpeg4_version= 2;
1028         avctx->delay=0;
1029         s->low_delay=1;
1030         break;
1031     case CODEC_ID_MSMPEG4V3:
1032         s->out_format = FMT_H263;
1033         s->h263_msmpeg4 = 1;
1034         s->h263_pred = 1;
1035         s->unrestricted_mv = 1;
1036         s->msmpeg4_version= 3;
1037         s->flipflop_rounding=1;
1038         avctx->delay=0;
1039         s->low_delay=1;
1040         break;
1041     case CODEC_ID_WMV1:
1042         s->out_format = FMT_H263;
1043         s->h263_msmpeg4 = 1;
1044         s->h263_pred = 1;
1045         s->unrestricted_mv = 1;
1046         s->msmpeg4_version= 4;
1047         s->flipflop_rounding=1;
1048         avctx->delay=0;
1049         s->low_delay=1;
1050         break;
1051     case CODEC_ID_WMV2:
1052         s->out_format = FMT_H263;
1053         s->h263_msmpeg4 = 1;
1054         s->h263_pred = 1;
1055         s->unrestricted_mv = 1;
1056         s->msmpeg4_version= 5;
1057         s->flipflop_rounding=1;
1058         avctx->delay=0;
1059         s->low_delay=1;
1060         break;
1061 #endif
1062     default:
1063         return -1;
1064     }
1065
1066     { /* set up some save defaults, some codecs might override them later */
1067         static int done=0;
1068         if(!done){
1069             int i;
1070             done=1;
1071
1072             default_mv_penalty= av_mallocz( sizeof(uint8_t)*(MAX_FCODE+1)*(2*MAX_MV+1) );
1073             memset(default_mv_penalty, 0, sizeof(uint8_t)*(MAX_FCODE+1)*(2*MAX_MV+1));
1074             memset(default_fcode_tab , 0, sizeof(uint8_t)*(2*MAX_MV+1));
1075
1076             for(i=-16; i<16; i++){
1077                 default_fcode_tab[i + MAX_MV]= 1;
1078             }
1079         }
1080     }
1081     s->me.mv_penalty= default_mv_penalty;
1082     s->fcode_tab= default_fcode_tab;
1083  
1084     /* dont use mv_penalty table for crap MV as it would be confused */
1085     //FIXME remove after fixing / removing old ME
1086     if (s->me_method < ME_EPZS) s->me.mv_penalty = default_mv_penalty;
1087
1088     s->encoding = 1;
1089
1090     /* init */
1091     if (MPV_common_init(s) < 0)
1092         return -1;
1093
1094     if(s->modified_quant)
1095         s->chroma_qscale_table= ff_h263_chroma_qscale_table;
1096     s->progressive_frame= 
1097     s->progressive_sequence= !(avctx->flags & (CODEC_FLAG_INTERLACED_DCT|CODEC_FLAG_INTERLACED_ME));
1098     s->quant_precision=5;
1099     
1100     ff_set_cmp(&s->dsp, s->dsp.ildct_cmp, s->avctx->ildct_cmp);
1101     
1102     ff_init_me(s);
1103
1104 #ifdef CONFIG_ENCODERS
1105 #ifdef CONFIG_RISKY
1106     if (s->out_format == FMT_H263)
1107         h263_encode_init(s);
1108     if(s->msmpeg4_version)
1109         ff_msmpeg4_encode_init(s);
1110 #endif
1111     if (s->out_format == FMT_MPEG1)
1112         ff_mpeg1_encode_init(s);
1113 #endif
1114
1115     /* init default q matrix */
1116     for(i=0;i<64;i++) {
1117         int j= s->dsp.idct_permutation[i];
1118 #ifdef CONFIG_RISKY
1119         if(s->codec_id==CODEC_ID_MPEG4 && s->mpeg_quant){
1120             s->intra_matrix[j] = ff_mpeg4_default_intra_matrix[i];
1121             s->inter_matrix[j] = ff_mpeg4_default_non_intra_matrix[i];
1122         }else if(s->out_format == FMT_H263){
1123             s->intra_matrix[j] =
1124             s->inter_matrix[j] = ff_mpeg1_default_non_intra_matrix[i];
1125         }else
1126 #endif
1127         { /* mpeg1/2 */
1128             s->intra_matrix[j] = ff_mpeg1_default_intra_matrix[i];
1129             s->inter_matrix[j] = ff_mpeg1_default_non_intra_matrix[i];
1130         }
1131         if(s->avctx->intra_matrix)
1132             s->intra_matrix[j] = s->avctx->intra_matrix[i];
1133         if(s->avctx->inter_matrix)
1134             s->inter_matrix[j] = s->avctx->inter_matrix[i];
1135     }
1136
1137     /* precompute matrix */
1138     /* for mjpeg, we do include qscale in the matrix */
1139     if (s->out_format != FMT_MJPEG) {
1140         convert_matrix(&s->dsp, s->q_intra_matrix, s->q_intra_matrix16, 
1141                        s->intra_matrix, s->intra_quant_bias, 1, 31);
1142         convert_matrix(&s->dsp, s->q_inter_matrix, s->q_inter_matrix16, 
1143                        s->inter_matrix, s->inter_quant_bias, 1, 31);
1144     }
1145
1146     if(ff_rate_control_init(s) < 0)
1147         return -1;
1148
1149     s->picture_number = 0;
1150     s->input_picture_number = 0;
1151     s->picture_in_gop_number = 0;
1152     /* motion detector init */
1153     s->f_code = 1;
1154     s->b_code = 1;
1155
1156     return 0;
1157 }
1158
1159 int MPV_encode_end(AVCodecContext *avctx)
1160 {
1161     MpegEncContext *s = avctx->priv_data;
1162
1163 #ifdef STATS
1164     print_stats();
1165 #endif
1166
1167     ff_rate_control_uninit(s);
1168
1169     MPV_common_end(s);
1170     if (s->out_format == FMT_MJPEG)
1171         mjpeg_close(s);
1172
1173     av_freep(&avctx->extradata);
1174       
1175     return 0;
1176 }
1177
1178 #endif //CONFIG_ENCODERS
1179
1180 void init_rl(RLTable *rl)
1181 {
1182     int8_t max_level[MAX_RUN+1], max_run[MAX_LEVEL+1];
1183     uint8_t index_run[MAX_RUN+1];
1184     int last, run, level, start, end, i;
1185
1186     /* compute max_level[], max_run[] and index_run[] */
1187     for(last=0;last<2;last++) {
1188         if (last == 0) {
1189             start = 0;
1190             end = rl->last;
1191         } else {
1192             start = rl->last;
1193             end = rl->n;
1194         }
1195
1196         memset(max_level, 0, MAX_RUN + 1);
1197         memset(max_run, 0, MAX_LEVEL + 1);
1198         memset(index_run, rl->n, MAX_RUN + 1);
1199         for(i=start;i<end;i++) {
1200             run = rl->table_run[i];
1201             level = rl->table_level[i];
1202             if (index_run[run] == rl->n)
1203                 index_run[run] = i;
1204             if (level > max_level[run])
1205                 max_level[run] = level;
1206             if (run > max_run[level])
1207                 max_run[level] = run;
1208         }
1209         rl->max_level[last] = av_malloc(MAX_RUN + 1);
1210         memcpy(rl->max_level[last], max_level, MAX_RUN + 1);
1211         rl->max_run[last] = av_malloc(MAX_LEVEL + 1);
1212         memcpy(rl->max_run[last], max_run, MAX_LEVEL + 1);
1213         rl->index_run[last] = av_malloc(MAX_RUN + 1);
1214         memcpy(rl->index_run[last], index_run, MAX_RUN + 1);
1215     }
1216 }
1217
1218 /* draw the edges of width 'w' of an image of size width, height */
1219 //FIXME check that this is ok for mpeg4 interlaced
1220 static void draw_edges_c(uint8_t *buf, int wrap, int width, int height, int w)
1221 {
1222     uint8_t *ptr, *last_line;
1223     int i;
1224
1225     last_line = buf + (height - 1) * wrap;
1226     for(i=0;i<w;i++) {
1227         /* top and bottom */
1228         memcpy(buf - (i + 1) * wrap, buf, width);
1229         memcpy(last_line + (i + 1) * wrap, last_line, width);
1230     }
1231     /* left and right */
1232     ptr = buf;
1233     for(i=0;i<height;i++) {
1234         memset(ptr - w, ptr[0], w);
1235         memset(ptr + width, ptr[width-1], w);
1236         ptr += wrap;
1237     }
1238     /* corners */
1239     for(i=0;i<w;i++) {
1240         memset(buf - (i + 1) * wrap - w, buf[0], w); /* top left */
1241         memset(buf - (i + 1) * wrap + width, buf[width-1], w); /* top right */
1242         memset(last_line + (i + 1) * wrap - w, last_line[0], w); /* top left */
1243         memset(last_line + (i + 1) * wrap + width, last_line[width-1], w); /* top right */
1244     }
1245 }
1246
1247 int ff_find_unused_picture(MpegEncContext *s, int shared){
1248     int i;
1249     
1250     if(shared){
1251         for(i=0; i<MAX_PICTURE_COUNT; i++){
1252             if(s->picture[i].data[0]==NULL && s->picture[i].type==0) return i;
1253         }
1254     }else{
1255         for(i=0; i<MAX_PICTURE_COUNT; i++){
1256             if(s->picture[i].data[0]==NULL && s->picture[i].type!=0) return i; //FIXME
1257         }
1258         for(i=0; i<MAX_PICTURE_COUNT; i++){
1259             if(s->picture[i].data[0]==NULL) return i;
1260         }
1261     }
1262
1263     assert(0);
1264     return -1;
1265 }
1266
1267 static void update_noise_reduction(MpegEncContext *s){
1268     int intra, i;
1269
1270     for(intra=0; intra<2; intra++){
1271         if(s->dct_count[intra] > (1<<16)){
1272             for(i=0; i<64; i++){
1273                 s->dct_error_sum[intra][i] >>=1;
1274             }
1275             s->dct_count[intra] >>= 1;
1276         }
1277         
1278         for(i=0; i<64; i++){
1279             s->dct_offset[intra][i]= (s->avctx->noise_reduction * s->dct_count[intra] + s->dct_error_sum[intra][i]/2) / (s->dct_error_sum[intra][i]+1);
1280         }
1281     }
1282 }
1283
1284 /**
1285  * generic function for encode/decode called after coding/decoding the header and before a frame is coded/decoded
1286  */
1287 int MPV_frame_start(MpegEncContext *s, AVCodecContext *avctx)
1288 {
1289     int i;
1290     AVFrame *pic;
1291     s->mb_skiped = 0;
1292
1293     assert(s->last_picture_ptr==NULL || s->out_format != FMT_H264 || s->codec_id == CODEC_ID_SVQ3);
1294
1295     /* mark&release old frames */
1296     if (s->pict_type != B_TYPE && s->last_picture_ptr && s->last_picture_ptr->data[0]) {
1297         avctx->release_buffer(avctx, (AVFrame*)s->last_picture_ptr);
1298
1299         /* release forgotten pictures */
1300         /* if(mpeg124/h263) */
1301         if(!s->encoding){
1302             for(i=0; i<MAX_PICTURE_COUNT; i++){
1303                 if(s->picture[i].data[0] && &s->picture[i] != s->next_picture_ptr && s->picture[i].reference){
1304                     av_log(avctx, AV_LOG_ERROR, "releasing zombie picture\n");
1305                     avctx->release_buffer(avctx, (AVFrame*)&s->picture[i]);                
1306                 }
1307             }
1308         }
1309     }
1310 alloc:
1311     if(!s->encoding){
1312         /* release non refernce frames */
1313         for(i=0; i<MAX_PICTURE_COUNT; i++){
1314             if(s->picture[i].data[0] && !s->picture[i].reference /*&& s->picture[i].type!=FF_BUFFER_TYPE_SHARED*/){
1315                 s->avctx->release_buffer(s->avctx, (AVFrame*)&s->picture[i]);
1316             }
1317         }
1318
1319         if(s->current_picture_ptr && s->current_picture_ptr->data[0]==NULL)
1320             pic= (AVFrame*)s->current_picture_ptr; //we allready have a unused image (maybe it was set before reading the header)
1321         else{
1322             i= ff_find_unused_picture(s, 0);
1323             pic= (AVFrame*)&s->picture[i];
1324         }
1325
1326         pic->reference= s->pict_type != B_TYPE ? 3 : 0;
1327
1328         pic->coded_picture_number= s->coded_picture_number++;
1329         
1330         if( alloc_picture(s, (Picture*)pic, 0) < 0)
1331             return -1;
1332
1333         s->current_picture_ptr= (Picture*)pic;
1334         s->current_picture_ptr->top_field_first= s->top_field_first; //FIXME use only the vars from current_pic
1335         s->current_picture_ptr->interlaced_frame= !s->progressive_frame && !s->progressive_sequence;
1336     }
1337
1338     s->current_picture_ptr->pict_type= s->pict_type;
1339 //    if(s->flags && CODEC_FLAG_QSCALE) 
1340   //      s->current_picture_ptr->quality= s->new_picture_ptr->quality;
1341     s->current_picture_ptr->key_frame= s->pict_type == I_TYPE;
1342
1343     copy_picture(&s->current_picture, s->current_picture_ptr);
1344   
1345   if(s->out_format != FMT_H264 || s->codec_id == CODEC_ID_SVQ3){
1346     if (s->pict_type != B_TYPE) {
1347         s->last_picture_ptr= s->next_picture_ptr;
1348         s->next_picture_ptr= s->current_picture_ptr;
1349     }
1350     
1351     if(s->last_picture_ptr) copy_picture(&s->last_picture, s->last_picture_ptr);
1352     if(s->next_picture_ptr) copy_picture(&s->next_picture, s->next_picture_ptr);
1353     
1354     if(s->pict_type != I_TYPE && (s->last_picture_ptr==NULL || s->last_picture_ptr->data[0]==NULL)){
1355         av_log(avctx, AV_LOG_ERROR, "warning: first frame is no keyframe\n");
1356         assert(s->pict_type != B_TYPE); //these should have been dropped if we dont have a reference
1357         goto alloc;
1358     }
1359
1360     assert(s->pict_type == I_TYPE || (s->last_picture_ptr && s->last_picture_ptr->data[0]));
1361
1362     if(s->picture_structure!=PICT_FRAME){
1363         int i;
1364         for(i=0; i<4; i++){
1365             if(s->picture_structure == PICT_BOTTOM_FIELD){
1366                  s->current_picture.data[i] += s->current_picture.linesize[i];
1367             } 
1368             s->current_picture.linesize[i] *= 2;
1369             s->last_picture.linesize[i] *=2;
1370             s->next_picture.linesize[i] *=2;
1371         }
1372     }
1373   }
1374    
1375     s->hurry_up= s->avctx->hurry_up;
1376     s->error_resilience= avctx->error_resilience;
1377
1378     /* set dequantizer, we cant do it during init as it might change for mpeg4
1379        and we cant do it in the header decode as init isnt called for mpeg4 there yet */
1380     if(s->mpeg_quant || s->codec_id == CODEC_ID_MPEG2VIDEO){
1381         s->dct_unquantize_intra = s->dct_unquantize_mpeg2_intra;
1382         s->dct_unquantize_inter = s->dct_unquantize_mpeg2_inter;
1383     }else if(s->out_format == FMT_H263){
1384         s->dct_unquantize_intra = s->dct_unquantize_h263_intra;
1385         s->dct_unquantize_inter = s->dct_unquantize_h263_inter;
1386     }else{
1387         s->dct_unquantize_intra = s->dct_unquantize_mpeg1_intra;
1388         s->dct_unquantize_inter = s->dct_unquantize_mpeg1_inter;
1389     }
1390
1391     if(s->dct_error_sum){
1392         assert(s->avctx->noise_reduction && s->encoding);
1393
1394         update_noise_reduction(s);
1395     }
1396         
1397 #ifdef HAVE_XVMC
1398     if(s->avctx->xvmc_acceleration)
1399         return XVMC_field_start(s, avctx);
1400 #endif
1401     return 0;
1402 }
1403
1404 /* generic function for encode/decode called after a frame has been coded/decoded */
1405 void MPV_frame_end(MpegEncContext *s)
1406 {
1407     int i;
1408     /* draw edge for correct motion prediction if outside */
1409 #ifdef HAVE_XVMC
1410 //just to make sure that all data is rendered.
1411     if(s->avctx->xvmc_acceleration){
1412         XVMC_field_end(s);
1413     }else
1414 #endif
1415     if(s->unrestricted_mv && s->pict_type != B_TYPE && !s->intra_only && !(s->flags&CODEC_FLAG_EMU_EDGE)) {
1416             draw_edges(s->current_picture.data[0], s->linesize  , s->h_edge_pos   , s->v_edge_pos   , EDGE_WIDTH  );
1417             draw_edges(s->current_picture.data[1], s->uvlinesize, s->h_edge_pos>>1, s->v_edge_pos>>1, EDGE_WIDTH/2);
1418             draw_edges(s->current_picture.data[2], s->uvlinesize, s->h_edge_pos>>1, s->v_edge_pos>>1, EDGE_WIDTH/2);
1419     }
1420     emms_c();
1421     
1422     s->last_pict_type    = s->pict_type;
1423     if(s->pict_type!=B_TYPE){
1424         s->last_non_b_pict_type= s->pict_type;
1425     }
1426 #if 0
1427         /* copy back current_picture variables */
1428     for(i=0; i<MAX_PICTURE_COUNT; i++){
1429         if(s->picture[i].data[0] == s->current_picture.data[0]){
1430             s->picture[i]= s->current_picture;
1431             break;
1432         }    
1433     }
1434     assert(i<MAX_PICTURE_COUNT);
1435 #endif    
1436
1437     if(s->encoding){
1438         /* release non refernce frames */
1439         for(i=0; i<MAX_PICTURE_COUNT; i++){
1440             if(s->picture[i].data[0] && !s->picture[i].reference /*&& s->picture[i].type!=FF_BUFFER_TYPE_SHARED*/){
1441                 s->avctx->release_buffer(s->avctx, (AVFrame*)&s->picture[i]);
1442             }
1443         }
1444     }
1445     // clear copies, to avoid confusion
1446 #if 0
1447     memset(&s->last_picture, 0, sizeof(Picture));
1448     memset(&s->next_picture, 0, sizeof(Picture));
1449     memset(&s->current_picture, 0, sizeof(Picture));
1450 #endif
1451 }
1452
1453 /**
1454  * draws an line from (ex, ey) -> (sx, sy).
1455  * @param w width of the image
1456  * @param h height of the image
1457  * @param stride stride/linesize of the image
1458  * @param color color of the arrow
1459  */
1460 static void draw_line(uint8_t *buf, int sx, int sy, int ex, int ey, int w, int h, int stride, int color){
1461     int t, x, y, f;
1462     
1463     sx= clip(sx, 0, w-1);
1464     sy= clip(sy, 0, h-1);
1465     ex= clip(ex, 0, w-1);
1466     ey= clip(ey, 0, h-1);
1467     
1468     buf[sy*stride + sx]+= color;
1469     
1470     if(ABS(ex - sx) > ABS(ey - sy)){
1471         if(sx > ex){
1472             t=sx; sx=ex; ex=t;
1473             t=sy; sy=ey; ey=t;
1474         }
1475         buf+= sx + sy*stride;
1476         ex-= sx;
1477         f= ((ey-sy)<<16)/ex;
1478         for(x= 0; x <= ex; x++){
1479             y= ((x*f) + (1<<15))>>16;
1480             buf[y*stride + x]+= color;
1481         }
1482     }else{
1483         if(sy > ey){
1484             t=sx; sx=ex; ex=t;
1485             t=sy; sy=ey; ey=t;
1486         }
1487         buf+= sx + sy*stride;
1488         ey-= sy;
1489         if(ey) f= ((ex-sx)<<16)/ey;
1490         else   f= 0;
1491         for(y= 0; y <= ey; y++){
1492             x= ((y*f) + (1<<15))>>16;
1493             buf[y*stride + x]+= color;
1494         }
1495     }
1496 }
1497
1498 /**
1499  * draws an arrow from (ex, ey) -> (sx, sy).
1500  * @param w width of the image
1501  * @param h height of the image
1502  * @param stride stride/linesize of the image
1503  * @param color color of the arrow
1504  */
1505 static void draw_arrow(uint8_t *buf, int sx, int sy, int ex, int ey, int w, int h, int stride, int color){ 
1506     int dx,dy;
1507
1508     sx= clip(sx, -100, w+100);
1509     sy= clip(sy, -100, h+100);
1510     ex= clip(ex, -100, w+100);
1511     ey= clip(ey, -100, h+100);
1512     
1513     dx= ex - sx;
1514     dy= ey - sy;
1515     
1516     if(dx*dx + dy*dy > 3*3){
1517         int rx=  dx + dy;
1518         int ry= -dx + dy;
1519         int length= ff_sqrt((rx*rx + ry*ry)<<8);
1520         
1521         //FIXME subpixel accuracy
1522         rx= ROUNDED_DIV(rx*3<<4, length);
1523         ry= ROUNDED_DIV(ry*3<<4, length);
1524         
1525         draw_line(buf, sx, sy, sx + rx, sy + ry, w, h, stride, color);
1526         draw_line(buf, sx, sy, sx - ry, sy + rx, w, h, stride, color);
1527     }
1528     draw_line(buf, sx, sy, ex, ey, w, h, stride, color);
1529 }
1530
1531 /**
1532  * prints debuging info for the given picture.
1533  */
1534 void ff_print_debug_info(MpegEncContext *s, AVFrame *pict){
1535
1536     if(!pict || !pict->mb_type) return;
1537
1538     if(s->avctx->debug&(FF_DEBUG_SKIP | FF_DEBUG_QP | FF_DEBUG_MB_TYPE)){
1539         int x,y;
1540         
1541         av_log(s->avctx,AV_LOG_DEBUG,"New frame, type: ");
1542         switch (pict->pict_type) {
1543             case FF_I_TYPE: av_log(s->avctx,AV_LOG_DEBUG,"I\n"); break;
1544             case FF_P_TYPE: av_log(s->avctx,AV_LOG_DEBUG,"P\n"); break;
1545             case FF_B_TYPE: av_log(s->avctx,AV_LOG_DEBUG,"B\n"); break;
1546             case FF_S_TYPE: av_log(s->avctx,AV_LOG_DEBUG,"S\n"); break;
1547             case FF_SI_TYPE: av_log(s->avctx,AV_LOG_DEBUG,"SI\n"); break;
1548             case FF_SP_TYPE: av_log(s->avctx,AV_LOG_DEBUG,"SP\n"); break;            
1549         }
1550         for(y=0; y<s->mb_height; y++){
1551             for(x=0; x<s->mb_width; x++){
1552                 if(s->avctx->debug&FF_DEBUG_SKIP){
1553                     int count= s->mbskip_table[x + y*s->mb_stride];
1554                     if(count>9) count=9;
1555                     av_log(s->avctx, AV_LOG_DEBUG, "%1d", count);
1556                 }
1557                 if(s->avctx->debug&FF_DEBUG_QP){
1558                     av_log(s->avctx, AV_LOG_DEBUG, "%2d", pict->qscale_table[x + y*s->mb_stride]);
1559                 }
1560                 if(s->avctx->debug&FF_DEBUG_MB_TYPE){
1561                     int mb_type= pict->mb_type[x + y*s->mb_stride];
1562                     //Type & MV direction
1563                     if(IS_PCM(mb_type))
1564                         av_log(s->avctx, AV_LOG_DEBUG, "P");
1565                     else if(IS_INTRA(mb_type) && IS_ACPRED(mb_type))
1566                         av_log(s->avctx, AV_LOG_DEBUG, "A");
1567                     else if(IS_INTRA4x4(mb_type))
1568                         av_log(s->avctx, AV_LOG_DEBUG, "i");
1569                     else if(IS_INTRA16x16(mb_type))
1570                         av_log(s->avctx, AV_LOG_DEBUG, "I");
1571                     else if(IS_DIRECT(mb_type) && IS_SKIP(mb_type))
1572                         av_log(s->avctx, AV_LOG_DEBUG, "d");
1573                     else if(IS_DIRECT(mb_type))
1574                         av_log(s->avctx, AV_LOG_DEBUG, "D");
1575                     else if(IS_GMC(mb_type) && IS_SKIP(mb_type))
1576                         av_log(s->avctx, AV_LOG_DEBUG, "g");
1577                     else if(IS_GMC(mb_type))
1578                         av_log(s->avctx, AV_LOG_DEBUG, "G");
1579                     else if(IS_SKIP(mb_type))
1580                         av_log(s->avctx, AV_LOG_DEBUG, "S");
1581                     else if(!USES_LIST(mb_type, 1))
1582                         av_log(s->avctx, AV_LOG_DEBUG, ">");
1583                     else if(!USES_LIST(mb_type, 0))
1584                         av_log(s->avctx, AV_LOG_DEBUG, "<");
1585                     else{
1586                         assert(USES_LIST(mb_type, 0) && USES_LIST(mb_type, 1));
1587                         av_log(s->avctx, AV_LOG_DEBUG, "X");
1588                     }
1589                     
1590                     //segmentation
1591                     if(IS_8X8(mb_type))
1592                         av_log(s->avctx, AV_LOG_DEBUG, "+");
1593                     else if(IS_16X8(mb_type))
1594                         av_log(s->avctx, AV_LOG_DEBUG, "-");
1595                     else if(IS_8X16(mb_type))
1596                         av_log(s->avctx, AV_LOG_DEBUG, "¦");
1597                     else if(IS_INTRA(mb_type) || IS_16X16(mb_type))
1598                         av_log(s->avctx, AV_LOG_DEBUG, " ");
1599                     else
1600                         av_log(s->avctx, AV_LOG_DEBUG, "?");
1601                     
1602                         
1603                     if(IS_INTERLACED(mb_type) && s->codec_id == CODEC_ID_H264)
1604                         av_log(s->avctx, AV_LOG_DEBUG, "=");
1605                     else
1606                         av_log(s->avctx, AV_LOG_DEBUG, " ");
1607                 }
1608 //                av_log(s->avctx, AV_LOG_DEBUG, " ");
1609             }
1610             av_log(s->avctx, AV_LOG_DEBUG, "\n");
1611         }
1612     }
1613
1614     if((s->avctx->debug&(FF_DEBUG_VIS_QP|FF_DEBUG_VIS_MB_TYPE)) || (s->avctx->debug_mv)){
1615         const int shift= 1 + s->quarter_sample;
1616         int mb_y;
1617         uint8_t *ptr;
1618         int i;
1619         int h_chroma_shift, v_chroma_shift;
1620         s->low_delay=0; //needed to see the vectors without trashing the buffers
1621
1622         avcodec_get_chroma_sub_sample(s->avctx->pix_fmt, &h_chroma_shift, &v_chroma_shift);
1623         for(i=0; i<3; i++){
1624             memcpy(s->visualization_buffer[i], pict->data[i], (i==0) ? pict->linesize[i]*s->height:pict->linesize[i]*s->height >> v_chroma_shift);
1625             pict->data[i]= s->visualization_buffer[i];
1626         }
1627         pict->type= FF_BUFFER_TYPE_COPY;
1628         ptr= pict->data[0];
1629
1630         for(mb_y=0; mb_y<s->mb_height; mb_y++){
1631             int mb_x;
1632             for(mb_x=0; mb_x<s->mb_width; mb_x++){
1633                 const int mb_index= mb_x + mb_y*s->mb_stride;
1634                 if((s->avctx->debug_mv) && pict->motion_val){
1635                   int type;
1636                   for(type=0; type<3; type++){
1637                     int direction;
1638                     switch (type) {
1639                       case 0: if ((!(s->avctx->debug_mv&FF_DEBUG_VIS_MV_P_FOR)) || (pict->pict_type!=FF_P_TYPE))
1640                                 continue;
1641                               direction = 0;
1642                               break;
1643                       case 1: if ((!(s->avctx->debug_mv&FF_DEBUG_VIS_MV_B_FOR)) || (pict->pict_type!=FF_B_TYPE))
1644                                 continue;
1645                               direction = 0;
1646                               break;
1647                       case 2: if ((!(s->avctx->debug_mv&FF_DEBUG_VIS_MV_B_BACK)) || (pict->pict_type!=FF_B_TYPE))
1648                                 continue;
1649                               direction = 1;
1650                               break;
1651                     }
1652                     if(!USES_LIST(pict->mb_type[mb_index], direction))
1653                         continue;
1654
1655                     if(IS_8X8(pict->mb_type[mb_index])){
1656                       int i;
1657                       for(i=0; i<4; i++){
1658                         int sx= mb_x*16 + 4 + 8*(i&1);
1659                         int sy= mb_y*16 + 4 + 8*(i>>1);
1660                         int xy= 1 + mb_x*2 + (i&1) + (mb_y*2 + 1 + (i>>1))*(s->mb_width*2 + 2);
1661                         int mx= (pict->motion_val[direction][xy][0]>>shift) + sx;
1662                         int my= (pict->motion_val[direction][xy][1]>>shift) + sy;
1663                         draw_arrow(ptr, sx, sy, mx, my, s->width, s->height, s->linesize, 100);
1664                       }
1665                     }else if(IS_16X8(pict->mb_type[mb_index])){
1666                       int i;
1667                       for(i=0; i<2; i++){
1668                         int sx=mb_x*16 + 8;
1669                         int sy=mb_y*16 + 4 + 8*i;
1670                         int xy=1 + mb_x*2 + (mb_y*2 + 1 + i)*(s->mb_width*2 + 2);
1671                         int mx=(pict->motion_val[direction][xy][0]>>shift) + sx;
1672                         int my=(pict->motion_val[direction][xy][1]>>shift) + sy;
1673                         draw_arrow(ptr, sx, sy, mx, my, s->width, s->height, s->linesize, 100);
1674                       }
1675                     }else{
1676                       int sx= mb_x*16 + 8;
1677                       int sy= mb_y*16 + 8;
1678                       int xy= 1 + mb_x*2 + (mb_y*2 + 1)*(s->mb_width*2 + 2);
1679                       int mx= (pict->motion_val[direction][xy][0]>>shift) + sx;
1680                       int my= (pict->motion_val[direction][xy][1]>>shift) + sy;
1681                       draw_arrow(ptr, sx, sy, mx, my, s->width, s->height, s->linesize, 100);
1682                     }
1683                   }                  
1684                 }
1685                 if((s->avctx->debug&FF_DEBUG_VIS_QP) && pict->motion_val){
1686                     uint64_t c= (pict->qscale_table[mb_index]*128/31) * 0x0101010101010101ULL;
1687                     int y;
1688                     for(y=0; y<8; y++){
1689                         *(uint64_t*)(pict->data[1] + 8*mb_x + (8*mb_y + y)*pict->linesize[1])= c;
1690                         *(uint64_t*)(pict->data[2] + 8*mb_x + (8*mb_y + y)*pict->linesize[2])= c;
1691                     }
1692                 }
1693                 if((s->avctx->debug&FF_DEBUG_VIS_MB_TYPE) && pict->motion_val){
1694                     int mb_type= pict->mb_type[mb_index];
1695                     uint64_t u,v;
1696                     int y;
1697 #define COLOR(theta, r)\
1698 u= (int)(128 + r*cos(theta*3.141592/180));\
1699 v= (int)(128 + r*sin(theta*3.141592/180));
1700
1701                     
1702                     u=v=128;
1703                     if(IS_PCM(mb_type)){
1704                         COLOR(120,48)
1705                     }else if((IS_INTRA(mb_type) && IS_ACPRED(mb_type)) || IS_INTRA16x16(mb_type)){
1706                         COLOR(30,48)
1707                     }else if(IS_INTRA4x4(mb_type)){
1708                         COLOR(90,48)
1709                     }else if(IS_DIRECT(mb_type) && IS_SKIP(mb_type)){
1710 //                        COLOR(120,48)
1711                     }else if(IS_DIRECT(mb_type)){
1712                         COLOR(150,48)
1713                     }else if(IS_GMC(mb_type) && IS_SKIP(mb_type)){
1714                         COLOR(170,48)
1715                     }else if(IS_GMC(mb_type)){
1716                         COLOR(190,48)
1717                     }else if(IS_SKIP(mb_type)){
1718 //                        COLOR(180,48)
1719                     }else if(!USES_LIST(mb_type, 1)){
1720                         COLOR(240,48)
1721                     }else if(!USES_LIST(mb_type, 0)){
1722                         COLOR(0,48)
1723                     }else{
1724                         assert(USES_LIST(mb_type, 0) && USES_LIST(mb_type, 1));
1725                         COLOR(300,48)
1726                     }
1727
1728                     u*= 0x0101010101010101ULL;
1729                     v*= 0x0101010101010101ULL;
1730                     for(y=0; y<8; y++){
1731                         *(uint64_t*)(pict->data[1] + 8*mb_x + (8*mb_y + y)*pict->linesize[1])= u;
1732                         *(uint64_t*)(pict->data[2] + 8*mb_x + (8*mb_y + y)*pict->linesize[2])= v;
1733                     }
1734
1735                     //segmentation
1736                     if(IS_8X8(mb_type) || IS_16X8(mb_type)){
1737                         *(uint64_t*)(pict->data[0] + 16*mb_x + 0 + (16*mb_y + 8)*pict->linesize[0])^= 0x8080808080808080ULL;
1738                         *(uint64_t*)(pict->data[0] + 16*mb_x + 8 + (16*mb_y + 8)*pict->linesize[0])^= 0x8080808080808080ULL;
1739                     }
1740                     if(IS_8X8(mb_type) || IS_8X16(mb_type)){
1741                         for(y=0; y<16; y++)
1742                             pict->data[0][16*mb_x + 8 + (16*mb_y + y)*pict->linesize[0]]^= 0x80;
1743                     }
1744                         
1745                     if(IS_INTERLACED(mb_type) && s->codec_id == CODEC_ID_H264){
1746                         // hmm
1747                     }
1748                 }
1749                 s->mbskip_table[mb_index]=0;
1750             }
1751         }
1752     }
1753 }
1754
1755 #ifdef CONFIG_ENCODERS
1756
1757 static int get_sae(uint8_t *src, int ref, int stride){
1758     int x,y;
1759     int acc=0;
1760     
1761     for(y=0; y<16; y++){
1762         for(x=0; x<16; x++){
1763             acc+= ABS(src[x+y*stride] - ref);
1764         }
1765     }
1766     
1767     return acc;
1768 }
1769
1770 static int get_intra_count(MpegEncContext *s, uint8_t *src, uint8_t *ref, int stride){
1771     int x, y, w, h;
1772     int acc=0;
1773     
1774     w= s->width &~15;
1775     h= s->height&~15;
1776     
1777     for(y=0; y<h; y+=16){
1778         for(x=0; x<w; x+=16){
1779             int offset= x + y*stride;
1780             int sad = s->dsp.sad[0](NULL, src + offset, ref + offset, stride, 16);
1781             int mean= (s->dsp.pix_sum(src + offset, stride) + 128)>>8;
1782             int sae = get_sae(src + offset, mean, stride);
1783             
1784             acc+= sae + 500 < sad;
1785         }
1786     }
1787     return acc;
1788 }
1789
1790
1791 static int load_input_picture(MpegEncContext *s, AVFrame *pic_arg){
1792     AVFrame *pic=NULL;
1793     int i;
1794     const int encoding_delay= s->max_b_frames;
1795     int direct=1;
1796     
1797   if(pic_arg){
1798     if(encoding_delay && !(s->flags&CODEC_FLAG_INPUT_PRESERVED)) direct=0;
1799     if(pic_arg->linesize[0] != s->linesize) direct=0;
1800     if(pic_arg->linesize[1] != s->uvlinesize) direct=0;
1801     if(pic_arg->linesize[2] != s->uvlinesize) direct=0;
1802   
1803 //    av_log(AV_LOG_DEBUG, "%d %d %d %d\n",pic_arg->linesize[0], pic_arg->linesize[1], s->linesize, s->uvlinesize);
1804     
1805     if(direct){
1806         i= ff_find_unused_picture(s, 1);
1807
1808         pic= (AVFrame*)&s->picture[i];
1809         pic->reference= 3;
1810     
1811         for(i=0; i<4; i++){
1812             pic->data[i]= pic_arg->data[i];
1813             pic->linesize[i]= pic_arg->linesize[i];
1814         }
1815         alloc_picture(s, (Picture*)pic, 1);
1816     }else{
1817         int offset= 16;
1818         i= ff_find_unused_picture(s, 0);
1819
1820         pic= (AVFrame*)&s->picture[i];
1821         pic->reference= 3;
1822
1823         alloc_picture(s, (Picture*)pic, 0);
1824
1825         if(   pic->data[0] + offset == pic_arg->data[0] 
1826            && pic->data[1] + offset == pic_arg->data[1]
1827            && pic->data[2] + offset == pic_arg->data[2]){
1828        // empty
1829         }else{
1830             int h_chroma_shift, v_chroma_shift;
1831             avcodec_get_chroma_sub_sample(s->avctx->pix_fmt, &h_chroma_shift, &v_chroma_shift);
1832         
1833             for(i=0; i<3; i++){
1834                 int src_stride= pic_arg->linesize[i];
1835                 int dst_stride= i ? s->uvlinesize : s->linesize;
1836                 int h_shift= i ? h_chroma_shift : 0;
1837                 int v_shift= i ? v_chroma_shift : 0;
1838                 int w= s->width >>h_shift;
1839                 int h= s->height>>v_shift;
1840                 uint8_t *src= pic_arg->data[i];
1841                 uint8_t *dst= pic->data[i] + offset;
1842             
1843                 if(src_stride==dst_stride)
1844                     memcpy(dst, src, src_stride*h);
1845                 else{
1846                     while(h--){
1847                         memcpy(dst, src, w);
1848                         dst += dst_stride;
1849                         src += src_stride;
1850                     }
1851                 }
1852             }
1853         }
1854     }
1855     copy_picture_attributes(pic, pic_arg);
1856     
1857     pic->display_picture_number= s->input_picture_number++;
1858     if(pic->pts != AV_NOPTS_VALUE){ 
1859         s->user_specified_pts= pic->pts;
1860     }else{
1861         if(s->user_specified_pts){
1862             pic->pts= s->user_specified_pts + AV_TIME_BASE*(int64_t)s->avctx->frame_rate_base / s->avctx->frame_rate;
1863             av_log(s->avctx, AV_LOG_INFO, "Warning: AVFrame.pts=? trying to guess (%Ld)\n", pic->pts);
1864         }else{
1865             pic->pts= av_rescale(pic->display_picture_number*(int64_t)s->avctx->frame_rate_base, AV_TIME_BASE, s->avctx->frame_rate);
1866         }
1867     }
1868   }
1869   
1870     /* shift buffer entries */
1871     for(i=1; i<MAX_PICTURE_COUNT /*s->encoding_delay+1*/; i++)
1872         s->input_picture[i-1]= s->input_picture[i];
1873         
1874     s->input_picture[encoding_delay]= (Picture*)pic;
1875
1876     return 0;
1877 }
1878
1879 static void select_input_picture(MpegEncContext *s){
1880     int i;
1881
1882     for(i=1; i<MAX_PICTURE_COUNT; i++)
1883         s->reordered_input_picture[i-1]= s->reordered_input_picture[i];
1884     s->reordered_input_picture[MAX_PICTURE_COUNT-1]= NULL;
1885
1886     /* set next picture types & ordering */
1887     if(s->reordered_input_picture[0]==NULL && s->input_picture[0]){
1888         if(/*s->picture_in_gop_number >= s->gop_size ||*/ s->next_picture_ptr==NULL || s->intra_only){
1889             s->reordered_input_picture[0]= s->input_picture[0];
1890             s->reordered_input_picture[0]->pict_type= I_TYPE;
1891             s->reordered_input_picture[0]->coded_picture_number= s->coded_picture_number++;
1892         }else{
1893             int b_frames;
1894             
1895             if(s->flags&CODEC_FLAG_PASS2){
1896                 for(i=0; i<s->max_b_frames+1; i++){
1897                     int pict_num= s->input_picture[0]->display_picture_number + i;
1898                     int pict_type= s->rc_context.entry[pict_num].new_pict_type;
1899                     s->input_picture[i]->pict_type= pict_type;
1900                     
1901                     if(i + 1 >= s->rc_context.num_entries) break;
1902                 }
1903             }
1904
1905             if(s->input_picture[0]->pict_type){
1906                 /* user selected pict_type */
1907                 for(b_frames=0; b_frames<s->max_b_frames+1; b_frames++){
1908                     if(s->input_picture[b_frames]->pict_type!=B_TYPE) break;
1909                 }
1910             
1911                 if(b_frames > s->max_b_frames){
1912                     av_log(s->avctx, AV_LOG_ERROR, "warning, too many bframes in a row\n");
1913                     b_frames = s->max_b_frames;
1914                 }
1915             }else if(s->avctx->b_frame_strategy==0){
1916                 b_frames= s->max_b_frames;
1917                 while(b_frames && !s->input_picture[b_frames]) b_frames--;
1918             }else if(s->avctx->b_frame_strategy==1){
1919                 for(i=1; i<s->max_b_frames+1; i++){
1920                     if(s->input_picture[i] && s->input_picture[i]->b_frame_score==0){
1921                         s->input_picture[i]->b_frame_score= 
1922                             get_intra_count(s, s->input_picture[i  ]->data[0], 
1923                                                s->input_picture[i-1]->data[0], s->linesize) + 1;
1924                     }
1925                 }
1926                 for(i=0; i<s->max_b_frames; i++){
1927                     if(s->input_picture[i]==NULL || s->input_picture[i]->b_frame_score - 1 > s->mb_num/40) break;
1928                 }
1929                                 
1930                 b_frames= FFMAX(0, i-1);
1931                 
1932                 /* reset scores */
1933                 for(i=0; i<b_frames+1; i++){
1934                     s->input_picture[i]->b_frame_score=0;
1935                 }
1936             }else{
1937                 av_log(s->avctx, AV_LOG_ERROR, "illegal b frame strategy\n");
1938                 b_frames=0;
1939             }
1940
1941             emms_c();
1942 //static int b_count=0;
1943 //b_count+= b_frames;
1944 //av_log(s->avctx, AV_LOG_DEBUG, "b_frames: %d\n", b_count);
1945             if(s->picture_in_gop_number + b_frames >= s->gop_size){
1946                 if(s->flags & CODEC_FLAG_CLOSED_GOP)
1947                     b_frames=0;
1948                 s->input_picture[b_frames]->pict_type= I_TYPE;
1949             }
1950             
1951             if(   (s->flags & CODEC_FLAG_CLOSED_GOP)
1952                && b_frames
1953                && s->input_picture[b_frames]->pict_type== I_TYPE)
1954                 b_frames--;
1955
1956             s->reordered_input_picture[0]= s->input_picture[b_frames];
1957             if(s->reordered_input_picture[0]->pict_type != I_TYPE)
1958                 s->reordered_input_picture[0]->pict_type= P_TYPE;
1959             s->reordered_input_picture[0]->coded_picture_number= s->coded_picture_number++;
1960             for(i=0; i<b_frames; i++){
1961                 s->reordered_input_picture[i+1]= s->input_picture[i];
1962                 s->reordered_input_picture[i+1]->pict_type= B_TYPE;
1963                 s->reordered_input_picture[i+1]->coded_picture_number= s->coded_picture_number++;
1964             }
1965         }
1966     }
1967     
1968     if(s->reordered_input_picture[0]){
1969         s->reordered_input_picture[0]->reference= s->reordered_input_picture[0]->pict_type!=B_TYPE ? 3 : 0;
1970
1971         copy_picture(&s->new_picture, s->reordered_input_picture[0]);
1972
1973         if(s->reordered_input_picture[0]->type == FF_BUFFER_TYPE_SHARED){
1974             // input is a shared pix, so we cant modifiy it -> alloc a new one & ensure that the shared one is reuseable
1975         
1976             int i= ff_find_unused_picture(s, 0);
1977             Picture *pic= &s->picture[i];
1978
1979             /* mark us unused / free shared pic */
1980             for(i=0; i<4; i++)
1981                 s->reordered_input_picture[0]->data[i]= NULL;
1982             s->reordered_input_picture[0]->type= 0;
1983             
1984             copy_picture_attributes((AVFrame*)pic, (AVFrame*)s->reordered_input_picture[0]);
1985             pic->reference              = s->reordered_input_picture[0]->reference;
1986             
1987             alloc_picture(s, pic, 0);
1988
1989             s->current_picture_ptr= pic;
1990         }else{
1991             // input is not a shared pix -> reuse buffer for current_pix
1992
1993             assert(   s->reordered_input_picture[0]->type==FF_BUFFER_TYPE_USER 
1994                    || s->reordered_input_picture[0]->type==FF_BUFFER_TYPE_INTERNAL);
1995             
1996             s->current_picture_ptr= s->reordered_input_picture[0];
1997             for(i=0; i<4; i++){
1998                 s->new_picture.data[i]+=16;
1999             }
2000         }
2001         copy_picture(&s->current_picture, s->current_picture_ptr);
2002     
2003         s->picture_number= s->new_picture.display_picture_number;
2004 //printf("dpn:%d\n", s->picture_number);
2005     }else{
2006        memset(&s->new_picture, 0, sizeof(Picture));
2007     }
2008 }
2009
2010 int MPV_encode_picture(AVCodecContext *avctx,
2011                        unsigned char *buf, int buf_size, void *data)
2012 {
2013     MpegEncContext *s = avctx->priv_data;
2014     AVFrame *pic_arg = data;
2015     int i, stuffing_count;
2016
2017     if(avctx->pix_fmt != PIX_FMT_YUV420P){
2018         av_log(avctx, AV_LOG_ERROR, "this codec supports only YUV420P\n");
2019         return -1;
2020     }
2021     
2022     for(i=0; i<avctx->thread_count; i++){
2023         int start_y= s->thread_context[i]->start_mb_y;
2024         int   end_y= s->thread_context[i]->  end_mb_y;
2025         int h= s->mb_height;
2026         uint8_t *start= buf + buf_size*start_y/h;
2027         uint8_t *end  = buf + buf_size*  end_y/h;
2028
2029         init_put_bits(&s->thread_context[i]->pb, start, end - start);
2030     }
2031
2032     s->picture_in_gop_number++;
2033
2034     load_input_picture(s, pic_arg);
2035     
2036     select_input_picture(s);
2037     
2038     /* output? */
2039     if(s->new_picture.data[0]){
2040         s->pict_type= s->new_picture.pict_type;
2041 //emms_c();
2042 //printf("qs:%f %f %d\n", s->new_picture.quality, s->current_picture.quality, s->qscale);
2043         MPV_frame_start(s, avctx);
2044
2045         encode_picture(s, s->picture_number);
2046         
2047         avctx->real_pict_num  = s->picture_number;
2048         avctx->header_bits = s->header_bits;
2049         avctx->mv_bits     = s->mv_bits;
2050         avctx->misc_bits   = s->misc_bits;
2051         avctx->i_tex_bits  = s->i_tex_bits;
2052         avctx->p_tex_bits  = s->p_tex_bits;
2053         avctx->i_count     = s->i_count;
2054         avctx->p_count     = s->mb_num - s->i_count - s->skip_count; //FIXME f/b_count in avctx
2055         avctx->skip_count  = s->skip_count;
2056
2057         MPV_frame_end(s);
2058
2059         if (s->out_format == FMT_MJPEG)
2060             mjpeg_picture_trailer(s);
2061         
2062         if(s->flags&CODEC_FLAG_PASS1)
2063             ff_write_pass1_stats(s);
2064
2065         for(i=0; i<4; i++){
2066             avctx->error[i] += s->current_picture_ptr->error[i];
2067         }
2068
2069         flush_put_bits(&s->pb);
2070         s->frame_bits  = put_bits_count(&s->pb);
2071
2072         stuffing_count= ff_vbv_update(s, s->frame_bits);
2073         if(stuffing_count){
2074             switch(s->codec_id){
2075             case CODEC_ID_MPEG1VIDEO:
2076             case CODEC_ID_MPEG2VIDEO:
2077                 while(stuffing_count--){
2078                     put_bits(&s->pb, 8, 0);
2079                 }
2080             break;
2081             case CODEC_ID_MPEG4:
2082                 put_bits(&s->pb, 16, 0);
2083                 put_bits(&s->pb, 16, 0x1C3);
2084                 stuffing_count -= 4;
2085                 while(stuffing_count--){
2086                     put_bits(&s->pb, 8, 0xFF);
2087                 }
2088             break;
2089             default:
2090                 av_log(s->avctx, AV_LOG_ERROR, "vbv buffer overflow\n");
2091             }
2092             flush_put_bits(&s->pb);
2093             s->frame_bits  = put_bits_count(&s->pb);
2094         }
2095
2096         /* update mpeg1/2 vbv_delay for CBR */    
2097         if(s->avctx->rc_max_rate && s->avctx->rc_min_rate == s->avctx->rc_max_rate){
2098             int vbv_delay;
2099
2100             assert(s->repeat_first_field==0);
2101             
2102             vbv_delay= lrintf(90000 * s->rc_context.buffer_index / s->avctx->rc_max_rate);
2103             assert(vbv_delay < 0xFFFF);
2104
2105             s->vbv_delay_ptr[0] &= 0xF8;
2106             s->vbv_delay_ptr[0] |= vbv_delay>>13;
2107             s->vbv_delay_ptr[1]  = vbv_delay>>5;
2108             s->vbv_delay_ptr[2] &= 0x07;
2109             s->vbv_delay_ptr[2] |= vbv_delay<<3;
2110         }
2111         s->total_bits += s->frame_bits;
2112         avctx->frame_bits  = s->frame_bits;
2113     }else{
2114         assert((pbBufPtr(&s->pb) == s->pb.buf));
2115         s->frame_bits=0;
2116     }
2117     assert((s->frame_bits&7)==0);
2118     
2119     return s->frame_bits/8;
2120 }
2121
2122 #endif //CONFIG_ENCODERS
2123
2124 static inline void gmc1_motion(MpegEncContext *s,
2125                                uint8_t *dest_y, uint8_t *dest_cb, uint8_t *dest_cr,
2126                                uint8_t **ref_picture)
2127 {
2128     uint8_t *ptr;
2129     int offset, src_x, src_y, linesize, uvlinesize;
2130     int motion_x, motion_y;
2131     int emu=0;
2132
2133     motion_x= s->sprite_offset[0][0];
2134     motion_y= s->sprite_offset[0][1];
2135     src_x = s->mb_x * 16 + (motion_x >> (s->sprite_warping_accuracy+1));
2136     src_y = s->mb_y * 16 + (motion_y >> (s->sprite_warping_accuracy+1));
2137     motion_x<<=(3-s->sprite_warping_accuracy);
2138     motion_y<<=(3-s->sprite_warping_accuracy);
2139     src_x = clip(src_x, -16, s->width);
2140     if (src_x == s->width)
2141         motion_x =0;
2142     src_y = clip(src_y, -16, s->height);
2143     if (src_y == s->height)
2144         motion_y =0;
2145
2146     linesize = s->linesize;
2147     uvlinesize = s->uvlinesize;
2148     
2149     ptr = ref_picture[0] + (src_y * linesize) + src_x;
2150
2151     if(s->flags&CODEC_FLAG_EMU_EDGE){
2152         if(   (unsigned)src_x >= s->h_edge_pos - 17
2153            || (unsigned)src_y >= s->v_edge_pos - 17){
2154             ff_emulated_edge_mc(s->edge_emu_buffer, ptr, linesize, 17, 17, src_x, src_y, s->h_edge_pos, s->v_edge_pos);
2155             ptr= s->edge_emu_buffer;
2156         }
2157     }
2158     
2159     if((motion_x|motion_y)&7){
2160         s->dsp.gmc1(dest_y  , ptr  , linesize, 16, motion_x&15, motion_y&15, 128 - s->no_rounding);
2161         s->dsp.gmc1(dest_y+8, ptr+8, linesize, 16, motion_x&15, motion_y&15, 128 - s->no_rounding);
2162     }else{
2163         int dxy;
2164         
2165         dxy= ((motion_x>>3)&1) | ((motion_y>>2)&2);
2166         if (s->no_rounding){
2167             s->dsp.put_no_rnd_pixels_tab[0][dxy](dest_y, ptr, linesize, 16);
2168         }else{
2169             s->dsp.put_pixels_tab       [0][dxy](dest_y, ptr, linesize, 16);
2170         }
2171     }
2172     
2173     if(s->flags&CODEC_FLAG_GRAY) return;
2174
2175     motion_x= s->sprite_offset[1][0];
2176     motion_y= s->sprite_offset[1][1];
2177     src_x = s->mb_x * 8 + (motion_x >> (s->sprite_warping_accuracy+1));
2178     src_y = s->mb_y * 8 + (motion_y >> (s->sprite_warping_accuracy+1));
2179     motion_x<<=(3-s->sprite_warping_accuracy);
2180     motion_y<<=(3-s->sprite_warping_accuracy);
2181     src_x = clip(src_x, -8, s->width>>1);
2182     if (src_x == s->width>>1)
2183         motion_x =0;
2184     src_y = clip(src_y, -8, s->height>>1);
2185     if (src_y == s->height>>1)
2186         motion_y =0;
2187
2188     offset = (src_y * uvlinesize) + src_x;
2189     ptr = ref_picture[1] + offset;
2190     if(s->flags&CODEC_FLAG_EMU_EDGE){
2191         if(   (unsigned)src_x >= (s->h_edge_pos>>1) - 9
2192            || (unsigned)src_y >= (s->v_edge_pos>>1) - 9){
2193             ff_emulated_edge_mc(s->edge_emu_buffer, ptr, uvlinesize, 9, 9, src_x, src_y, s->h_edge_pos>>1, s->v_edge_pos>>1);
2194             ptr= s->edge_emu_buffer;
2195             emu=1;
2196         }
2197     }
2198     s->dsp.gmc1(dest_cb, ptr, uvlinesize, 8, motion_x&15, motion_y&15, 128 - s->no_rounding);
2199     
2200     ptr = ref_picture[2] + offset;
2201     if(emu){
2202         ff_emulated_edge_mc(s->edge_emu_buffer, ptr, uvlinesize, 9, 9, src_x, src_y, s->h_edge_pos>>1, s->v_edge_pos>>1);
2203         ptr= s->edge_emu_buffer;
2204     }
2205     s->dsp.gmc1(dest_cr, ptr, uvlinesize, 8, motion_x&15, motion_y&15, 128 - s->no_rounding);
2206     
2207     return;
2208 }
2209
2210 static inline void gmc_motion(MpegEncContext *s,
2211                                uint8_t *dest_y, uint8_t *dest_cb, uint8_t *dest_cr,
2212                                uint8_t **ref_picture)
2213 {
2214     uint8_t *ptr;
2215     int linesize, uvlinesize;
2216     const int a= s->sprite_warping_accuracy;
2217     int ox, oy;
2218
2219     linesize = s->linesize;
2220     uvlinesize = s->uvlinesize;
2221
2222     ptr = ref_picture[0];
2223
2224     ox= s->sprite_offset[0][0] + s->sprite_delta[0][0]*s->mb_x*16 + s->sprite_delta[0][1]*s->mb_y*16;
2225     oy= s->sprite_offset[0][1] + s->sprite_delta[1][0]*s->mb_x*16 + s->sprite_delta[1][1]*s->mb_y*16;
2226
2227     s->dsp.gmc(dest_y, ptr, linesize, 16,
2228            ox, 
2229            oy, 
2230            s->sprite_delta[0][0], s->sprite_delta[0][1],
2231            s->sprite_delta[1][0], s->sprite_delta[1][1], 
2232            a+1, (1<<(2*a+1)) - s->no_rounding,
2233            s->h_edge_pos, s->v_edge_pos);
2234     s->dsp.gmc(dest_y+8, ptr, linesize, 16,
2235            ox + s->sprite_delta[0][0]*8, 
2236            oy + s->sprite_delta[1][0]*8, 
2237            s->sprite_delta[0][0], s->sprite_delta[0][1],
2238            s->sprite_delta[1][0], s->sprite_delta[1][1], 
2239            a+1, (1<<(2*a+1)) - s->no_rounding,
2240            s->h_edge_pos, s->v_edge_pos);
2241
2242     if(s->flags&CODEC_FLAG_GRAY) return;
2243
2244     ox= s->sprite_offset[1][0] + s->sprite_delta[0][0]*s->mb_x*8 + s->sprite_delta[0][1]*s->mb_y*8;
2245     oy= s->sprite_offset[1][1] + s->sprite_delta[1][0]*s->mb_x*8 + s->sprite_delta[1][1]*s->mb_y*8;
2246
2247     ptr = ref_picture[1];
2248     s->dsp.gmc(dest_cb, ptr, uvlinesize, 8,
2249            ox, 
2250            oy, 
2251            s->sprite_delta[0][0], s->sprite_delta[0][1],
2252            s->sprite_delta[1][0], s->sprite_delta[1][1], 
2253            a+1, (1<<(2*a+1)) - s->no_rounding,
2254            s->h_edge_pos>>1, s->v_edge_pos>>1);
2255     
2256     ptr = ref_picture[2];
2257     s->dsp.gmc(dest_cr, ptr, uvlinesize, 8,
2258            ox, 
2259            oy, 
2260            s->sprite_delta[0][0], s->sprite_delta[0][1],
2261            s->sprite_delta[1][0], s->sprite_delta[1][1], 
2262            a+1, (1<<(2*a+1)) - s->no_rounding,
2263            s->h_edge_pos>>1, s->v_edge_pos>>1);
2264 }
2265
2266 /**
2267  * Copies a rectangular area of samples to a temporary buffer and replicates the boarder samples.
2268  * @param buf destination buffer
2269  * @param src source buffer
2270  * @param linesize number of bytes between 2 vertically adjacent samples in both the source and destination buffers
2271  * @param block_w width of block
2272  * @param block_h height of block
2273  * @param src_x x coordinate of the top left sample of the block in the source buffer
2274  * @param src_y y coordinate of the top left sample of the block in the source buffer
2275  * @param w width of the source buffer
2276  * @param h height of the source buffer
2277  */
2278 void ff_emulated_edge_mc(uint8_t *buf, uint8_t *src, int linesize, int block_w, int block_h, 
2279                                     int src_x, int src_y, int w, int h){
2280     int x, y;
2281     int start_y, start_x, end_y, end_x;
2282
2283     if(src_y>= h){
2284         src+= (h-1-src_y)*linesize;
2285         src_y=h-1;
2286     }else if(src_y<=-block_h){
2287         src+= (1-block_h-src_y)*linesize;
2288         src_y=1-block_h;
2289     }
2290     if(src_x>= w){
2291         src+= (w-1-src_x);
2292         src_x=w-1;
2293     }else if(src_x<=-block_w){
2294         src+= (1-block_w-src_x);
2295         src_x=1-block_w;
2296     }
2297
2298     start_y= FFMAX(0, -src_y);
2299     start_x= FFMAX(0, -src_x);
2300     end_y= FFMIN(block_h, h-src_y);
2301     end_x= FFMIN(block_w, w-src_x);
2302
2303     // copy existing part
2304     for(y=start_y; y<end_y; y++){
2305         for(x=start_x; x<end_x; x++){
2306             buf[x + y*linesize]= src[x + y*linesize];
2307         }
2308     }
2309
2310     //top
2311     for(y=0; y<start_y; y++){
2312         for(x=start_x; x<end_x; x++){
2313             buf[x + y*linesize]= buf[x + start_y*linesize];
2314         }
2315     }
2316
2317     //bottom
2318     for(y=end_y; y<block_h; y++){
2319         for(x=start_x; x<end_x; x++){
2320             buf[x + y*linesize]= buf[x + (end_y-1)*linesize];
2321         }
2322     }
2323                                     
2324     for(y=0; y<block_h; y++){
2325        //left
2326         for(x=0; x<start_x; x++){
2327             buf[x + y*linesize]= buf[start_x + y*linesize];
2328         }
2329        
2330        //right
2331         for(x=end_x; x<block_w; x++){
2332             buf[x + y*linesize]= buf[end_x - 1 + y*linesize];
2333         }
2334     }
2335 }
2336
2337 static inline int hpel_motion(MpegEncContext *s, 
2338                                   uint8_t *dest, uint8_t *src,
2339                                   int field_based, int field_select,
2340                                   int src_x, int src_y,
2341                                   int width, int height, int stride,
2342                                   int h_edge_pos, int v_edge_pos,
2343                                   int w, int h, op_pixels_func *pix_op,
2344                                   int motion_x, int motion_y)
2345 {
2346     int dxy;
2347     int emu=0;
2348
2349     dxy = ((motion_y & 1) << 1) | (motion_x & 1);
2350     src_x += motion_x >> 1;
2351     src_y += motion_y >> 1;
2352                 
2353     /* WARNING: do no forget half pels */
2354     src_x = clip(src_x, -16, width); //FIXME unneeded for emu?
2355     if (src_x == width)
2356         dxy &= ~1;
2357     src_y = clip(src_y, -16, height);
2358     if (src_y == height)
2359         dxy &= ~2;
2360     src += src_y * stride + src_x;
2361
2362     if(s->unrestricted_mv && (s->flags&CODEC_FLAG_EMU_EDGE)){
2363         if(   (unsigned)src_x > h_edge_pos - (motion_x&1) - w
2364            || (unsigned)src_y > v_edge_pos - (motion_y&1) - h){
2365             ff_emulated_edge_mc(s->edge_emu_buffer, src, s->linesize, w+1, (h+1)<<field_based,
2366                              src_x, src_y<<field_based, h_edge_pos, s->v_edge_pos);
2367             src= s->edge_emu_buffer;
2368             emu=1;
2369         }
2370     }
2371     if(field_select)
2372         src += s->linesize;
2373     pix_op[dxy](dest, src, stride, h);
2374     return emu;
2375 }
2376
2377 /* apply one mpeg motion vector to the three components */
2378 static inline void mpeg_motion(MpegEncContext *s,
2379                                uint8_t *dest_y, uint8_t *dest_cb, uint8_t *dest_cr,
2380                                int field_based, int bottom_field, int field_select,
2381                                uint8_t **ref_picture, op_pixels_func (*pix_op)[4],
2382                                int motion_x, int motion_y, int h)
2383 {
2384     uint8_t *ptr_y, *ptr_cb, *ptr_cr;
2385     int dxy, uvdxy, mx, my, src_x, src_y, uvsrc_x, uvsrc_y, v_edge_pos, uvlinesize, linesize;
2386     
2387 #if 0    
2388 if(s->quarter_sample)
2389 {
2390     motion_x>>=1;
2391     motion_y>>=1;
2392 }
2393 #endif
2394
2395     v_edge_pos = s->v_edge_pos >> field_based;
2396     linesize   = s->current_picture.linesize[0] << field_based;
2397     uvlinesize = s->current_picture.linesize[1] << field_based;
2398
2399     dxy = ((motion_y & 1) << 1) | (motion_x & 1);
2400     src_x = s->mb_x* 16               + (motion_x >> 1);
2401     src_y = s->mb_y*(16>>field_based) + (motion_y >> 1);
2402
2403     if (s->out_format == FMT_H263) {
2404         uvdxy = dxy | (motion_y & 2) | ((motion_x & 2) >> 1);
2405         uvsrc_x = src_x>>1;
2406         uvsrc_y = src_y>>1;
2407     } else {
2408         mx = motion_x / 2;
2409         my = motion_y / 2;
2410         uvdxy = ((my & 1) << 1) | (mx & 1);
2411         uvsrc_x = s->mb_x* 8               + (mx >> 1);
2412         uvsrc_y = s->mb_y*(8>>field_based) + (my >> 1);
2413     }
2414
2415     ptr_y  = ref_picture[0] + src_y * linesize + src_x;
2416     ptr_cb = ref_picture[1] + uvsrc_y * uvlinesize + uvsrc_x;
2417     ptr_cr = ref_picture[2] + uvsrc_y * uvlinesize + uvsrc_x;
2418
2419     if(   (unsigned)src_x > s->h_edge_pos - (motion_x&1) - 16
2420        || (unsigned)src_y >    v_edge_pos - (motion_y&1) - h){
2421             ff_emulated_edge_mc(s->edge_emu_buffer, ptr_y, s->linesize, 17, 17+field_based,
2422                              src_x, src_y<<field_based, s->h_edge_pos, s->v_edge_pos);
2423             ptr_y = s->edge_emu_buffer;
2424             if(!(s->flags&CODEC_FLAG_GRAY)){
2425                 uint8_t *uvbuf= s->edge_emu_buffer+17*s->linesize;
2426                 ff_emulated_edge_mc(uvbuf  , ptr_cb, s->uvlinesize, 9, 9+field_based, 
2427                                  uvsrc_x, uvsrc_y<<field_based, s->h_edge_pos>>1, s->v_edge_pos>>1);
2428                 ff_emulated_edge_mc(uvbuf+16, ptr_cr, s->uvlinesize, 9, 9+field_based, 
2429                                  uvsrc_x, uvsrc_y<<field_based, s->h_edge_pos>>1, s->v_edge_pos>>1);
2430                 ptr_cb= uvbuf;
2431                 ptr_cr= uvbuf+16;
2432             }
2433     }
2434
2435     if(bottom_field){ //FIXME use this for field pix too instead of the obnoxious hack which changes picture.data
2436         dest_y += s->linesize;
2437         dest_cb+= s->uvlinesize;
2438         dest_cr+= s->uvlinesize;
2439     }
2440
2441     if(field_select){
2442         ptr_y += s->linesize;
2443         ptr_cb+= s->uvlinesize;
2444         ptr_cr+= s->uvlinesize;
2445     }
2446
2447     pix_op[0][dxy](dest_y, ptr_y, linesize, h);
2448     
2449     if(!(s->flags&CODEC_FLAG_GRAY)){
2450         pix_op[1][uvdxy](dest_cb, ptr_cb, uvlinesize, h >> 1);
2451         pix_op[1][uvdxy](dest_cr, ptr_cr, uvlinesize, h >> 1);
2452     }
2453 }
2454 //FIXME move to dsputil, avg variant, 16x16 version
2455 static inline void put_obmc(uint8_t *dst, uint8_t *src[5], int stride){
2456     int x;
2457     uint8_t * const top   = src[1];
2458     uint8_t * const left  = src[2];
2459     uint8_t * const mid   = src[0];
2460     uint8_t * const right = src[3];
2461     uint8_t * const bottom= src[4];
2462 #define OBMC_FILTER(x, t, l, m, r, b)\
2463     dst[x]= (t*top[x] + l*left[x] + m*mid[x] + r*right[x] + b*bottom[x] + 4)>>3
2464 #define OBMC_FILTER4(x, t, l, m, r, b)\
2465     OBMC_FILTER(x         , t, l, m, r, b);\
2466     OBMC_FILTER(x+1       , t, l, m, r, b);\
2467     OBMC_FILTER(x  +stride, t, l, m, r, b);\
2468     OBMC_FILTER(x+1+stride, t, l, m, r, b);
2469     
2470     x=0;
2471     OBMC_FILTER (x  , 2, 2, 4, 0, 0);
2472     OBMC_FILTER (x+1, 2, 1, 5, 0, 0);
2473     OBMC_FILTER4(x+2, 2, 1, 5, 0, 0);
2474     OBMC_FILTER4(x+4, 2, 0, 5, 1, 0);
2475     OBMC_FILTER (x+6, 2, 0, 5, 1, 0);
2476     OBMC_FILTER (x+7, 2, 0, 4, 2, 0);
2477     x+= stride;
2478     OBMC_FILTER (x  , 1, 2, 5, 0, 0);
2479     OBMC_FILTER (x+1, 1, 2, 5, 0, 0);
2480     OBMC_FILTER (x+6, 1, 0, 5, 2, 0);
2481     OBMC_FILTER (x+7, 1, 0, 5, 2, 0);
2482     x+= stride;
2483     OBMC_FILTER4(x  , 1, 2, 5, 0, 0);
2484     OBMC_FILTER4(x+2, 1, 1, 6, 0, 0);
2485     OBMC_FILTER4(x+4, 1, 0, 6, 1, 0);
2486     OBMC_FILTER4(x+6, 1, 0, 5, 2, 0);
2487     x+= 2*stride;
2488     OBMC_FILTER4(x  , 0, 2, 5, 0, 1);
2489     OBMC_FILTER4(x+2, 0, 1, 6, 0, 1);
2490     OBMC_FILTER4(x+4, 0, 0, 6, 1, 1);
2491     OBMC_FILTER4(x+6, 0, 0, 5, 2, 1);
2492     x+= 2*stride;
2493     OBMC_FILTER (x  , 0, 2, 5, 0, 1);
2494     OBMC_FILTER (x+1, 0, 2, 5, 0, 1);
2495     OBMC_FILTER4(x+2, 0, 1, 5, 0, 2);
2496     OBMC_FILTER4(x+4, 0, 0, 5, 1, 2);
2497     OBMC_FILTER (x+6, 0, 0, 5, 2, 1);
2498     OBMC_FILTER (x+7, 0, 0, 5, 2, 1);
2499     x+= stride;
2500     OBMC_FILTER (x  , 0, 2, 4, 0, 2);
2501     OBMC_FILTER (x+1, 0, 1, 5, 0, 2);
2502     OBMC_FILTER (x+6, 0, 0, 5, 1, 2);
2503     OBMC_FILTER (x+7, 0, 0, 4, 2, 2);
2504 }
2505
2506 /* obmc for 1 8x8 luma block */
2507 static inline void obmc_motion(MpegEncContext *s,
2508                                uint8_t *dest, uint8_t *src,
2509                                int src_x, int src_y,
2510                                op_pixels_func *pix_op,
2511                                int16_t mv[5][2]/* mid top left right bottom*/)
2512 #define MID    0
2513 {
2514     int i;
2515     uint8_t *ptr[5];
2516     
2517     assert(s->quarter_sample==0);
2518     
2519     for(i=0; i<5; i++){
2520         if(i && mv[i][0]==mv[MID][0] && mv[i][1]==mv[MID][1]){
2521             ptr[i]= ptr[MID];
2522         }else{
2523             ptr[i]= s->obmc_scratchpad + 8*(i&1) + s->linesize*8*(i>>1);
2524             hpel_motion(s, ptr[i], src, 0, 0,
2525                         src_x, src_y,
2526                         s->width, s->height, s->linesize,
2527                         s->h_edge_pos, s->v_edge_pos,
2528                         8, 8, pix_op,
2529                         mv[i][0], mv[i][1]);
2530         }
2531     }
2532
2533     put_obmc(dest, ptr, s->linesize);                
2534 }
2535
2536 static inline void qpel_motion(MpegEncContext *s,
2537                                uint8_t *dest_y, uint8_t *dest_cb, uint8_t *dest_cr,
2538                                int field_based, int bottom_field, int field_select,
2539                                uint8_t **ref_picture, op_pixels_func (*pix_op)[4],
2540                                qpel_mc_func (*qpix_op)[16],
2541                                int motion_x, int motion_y, int h)
2542 {
2543     uint8_t *ptr_y, *ptr_cb, *ptr_cr;
2544     int dxy, uvdxy, mx, my, src_x, src_y, uvsrc_x, uvsrc_y, v_edge_pos, linesize, uvlinesize;
2545
2546     dxy = ((motion_y & 3) << 2) | (motion_x & 3);
2547     src_x = s->mb_x *  16                 + (motion_x >> 2);
2548     src_y = s->mb_y * (16 >> field_based) + (motion_y >> 2);
2549
2550     v_edge_pos = s->v_edge_pos >> field_based;
2551     linesize = s->linesize << field_based;
2552     uvlinesize = s->uvlinesize << field_based;
2553     
2554     if(field_based){
2555         mx= motion_x/2;
2556         my= motion_y>>1;
2557     }else if(s->workaround_bugs&FF_BUG_QPEL_CHROMA2){
2558         static const int rtab[8]= {0,0,1,1,0,0,0,1};
2559         mx= (motion_x>>1) + rtab[motion_x&7];
2560         my= (motion_y>>1) + rtab[motion_y&7];
2561     }else if(s->workaround_bugs&FF_BUG_QPEL_CHROMA){
2562         mx= (motion_x>>1)|(motion_x&1);
2563         my= (motion_y>>1)|(motion_y&1);
2564     }else{
2565         mx= motion_x/2;
2566         my= motion_y/2;
2567     }
2568     mx= (mx>>1)|(mx&1);
2569     my= (my>>1)|(my&1);
2570
2571     uvdxy= (mx&1) | ((my&1)<<1);
2572     mx>>=1;
2573     my>>=1;
2574
2575     uvsrc_x = s->mb_x *  8                 + mx;
2576     uvsrc_y = s->mb_y * (8 >> field_based) + my;
2577
2578     ptr_y  = ref_picture[0] +   src_y *   linesize +   src_x;
2579     ptr_cb = ref_picture[1] + uvsrc_y * uvlinesize + uvsrc_x;
2580     ptr_cr = ref_picture[2] + uvsrc_y * uvlinesize + uvsrc_x;
2581
2582     if(   (unsigned)src_x > s->h_edge_pos - (motion_x&3) - 16 
2583        || (unsigned)src_y >    v_edge_pos - (motion_y&3) - h  ){
2584         ff_emulated_edge_mc(s->edge_emu_buffer, ptr_y, s->linesize, 17, 17+field_based, 
2585                          src_x, src_y<<field_based, s->h_edge_pos, s->v_edge_pos);
2586         ptr_y= s->edge_emu_buffer;
2587         if(!(s->flags&CODEC_FLAG_GRAY)){
2588             uint8_t *uvbuf= s->edge_emu_buffer + 17*s->linesize;
2589             ff_emulated_edge_mc(uvbuf, ptr_cb, s->uvlinesize, 9, 9 + field_based, 
2590                              uvsrc_x, uvsrc_y<<field_based, s->h_edge_pos>>1, s->v_edge_pos>>1);
2591             ff_emulated_edge_mc(uvbuf + 16, ptr_cr, s->uvlinesize, 9, 9 + field_based, 
2592                              uvsrc_x, uvsrc_y<<field_based, s->h_edge_pos>>1, s->v_edge_pos>>1);
2593             ptr_cb= uvbuf;
2594             ptr_cr= uvbuf + 16;
2595         }
2596     }
2597
2598     if(!field_based)
2599         qpix_op[0][dxy](dest_y, ptr_y, linesize);
2600     else{
2601         if(bottom_field){
2602             dest_y += s->linesize;
2603             dest_cb+= s->uvlinesize;
2604             dest_cr+= s->uvlinesize;
2605         }
2606
2607         if(field_select){
2608             ptr_y  += s->linesize;
2609             ptr_cb += s->uvlinesize;
2610             ptr_cr += s->uvlinesize;
2611         }
2612         //damn interlaced mode
2613         //FIXME boundary mirroring is not exactly correct here
2614         qpix_op[1][dxy](dest_y  , ptr_y  , linesize);
2615         qpix_op[1][dxy](dest_y+8, ptr_y+8, linesize);
2616     }
2617     if(!(s->flags&CODEC_FLAG_GRAY)){
2618         pix_op[1][uvdxy](dest_cr, ptr_cr, uvlinesize, h >> 1);
2619         pix_op[1][uvdxy](dest_cb, ptr_cb, uvlinesize, h >> 1);
2620     }
2621 }
2622
2623 inline int ff_h263_round_chroma(int x){
2624     if (x >= 0)
2625         return  (h263_chroma_roundtab[x & 0xf] + ((x >> 3) & ~1));
2626     else {
2627         x = -x;
2628         return -(h263_chroma_roundtab[x & 0xf] + ((x >> 3) & ~1));
2629     }
2630 }
2631
2632 /**
2633  * h263 chorma 4mv motion compensation.
2634  */
2635 static inline void chroma_4mv_motion(MpegEncContext *s,
2636                                      uint8_t *dest_cb, uint8_t *dest_cr,
2637                                      uint8_t **ref_picture,
2638                                      op_pixels_func *pix_op,
2639                                      int mx, int my){
2640     int dxy, emu=0, src_x, src_y, offset;
2641     uint8_t *ptr;
2642     
2643     /* In case of 8X8, we construct a single chroma motion vector
2644        with a special rounding */
2645     mx= ff_h263_round_chroma(mx);
2646     my= ff_h263_round_chroma(my);
2647     
2648     dxy = ((my & 1) << 1) | (mx & 1);
2649     mx >>= 1;
2650     my >>= 1;
2651
2652     src_x = s->mb_x * 8 + mx;
2653     src_y = s->mb_y * 8 + my;
2654     src_x = clip(src_x, -8, s->width/2);
2655     if (src_x == s->width/2)
2656         dxy &= ~1;
2657     src_y = clip(src_y, -8, s->height/2);
2658     if (src_y == s->height/2)
2659         dxy &= ~2;
2660     
2661     offset = (src_y * (s->uvlinesize)) + src_x;
2662     ptr = ref_picture[1] + offset;
2663     if(s->flags&CODEC_FLAG_EMU_EDGE){
2664         if(   (unsigned)src_x > (s->h_edge_pos>>1) - (dxy &1) - 8
2665            || (unsigned)src_y > (s->v_edge_pos>>1) - (dxy>>1) - 8){
2666             ff_emulated_edge_mc(s->edge_emu_buffer, ptr, s->uvlinesize, 9, 9, src_x, src_y, s->h_edge_pos>>1, s->v_edge_pos>>1);
2667             ptr= s->edge_emu_buffer;
2668             emu=1;
2669         }
2670     }
2671     pix_op[dxy](dest_cb, ptr, s->uvlinesize, 8);
2672
2673     ptr = ref_picture[2] + offset;
2674     if(emu){
2675         ff_emulated_edge_mc(s->edge_emu_buffer, ptr, s->uvlinesize, 9, 9, src_x, src_y, s->h_edge_pos>>1, s->v_edge_pos>>1);
2676         ptr= s->edge_emu_buffer;
2677     }
2678     pix_op[dxy](dest_cr, ptr, s->uvlinesize, 8);
2679 }
2680
2681 /**
2682  * motion compesation of a single macroblock
2683  * @param s context
2684  * @param dest_y luma destination pointer
2685  * @param dest_cb chroma cb/u destination pointer
2686  * @param dest_cr chroma cr/v destination pointer
2687  * @param dir direction (0->forward, 1->backward)
2688  * @param ref_picture array[3] of pointers to the 3 planes of the reference picture
2689  * @param pic_op halfpel motion compensation function (average or put normally)
2690  * @param pic_op qpel motion compensation function (average or put normally)
2691  * the motion vectors are taken from s->mv and the MV type from s->mv_type
2692  */
2693 static inline void MPV_motion(MpegEncContext *s, 
2694                               uint8_t *dest_y, uint8_t *dest_cb, uint8_t *dest_cr,
2695                               int dir, uint8_t **ref_picture, 
2696                               op_pixels_func (*pix_op)[4], qpel_mc_func (*qpix_op)[16])
2697 {
2698     int dxy, mx, my, src_x, src_y, motion_x, motion_y;
2699     int mb_x, mb_y, i;
2700     uint8_t *ptr, *dest;
2701
2702     mb_x = s->mb_x;
2703     mb_y = s->mb_y;
2704
2705     if(s->obmc && s->pict_type != B_TYPE){
2706         int16_t mv_cache[4][4][2];
2707         const int xy= s->mb_x + s->mb_y*s->mb_stride;
2708         const int mot_stride= s->mb_width*2 + 2;
2709         const int mot_xy= 1 + mb_x*2 + (mb_y*2 + 1)*mot_stride;
2710
2711         assert(!s->mb_skiped);
2712                 
2713         memcpy(mv_cache[1][1], s->current_picture.motion_val[0][mot_xy           ], sizeof(int16_t)*4);
2714         memcpy(mv_cache[2][1], s->current_picture.motion_val[0][mot_xy+mot_stride], sizeof(int16_t)*4);
2715         memcpy(mv_cache[3][1], s->current_picture.motion_val[0][mot_xy+mot_stride], sizeof(int16_t)*4);
2716
2717         if(mb_y==0 || IS_INTRA(s->current_picture.mb_type[xy-s->mb_stride])){
2718             memcpy(mv_cache[0][1], mv_cache[1][1], sizeof(int16_t)*4);
2719         }else{
2720             memcpy(mv_cache[0][1], s->current_picture.motion_val[0][mot_xy-mot_stride], sizeof(int16_t)*4);
2721         }
2722
2723         if(mb_x==0 || IS_INTRA(s->current_picture.mb_type[xy-1])){
2724             *(int32_t*)mv_cache[1][0]= *(int32_t*)mv_cache[1][1];
2725             *(int32_t*)mv_cache[2][0]= *(int32_t*)mv_cache[2][1];
2726         }else{
2727             *(int32_t*)mv_cache[1][0]= *(int32_t*)s->current_picture.motion_val[0][mot_xy-1];
2728             *(int32_t*)mv_cache[2][0]= *(int32_t*)s->current_picture.motion_val[0][mot_xy-1+mot_stride];
2729         }
2730
2731         if(mb_x+1>=s->mb_width || IS_INTRA(s->current_picture.mb_type[xy+1])){
2732             *(int32_t*)mv_cache[1][3]= *(int32_t*)mv_cache[1][2];
2733             *(int32_t*)mv_cache[2][3]= *(int32_t*)mv_cache[2][2];
2734         }else{
2735             *(int32_t*)mv_cache[1][3]= *(int32_t*)s->current_picture.motion_val[0][mot_xy+2];
2736             *(int32_t*)mv_cache[2][3]= *(int32_t*)s->current_picture.motion_val[0][mot_xy+2+mot_stride];
2737         }
2738         
2739         mx = 0;
2740         my = 0;
2741         for(i=0;i<4;i++) {
2742             const int x= (i&1)+1;
2743             const int y= (i>>1)+1;
2744             int16_t mv[5][2]= {
2745                 {mv_cache[y][x  ][0], mv_cache[y][x  ][1]},
2746                 {mv_cache[y-1][x][0], mv_cache[y-1][x][1]},
2747                 {mv_cache[y][x-1][0], mv_cache[y][x-1][1]},
2748                 {mv_cache[y][x+1][0], mv_cache[y][x+1][1]},
2749                 {mv_cache[y+1][x][0], mv_cache[y+1][x][1]}};
2750             //FIXME cleanup
2751             obmc_motion(s, dest_y + ((i & 1) * 8) + (i >> 1) * 8 * s->linesize,
2752                         ref_picture[0],
2753                         mb_x * 16 + (i & 1) * 8, mb_y * 16 + (i >>1) * 8,
2754                         pix_op[1],
2755                         mv);
2756
2757             mx += mv[0][0];
2758             my += mv[0][1];
2759         }
2760         if(!(s->flags&CODEC_FLAG_GRAY))
2761             chroma_4mv_motion(s, dest_cb, dest_cr, ref_picture, pix_op[1], mx, my);
2762
2763         return;
2764     }
2765    
2766     switch(s->mv_type) {
2767     case MV_TYPE_16X16:
2768 #ifdef CONFIG_RISKY
2769         if(s->mcsel){
2770             if(s->real_sprite_warping_points==1){
2771                 gmc1_motion(s, dest_y, dest_cb, dest_cr,
2772                             ref_picture);
2773             }else{
2774                 gmc_motion(s, dest_y, dest_cb, dest_cr,
2775                             ref_picture);
2776             }
2777         }else if(s->quarter_sample){
2778             qpel_motion(s, dest_y, dest_cb, dest_cr, 
2779                         0, 0, 0,
2780                         ref_picture, pix_op, qpix_op,
2781                         s->mv[dir][0][0], s->mv[dir][0][1], 16);
2782         }else if(s->mspel){
2783             ff_mspel_motion(s, dest_y, dest_cb, dest_cr,
2784                         ref_picture, pix_op,
2785                         s->mv[dir][0][0], s->mv[dir][0][1], 16);
2786         }else
2787 #endif
2788         {
2789             mpeg_motion(s, dest_y, dest_cb, dest_cr, 
2790                         0, 0, 0,
2791                         ref_picture, pix_op,
2792                         s->mv[dir][0][0], s->mv[dir][0][1], 16);
2793         }           
2794         break;
2795     case MV_TYPE_8X8:
2796         mx = 0;
2797         my = 0;
2798         if(s->quarter_sample){
2799             for(i=0;i<4;i++) {
2800                 motion_x = s->mv[dir][i][0];
2801                 motion_y = s->mv[dir][i][1];
2802
2803                 dxy = ((motion_y & 3) << 2) | (motion_x & 3);
2804                 src_x = mb_x * 16 + (motion_x >> 2) + (i & 1) * 8;
2805                 src_y = mb_y * 16 + (motion_y >> 2) + (i >>1) * 8;
2806                     
2807                 /* WARNING: do no forget half pels */
2808                 src_x = clip(src_x, -16, s->width);
2809                 if (src_x == s->width)
2810                     dxy &= ~3;
2811                 src_y = clip(src_y, -16, s->height);
2812                 if (src_y == s->height)
2813                     dxy &= ~12;
2814                     
2815                 ptr = ref_picture[0] + (src_y * s->linesize) + (src_x);
2816                 if(s->flags&CODEC_FLAG_EMU_EDGE){
2817                     if(   (unsigned)src_x > s->h_edge_pos - (motion_x&3) - 8 
2818                        || (unsigned)src_y > s->v_edge_pos - (motion_y&3) - 8 ){
2819                         ff_emulated_edge_mc(s->edge_emu_buffer, ptr, s->linesize, 9, 9, src_x, src_y, s->h_edge_pos, s->v_edge_pos);
2820                         ptr= s->edge_emu_buffer;
2821                     }
2822                 }
2823                 dest = dest_y + ((i & 1) * 8) + (i >> 1) * 8 * s->linesize;
2824                 qpix_op[1][dxy](dest, ptr, s->linesize);
2825
2826                 mx += s->mv[dir][i][0]/2;
2827                 my += s->mv[dir][i][1]/2;
2828             }
2829         }else{
2830             for(i=0;i<4;i++) {
2831                 hpel_motion(s, dest_y + ((i & 1) * 8) + (i >> 1) * 8 * s->linesize,
2832                             ref_picture[0], 0, 0,
2833                             mb_x * 16 + (i & 1) * 8, mb_y * 16 + (i >>1) * 8,
2834                             s->width, s->height, s->linesize,
2835                             s->h_edge_pos, s->v_edge_pos,
2836                             8, 8, pix_op[1],
2837                             s->mv[dir][i][0], s->mv[dir][i][1]);
2838
2839                 mx += s->mv[dir][i][0];
2840                 my += s->mv[dir][i][1];
2841             }
2842         }
2843
2844         if(!(s->flags&CODEC_FLAG_GRAY))
2845             chroma_4mv_motion(s, dest_cb, dest_cr, ref_picture, pix_op[1], mx, my);
2846         break;
2847     case MV_TYPE_FIELD:
2848         if (s->picture_structure == PICT_FRAME) {
2849             if(s->quarter_sample){
2850                 for(i=0; i<2; i++){
2851                     qpel_motion(s, dest_y, dest_cb, dest_cr,
2852                                 1, i, s->field_select[dir][i],
2853                                 ref_picture, pix_op, qpix_op,
2854                                 s->mv[dir][i][0], s->mv[dir][i][1], 8);
2855                 }
2856             }else{
2857                 /* top field */       
2858                 mpeg_motion(s, dest_y, dest_cb, dest_cr,
2859                             1, 0, s->field_select[dir][0],
2860                             ref_picture, pix_op,
2861                             s->mv[dir][0][0], s->mv[dir][0][1], 8);
2862                 /* bottom field */
2863                 mpeg_motion(s, dest_y, dest_cb, dest_cr,
2864                             1, 1, s->field_select[dir][1],
2865                             ref_picture, pix_op,
2866                             s->mv[dir][1][0], s->mv[dir][1][1], 8);
2867             }
2868         } else {
2869             if(s->picture_structure != s->field_select[dir][0] + 1 && s->pict_type != B_TYPE && !s->first_field){
2870                 ref_picture= s->current_picture_ptr->data;
2871             } 
2872
2873             mpeg_motion(s, dest_y, dest_cb, dest_cr,
2874                         0, 0, s->field_select[dir][0],
2875                         ref_picture, pix_op,
2876                         s->mv[dir][0][0], s->mv[dir][0][1], 16);
2877         }
2878         break;
2879     case MV_TYPE_16X8:
2880         for(i=0; i<2; i++){
2881             uint8_t ** ref2picture;
2882
2883             if(s->picture_structure == s->field_select[dir][i] + 1 || s->pict_type == B_TYPE || s->first_field){
2884                 ref2picture= ref_picture;
2885             }else{
2886                 ref2picture= s->current_picture_ptr->data;
2887             } 
2888
2889             mpeg_motion(s, dest_y, dest_cb, dest_cr, 
2890                         0, 0, s->field_select[dir][i],
2891                         ref2picture, pix_op,
2892                         s->mv[dir][i][0], s->mv[dir][i][1] + 16*i, 8);
2893                 
2894             dest_y += 16*s->linesize;
2895             dest_cb+=  8*s->uvlinesize;
2896             dest_cr+=  8*s->uvlinesize;
2897         }        
2898         break;
2899     case MV_TYPE_DMV:
2900         if(s->picture_structure == PICT_FRAME){
2901             for(i=0; i<2; i++){
2902                 int j;
2903                 for(j=0; j<2; j++){
2904                     mpeg_motion(s, dest_y, dest_cb, dest_cr,
2905                                 1, j, j^i,
2906                                 ref_picture, pix_op,
2907                                 s->mv[dir][2*i + j][0], s->mv[dir][2*i + j][1], 8);
2908                 }
2909                 pix_op = s->dsp.avg_pixels_tab; 
2910             }
2911         }else{
2912             for(i=0; i<2; i++){
2913                 mpeg_motion(s, dest_y, dest_cb, dest_cr, 
2914                             0, 0, s->picture_structure != i+1,
2915                             ref_picture, pix_op,
2916                             s->mv[dir][2*i][0],s->mv[dir][2*i][1],16);
2917
2918                 // after put we make avg of the same block
2919                 pix_op=s->dsp.avg_pixels_tab; 
2920
2921                 //opposite parity is always in the same frame if this is second field
2922                 if(!s->first_field){
2923                     ref_picture = s->current_picture_ptr->data;    
2924                 }
2925             }
2926         }
2927     break;
2928     default: assert(0);
2929     }
2930 }
2931
2932
2933 /* put block[] to dest[] */
2934 static inline void put_dct(MpegEncContext *s, 
2935                            DCTELEM *block, int i, uint8_t *dest, int line_size, int qscale)
2936 {
2937     s->dct_unquantize_intra(s, block, i, qscale);
2938     s->dsp.idct_put (dest, line_size, block);
2939 }
2940
2941 /* add block[] to dest[] */
2942 static inline void add_dct(MpegEncContext *s, 
2943                            DCTELEM *block, int i, uint8_t *dest, int line_size)
2944 {
2945     if (s->block_last_index[i] >= 0) {
2946         s->dsp.idct_add (dest, line_size, block);
2947     }
2948 }
2949
2950 static inline void add_dequant_dct(MpegEncContext *s, 
2951                            DCTELEM *block, int i, uint8_t *dest, int line_size, int qscale)
2952 {
2953     if (s->block_last_index[i] >= 0) {
2954         s->dct_unquantize_inter(s, block, i, qscale);
2955
2956         s->dsp.idct_add (dest, line_size, block);
2957     }
2958 }
2959
2960 /**
2961  * cleans dc, ac, coded_block for the current non intra MB
2962  */
2963 void ff_clean_intra_table_entries(MpegEncContext *s)
2964 {
2965     int wrap = s->block_wrap[0];
2966     int xy = s->block_index[0];
2967     
2968     s->dc_val[0][xy           ] = 
2969     s->dc_val[0][xy + 1       ] = 
2970     s->dc_val[0][xy     + wrap] =
2971     s->dc_val[0][xy + 1 + wrap] = 1024;
2972     /* ac pred */
2973     memset(s->ac_val[0][xy       ], 0, 32 * sizeof(int16_t));
2974     memset(s->ac_val[0][xy + wrap], 0, 32 * sizeof(int16_t));
2975     if (s->msmpeg4_version>=3) {
2976         s->coded_block[xy           ] =
2977         s->coded_block[xy + 1       ] =
2978         s->coded_block[xy     + wrap] =
2979         s->coded_block[xy + 1 + wrap] = 0;
2980     }
2981     /* chroma */
2982     wrap = s->block_wrap[4];
2983     xy = s->mb_x + 1 + (s->mb_y + 1) * wrap;
2984     s->dc_val[1][xy] =
2985     s->dc_val[2][xy] = 1024;
2986     /* ac pred */
2987     memset(s->ac_val[1][xy], 0, 16 * sizeof(int16_t));
2988     memset(s->ac_val[2][xy], 0, 16 * sizeof(int16_t));
2989     
2990     s->mbintra_table[s->mb_x + s->mb_y*s->mb_stride]= 0;
2991 }
2992
2993 /* generic function called after a macroblock has been parsed by the
2994    decoder or after it has been encoded by the encoder.
2995
2996    Important variables used:
2997    s->mb_intra : true if intra macroblock
2998    s->mv_dir   : motion vector direction
2999    s->mv_type  : motion vector type
3000    s->mv       : motion vector
3001    s->interlaced_dct : true if interlaced dct used (mpeg2)
3002  */
3003 void MPV_decode_mb(MpegEncContext *s, DCTELEM block[6][64])
3004 {
3005     int mb_x, mb_y;
3006     const int mb_xy = s->mb_y * s->mb_stride + s->mb_x;
3007 #ifdef HAVE_XVMC
3008     if(s->avctx->xvmc_acceleration){
3009         XVMC_decode_mb(s);//xvmc uses pblocks
3010         return;
3011     }
3012 #endif
3013
3014     mb_x = s->mb_x;
3015     mb_y = s->mb_y;
3016
3017     if(s->avctx->debug&FF_DEBUG_DCT_COEFF) {
3018        /* save DCT coefficients */
3019        int i,j;
3020        DCTELEM *dct = &s->current_picture.dct_coeff[mb_xy*64*6];
3021        for(i=0; i<6; i++)
3022            for(j=0; j<64; j++)
3023                *dct++ = block[i][s->dsp.idct_permutation[j]];
3024     }
3025
3026     s->current_picture.qscale_table[mb_xy]= s->qscale;
3027
3028     /* update DC predictors for P macroblocks */
3029     if (!s->mb_intra) {
3030         if (s->h263_pred || s->h263_aic) {
3031             if(s->mbintra_table[mb_xy])
3032                 ff_clean_intra_table_entries(s);
3033         } else {
3034             s->last_dc[0] =
3035             s->last_dc[1] =
3036             s->last_dc[2] = 128 << s->intra_dc_precision;
3037         }
3038     }
3039     else if (s->h263_pred || s->h263_aic)
3040         s->mbintra_table[mb_xy]=1;
3041
3042     if ((s->flags&CODEC_FLAG_PSNR) || !(s->encoding && (s->intra_only || s->pict_type==B_TYPE))) { //FIXME precalc
3043         uint8_t *dest_y, *dest_cb, *dest_cr;
3044         int dct_linesize, dct_offset;
3045         op_pixels_func (*op_pix)[4];
3046         qpel_mc_func (*op_qpix)[16];
3047         const int linesize= s->current_picture.linesize[0]; //not s->linesize as this woulnd be wrong for field pics
3048         const int uvlinesize= s->current_picture.linesize[1];
3049         const int readable= s->pict_type != B_TYPE || s->encoding || s->avctx->draw_horiz_band;
3050
3051         /* avoid copy if macroblock skipped in last frame too */
3052         /* skip only during decoding as we might trash the buffers during encoding a bit */
3053         if(!s->encoding){
3054             uint8_t *mbskip_ptr = &s->mbskip_table[mb_xy];
3055             const int age= s->current_picture.age;
3056
3057             assert(age);
3058
3059             if (s->mb_skiped) {
3060                 s->mb_skiped= 0;
3061                 assert(s->pict_type!=I_TYPE);
3062  
3063                 (*mbskip_ptr) ++; /* indicate that this time we skiped it */
3064                 if(*mbskip_ptr >99) *mbskip_ptr= 99;
3065
3066                 /* if previous was skipped too, then nothing to do !  */
3067                 if (*mbskip_ptr >= age && s->current_picture.reference){
3068                     return;
3069                 }
3070             } else if(!s->current_picture.reference){
3071                 (*mbskip_ptr) ++; /* increase counter so the age can be compared cleanly */
3072                 if(*mbskip_ptr >99) *mbskip_ptr= 99;
3073             } else{
3074                 *mbskip_ptr = 0; /* not skipped */
3075             }
3076         }
3077
3078         if (s->interlaced_dct) {
3079             dct_linesize = linesize * 2;
3080             dct_offset = linesize;
3081         } else {
3082             dct_linesize = linesize;
3083             dct_offset = linesize * 8;
3084         }
3085         if(readable){
3086             dest_y=  s->dest[0];
3087             dest_cb= s->dest[1];
3088             dest_cr= s->dest[2];
3089         }else{
3090             dest_y = s->b_scratchpad;
3091             dest_cb= s->b_scratchpad+16*linesize;
3092             dest_cr= s->b_scratchpad+16*linesize+8;
3093         }
3094         if (!s->mb_intra) {
3095             /* motion handling */
3096             /* decoding or more than one mb_type (MC was allready done otherwise) */
3097             if(!s->encoding){
3098                 if ((!s->no_rounding) || s->pict_type==B_TYPE){                
3099                     op_pix = s->dsp.put_pixels_tab;
3100                     op_qpix= s->dsp.put_qpel_pixels_tab;
3101                 }else{
3102                     op_pix = s->dsp.put_no_rnd_pixels_tab;
3103                     op_qpix= s->dsp.put_no_rnd_qpel_pixels_tab;
3104                 }
3105
3106                 if (s->mv_dir & MV_DIR_FORWARD) {
3107                     MPV_motion(s, dest_y, dest_cb, dest_cr, 0, s->last_picture.data, op_pix, op_qpix);
3108                     op_pix = s->dsp.avg_pixels_tab;
3109                     op_qpix= s->dsp.avg_qpel_pixels_tab;
3110                 }
3111                 if (s->mv_dir & MV_DIR_BACKWARD) {
3112                     MPV_motion(s, dest_y, dest_cb, dest_cr, 1, s->next_picture.data, op_pix, op_qpix);
3113                 }
3114             }
3115
3116             /* skip dequant / idct if we are really late ;) */
3117             if(s->hurry_up>1) return;
3118
3119             /* add dct residue */
3120             if(s->encoding || !(   s->h263_msmpeg4 || s->codec_id==CODEC_ID_MPEG1VIDEO || s->codec_id==CODEC_ID_MPEG2VIDEO
3121                                 || (s->codec_id==CODEC_ID_MPEG4 && !s->mpeg_quant))){
3122                 add_dequant_dct(s, block[0], 0, dest_y, dct_linesize, s->qscale);
3123                 add_dequant_dct(s, block[1], 1, dest_y + 8, dct_linesize, s->qscale);
3124                 add_dequant_dct(s, block[2], 2, dest_y + dct_offset, dct_linesize, s->qscale);
3125                 add_dequant_dct(s, block[3], 3, dest_y + dct_offset + 8, dct_linesize, s->qscale);
3126
3127                 if(!(s->flags&CODEC_FLAG_GRAY)){
3128                     add_dequant_dct(s, block[4], 4, dest_cb, uvlinesize, s->chroma_qscale);
3129                     add_dequant_dct(s, block[5], 5, dest_cr, uvlinesize, s->chroma_qscale);
3130                 }
3131             } else if(s->codec_id != CODEC_ID_WMV2){
3132                 add_dct(s, block[0], 0, dest_y, dct_linesize);
3133                 add_dct(s, block[1], 1, dest_y + 8, dct_linesize);
3134                 add_dct(s, block[2], 2, dest_y + dct_offset, dct_linesize);
3135                 add_dct(s, block[3], 3, dest_y + dct_offset + 8, dct_linesize);
3136
3137                 if(!(s->flags&CODEC_FLAG_GRAY)){
3138                     add_dct(s, block[4], 4, dest_cb, uvlinesize);
3139                     add_dct(s, block[5], 5, dest_cr, uvlinesize);
3140                 }
3141             } 
3142 #ifdef CONFIG_RISKY
3143             else{
3144                 ff_wmv2_add_mb(s, block, dest_y, dest_cb, dest_cr);
3145             }
3146 #endif
3147         } else {
3148             /* dct only in intra block */
3149             if(s->encoding || !(s->codec_id==CODEC_ID_MPEG1VIDEO || s->codec_id==CODEC_ID_MPEG2VIDEO)){
3150                 put_dct(s, block[0], 0, dest_y, dct_linesize, s->qscale);
3151                 put_dct(s, block[1], 1, dest_y + 8, dct_linesize, s->qscale);
3152                 put_dct(s, block[2], 2, dest_y + dct_offset, dct_linesize, s->qscale);
3153                 put_dct(s, block[3], 3, dest_y + dct_offset + 8, dct_linesize, s->qscale);
3154
3155                 if(!(s->flags&CODEC_FLAG_GRAY)){
3156                     put_dct(s, block[4], 4, dest_cb, uvlinesize, s->chroma_qscale);
3157                     put_dct(s, block[5], 5, dest_cr, uvlinesize, s->chroma_qscale);
3158                 }
3159             }else{
3160                 s->dsp.idct_put(dest_y                 , dct_linesize, block[0]);
3161                 s->dsp.idct_put(dest_y              + 8, dct_linesize, block[1]);
3162                 s->dsp.idct_put(dest_y + dct_offset    , dct_linesize, block[2]);
3163                 s->dsp.idct_put(dest_y + dct_offset + 8, dct_linesize, block[3]);
3164
3165                 if(!(s->flags&CODEC_FLAG_GRAY)){
3166                     s->dsp.idct_put(dest_cb, uvlinesize, block[4]);
3167                     s->dsp.idct_put(dest_cr, uvlinesize, block[5]);
3168                 }
3169             }
3170         }
3171         if(!readable){
3172             s->dsp.put_pixels_tab[0][0](s->dest[0], dest_y ,   linesize,16);
3173             s->dsp.put_pixels_tab[1][0](s->dest[1], dest_cb, uvlinesize, 8);
3174             s->dsp.put_pixels_tab[1][0](s->dest[2], dest_cr, uvlinesize, 8);
3175         }
3176     }
3177 }
3178
3179 #ifdef CONFIG_ENCODERS
3180
3181 static inline void dct_single_coeff_elimination(MpegEncContext *s, int n, int threshold)
3182 {
3183     static const char tab[64]=
3184         {3,2,2,1,1,1,1,1,
3185          1,1,1,1,1,1,1,1,
3186          1,1,1,1,1,1,1,1,
3187          0,0,0,0,0,0,0,0,
3188          0,0,0,0,0,0,0,0,
3189          0,0,0,0,0,0,0,0,
3190          0,0,0,0,0,0,0,0,
3191          0,0,0,0,0,0,0,0};
3192     int score=0;
3193     int run=0;
3194     int i;
3195     DCTELEM *block= s->block[n];
3196     const int last_index= s->block_last_index[n];
3197     int skip_dc;
3198
3199     if(threshold<0){
3200         skip_dc=0;
3201         threshold= -threshold;
3202     }else
3203         skip_dc=1;
3204
3205     /* are all which we could set to zero are allready zero? */
3206     if(last_index<=skip_dc - 1) return;
3207
3208     for(i=0; i<=last_index; i++){
3209         const int j = s->intra_scantable.permutated[i];
3210         const int level = ABS(block[j]);
3211         if(level==1){
3212             if(skip_dc && i==0) continue;
3213             score+= tab[run];
3214             run=0;
3215         }else if(level>1){
3216             return;
3217         }else{
3218             run++;
3219         }
3220     }
3221     if(score >= threshold) return;
3222     for(i=skip_dc; i<=last_index; i++){
3223         const int j = s->intra_scantable.permutated[i];
3224         block[j]=0;
3225     }
3226     if(block[0]) s->block_last_index[n]= 0;
3227     else         s->block_last_index[n]= -1;
3228 }
3229
3230 static inline void clip_coeffs(MpegEncContext *s, DCTELEM *block, int last_index)
3231 {
3232     int i;
3233     const int maxlevel= s->max_qcoeff;
3234     const int minlevel= s->min_qcoeff;
3235     int overflow=0;
3236     
3237     if(s->mb_intra){
3238         i=1; //skip clipping of intra dc
3239     }else
3240         i=0;
3241     
3242     for(;i<=last_index; i++){
3243         const int j= s->intra_scantable.permutated[i];
3244         int level = block[j];
3245        
3246         if     (level>maxlevel){
3247             level=maxlevel;
3248             overflow++;
3249         }else if(level<minlevel){
3250             level=minlevel;
3251             overflow++;
3252         }
3253         
3254         block[j]= level;
3255     }
3256     
3257     if(overflow && s->avctx->mb_decision == FF_MB_DECISION_SIMPLE)
3258         av_log(s->avctx, AV_LOG_INFO, "warning, cliping %d dct coefficents to %d..%d\n", overflow, minlevel, maxlevel);
3259 }
3260
3261 #endif //CONFIG_ENCODERS
3262
3263 /**
3264  *
3265  * @param h is the normal height, this will be reduced automatically if needed for the last row
3266  */
3267 void ff_draw_horiz_band(MpegEncContext *s, int y, int h){
3268     if (s->avctx->draw_horiz_band) {
3269         AVFrame *src;
3270         int offset[4];
3271         
3272         if(s->picture_structure != PICT_FRAME){
3273             h <<= 1;
3274             y <<= 1;
3275             if(s->first_field  && !(s->avctx->slice_flags&SLICE_FLAG_ALLOW_FIELD)) return;
3276         }
3277
3278         h= FFMIN(h, s->height - y);
3279
3280         if(s->pict_type==B_TYPE || s->low_delay || (s->avctx->slice_flags&SLICE_FLAG_CODED_ORDER)) 
3281             src= (AVFrame*)s->current_picture_ptr;
3282         else if(s->last_picture_ptr)
3283             src= (AVFrame*)s->last_picture_ptr;
3284         else
3285             return;
3286             
3287         if(s->pict_type==B_TYPE && s->picture_structure == PICT_FRAME && s->out_format != FMT_H264){
3288             offset[0]=
3289             offset[1]=
3290             offset[2]=
3291             offset[3]= 0;
3292         }else{
3293             offset[0]= y * s->linesize;;
3294             offset[1]= 
3295             offset[2]= (y>>1) * s->uvlinesize;;
3296             offset[3]= 0;
3297         }
3298
3299         emms_c();
3300
3301         s->avctx->draw_horiz_band(s->avctx, src, offset,
3302                                   y, s->picture_structure, h);
3303     }
3304 }
3305
3306 void ff_init_block_index(MpegEncContext *s){ //FIXME maybe rename
3307     const int linesize= s->current_picture.linesize[0]; //not s->linesize as this woulnd be wrong for field pics
3308     const int uvlinesize= s->current_picture.linesize[1];
3309         
3310     s->block_index[0]= s->block_wrap[0]*(s->mb_y*2 + 1) - 1 + s->mb_x*2;
3311     s->block_index[1]= s->block_wrap[0]*(s->mb_y*2 + 1)     + s->mb_x*2;
3312     s->block_index[2]= s->block_wrap[0]*(s->mb_y*2 + 2) - 1 + s->mb_x*2;
3313     s->block_index[3]= s->block_wrap[0]*(s->mb_y*2 + 2)     + s->mb_x*2;
3314     s->block_index[4]= s->block_wrap[4]*(s->mb_y + 1)                    + s->block_wrap[0]*(s->mb_height*2 + 2) + s->mb_x;
3315     s->block_index[5]= s->block_wrap[4]*(s->mb_y + 1 + s->mb_height + 2) + s->block_wrap[0]*(s->mb_height*2 + 2) + s->mb_x;
3316     
3317     if(s->pict_type==B_TYPE && s->avctx->draw_horiz_band && s->picture_structure==PICT_FRAME){
3318         s->dest[0] = s->current_picture.data[0] + s->mb_x * 16 - 16;
3319         s->dest[1] = s->current_picture.data[1] + s->mb_x * 8 - 8;
3320         s->dest[2] = s->current_picture.data[2] + s->mb_x * 8 - 8;
3321     }else{
3322         s->dest[0] = s->current_picture.data[0] + (s->mb_y * 16* linesize  ) + s->mb_x * 16 - 16;
3323         s->dest[1] = s->current_picture.data[1] + (s->mb_y * 8 * uvlinesize) + s->mb_x * 8 - 8;
3324         s->dest[2] = s->current_picture.data[2] + (s->mb_y * 8 * uvlinesize) + s->mb_x * 8 - 8;
3325     }    
3326 }
3327
3328 #ifdef CONFIG_ENCODERS
3329
3330 static void get_vissual_weight(int16_t *weight, uint8_t *ptr, int stride){
3331     int x, y;
3332 //FIXME optimize
3333     for(y=0; y<8; y++){
3334         for(x=0; x<8; x++){
3335             int x2, y2;
3336             int sum=0;
3337             int sqr=0;
3338             int count=0;
3339
3340             for(y2= FFMAX(y-1, 0); y2 < FFMIN(8, y+2); y2++){
3341                 for(x2= FFMAX(x-1, 0); x2 < FFMIN(8, x+2); x2++){
3342                     int v= ptr[x2 + y2*stride];
3343                     sum += v;
3344                     sqr += v*v;
3345                     count++;
3346                 }
3347             }
3348             weight[x + 8*y]= (36*ff_sqrt(count*sqr - sum*sum)) / count;
3349         }
3350     }
3351 }
3352
3353 static void encode_mb(MpegEncContext *s, int motion_x, int motion_y)
3354 {
3355     int16_t weight[6][64];
3356     DCTELEM orig[6][64];
3357     const int mb_x= s->mb_x;
3358     const int mb_y= s->mb_y;
3359     int i;
3360     int skip_dct[6];
3361     int dct_offset   = s->linesize*8; //default for progressive frames
3362     uint8_t *ptr_y, *ptr_cb, *ptr_cr;
3363     int wrap_y, wrap_c;
3364     int emu=0;
3365     
3366     for(i=0; i<6; i++) skip_dct[i]=0;
3367     
3368     if(s->adaptive_quant){
3369         const int last_qp= s->qscale;
3370         const int mb_xy= mb_x + mb_y*s->mb_stride;
3371
3372         s->lambda= s->lambda_table[mb_xy];
3373         update_qscale(s);
3374     
3375         if(!(s->flags&CODEC_FLAG_QP_RD)){
3376             s->dquant= s->qscale - last_qp;
3377
3378             if(s->out_format==FMT_H263){
3379                 s->dquant= clip(s->dquant, -2, 2); //FIXME RD
3380             
3381                 if(s->codec_id==CODEC_ID_MPEG4){        
3382                     if(!s->mb_intra){
3383                         if(s->pict_type == B_TYPE){
3384                             if(s->dquant&1) 
3385                                 s->dquant= (s->dquant/2)*2;
3386                             if(s->mv_dir&MV_DIRECT)
3387                                 s->dquant= 0;
3388                         }
3389                         if(s->mv_type==MV_TYPE_8X8)
3390                             s->dquant=0;
3391                     }
3392                 }
3393             }
3394         }
3395         ff_set_qscale(s, last_qp + s->dquant);
3396     }
3397
3398     wrap_y = s->linesize;
3399     wrap_c = s->uvlinesize;
3400     ptr_y = s->new_picture.data[0] + (mb_y * 16 * wrap_y) + mb_x * 16;
3401     ptr_cb = s->new_picture.data[1] + (mb_y * 8 * wrap_c) + mb_x * 8;
3402     ptr_cr = s->new_picture.data[2] + (mb_y * 8 * wrap_c) + mb_x * 8;
3403
3404     if(mb_x*16+16 > s->width || mb_y*16+16 > s->height){
3405         ff_emulated_edge_mc(s->edge_emu_buffer            , ptr_y , wrap_y,16,16,mb_x*16,mb_y*16, s->width   , s->height);
3406         ptr_y= s->edge_emu_buffer;
3407         ff_emulated_edge_mc(s->edge_emu_buffer+16*wrap_y  , ptr_cb, wrap_c, 8, 8, mb_x*8, mb_y*8, s->width>>1, s->height>>1);
3408         ptr_cb= s->edge_emu_buffer+16*wrap_y;
3409         ff_emulated_edge_mc(s->edge_emu_buffer+16*wrap_y+8, ptr_cr, wrap_c, 8, 8, mb_x*8, mb_y*8, s->width>>1, s->height>>1);
3410         ptr_cr= s->edge_emu_buffer+16*wrap_y+8;
3411     }
3412
3413     if (s->mb_intra) {
3414         if(s->flags&CODEC_FLAG_INTERLACED_DCT){
3415             int progressive_score, interlaced_score;
3416
3417             s->interlaced_dct=0;
3418             progressive_score= s->dsp.ildct_cmp[4](s, ptr_y           , NULL, wrap_y, 8) 
3419                               +s->dsp.ildct_cmp[4](s, ptr_y + wrap_y*8, NULL, wrap_y, 8) - 400;
3420
3421             if(progressive_score > 0){
3422                 interlaced_score = s->dsp.ildct_cmp[4](s, ptr_y           , NULL, wrap_y*2, 8) 
3423                                   +s->dsp.ildct_cmp[4](s, ptr_y + wrap_y  , NULL, wrap_y*2, 8);
3424                 if(progressive_score > interlaced_score){
3425                     s->interlaced_dct=1;
3426             
3427                     dct_offset= wrap_y;
3428                     wrap_y<<=1;
3429                 }
3430             }
3431         }
3432         
3433         s->dsp.get_pixels(s->block[0], ptr_y                 , wrap_y);
3434         s->dsp.get_pixels(s->block[1], ptr_y              + 8, wrap_y);
3435         s->dsp.get_pixels(s->block[2], ptr_y + dct_offset    , wrap_y);
3436         s->dsp.get_pixels(s->block[3], ptr_y + dct_offset + 8, wrap_y);
3437
3438         if(s->flags&CODEC_FLAG_GRAY){
3439             skip_dct[4]= 1;
3440             skip_dct[5]= 1;
3441         }else{
3442             s->dsp.get_pixels(s->block[4], ptr_cb, wrap_c);
3443             s->dsp.get_pixels(s->block[5], ptr_cr, wrap_c);
3444         }
3445     }else{
3446         op_pixels_func (*op_pix)[4];
3447         qpel_mc_func (*op_qpix)[16];
3448         uint8_t *dest_y, *dest_cb, *dest_cr;
3449
3450         dest_y  = s->dest[0];
3451         dest_cb = s->dest[1];
3452         dest_cr = s->dest[2];
3453
3454         if ((!s->no_rounding) || s->pict_type==B_TYPE){
3455             op_pix = s->dsp.put_pixels_tab;
3456             op_qpix= s->dsp.put_qpel_pixels_tab;
3457         }else{
3458             op_pix = s->dsp.put_no_rnd_pixels_tab;
3459             op_qpix= s->dsp.put_no_rnd_qpel_pixels_tab;
3460         }
3461
3462         if (s->mv_dir & MV_DIR_FORWARD) {
3463             MPV_motion(s, dest_y, dest_cb, dest_cr, 0, s->last_picture.data, op_pix, op_qpix);
3464             op_pix = s->dsp.avg_pixels_tab;
3465             op_qpix= s->dsp.avg_qpel_pixels_tab;
3466         }
3467         if (s->mv_dir & MV_DIR_BACKWARD) {
3468             MPV_motion(s, dest_y, dest_cb, dest_cr, 1, s->next_picture.data, op_pix, op_qpix);
3469         }
3470
3471         if(s->flags&CODEC_FLAG_INTERLACED_DCT){
3472             int progressive_score, interlaced_score;
3473
3474             s->interlaced_dct=0;
3475             progressive_score= s->dsp.ildct_cmp[0](s, dest_y           , ptr_y           , wrap_y, 8) 
3476                               +s->dsp.ildct_cmp[0](s, dest_y + wrap_y*8, ptr_y + wrap_y*8, wrap_y, 8) - 400;
3477             
3478             if(s->avctx->ildct_cmp == FF_CMP_VSSE) progressive_score -= 400;
3479
3480             if(progressive_score>0){
3481                 interlaced_score = s->dsp.ildct_cmp[0](s, dest_y           , ptr_y           , wrap_y*2, 8) 
3482                                   +s->dsp.ildct_cmp[0](s, dest_y + wrap_y  , ptr_y + wrap_y  , wrap_y*2, 8);
3483             
3484                 if(progressive_score > interlaced_score){
3485                     s->interlaced_dct=1;
3486             
3487                     dct_offset= wrap_y;
3488                     wrap_y<<=1;
3489                 }
3490             }
3491         }
3492         
3493         s->dsp.diff_pixels(s->block[0], ptr_y                 , dest_y                 , wrap_y);
3494         s->dsp.diff_pixels(s->block[1], ptr_y              + 8, dest_y              + 8, wrap_y);
3495         s->dsp.diff_pixels(s->block[2], ptr_y + dct_offset    , dest_y + dct_offset    , wrap_y);
3496         s->dsp.diff_pixels(s->block[3], ptr_y + dct_offset + 8, dest_y + dct_offset + 8, wrap_y);
3497         
3498         if(s->flags&CODEC_FLAG_GRAY){
3499             skip_dct[4]= 1;
3500             skip_dct[5]= 1;
3501         }else{
3502             s->dsp.diff_pixels(s->block[4], ptr_cb, dest_cb, wrap_c);
3503             s->dsp.diff_pixels(s->block[5], ptr_cr, dest_cr, wrap_c);
3504         }
3505         /* pre quantization */         
3506         if(s->current_picture.mc_mb_var[s->mb_stride*mb_y+ mb_x]<2*s->qscale*s->qscale){
3507             //FIXME optimize
3508             if(s->dsp.sad[1](NULL, ptr_y               , dest_y               , wrap_y, 8) < 20*s->qscale) skip_dct[0]= 1;
3509             if(s->dsp.sad[1](NULL, ptr_y            + 8, dest_y            + 8, wrap_y, 8) < 20*s->qscale) skip_dct[1]= 1;
3510             if(s->dsp.sad[1](NULL, ptr_y +dct_offset   , dest_y +dct_offset   , wrap_y, 8) < 20*s->qscale) skip_dct[2]= 1;
3511             if(s->dsp.sad[1](NULL, ptr_y +dct_offset+ 8, dest_y +dct_offset+ 8, wrap_y, 8) < 20*s->qscale) skip_dct[3]= 1;
3512             if(s->dsp.sad[1](NULL, ptr_cb              , dest_cb              , wrap_c, 8) < 20*s->qscale) skip_dct[4]= 1;
3513             if(s->dsp.sad[1](NULL, ptr_cr              , dest_cr              , wrap_c, 8) < 20*s->qscale) skip_dct[5]= 1;
3514         }
3515     }
3516
3517     if(s->avctx->quantizer_noise_shaping){
3518         if(!skip_dct[0]) get_vissual_weight(weight[0], ptr_y                 , wrap_y);
3519         if(!skip_dct[1]) get_vissual_weight(weight[1], ptr_y              + 8, wrap_y);
3520         if(!skip_dct[2]) get_vissual_weight(weight[2], ptr_y + dct_offset    , wrap_y);
3521         if(!skip_dct[3]) get_vissual_weight(weight[3], ptr_y + dct_offset + 8, wrap_y);
3522         if(!skip_dct[4]) get_vissual_weight(weight[4], ptr_cb                , wrap_c);
3523         if(!skip_dct[5]) get_vissual_weight(weight[5], ptr_cr                , wrap_c);
3524         memcpy(orig[0], s->block[0], sizeof(DCTELEM)*64*6);
3525     }
3526             
3527     /* DCT & quantize */
3528     assert(s->out_format!=FMT_MJPEG || s->qscale==8);
3529     {
3530         for(i=0;i<6;i++) {
3531             if(!skip_dct[i]){
3532                 int overflow;
3533                 s->block_last_index[i] = s->dct_quantize(s, s->block[i], i, s->qscale, &overflow);
3534             // FIXME we could decide to change to quantizer instead of clipping
3535             // JS: I don't think that would be a good idea it could lower quality instead
3536             //     of improve it. Just INTRADC clipping deserves changes in quantizer
3537                 if (overflow) clip_coeffs(s, s->block[i], s->block_last_index[i]);
3538             }else
3539                 s->block_last_index[i]= -1;
3540         }
3541         if(s->avctx->quantizer_noise_shaping){
3542             for(i=0;i<6;i++) {
3543                 if(!skip_dct[i]){
3544                     s->block_last_index[i] = dct_quantize_refine(s, s->block[i], weight[i], orig[i], i, s->qscale);
3545                 }
3546             }
3547         }
3548         
3549         if(s->luma_elim_threshold && !s->mb_intra)
3550             for(i=0; i<4; i++)
3551                 dct_single_coeff_elimination(s, i, s->luma_elim_threshold);
3552         if(s->chroma_elim_threshold && !s->mb_intra)
3553             for(i=4; i<6; i++)
3554                 dct_single_coeff_elimination(s, i, s->chroma_elim_threshold);
3555
3556         if(s->flags & CODEC_FLAG_CBP_RD){
3557             for(i=0;i<6;i++) {
3558                 if(s->block_last_index[i] == -1)
3559                     s->coded_score[i]= INT_MAX/256;
3560             }
3561         }
3562     }
3563
3564     if((s->flags&CODEC_FLAG_GRAY) && s->mb_intra){
3565         s->block_last_index[4]=
3566         s->block_last_index[5]= 0;
3567         s->block[4][0]=
3568         s->block[5][0]= (1024 + s->c_dc_scale/2)/ s->c_dc_scale;
3569     }
3570
3571     //non c quantize code returns incorrect block_last_index FIXME
3572     if(s->alternate_scan && s->dct_quantize != dct_quantize_c){
3573         for(i=0; i<6; i++){
3574             int j;
3575             if(s->block_last_index[i]>0){
3576                 for(j=63; j>0; j--){
3577                     if(s->block[i][ s->intra_scantable.permutated[j] ]) break;
3578                 }
3579                 s->block_last_index[i]= j;
3580             }
3581         }
3582     }
3583
3584     /* huffman encode */
3585     switch(s->codec_id){ //FIXME funct ptr could be slightly faster
3586     case CODEC_ID_MPEG1VIDEO:
3587     case CODEC_ID_MPEG2VIDEO:
3588         mpeg1_encode_mb(s, s->block, motion_x, motion_y); break;
3589 #ifdef CONFIG_RISKY
3590     case CODEC_ID_MPEG4:
3591         mpeg4_encode_mb(s, s->block, motion_x, motion_y); break;
3592     case CODEC_ID_MSMPEG4V2:
3593     case CODEC_ID_MSMPEG4V3:
3594     case CODEC_ID_WMV1:
3595         msmpeg4_encode_mb(s, s->block, motion_x, motion_y); break;
3596     case CODEC_ID_WMV2:
3597          ff_wmv2_encode_mb(s, s->block, motion_x, motion_y); break;
3598     case CODEC_ID_H263:
3599     case CODEC_ID_H263P:
3600     case CODEC_ID_FLV1:
3601     case CODEC_ID_RV10:
3602         h263_encode_mb(s, s->block, motion_x, motion_y); break;
3603 #endif
3604     case CODEC_ID_MJPEG:
3605         mjpeg_encode_mb(s, s->block); break;
3606     default:
3607         assert(0);
3608     }
3609 }
3610
3611 #endif //CONFIG_ENCODERS
3612
3613 /**
3614  * combines the (truncated) bitstream to a complete frame
3615  * @returns -1 if no complete frame could be created
3616  */
3617 int ff_combine_frame( MpegEncContext *s, int next, uint8_t **buf, int *buf_size){
3618     ParseContext *pc= &s->parse_context;
3619
3620 #if 0
3621     if(pc->overread){
3622         printf("overread %d, state:%X next:%d index:%d o_index:%d\n", pc->overread, pc->state, next, pc->index, pc->overread_index);
3623         printf("%X %X %X %X\n", (*buf)[0], (*buf)[1],(*buf)[2],(*buf)[3]);
3624     }
3625 #endif
3626
3627     /* copy overreaded byes from last frame into buffer */
3628     for(; pc->overread>0; pc->overread--){
3629         pc->buffer[pc->index++]= pc->buffer[pc->overread_index++];
3630     }
3631     
3632     pc->last_index= pc->index;
3633
3634     /* copy into buffer end return */
3635     if(next == END_NOT_FOUND){
3636         pc->buffer= av_fast_realloc(pc->buffer, &pc->buffer_size, (*buf_size) + pc->index + FF_INPUT_BUFFER_PADDING_SIZE);
3637
3638         memcpy(&pc->buffer[pc->index], *buf, *buf_size);
3639         pc->index += *buf_size;
3640         return -1;
3641     }
3642
3643     *buf_size=
3644     pc->overread_index= pc->index + next;
3645     
3646     /* append to buffer */
3647     if(pc->index){
3648         pc->buffer= av_fast_realloc(pc->buffer, &pc->buffer_size, next + pc->index + FF_INPUT_BUFFER_PADDING_SIZE);
3649
3650         memcpy(&pc->buffer[pc->index], *buf, next + FF_INPUT_BUFFER_PADDING_SIZE );
3651         pc->index = 0;
3652         *buf= pc->buffer;
3653     }
3654
3655     /* store overread bytes */
3656     for(;next < 0; next++){
3657         pc->state = (pc->state<<8) | pc->buffer[pc->last_index + next];
3658         pc->overread++;
3659     }
3660
3661 #if 0
3662     if(pc->overread){
3663         printf("overread %d, state:%X next:%d index:%d o_index:%d\n", pc->overread, pc->state, next, pc->index, pc->overread_index);
3664         printf("%X %X %X %X\n", (*buf)[0], (*buf)[1],(*buf)[2],(*buf)[3]);
3665     }
3666 #endif
3667
3668     return 0;
3669 }
3670
3671 void ff_mpeg_flush(AVCodecContext *avctx){
3672     int i;
3673     MpegEncContext *s = avctx->priv_data;
3674     
3675     if(s==NULL || s->picture==NULL) 
3676         return;
3677     
3678     for(i=0; i<MAX_PICTURE_COUNT; i++){
3679        if(s->picture[i].data[0] && (   s->picture[i].type == FF_BUFFER_TYPE_INTERNAL
3680                                     || s->picture[i].type == FF_BUFFER_TYPE_USER))
3681         avctx->release_buffer(avctx, (AVFrame*)&s->picture[i]);
3682     }
3683     s->current_picture_ptr = s->last_picture_ptr = s->next_picture_ptr = NULL;
3684     
3685     s->parse_context.state= -1;
3686     s->parse_context.frame_start_found= 0;
3687     s->parse_context.overread= 0;
3688     s->parse_context.overread_index= 0;
3689     s->parse_context.index= 0;
3690     s->parse_context.last_index= 0;
3691 }
3692
3693 #ifdef CONFIG_ENCODERS
3694 void ff_copy_bits(PutBitContext *pb, uint8_t *src, int length)
3695 {
3696     const uint16_t *srcw= (uint16_t*)src;
3697     int words= length>>4;
3698     int bits= length&15;
3699     int i;
3700
3701     if(length==0) return;
3702     
3703     if(words < 16){
3704         for(i=0; i<words; i++) put_bits(pb, 16, be2me_16(srcw[i]));
3705     }else if(put_bits_count(pb)&7){
3706         for(i=0; i<words; i++) put_bits(pb, 16, be2me_16(srcw[i]));
3707     }else{
3708         for(i=0; put_bits_count(pb)&31; i++)
3709             put_bits(pb, 8, src[i]);
3710         flush_put_bits(pb);
3711         memcpy(pbBufPtr(pb), src+i, 2*words-i);
3712         skip_put_bytes(pb, 2*words-i);
3713     }
3714         
3715     put_bits(pb, bits, be2me_16(srcw[words])>>(16-bits));
3716 }
3717
3718 static inline void copy_context_before_encode(MpegEncContext *d, MpegEncContext *s, int type){
3719     int i;
3720
3721     memcpy(d->last_mv, s->last_mv, 2*2*2*sizeof(int)); //FIXME is memcpy faster then a loop?
3722
3723     /* mpeg1 */
3724     d->mb_skip_run= s->mb_skip_run;
3725     for(i=0; i<3; i++)
3726         d->last_dc[i]= s->last_dc[i];
3727     
3728     /* statistics */
3729     d->mv_bits= s->mv_bits;
3730     d->i_tex_bits= s->i_tex_bits;
3731     d->p_tex_bits= s->p_tex_bits;
3732     d->i_count= s->i_count;
3733     d->f_count= s->f_count;
3734     d->b_count= s->b_count;
3735     d->skip_count= s->skip_count;
3736     d->misc_bits= s->misc_bits;
3737     d->last_bits= 0;
3738
3739     d->mb_skiped= 0;
3740     d->qscale= s->qscale;
3741     d->dquant= s->dquant;
3742 }
3743
3744 static inline void copy_context_after_encode(MpegEncContext *d, MpegEncContext *s, int type){
3745     int i;
3746
3747     memcpy(d->mv, s->mv, 2*4*2*sizeof(int)); 
3748     memcpy(d->last_mv, s->last_mv, 2*2*2*sizeof(int)); //FIXME is memcpy faster then a loop?
3749     
3750     /* mpeg1 */
3751     d->mb_skip_run= s->mb_skip_run;
3752     for(i=0; i<3; i++)
3753         d->last_dc[i]= s->last_dc[i];
3754     
3755     /* statistics */
3756     d->mv_bits= s->mv_bits;
3757     d->i_tex_bits= s->i_tex_bits;
3758     d->p_tex_bits= s->p_tex_bits;
3759     d->i_count= s->i_count;
3760     d->f_count= s->f_count;
3761     d->b_count= s->b_count;
3762     d->skip_count= s->skip_count;
3763     d->misc_bits= s->misc_bits;
3764
3765     d->mb_intra= s->mb_intra;
3766     d->mb_skiped= s->mb_skiped;
3767     d->mv_type= s->mv_type;
3768     d->mv_dir= s->mv_dir;
3769     d->pb= s->pb;
3770     if(s->data_partitioning){
3771         d->pb2= s->pb2;
3772         d->tex_pb= s->tex_pb;
3773     }
3774     d->block= s->block;
3775     for(i=0; i<6; i++)
3776         d->block_last_index[i]= s->block_last_index[i];
3777     d->interlaced_dct= s->interlaced_dct;
3778     d->qscale= s->qscale;
3779 }
3780
3781 static inline void encode_mb_hq(MpegEncContext *s, MpegEncContext *backup, MpegEncContext *best, int type, 
3782                            PutBitContext pb[2], PutBitContext pb2[2], PutBitContext tex_pb[2],
3783                            int *dmin, int *next_block, int motion_x, int motion_y)
3784 {
3785     int score;
3786     uint8_t *dest_backup[3];
3787     
3788     copy_context_before_encode(s, backup, type);
3789
3790     s->block= s->blocks[*next_block];
3791     s->pb= pb[*next_block];
3792     if(s->data_partitioning){
3793         s->pb2   = pb2   [*next_block];
3794         s->tex_pb= tex_pb[*next_block];
3795     }
3796     
3797     if(*next_block){
3798         memcpy(dest_backup, s->dest, sizeof(s->dest));
3799         s->dest[0] = s->rd_scratchpad;
3800         s->dest[1] = s->rd_scratchpad + 16*s->linesize;
3801         s->dest[2] = s->rd_scratchpad + 16*s->linesize + 8;
3802         assert(s->linesize >= 32); //FIXME
3803     }
3804
3805     encode_mb(s, motion_x, motion_y);
3806     
3807     score= put_bits_count(&s->pb);
3808     if(s->data_partitioning){
3809         score+= put_bits_count(&s->pb2);
3810         score+= put_bits_count(&s->tex_pb);
3811     }
3812    
3813     if(s->avctx->mb_decision == FF_MB_DECISION_RD){
3814         MPV_decode_mb(s, s->block);
3815
3816         score *= s->lambda2;
3817         score += sse_mb(s) << FF_LAMBDA_SHIFT;
3818     }
3819     
3820     if(*next_block){
3821         memcpy(s->dest, dest_backup, sizeof(s->dest));
3822     }
3823
3824     if(score<*dmin){
3825         *dmin= score;
3826         *next_block^=1;
3827
3828         copy_context_after_encode(best, s, type);
3829     }
3830 }
3831                 
3832 static int sse(MpegEncContext *s, uint8_t *src1, uint8_t *src2, int w, int h, int stride){
3833     uint32_t *sq = squareTbl + 256;
3834     int acc=0;
3835     int x,y;
3836     
3837     if(w==16 && h==16) 
3838         return s->dsp.sse[0](NULL, src1, src2, stride, 16);
3839     else if(w==8 && h==8)
3840         return s->dsp.sse[1](NULL, src1, src2, stride, 8);
3841     
3842     for(y=0; y<h; y++){
3843         for(x=0; x<w; x++){
3844             acc+= sq[src1[x + y*stride] - src2[x + y*stride]];
3845         } 
3846     }
3847     
3848     assert(acc>=0);
3849     
3850     return acc;
3851 }
3852
3853 static int sse_mb(MpegEncContext *s){
3854     int w= 16;
3855     int h= 16;
3856
3857     if(s->mb_x*16 + 16 > s->width ) w= s->width - s->mb_x*16;
3858     if(s->mb_y*16 + 16 > s->height) h= s->height- s->mb_y*16;
3859
3860     if(w==16 && h==16)
3861         return  s->dsp.sse[0](NULL, s->new_picture.data[0] + s->mb_x*16 + s->mb_y*s->linesize*16, s->dest[0], s->linesize, 16)
3862                +s->dsp.sse[1](NULL, s->new_picture.data[1] + s->mb_x*8  + s->mb_y*s->uvlinesize*8,s->dest[1], s->uvlinesize, 8)
3863                +s->dsp.sse[1](NULL, s->new_picture.data[2] + s->mb_x*8  + s->mb_y*s->uvlinesize*8,s->dest[2], s->uvlinesize, 8);
3864     else
3865         return  sse(s, s->new_picture.data[0] + s->mb_x*16 + s->mb_y*s->linesize*16, s->dest[0], w, h, s->linesize)
3866                +sse(s, s->new_picture.data[1] + s->mb_x*8  + s->mb_y*s->uvlinesize*8,s->dest[1], w>>1, h>>1, s->uvlinesize)
3867                +sse(s, s->new_picture.data[2] + s->mb_x*8  + s->mb_y*s->uvlinesize*8,s->dest[2], w>>1, h>>1, s->uvlinesize);
3868 }
3869
3870 static int pre_estimate_motion_thread(AVCodecContext *c, void *arg){
3871     MpegEncContext *s= arg;
3872
3873     
3874     s->me.pre_pass=1;
3875     s->me.dia_size= s->avctx->pre_dia_size;
3876     s->first_slice_line=1;
3877     for(s->mb_y= s->end_mb_y-1; s->mb_y >= s->start_mb_y; s->mb_y--) {
3878         for(s->mb_x=s->mb_width-1; s->mb_x >=0 ;s->mb_x--) {
3879             ff_pre_estimate_p_frame_motion(s, s->mb_x, s->mb_y);
3880         }
3881         s->first_slice_line=0;
3882     }
3883     
3884     s->me.pre_pass=0;
3885     
3886     return 0;
3887 }
3888
3889 static int estimate_motion_thread(AVCodecContext *c, void *arg){
3890     MpegEncContext *s= arg;
3891
3892     s->me.dia_size= s->avctx->dia_size;
3893     s->first_slice_line=1;
3894     for(s->mb_y= s->start_mb_y; s->mb_y < s->end_mb_y; s->mb_y++) {
3895         s->mb_x=0; //for block init below
3896         ff_init_block_index(s);
3897         for(s->mb_x=0; s->mb_x < s->mb_width; s->mb_x++) {
3898             s->block_index[0]+=2;
3899             s->block_index[1]+=2;
3900             s->block_index[2]+=2;
3901             s->block_index[3]+=2;
3902             
3903             /* compute motion vector & mb_type and store in context */
3904             if(s->pict_type==B_TYPE)
3905                 ff_estimate_b_frame_motion(s, s->mb_x, s->mb_y);
3906             else
3907                 ff_estimate_p_frame_motion(s, s->mb_x, s->mb_y);
3908         }
3909         s->first_slice_line=0;
3910     }
3911     return 0;
3912 }
3913
3914 static int mb_var_thread(AVCodecContext *c, void *arg){
3915     MpegEncContext *s= arg;
3916     int mb_x, mb_y;
3917
3918     for(mb_y=s->start_mb_y; mb_y < s->end_mb_y; mb_y++) {
3919         for(mb_x=0; mb_x < s->mb_width; mb_x++) {
3920             int xx = mb_x * 16;
3921             int yy = mb_y * 16;
3922             uint8_t *pix = s->new_picture.data[0] + (yy * s->linesize) + xx;
3923             int varc;
3924             int sum = s->dsp.pix_sum(pix, s->linesize);
3925     
3926             varc = (s->dsp.pix_norm1(pix, s->linesize) - (((unsigned)(sum*sum))>>8) + 500 + 128)>>8;
3927
3928             s->current_picture.mb_var [s->mb_stride * mb_y + mb_x] = varc;
3929             s->current_picture.mb_mean[s->mb_stride * mb_y + mb_x] = (sum+128)>>8;
3930             s->mb_var_sum_temp    += varc;
3931         }
3932     }
3933     return 0;
3934 }
3935
3936 static void write_slice_end(MpegEncContext *s){
3937     if(s->codec_id==CODEC_ID_MPEG4){
3938         if(s->partitioned_frame){
3939             ff_mpeg4_merge_partitions(s);
3940         }
3941     
3942         ff_mpeg4_stuffing(&s->pb);
3943     }else if(s->out_format == FMT_MJPEG){
3944         ff_mjpeg_stuffing(&s->pb);
3945     }
3946
3947     align_put_bits(&s->pb);
3948     flush_put_bits(&s->pb);
3949 }
3950
3951 static int encode_thread(AVCodecContext *c, void *arg){
3952     MpegEncContext *s= arg;
3953     int mb_x, mb_y, pdif = 0;
3954     int i, j;
3955     MpegEncContext best_s, backup_s;
3956     uint8_t bit_buf[2][3000];
3957     uint8_t bit_buf2[2][3000];
3958     uint8_t bit_buf_tex[2][3000];
3959     PutBitContext pb[2], pb2[2], tex_pb[2];
3960 //printf("%d->%d\n", s->resync_mb_y, s->end_mb_y);
3961
3962     for(i=0; i<2; i++){
3963         init_put_bits(&pb    [i], bit_buf    [i], 3000);
3964         init_put_bits(&pb2   [i], bit_buf2   [i], 3000);
3965         init_put_bits(&tex_pb[i], bit_buf_tex[i], 3000);
3966     }
3967
3968     s->last_bits= put_bits_count(&s->pb);
3969     s->mv_bits=0;
3970     s->misc_bits=0;
3971     s->i_tex_bits=0;
3972     s->p_tex_bits=0;
3973     s->i_count=0;
3974     s->f_count=0;
3975     s->b_count=0;
3976     s->skip_count=0;
3977
3978     for(i=0; i<3; i++){
3979         /* init last dc values */
3980         /* note: quant matrix value (8) is implied here */
3981         s->last_dc[i] = 128;
3982         
3983         s->current_picture_ptr->error[i] = 0;
3984     }
3985     s->mb_skip_run = 0;
3986     memset(s->last_mv, 0, sizeof(s->last_mv));
3987      
3988     s->last_mv_dir = 0;
3989
3990 #ifdef CONFIG_RISKY
3991     switch(s->codec_id){
3992     case CODEC_ID_H263:
3993     case CODEC_ID_H263P:
3994     case CODEC_ID_FLV1:
3995         s->gob_index = ff_h263_get_gob_height(s);
3996         break;
3997     case CODEC_ID_MPEG4:
3998         if(s->partitioned_frame)
3999             ff_mpeg4_init_partitions(s);
4000         break;
4001     }
4002 #endif
4003
4004     s->resync_mb_x=0;
4005     s->resync_mb_y=0; 
4006     s->first_slice_line = 1;
4007     s->ptr_lastgob = s->pb.buf;
4008     for(mb_y= s->start_mb_y; mb_y < s->end_mb_y; mb_y++) {
4009 //    printf("row %d at %X\n", s->mb_y, (int)s);
4010         s->mb_x=0;
4011         s->mb_y= mb_y;
4012
4013         ff_set_qscale(s, s->qscale);
4014         ff_init_block_index(s);
4015         
4016         for(mb_x=0; mb_x < s->mb_width; mb_x++) {
4017             const int xy= mb_y*s->mb_stride + mb_x;
4018             int mb_type= s->mb_type[xy];
4019 //            int d;
4020             int dmin= INT_MAX;
4021             int dir;
4022
4023             s->mb_x = mb_x;
4024             ff_update_block_index(s);
4025
4026             /* write gob / video packet header  */
4027 #ifdef CONFIG_RISKY
4028             if(s->rtp_mode){
4029                 int current_packet_size, is_gob_start;
4030                 
4031                 current_packet_size= ((put_bits_count(&s->pb)+7)>>3) - (s->ptr_lastgob - s->pb.buf);
4032                 
4033                 is_gob_start= s->avctx->rtp_payload_size && current_packet_size >= s->avctx->rtp_payload_size && mb_y + mb_x>0; 
4034                 
4035                 if(s->start_mb_y == mb_y && mb_y > 0 && mb_x==0) is_gob_start=1;
4036                 
4037                 switch(s->codec_id){
4038                 case CODEC_ID_H263:
4039                 case CODEC_ID_H263P:
4040                     if(!s->h263_slice_structured)
4041                         if(s->mb_x || s->mb_y%s->gob_index) is_gob_start=0;
4042                     break;
4043                 case CODEC_ID_MPEG2VIDEO:
4044                     if(s->mb_x==0 && s->mb_y!=0) is_gob_start=1;
4045                 case CODEC_ID_MPEG1VIDEO:
4046                     if(s->mb_skip_run) is_gob_start=0;
4047                     break;
4048                 }
4049
4050                 if(is_gob_start){
4051                     if(s->start_mb_y != mb_y || mb_x!=0){
4052                         write_slice_end(s);
4053
4054                         if(s->codec_id==CODEC_ID_MPEG4 && s->partitioned_frame){
4055                             ff_mpeg4_init_partitions(s);
4056                         }
4057                     }
4058                 
4059                     assert((put_bits_count(&s->pb)&7) == 0);
4060                     current_packet_size= pbBufPtr(&s->pb) - s->ptr_lastgob;
4061                     
4062                     if(s->avctx->error_rate && s->resync_mb_x + s->resync_mb_y > 0){
4063                         int r= put_bits_count(&s->pb)/8 + s->picture_number + s->codec_id + s->mb_x + s->mb_y;
4064                         int d= 100 / s->avctx->error_rate;
4065                         if(r % d == 0){
4066                             current_packet_size=0;
4067 #ifndef ALT_BITSTREAM_WRITER
4068                             s->pb.buf_ptr= s->ptr_lastgob;
4069 #endif
4070                             assert(pbBufPtr(&s->pb) == s->ptr_lastgob);
4071                         }
4072                     }
4073         
4074                     if (s->avctx->rtp_callback)
4075                         s->avctx->rtp_callback(s->ptr_lastgob, current_packet_size, 0);
4076                     
4077                     switch(s->codec_id){
4078                     case CODEC_ID_MPEG4:
4079                         ff_mpeg4_encode_video_packet_header(s);
4080                         ff_mpeg4_clean_buffers(s);
4081                     break;
4082                     case CODEC_ID_MPEG1VIDEO:
4083                     case CODEC_ID_MPEG2VIDEO:
4084                         ff_mpeg1_encode_slice_header(s);
4085                         ff_mpeg1_clean_buffers(s);
4086                     break;
4087                     case CODEC_ID_H263:
4088                     case CODEC_ID_H263P:
4089                         h263_encode_gob_header(s, mb_y);                       
4090                     break;
4091                     }
4092
4093                     if(s->flags&CODEC_FLAG_PASS1){
4094                         int bits= put_bits_count(&s->pb);
4095                         s->misc_bits+= bits - s->last_bits;
4096                         s->last_bits= bits;
4097                     }
4098     
4099                     s->ptr_lastgob += current_packet_size;
4100                     s->first_slice_line=1;
4101                     s->resync_mb_x=mb_x;
4102                     s->resync_mb_y=mb_y;
4103                 }
4104             }